using System.Net; using System.Text.Json; using Helpdesk.Application.Auth; 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, $"absent-{attempt}@example.test")); Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient, "absent@example.test")); Assert.Equal(401, await LoginAsync(api.Server, web, secondClient, "absent@example.test")); Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient, "absent@example.test")); } private static async Task LoginAsync(TestServer server, string peer, string client, string email) { using var body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(new LoginRequest(email, "test-password"))); 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; } }