Enhance node update functionality to include base address
CI / Backend (build + test) (push) Successful in 1m25s
CI / Frontend (lint + typecheck + build) (push) Successful in 33s

- Added `BaseAddress` property to `UpdateNodeCommand` and `UpdateNodeBody` for improved node management.
- Implemented validation for the base address in `UpdateNodeCommandHandler`, ensuring it is a valid absolute URI.
- Updated `Node` class to support address updates, including logic to invalidate cached clients on address changes.
- Enhanced frontend components to handle base address input in the node editing dialog and API requests.
- Updated validation rules to enforce base address requirements in `UpdateNodeCommandValidator`.
This commit is contained in:
Leonid Pershin
2026-07-23 01:05:02 +03:00
parent 6b449dbfb5
commit ee6b8a35b8
10 changed files with 270 additions and 10 deletions
@@ -52,6 +52,7 @@ public static class NodeEndpoints
var command = new UpdateNodeCommand( var command = new UpdateNodeCommand(
id, id,
body.Name, body.Name,
body.BaseAddress,
body.Location, body.Location,
body.IsEnabled, body.IsEnabled,
body.Username, body.Username,
@@ -94,6 +95,7 @@ public static class NodeEndpoints
public sealed record UpdateNodeBody( public sealed record UpdateNodeBody(
string Name, string Name,
string BaseAddress,
string? Location, string? Location,
bool IsEnabled, bool IsEnabled,
string? Username, string? Username,
@@ -6,6 +6,7 @@ namespace PnvPanel.Application.Admin.Nodes;
public sealed record UpdateNodeCommand( public sealed record UpdateNodeCommand(
Guid NodeId, Guid NodeId,
string Name, string Name,
string BaseAddress,
string? Location, string? Location,
bool IsEnabled, bool IsEnabled,
string? Username, string? Username,
@@ -26,24 +26,43 @@ public sealed class UpdateNodeCommandHandler(
if (node is null) if (node is null)
return Result.Failure<NodeDto>(NodeErrors.NotFound); return Result.Failure<NodeDto>(NodeErrors.NotFound);
if (!Uri.TryCreate(command.BaseAddress, UriKind.Absolute, out var baseAddress))
return Result.Failure<NodeDto>(NodeErrors.InvalidBaseAddress);
var addressChanged = baseAddress != node.BaseAddress;
if (addressChanged)
{
var validation = gateway.ValidateBaseAddress(baseAddress);
if (!validation.IsSuccess)
return Result.Failure<NodeDto>(validation.Error);
}
node.UpdateDetails(command.Name, command.Location); node.UpdateDetails(command.Name, command.Location);
if (addressChanged)
node.UpdateAddress(baseAddress);
if (command.IsEnabled) if (command.IsEnabled)
node.Enable(); node.Enable();
else else
node.Disable(); node.Disable();
if ( var credentialsChanged =
!string.IsNullOrWhiteSpace(command.Username) !string.IsNullOrWhiteSpace(command.Username)
&& !string.IsNullOrWhiteSpace(command.Password) && !string.IsNullOrWhiteSpace(command.Password);
) if (credentialsChanged)
{ {
node.UpdateCredentials( node.UpdateCredentials(
new NodeCredentials(command.Username, secretProtector.Protect(command.Password)) new NodeCredentials(command.Username!, secretProtector.Protect(command.Password!))
); );
gateway.InvalidateClient(node.Id);
} }
// Клиент в гейтвее закэширован per-node (адрес+креденшлы захвачены при первом создании) —
// при смене любого из них старый закэшированный клиент нужно выбросить, иначе гейтвей
// продолжит стучаться по старому адресу/с старым паролем до перезапуска процесса.
if (addressChanged || credentialsChanged)
gateway.InvalidateClient(node.Id);
dbContext.AuditLogs.Add( dbContext.AuditLogs.Add(
AuditLog.Create( AuditLog.Create(
currentUser.UserId, currentUser.UserId,
@@ -7,6 +7,7 @@ public sealed class UpdateNodeCommandValidator : AbstractValidator<UpdateNodeCom
public UpdateNodeCommandValidator() public UpdateNodeCommandValidator()
{ {
RuleFor(x => x.Name).NotEmpty().MaximumLength(100); RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
RuleFor(x => x.BaseAddress).NotEmpty().MaximumLength(500);
RuleFor(x => x.Location).MaximumLength(100); RuleFor(x => x.Location).MaximumLength(100);
RuleFor(x => x.Username).MaximumLength(200); RuleFor(x => x.Username).MaximumLength(200);
} }
@@ -49,6 +49,14 @@ public sealed class Node : Entity
Location = location; Location = location;
} }
public void UpdateAddress(Uri baseAddress)
{
if (!baseAddress.IsAbsoluteUri)
throw new DomainException("Адрес ноды должен быть абсолютным URI.");
BaseAddress = baseAddress;
}
public void UpdateCredentials(NodeCredentials credentials) => Credentials = credentials; public void UpdateCredentials(NodeCredentials credentials) => Credentials = credentials;
public void Enable() => IsEnabled = true; public void Enable() => IsEnabled = true;
@@ -0,0 +1,212 @@
using NSubstitute;
using PnvPanel.Application.Admin.Nodes;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Nodes;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Nodes;
public class UpdateNodeCommandHandlerTests
{
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly ISecretProtector _secretProtector = Substitute.For<ISecretProtector>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
private static Node SeedNode(
string baseAddress = "https://node1.example.com",
string username = "admin",
string protectedPassword = "protected-old-password"
) => Node.Register("node-1", new Uri(baseAddress), new NodeCredentials(username, protectedPassword), null);
[Fact]
public async Task Handle_WhenAddressChanged_ValidatesAndUpdatesAddressAndInvalidatesClient()
{
using var dbContext = InMemoryDbContextFactory.Create();
var node = SeedNode();
dbContext.Nodes.Add(node);
await dbContext.SaveChangesAsync(CancellationToken.None);
_gateway.ValidateBaseAddress(Arg.Any<Uri>()).Returns(Result.Success());
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(
node.Id,
"node-1",
"https://node1-new.example.com",
null,
true,
null,
null
);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal("https://node1-new.example.com/", node.BaseAddress.ToString());
_gateway.Received(1).ValidateBaseAddress(Arg.Is<Uri>(u => u!.Host == "node1-new.example.com"));
_gateway.Received(1).InvalidateClient(node.Id);
}
[Fact]
public async Task Handle_WhenAddressUnchanged_DoesNotValidateOrInvalidateClient()
{
using var dbContext = InMemoryDbContextFactory.Create();
var node = SeedNode();
dbContext.Nodes.Add(node);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(
node.Id,
"node-1-renamed",
"https://node1.example.com",
"eu",
true,
null,
null
);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal("node-1-renamed", node.Name);
_gateway.DidNotReceive().ValidateBaseAddress(Arg.Any<Uri>());
_gateway.DidNotReceive().InvalidateClient(Arg.Any<Guid>());
}
[Fact]
public async Task Handle_WithInvalidBaseAddress_ReturnsValidationErrorWithoutChangingNode()
{
using var dbContext = InMemoryDbContextFactory.Create();
var node = SeedNode();
dbContext.Nodes.Add(node);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(node.Id, "node-1", "not-a-uri", null, true, null, null);
var result = await handler.Handle(command, CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(NodeErrors.InvalidBaseAddress, result.Error);
Assert.Equal("https://node1.example.com/", node.BaseAddress.ToString());
_gateway.DidNotReceive().ValidateBaseAddress(Arg.Any<Uri>());
}
[Fact]
public async Task Handle_WhenGatewayRejectsNewBaseAddress_ReturnsFailureWithoutChangingNode()
{
using var dbContext = InMemoryDbContextFactory.Create();
var node = SeedNode();
dbContext.Nodes.Add(node);
await dbContext.SaveChangesAsync(CancellationToken.None);
var error = Error.Validation("Nodes.SchemeNotAllowed", "Разрешён только HTTPS.");
_gateway.ValidateBaseAddress(Arg.Any<Uri>()).Returns(Result.Failure(error));
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(
node.Id,
"node-1",
"http://node1-new.example.com",
null,
true,
null,
null
);
var result = await handler.Handle(command, CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(error, result.Error);
Assert.Equal("https://node1.example.com/", node.BaseAddress.ToString());
_gateway.DidNotReceive().InvalidateClient(Arg.Any<Guid>());
}
[Fact]
public async Task Handle_WhenUsernameAndPasswordProvided_UpdatesCredentialsAndInvalidatesClient()
{
using var dbContext = InMemoryDbContextFactory.Create();
var node = SeedNode();
dbContext.Nodes.Add(node);
await dbContext.SaveChangesAsync(CancellationToken.None);
_secretProtector.Protect("new-password").Returns("protected-new-password");
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(
node.Id,
"node-1",
"https://node1.example.com",
null,
true,
"new-admin",
"new-password"
);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal("new-admin", node.Credentials.Username);
Assert.Equal("protected-new-password", node.Credentials.ProtectedPassword);
_gateway.Received(1).InvalidateClient(node.Id);
}
[Fact]
public async Task Handle_WhenOnlyUsernameProvided_DoesNotChangeCredentials()
{
using var dbContext = InMemoryDbContextFactory.Create();
var node = SeedNode();
dbContext.Nodes.Add(node);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(
node.Id,
"node-1",
"https://node1.example.com",
null,
true,
"new-admin",
null
);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal("admin", node.Credentials.Username);
Assert.Equal("protected-old-password", node.Credentials.ProtectedPassword);
_gateway.DidNotReceive().InvalidateClient(Arg.Any<Guid>());
}
[Fact]
public async Task Handle_WhenNodeNotFound_ReturnsNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new UpdateNodeCommandHandler(dbContext, _gateway, _secretProtector, _currentUser);
var command = new UpdateNodeCommand(
Guid.NewGuid(),
"node-1",
"https://node1.example.com",
null,
true,
null,
null
);
var result = await handler.Handle(command, CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(NodeErrors.NotFound, result.Error);
}
}
@@ -14,13 +14,15 @@ export function EditNodeDialog({ node, open, onOpenChange }: { node: NodeDto; op
const { t } = useTranslation() const { t } = useTranslation()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const [name, setName] = useState(node.name) const [name, setName] = useState(node.name)
const [baseAddress, setBaseAddress] = useState(node.baseAddress)
const [location, setLocation] = useState(node.location ?? '') const [location, setLocation] = useState(node.location ?? '')
const [isEnabled, setIsEnabled] = useState(node.isEnabled) const [isEnabled, setIsEnabled] = useState(node.isEnabled)
const [username, setUsername] = useState('') const [username, setUsername] = useState(node.username)
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const mutation = useMutation({ const mutation = useMutation({
mutationFn: () => updateNode(node.id, name.trim(), location.trim() || undefined, isEnabled, username.trim() || undefined, password || undefined), mutationFn: () =>
updateNode(node.id, name.trim(), baseAddress.trim(), location.trim() || undefined, isEnabled, username.trim() || undefined, password || undefined),
onSuccess: async () => { onSuccess: async () => {
toast.success(t('admin.nodes.updated')) toast.success(t('admin.nodes.updated'))
await queryClient.invalidateQueries({ queryKey: ['admin-nodes'] }) await queryClient.invalidateQueries({ queryKey: ['admin-nodes'] })
@@ -46,6 +48,16 @@ export function EditNodeDialog({ node, open, onOpenChange }: { node: NodeDto; op
<Label htmlFor="editName">{t('admin.nodes.name')}</Label> <Label htmlFor="editName">{t('admin.nodes.name')}</Label>
<Input id="editName" value={name} onChange={(e) => setName(e.target.value)} required /> <Input id="editName" value={name} onChange={(e) => setName(e.target.value)} required />
</div> </div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="editBaseAddress">{t('admin.nodes.baseAddress')}</Label>
<Input
id="editBaseAddress"
placeholder="https://panel.example.com:2053"
value={baseAddress}
onChange={(e) => setBaseAddress(e.target.value)}
required
/>
</div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<Label htmlFor="editLocation">{t('admin.nodes.location')}</Label> <Label htmlFor="editLocation">{t('admin.nodes.location')}</Label>
<Input id="editLocation" value={location} onChange={(e) => setLocation(e.target.value)} /> <Input id="editLocation" value={location} onChange={(e) => setLocation(e.target.value)} />
@@ -62,7 +74,7 @@ export function EditNodeDialog({ node, open, onOpenChange }: { node: NodeDto; op
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<Label htmlFor="editPassword"> <Label htmlFor="editPassword">
{t('admin.nodes.password')} ({t('admin.nodes.optional')}) {t('admin.nodes.password')} ({t('admin.nodes.passwordKeepUnchanged')})
</Label> </Label>
<Input <Input
id="editPassword" id="editPassword"
@@ -72,11 +84,12 @@ export function EditNodeDialog({ node, open, onOpenChange }: { node: NodeDto; op
data-1p-ignore data-1p-ignore
data-bwignore data-bwignore
data-form-type="other" data-form-type="other"
placeholder="••••••••"
value={password} value={password}
onChange={(e) => setPassword(e.target.value)} onChange={(e) => setPassword(e.target.value)}
/> />
</div> </div>
<Button type="submit" disabled={!name.trim() || mutation.isPending}> <Button type="submit" disabled={!name.trim() || !baseAddress.trim() || mutation.isPending}>
{t('admin.roles.save')} {t('admin.roles.save')}
</Button> </Button>
</form> </form>
+2 -1
View File
@@ -12,6 +12,7 @@ export function registerNode(name: string, baseAddress: string, username: string
export function updateNode( export function updateNode(
id: string, id: string,
name: string, name: string,
baseAddress: string,
location: string | undefined, location: string | undefined,
isEnabled: boolean, isEnabled: boolean,
username: string | undefined, username: string | undefined,
@@ -19,7 +20,7 @@ export function updateNode(
) { ) {
return apiRequest<NodeDto>(`/admin/nodes/${id}`, { return apiRequest<NodeDto>(`/admin/nodes/${id}`, {
method: 'PUT', method: 'PUT',
body: { name, location: location ?? null, isEnabled, username: username ?? null, password: password ?? null }, body: { name, baseAddress, location: location ?? null, isEnabled, username: username ?? null, password: password ?? null },
}) })
} }
+1
View File
@@ -3482,6 +3482,7 @@ export interface components {
}; };
UpdateNodeBody: { UpdateNodeBody: {
name: string; name: string;
baseAddress: string;
location: null | string; location: null | string;
isEnabled: boolean; isEnabled: boolean;
username: null | string; username: null | string;
+2
View File
@@ -443,6 +443,7 @@ const resources = {
allowedRoles: 'Доступно ролям', allowedRoles: 'Доступно ролям',
isPublishedLabel: 'Опубликовать инбаунд', isPublishedLabel: 'Опубликовать инбаунд',
optional: 'необязательно', optional: 'необязательно',
passwordKeepUnchanged: 'оставьте пустым, чтобы не менять',
}, },
apps: { apps: {
create: 'Добавить приложение', create: 'Добавить приложение',
@@ -1011,6 +1012,7 @@ const resources = {
allowedRoles: 'Allowed for roles', allowedRoles: 'Allowed for roles',
isPublishedLabel: 'Publish inbound', isPublishedLabel: 'Publish inbound',
optional: 'optional', optional: 'optional',
passwordKeepUnchanged: 'leave blank to keep unchanged',
}, },
apps: { apps: {
create: 'Add app', create: 'Add app',