Open-source personal finance manager. Self-hosted, privacy-first.
fix(rate-limit): derive client IP from a configured trusted-proxy hop (#839)
Amir Fathi54ff22384bb4
diff --git a/backend/.env.example b/backend/.env.exampleindex cf7b0897..d8eed5c7 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -10,6 +10,11 @@ REDIS_URL=redis://localhost:6379/0# (e.g. to avoid the dependency on the Brazilian government CSV endpoint).TESOURO_DIRETO_ENABLED=true+# Number of trusted reverse proxies in front of the backend (the bundled nginx+# frontend counts as 1). Rate limiting keys requests by client IP; leaving this+# at 0 in a proxied deployment means every client shares one rate-limit bucket.+TRUSTED_PROXY_HOPS=0+# Optional OIDC login (Authentik, Pocket ID, or standard OIDC providers)OIDC_ENABLED=falseOIDC_PROVIDER_NAME=OIDCdiff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex 0f6085e4..f8426141 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -111,6 +111,16 @@ class Settings(BaseSettings):# Celeryredis_url: str = "redis://localhost:6379/0"+ # Reverse-proxy trust for client-IP-based rate limiting. 0 (default) means+ # request.client.host is used as-is, which is only correct when nothing+ # sits between the client and this service. In the shipped docker-compose+ # topology the backend is reached through the bundled nginx frontend, so+ # request.client.host is always nginx's container address. Set this to the+ # number of trusted reverse proxies in front of the backend (usually 1) to+ # derive the client IP from X-Forwarded-For instead, trusting only that+ # many hops from the right; a chain shorter than expected is not trusted.+ trusted_proxy_hops: int = 0+# Logo size for market-priced asset icons. The logo URL is built from# the company website we get from the market-price provider; no API# key or third-party account is required. Defaults to 128×128 whichdiff --git a/backend/app/core/rate_limit.py b/backend/app/core/rate_limit.pyindex 9ee4729c..c6291cf4 100644--- a/backend/app/core/rate_limit.py+++ b/backend/app/core/rate_limit.py@@ -2,16 +2,37 @@ import timefrom fastapi import HTTPException, Request+from app.core.config import get_settingsfrom app.core.redis import get_redis+def resolve_client_ip(request: Request, trusted_proxy_hops: int) -> str:+ """Client IP for rate-limit keys, honoring `trusted_proxy_hops` trusted reverse proxies.++ Each trusted proxy appends its own observed peer address to the right end of+ X-Forwarded-For, so the Nth entry from the right is always a real, unspoofable+ observation rather than something the original client could have written into+ the header itself. A chain shorter than the configured hop count means the+ trust setting does not match what actually reached us, so it is not trusted.+ """+ if trusted_proxy_hops <= 0:+ return request.client.host if request.client else "unknown"++ forwarded_for = request.headers.get("x-forwarded-for")+ hops = [hop.strip() for hop in forwarded_for.split(",")] if forwarded_for else []+ if len(hops) < trusted_proxy_hops:+ return "unknown"++ return hops[-trusted_proxy_hops]++class RateLimiter:def __init__(self, max_requests: int, window_seconds: int):self.max_requests = max_requestsself.window_seconds = window_secondsasync def __call__(self, request: Request) -> None:- client_ip = request.client.host if request.client else "unknown"+ client_ip = resolve_client_ip(request, get_settings().trusted_proxy_hops)key = f"rate_limit:{request.url.path}:{client_ip}"r = await get_redis()diff --git a/backend/tests/test_rate_limit.py b/backend/tests/test_rate_limit.pyindex 9a8bda13..8d37f4c1 100644--- a/backend/tests/test_rate_limit.py+++ b/backend/tests/test_rate_limit.py@@ -2,6 +2,58 @@ from unittest.mock import AsyncMock, patchimport pytestfrom httpx import AsyncClient+from starlette.requests import Request++from app.core.rate_limit import resolve_client_ip+++def _request(client_host, forwarded_for=None):+ headers = [(b"x-forwarded-for", forwarded_for.encode())] if forwarded_for else []+ scope = {+ "type": "http",+ "client": (client_host, 12345) if client_host else None,+ "headers": headers,+ }+ return Request(scope)+++def test_resolve_client_ip_untrusted_uses_socket_peer():+ """trusted_proxy_hops=0 (default) ignores X-Forwarded-For entirely."""+ request = _request("172.26.0.3", forwarded_for="1.2.3.4")+ assert resolve_client_ip(request, trusted_proxy_hops=0) == "172.26.0.3"+++def test_resolve_client_ip_no_socket_peer_is_unknown():+ request = _request(None)+ assert resolve_client_ip(request, trusted_proxy_hops=0) == "unknown"+++def test_resolve_client_ip_one_trusted_hop():+ """One trusted proxy (nginx): the header it set is the real client."""+ request = _request("172.26.0.3", forwarded_for="203.0.113.9")+ assert resolve_client_ip(request, trusted_proxy_hops=1) == "203.0.113.9"+++def test_resolve_client_ip_ignores_client_supplied_prefix():+ """A client-forged leading entry must not override the trusted hop."""+ request = _request("172.26.0.3", forwarded_for="1.1.1.1, 203.0.113.9")+ assert resolve_client_ip(request, trusted_proxy_hops=1) == "203.0.113.9"+++def test_resolve_client_ip_two_trusted_hops():+ request = _request("172.26.0.3", forwarded_for="203.0.113.9, 10.0.0.5")+ assert resolve_client_ip(request, trusted_proxy_hops=2) == "203.0.113.9"+++def test_resolve_client_ip_short_chain_is_unknown():+ """Fewer hops than configured means the trust setting doesn't match reality."""+ request = _request("172.26.0.3", forwarded_for="10.0.0.5")+ assert resolve_client_ip(request, trusted_proxy_hops=2) == "unknown"+++def test_resolve_client_ip_missing_header_is_unknown():+ request = _request("172.26.0.3")+ assert resolve_client_ip(request, trusted_proxy_hops=1) == "unknown"@pytest.fixture(autouse=True)diff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex 9617e37b..ce8a1d1c 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -39,6 +39,10 @@ x-backend-env: &backend-envOPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}TESOURO_DIRETO_ENABLED: ${TESOURO_DIRETO_ENABLED:-true}+ # The backend is reached through the bundled nginx frontend below, so rate+ # limiting needs to trust exactly one reverse-proxy hop to key by real+ # client IP instead of nginx's own container address.+ TRUSTED_PROXY_HOPS: ${TRUSTED_PROXY_HOPS:-1}REDIS_URL: redis://redis:6379/0STORAGE_LOCAL_PATH: /app/data/attachmentsAGENTS_KNOWLEDGE_STORAGE_PATH: /app/data/agent_knowledge