Enhance configuration and logging for user management commands
CI / Backend (build + test) (push) Successful in 1m18s
CI / Frontend (lint + typecheck + build) (push) Successful in 31s

- Updated `.env.example` to include new settings for trusted proxies and networks for better security with X-Forwarded headers.
- Modified `BlockUserCommandHandler` and `UnblockUserCommandHandler` to include logging for gateway update failures, ensuring better traceability of issues during user blocking/unblocking.
- Adjusted tests for command handlers to incorporate logging functionality, improving test coverage and reliability.
- Updated frontend configuration to dynamically set the server port based on environment variables.
This commit is contained in:
Leonid Pershin
2026-07-02 14:33:32 +03:00
parent cdd67f8e2b
commit c04e0d7261
13 changed files with 162 additions and 17 deletions
+24 -3
View File
@@ -1,3 +1,4 @@
using System.Net;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.RateLimiting;
@@ -24,12 +25,23 @@ builder.Services.AddSerilog((services, configuration) => configuration
.ReadFrom.Services(services)
.Enrich.FromLogContext());
// За внешним прокси доверяем X-Forwarded-* (TLS терминируется вне контейнера).
// За внешним прокси доверяем X-Forwarded-* (TLS терминируется вне контейнера), но ТОЛЬКО от явно
// перечисленных адресов/сетей прокси — иначе клиент может подделать свой IP/схему напрямую, минуя
// прокси (спуфинг rate-limiting по IP, аудит-лога, Secure-cookie). По умолчанию (без конфигурации)
// остаётся дефолт ASP.NET Core — доверие только loopback; для прод-топологии прокси задаётся через
// ForwardedHeaders__KnownProxies / ForwardedHeaders__KnownNetworks (см. .env.example).
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
foreach (var proxy in builder.Configuration.GetSection("ForwardedHeaders:KnownProxies").Get<string[]>() ?? [])
options.KnownProxies.Add(IPAddress.Parse(proxy));
foreach (var network in builder.Configuration.GetSection("ForwardedHeaders:KnownNetworks").Get<string[]>() ?? [])
{
var parts = network.Split('/');
options.KnownIPNetworks.Add(new System.Net.IPNetwork(IPAddress.Parse(parts[0]), int.Parse(parts[1])));
}
});
builder.Services.AddHttpContextAccessor();
@@ -83,6 +95,15 @@ builder.Services.AddHealthChecks()
var app = builder.Build();
// Без персистентного пути key-ring живёт только в памяти контейнера — после пересоздания
// расшифровать уже сохранённые пароли нод будет невозможно. Предупреждаем громко, не молчим.
if (string.IsNullOrWhiteSpace(builder.Configuration["DataProtection:KeyRingPath"]))
{
app.Logger.LogWarning(
"DataProtection:KeyRingPath не задан — ключи шифрования секретов нод не персистентны " +
"и будут потеряны при пересоздании контейнера. В проде обязательно смонтируй том и укажи путь.");
}
// Авто-применение миграций и идемпотентный сидинг (роли + админ из env) на старте.
await app.Services.ApplyMigrationsAsync();
await app.Services.SeedDataAsync();
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
@@ -10,7 +11,8 @@ namespace PnvPanel.Application.Admin.Users;
/// <summary>Блокировка гасит все активные конфиги в 3x-ui (см. architecture.md).</summary>
public sealed class BlockUserCommandHandler(
IAppDbContext dbContext, IIdentityService identityService, IXuiPanelGateway gateway,
IRealtimeNotifier notifier, ITelegramNotifier telegramNotifier, ICurrentUser currentUser)
IRealtimeNotifier notifier, ITelegramNotifier telegramNotifier, ICurrentUser currentUser,
ILogger<BlockUserCommandHandler> logger)
: ICommandHandler<BlockUserCommand, Result>
{
public async Task<Result> Handle(BlockUserCommand command, CancellationToken cancellationToken)
@@ -32,9 +34,20 @@ public sealed class BlockUserCommandHandler(
if (inbound is not null && node is not null)
{
await gateway.UpdateClientAsync(
var updateResult = await gateway.UpdateClientAsync(
node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
config.Label ?? config.ClientEmail, config.DeviceLimit, enable: false, cancellationToken);
if (!updateResult.IsSuccess)
{
// Нода недоступна/сбой панели — не помечаем Disabled локально, иначе БД разойдётся
// с реальным состоянием клиента в 3x-ui (пользователь решит, что VPN погашен, а он жив).
// Конфиг останется Active и будет подхвачен повторным BlockUserCommand (идемпотентен).
logger.LogWarning(
"Не удалось отключить клиента конфига {ConfigId} на ноде {NodeId} при блокировке пользователя {UserId}: {Error}",
config.Id, node.Id, command.UserId, updateResult.Error);
continue;
}
}
config.Disable();
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Messaging;
using PnvPanel.Application.Common.Models;
@@ -10,7 +11,7 @@ namespace PnvPanel.Application.Admin.Users;
/// <summary>Разблокировка возвращает в 3x-ui только конфиги, погашенные блокировкой (Disabled).</summary>
public sealed class UnblockUserCommandHandler(
IAppDbContext dbContext, IIdentityService identityService, IXuiPanelGateway gateway,
IRealtimeNotifier notifier, ICurrentUser currentUser)
IRealtimeNotifier notifier, ICurrentUser currentUser, ILogger<UnblockUserCommandHandler> logger)
: ICommandHandler<UnblockUserCommand, Result>
{
public async Task<Result> Handle(UnblockUserCommand command, CancellationToken cancellationToken)
@@ -32,9 +33,20 @@ public sealed class UnblockUserCommandHandler(
if (inbound is not null && node is not null)
{
await gateway.UpdateClientAsync(
var updateResult = await gateway.UpdateClientAsync(
node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
config.Label ?? config.ClientEmail, config.DeviceLimit, enable: true, cancellationToken);
if (!updateResult.IsSuccess)
{
// Нода недоступна/сбой панели — не помечаем Enabled локально, иначе БД разойдётся
// с реальным состоянием клиента в 3x-ui. Конфиг останется Disabled и будет подхвачен
// повторным UnblockUserCommand (идемпотентен).
logger.LogWarning(
"Не удалось включить клиента конфига {ConfigId} на ноде {NodeId} при разблокировке пользователя {UserId}: {Error}",
config.Id, node.Id, command.UserId, updateResult.Error);
continue;
}
}
config.Enable();
@@ -1,3 +1,4 @@
using Microsoft.Extensions.Logging;
using NSubstitute;
using PnvPanel.Application.Admin.Users;
using PnvPanel.Application.Common.Interfaces;
@@ -17,6 +18,7 @@ public class BlockUserCommandHandlerTests
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ITelegramNotifier _telegramNotifier = Substitute.For<ITelegramNotifier>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
private readonly ILogger<BlockUserCommandHandler> _logger = Substitute.For<ILogger<BlockUserCommandHandler>>();
[Fact]
public async Task Handle_IdentityServiceFails_ReturnsFailureWithoutTouchingConfigs()
@@ -26,7 +28,7 @@ public class BlockUserCommandHandlerTests
var failure = UserErrors.NotFound;
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Failure(failure));
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser, _logger);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
@@ -55,8 +57,12 @@ public class BlockUserCommandHandlerTests
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(adminId);
_gateway.UpdateClientAsync(
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Success());
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser, _logger);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
@@ -82,7 +88,7 @@ public class BlockUserCommandHandlerTests
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(Guid.NewGuid());
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser, _logger);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
@@ -91,4 +97,37 @@ public class BlockUserCommandHandlerTests
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_GatewayFails_KeepsConfigActiveForRetryAndDoesNotNotify()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var adminId = Guid.NewGuid();
var node = Node.Register("node-1", new Uri("https://node1.example.com"), new NodeCredentials("admin", "protected"), null);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "my-config", 0);
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(adminId);
_gateway.UpdateClientAsync(
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _telegramNotifier, _currentUser, _logger);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Active, config.Status);
await _notifier.DidNotReceive().NotifyConfigStatusChangedAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<ConfigStatus>(), Arg.Any<CancellationToken>());
}
}
@@ -1,3 +1,4 @@
using Microsoft.Extensions.Logging;
using NSubstitute;
using PnvPanel.Application.Admin.Users;
using PnvPanel.Application.Common.Interfaces;
@@ -16,6 +17,7 @@ public class UnblockUserCommandHandlerTests
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
private readonly ILogger<UnblockUserCommandHandler> _logger = Substitute.For<ILogger<UnblockUserCommandHandler>>();
[Fact]
public async Task Handle_WhenUnblockSucceeds_ReEnablesDisabledConfigsAndWritesAudit()
@@ -36,8 +38,12 @@ public class UnblockUserCommandHandlerTests
_currentUser.UserId.Returns(adminId);
_identityService.UnblockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_gateway.UpdateClientAsync(
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Success());
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser, _logger);
var result = await handler.Handle(new UnblockUserCommand(userId), CancellationToken.None);
@@ -60,7 +66,7 @@ public class UnblockUserCommandHandlerTests
_identityService.UnblockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Failure(error));
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser, _logger);
var result = await handler.Handle(new UnblockUserCommand(userId), CancellationToken.None);
@@ -68,4 +74,38 @@ public class UnblockUserCommandHandlerTests
Assert.Equal(error, result.Error);
Assert.Empty(dbContext.AuditLogs);
}
[Fact]
public async Task Handle_GatewayFails_KeepsConfigDisabledForRetryAndDoesNotNotify()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var adminId = Guid.NewGuid();
var node = Node.Register("node-1", new Uri("https://node1.example.com"), new NodeCredentials("admin", "protected"), null);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "my-config", 0);
config.Disable();
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
await dbContext.SaveChangesAsync(CancellationToken.None);
_currentUser.UserId.Returns(adminId);
_identityService.UnblockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_gateway.UpdateClientAsync(
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
.Returns(Result.Failure(Error.Failure("Xui.UpdateClientFailed", "Нода недоступна.")));
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser, _logger);
var result = await handler.Handle(new UnblockUserCommand(userId), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Disabled, config.Status);
await _notifier.DidNotReceive().NotifyConfigStatusChangedAsync(
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<ConfigStatus>(), Arg.Any<CancellationToken>());
}
}