backend + web: Forward client IP through trusted web proxy

This commit is contained in:
GonnaHetzMe committed 2026-12-03 00:41:01 +01:00
1 parent 32bc5a4691
commit d8de714481
8 files changed
+138 -19

No files matched your search

+18 -10
View File
@@ -30,18 +30,21 @@ builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<AppExceptionHandler>();
builder.Services.AddHelpdeskSwagger();
var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"];
if (!string.IsNullOrWhiteSpace(trustedProxy))
{
if (!IPAddress.TryParse(trustedProxy, out var proxyAddress))
throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy.");
var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" }
.Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key]))
.Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address
: throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}."))
.ToArray();
if (trustedProxies.Length > 0)
{
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
options.KnownProxies.Add(proxyAddress);
foreach (var address in trustedProxies)
options.KnownProxies.Add(address);
});
}
@@ -49,9 +52,14 @@ if (!string.IsNullOrWhiteSpace(trustedProxy))
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
options.AddPolicy(RateLimitPolicies.Auth, http =>
{
var address = http.Connection.RemoteIpAddress;
if (address is { IsIPv4MappedToIPv6: true })
address = address.MapToIPv4();
return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) });
});
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
_ => new SlidingWindowRateLimiterOptions
@@ -64,7 +72,7 @@ builder.Services.AddRateLimiter(options =>
var app = builder.Build();
if (!string.IsNullOrWhiteSpace(trustedProxy))
if (trustedProxies.Length > 0)
app.UseForwardedHeaders();
app.UseExceptionHandler();
@@ -68,6 +68,9 @@ public sealed class BackendFixture : IAsyncLifetime
return client;
}
internal WebApplicationFactory<Program> CreateApiBehindProxies(string proxyIp, string webIp) =>
new ApiFactory(database.GetConnectionString(), email, TokenSaves, proxyIp, webIp);
internal async Task<UserDto> RegisterAsync(HttpClient client)
{
var address = $"{Guid.NewGuid():N}@student.example.test";
@@ -137,7 +140,8 @@ public sealed class BackendFixture : IAsyncLifetime
}
}
private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves)
private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves,
string proxyIp = "", string webIp = "")
: WebApplicationFactory<Program>
{
private readonly Dictionary<string, string?> settings = new()
@@ -152,7 +156,8 @@ public sealed class BackendFixture : IAsyncLifetime
["Firebase:ServiceAccountJson"] = "",
["Smtp:Mailbox"] = "",
["Smtp:Password"] = "",
["ReverseProxy:TrustedIp"] = "",
["ReverseProxy:TrustedIp"] = proxyIp,
["ReverseProxy:TrustedWebIp"] = webIp,
};
protected override IHost CreateHost(IHostBuilder builder)
@@ -0,0 +1,41 @@
using System.Net;
using Microsoft.AspNetCore.TestHost;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task TrustedProxiesShareTheLimitForEachClientAndSeparateDifferentClients()
{
const string externalProxy = "192.0.2.10";
const string web = "192.0.2.11";
const string firstClient = "198.51.100.10";
const string secondClient = "198.51.100.11";
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
for (var attempt = 0; attempt < 20; attempt++)
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient));
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient));
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient));
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient));
}
private static async Task<int> LoginAsync(TestServer server, string peer, string client)
{
using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray());
var response = await server.SendAsync(context =>
{
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
context.Request.Method = "POST";
context.Request.Path = "/api/v1/auth/login";
context.Request.ContentType = "application/json";
context.Request.ContentLength = body.Length;
context.Request.Body = body;
context.Request.Headers["X-Forwarded-For"] = client;
}, Cancellation);
return response.Response.StatusCode;
}
}