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

+1 -1
View File
@@ -40,7 +40,7 @@ Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adre
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS`: `/api/*` a `/swagger` na port `API_HTTP_PORT` (výchozí `8080`), ostatní na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli.
Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno.
Serverová reverse proxy předává IP klienta v `X-Forwarded-For` a schéma v `X-Forwarded-Proto`. Nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. Compose automaticky nastaví privátní síť a důvěryhodnou adresu webu, přes kterou web předává IP klienta dál do API.
S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase.
+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;
}
}
+17 -4
View File
@@ -53,6 +53,7 @@ services:
Smtp__Password: ${SMTP_PASSWORD:-}
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
ReverseProxy__TrustedWebIp: ${WEB_API_WEB_IP:-172.30.242.6}
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
volumes:
@@ -62,7 +63,11 @@ services:
condition: service_completed_successfully
ports:
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
networks: [frontend, backend]
networks:
frontend:
backend:
web-api:
aliases: [api-web]
web:
build:
@@ -70,8 +75,7 @@ services:
dockerfile: web/Dockerfile
environment:
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
# Web volá API uvnitř Docker sítě; do databáze přístup nemá (je jen v síti frontend).
Api__BaseUrl: http://api:8080/
Api__BaseUrl: http://api-web:8080/
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
volumes:
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
@@ -80,12 +84,21 @@ services:
- api
ports:
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
networks: [frontend]
networks:
frontend:
web-api:
ipv4_address: ${WEB_API_WEB_IP:-172.30.242.6}
networks:
frontend:
backend:
internal: true
web-api:
# Při kolizi s existující sítí lze společně přepsat WEB_API_SUBNET a WEB_API_WEB_IP.
internal: true
ipam:
config:
- subnet: ${WEB_API_SUBNET:-172.30.242.0/29}
volumes:
db-data:
@@ -0,0 +1,33 @@
using System.Net;
using Helpdesk.Web.Api;
using Microsoft.AspNetCore.Http;
namespace Helpdesk.Web.Tests;
public sealed class ForwardedClientIpHandlerTests
{
[Fact]
public async Task UsesTheCurrentConnectionAddressInsteadOfTheIncomingHeader()
{
const string header = "X-Forwarded-For";
var context = new DefaultHttpContext();
context.Connection.RemoteIpAddress = IPAddress.Parse("198.51.100.10");
context.Request.Headers[header] = "203.0.113.11";
var accessor = new HttpContextAccessor { HttpContext = context };
using var client = new HttpMessageInvoker(new ForwardedClientIpHandler(accessor) { InnerHandler = new Responder() });
using var request = new HttpRequestMessage(HttpMethod.Post, "http://api-web:8080/api/v1/auth/login");
using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
Assert.Equal("198.51.100.10", Assert.Single(request.Headers.GetValues(header)));
accessor.HttpContext = null;
using var next = new HttpRequestMessage(HttpMethod.Post, request.RequestUri);
using var nextResponse = await client.SendAsync(next, TestContext.Current.CancellationToken);
Assert.False(next.Headers.Contains(header));
}
private sealed class Responder : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
}
}
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.HttpOverrides;
namespace Helpdesk.Web.Api;
internal sealed class ForwardedClientIpHandler(IHttpContextAccessor accessor) : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var header = ForwardedHeadersDefaults.XForwardedForHeaderName;
request.Headers.Remove(header);
if (accessor.HttpContext?.Connection.RemoteIpAddress is { } address)
request.Headers.Add(header, address.ToString());
return base.SendAsync(request, cancellationToken);
}
}
+6 -2
View File
@@ -37,8 +37,12 @@ static void ConfigureApiClient(IServiceProvider services, HttpClient http)
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<BearerTokenHandler>();
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient);
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient).AddHttpMessageHandler<BearerTokenHandler>();
builder.Services.AddTransient<ForwardedClientIpHandler>();
builder.Services.AddHttpClient<AuthApiClient>(ConfigureApiClient)
.AddHttpMessageHandler<ForwardedClientIpHandler>();
builder.Services.AddHttpClient<HelpdeskApiClient>(ConfigureApiClient)
.AddHttpMessageHandler<ForwardedClientIpHandler>()
.AddHttpMessageHandler<BearerTokenHandler>();
// Přihlášení: tokeny API v šifrované HttpOnly cookie, obnova access tokenu při ověření cookie.
builder.Services.AddSingleton(TimeProvider.System);