Implement rate limiting and enhance authentication flow
- Added rate limiting configuration for authentication endpoints, allowing customizable request limits via environment variables. - Updated authentication flow to utilize HttpRequest for cookie management, ensuring secure handling of refresh tokens. - Introduced a new endpoint to retrieve user subscription details. - Enhanced the handling of Telegram bot token validation to prevent errors with empty tokens. - Updated the application to serialize enums as strings for better documentation and compatibility with TypeScript. - Improved test coverage for new features and adjustments in command handlers.
This commit is contained in:
@@ -38,13 +38,13 @@ public static class AuthEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> Login(LoginCommand command, ISender sender, HttpResponse response, CancellationToken cancellationToken)
|
||||
private static async Task<IResult> Login(LoginCommand command, ISender sender, HttpRequest request, HttpResponse response, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await sender.Send(command, cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
return result.ToHttpResult();
|
||||
|
||||
SetRefreshCookie(response, result.Value.RefreshToken, result.Value.RefreshTokenExpiresAt);
|
||||
SetRefreshCookie(request, response, result.Value.RefreshToken, result.Value.RefreshTokenExpiresAt);
|
||||
return Results.Ok(ToLoginResponse(result.Value));
|
||||
}
|
||||
|
||||
@@ -56,11 +56,11 @@ public static class AuthEndpoints
|
||||
var result = await sender.Send(new RefreshCommand(rawToken), cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
{
|
||||
response.Cookies.Delete(RefreshCookieName, BuildCookieOptions());
|
||||
response.Cookies.Delete(RefreshCookieName, BuildCookieOptions(request));
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
SetRefreshCookie(response, result.Value.RefreshToken, result.Value.RefreshTokenExpiresAt);
|
||||
SetRefreshCookie(request, response, result.Value.RefreshToken, result.Value.RefreshTokenExpiresAt);
|
||||
return Results.Ok(ToLoginResponse(result.Value));
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public static class AuthEndpoints
|
||||
if (request.Cookies.TryGetValue(RefreshCookieName, out var rawToken) && !string.IsNullOrEmpty(rawToken))
|
||||
await sender.Send(new LogoutCommand(rawToken), cancellationToken);
|
||||
|
||||
response.Cookies.Delete(RefreshCookieName, BuildCookieOptions());
|
||||
response.Cookies.Delete(RefreshCookieName, BuildCookieOptions(request));
|
||||
return Results.NoContent();
|
||||
}
|
||||
|
||||
@@ -85,10 +85,10 @@ public static class AuthEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> DeleteMe(HttpResponse response, ISender sender, CancellationToken cancellationToken)
|
||||
private static async Task<IResult> DeleteMe(HttpRequest request, HttpResponse response, ISender sender, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await sender.Send(new DeleteMyAccountCommand(), cancellationToken);
|
||||
response.Cookies.Delete(RefreshCookieName, BuildCookieOptions());
|
||||
response.Cookies.Delete(RefreshCookieName, BuildCookieOptions(request));
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
@@ -99,17 +99,19 @@ public static class AuthEndpoints
|
||||
user = auth.User,
|
||||
};
|
||||
|
||||
private static void SetRefreshCookie(HttpResponse response, string rawToken, DateTimeOffset expiresAt)
|
||||
private static void SetRefreshCookie(HttpRequest request, HttpResponse response, string rawToken, DateTimeOffset expiresAt)
|
||||
{
|
||||
var options = BuildCookieOptions();
|
||||
var options = BuildCookieOptions(request);
|
||||
options.Expires = expiresAt;
|
||||
response.Cookies.Append(RefreshCookieName, rawToken, options);
|
||||
}
|
||||
|
||||
private static CookieOptions BuildCookieOptions() => new()
|
||||
// Secure = IsHttps запроса (учитывает ForwardedHeaders за внешним TLS-прокси, см. CLAUDE.md) —
|
||||
// иначе браузер/HttpClient не пришлёт cookie обратно на plain-http (локальный dev, TestServer).
|
||||
private static CookieOptions BuildCookieOptions(HttpRequest request) => new()
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
Secure = request.IsHttps,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Path = "/api/auth",
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ using PnvPanel.Application.Configs.Create;
|
||||
using PnvPanel.Application.Configs.Edit;
|
||||
using PnvPanel.Application.Configs.GetConfigLink;
|
||||
using PnvPanel.Application.Configs.GetMyConfigs;
|
||||
using PnvPanel.Application.Configs.GetMySubscription;
|
||||
using PnvPanel.Application.Configs.ListAvailableInbounds;
|
||||
using PnvPanel.Application.Configs.Revoke;
|
||||
using PnvPanel.Application.Configs.Rotate;
|
||||
@@ -23,6 +24,7 @@ public static class ConfigEndpoints
|
||||
group.MapPost("/configs/{id:guid}/rotate", RotateConfig);
|
||||
group.MapDelete("/configs/{id:guid}", RevokeConfig);
|
||||
group.MapGet("/configs/{id:guid}/link", GetConfigLink);
|
||||
group.MapGet("/subscription", GetMySubscription);
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -74,6 +76,16 @@ public static class ConfigEndpoints
|
||||
var subscriptionUrl = $"{request.Scheme}://{request.Host}/sub/{result.Value.SubscriptionToken}";
|
||||
return Results.Ok(new { connectionString = result.Value.ConnectionString, subscriptionUrl });
|
||||
}
|
||||
|
||||
private static async Task<IResult> GetMySubscription(HttpRequest request, ISender sender, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await sender.Send(new GetMySubscriptionQuery(), cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
return result.ToHttpResult();
|
||||
|
||||
var subscriptionUrl = $"{request.Scheme}://{request.Host}/sub/{result.Value.SubscriptionToken}";
|
||||
return Results.Ok(new { subscriptionUrl });
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CreateConfigBody(Guid InboundId, string? Label, int? DeviceLimit);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
@@ -40,11 +41,17 @@ builder.Services.AddSignalR();
|
||||
builder.Services.AddSingleton<IRealtimeNotifier, SignalRRealtimeNotifier>();
|
||||
|
||||
// Telegram-бот: presentation-адаптер, хостится в процессе Api (long polling). Клиент регистрируем
|
||||
// всегда (даже с пустым токеном) — TelegramBotHostedService сам решает не стартовать без токена.
|
||||
// всегда (даже с пустым токеном) — TelegramBotHostedService сам решает не стартовать без токена,
|
||||
// а TelegramNotifier — не слать сообщения. TelegramBotClient(...) при этом валидирует формат токена
|
||||
// и падает на пустой строке, поэтому при пустом BotToken подставляем синтаксически валидную заглушку —
|
||||
// реальный HTTP-вызов через неё никогда не происходит (все вызывающие места сами проверяют BotToken).
|
||||
builder.Services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<TelegramOptions>>();
|
||||
return new TelegramBotClient(options.Value.BotToken ?? string.Empty);
|
||||
var token = options.Value.BotToken;
|
||||
return new TelegramBotClient(string.IsNullOrWhiteSpace(token)
|
||||
? "0:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
: token);
|
||||
});
|
||||
// Scoped — зависит от IIdentityService (scoped), не Singleton.
|
||||
builder.Services.AddScoped<ITelegramNotifier, TelegramNotifier>();
|
||||
@@ -55,13 +62,20 @@ builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.AddFixedWindowLimiter(RateLimiting.AuthPolicy, limiterOptions =>
|
||||
{
|
||||
limiterOptions.PermitLimit = 20;
|
||||
// Настраиваемо через конфиг, чтобы интеграционные тесты (общий TestServer/host на весь
|
||||
// collection, все запросы — от одного "клиента") могли поднять лимит и не ловить 429.
|
||||
limiterOptions.PermitLimit = builder.Configuration.GetValue("RateLimiting:AuthPermitLimit", 20);
|
||||
limiterOptions.Window = TimeSpan.FromMinutes(1);
|
||||
limiterOptions.QueueLimit = 0;
|
||||
});
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
});
|
||||
|
||||
// Энумы сериализуются строками ("Vless", "Active", ...), не числами — самодокументируемый JSON,
|
||||
// корректные строковые литералы при генерации TS-типов из OpenAPI-схемы (см. docs/frontend.md).
|
||||
builder.Services.ConfigureHttpJsonOptions(options =>
|
||||
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
|
||||
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddHealthChecks()
|
||||
|
||||
Reference in New Issue
Block a user