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

@@ -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;
}
}