Enhance node update functionality to include base address
- 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:
@@ -52,6 +52,7 @@ public static class NodeEndpoints
|
||||
var command = new UpdateNodeCommand(
|
||||
id,
|
||||
body.Name,
|
||||
body.BaseAddress,
|
||||
body.Location,
|
||||
body.IsEnabled,
|
||||
body.Username,
|
||||
@@ -94,6 +95,7 @@ public static class NodeEndpoints
|
||||
|
||||
public sealed record UpdateNodeBody(
|
||||
string Name,
|
||||
string BaseAddress,
|
||||
string? Location,
|
||||
bool IsEnabled,
|
||||
string? Username,
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace PnvPanel.Application.Admin.Nodes;
|
||||
public sealed record UpdateNodeCommand(
|
||||
Guid NodeId,
|
||||
string Name,
|
||||
string BaseAddress,
|
||||
string? Location,
|
||||
bool IsEnabled,
|
||||
string? Username,
|
||||
|
||||
@@ -26,24 +26,43 @@ public sealed class UpdateNodeCommandHandler(
|
||||
if (node is null)
|
||||
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);
|
||||
|
||||
if (addressChanged)
|
||||
node.UpdateAddress(baseAddress);
|
||||
|
||||
if (command.IsEnabled)
|
||||
node.Enable();
|
||||
else
|
||||
node.Disable();
|
||||
|
||||
if (
|
||||
var credentialsChanged =
|
||||
!string.IsNullOrWhiteSpace(command.Username)
|
||||
&& !string.IsNullOrWhiteSpace(command.Password)
|
||||
)
|
||||
&& !string.IsNullOrWhiteSpace(command.Password);
|
||||
if (credentialsChanged)
|
||||
{
|
||||
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(
|
||||
AuditLog.Create(
|
||||
currentUser.UserId,
|
||||
|
||||
@@ -7,6 +7,7 @@ public sealed class UpdateNodeCommandValidator : AbstractValidator<UpdateNodeCom
|
||||
public UpdateNodeCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.BaseAddress).NotEmpty().MaximumLength(500);
|
||||
RuleFor(x => x.Location).MaximumLength(100);
|
||||
RuleFor(x => x.Username).MaximumLength(200);
|
||||
}
|
||||
|
||||
@@ -49,6 +49,14 @@ public sealed class Node : Entity
|
||||
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 Enable() => IsEnabled = true;
|
||||
|
||||
+212
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user