Enhance configuration and logging for user management commands
- 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:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user