using System.Net; using Microsoft.AspNetCore.TestHost; using static Helpdesk.IntegrationTests.BackendFixture; namespace Helpdesk.IntegrationTests; public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture { [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 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; } }