Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(rate-limit): derive the key from the right-most X-Forwarded-For entry (#6442)

LearningCircuit0aa3aa889204
diff --git a/changelog.d/6442.security.md b/changelog.d/6442.security.md
new file mode 100644
index 0000000000..d306257056
--- /dev/null
+++ b/changelog.d/6442.security.md
@@ -0,0 +1 @@
+Hardened rate-limit key derivation for reverse proxies that append to X-Forwarded-For instead of overwriting it (#5787): the key is now the right-most entry — the one added by the nearest proxy — taken across all X-Forwarded-For header lines, so neither an appended same-line prefix (nginx `$proxy_add_x_forwarded_for`) nor a client-sent line ahead of the proxy's own line (HAProxy `option forwardfor`) can choose the bucket. A forwarded X-Forwarded-For or X-Real-IP value now becomes the key only if it parses as an IP address (an optional port, or `[IPv6]:port`, is accepted and dropped, so varying the port no longer yields a new bucket); an empty, whitespace-only (including `\xa0`/`\x85`, which `str.strip()` removes) or non-address value falls back to the request's client address instead of producing an empty key that disables limiting or a free-text key. A client address that is itself not an IP address — possible with `TRUST_PROXY_HEADERS=true`, where uvicorn copies the left-most X-Forwarded-For entry into it unchecked — keys one shared bucket. The 429 audit log line strips control and line-break characters from every field; its `ip` field is always a validated address or a fixed token, and the path and User-Agent are JSON-quoted, so a key=value log reader cannot be handed an extra field through them. The `/api/v1` limiter keys anonymous callers as `api_ip:<address>`, separate from `api_user:<username>`, and the chat limiter keys signed-in users as `user:<username>`, so a username shaped like an address no longer shares that address's bucket. The documented nginx configuration, which overwrites both client-IP headers with `$remote_addr`, was already safe and is unchanged. Exactly one proxy hop is supported: behind a chain such as CDN → nginx, every client shares the outer hop's bucket unless the inner proxy overwrites the header with the real client IP.
diff --git a/docs/deployment/reverse-proxy.md b/docs/deployment/reverse-proxy.md
index 69b2542bef..1462698418 100644
--- a/docs/deployment/reverse-proxy.md
+++ b/docs/deployment/reverse-proxy.md
@@ -32,11 +32,15 @@ linked upstream docs for the current spelling. `5000` is LDR's default port
> `LDR_` prefix — it is read at startup, before settings are loaded).
Rate-limit client-IP extraction is a separate application-level path. It reads
-`X-Forwarded-For` when `TRUST_PROXY_HEADERS` is enabled **or** when the direct
-peer is private/loopback, so a local proxy works before the uvicorn opt-in. The
-proxy must therefore **overwrite**, never append or pass through, any
-client-supplied forwarding chain. The one-hop nginx example below does that by
-setting both client-IP headers to `$remote_addr`.
+`X-Forwarded-For` (or, when that is absent, `X-Real-IP`) when
+`TRUST_PROXY_HEADERS` is enabled **or** when the direct peer is
+private/loopback, so a local proxy works before the uvicorn opt-in. The proxy
+must therefore **overwrite** both client-IP headers with the address it
+observed, never pass a client-supplied value through. The one-hop nginx example
+below does that by setting both to `$remote_addr`. Overwriting pins
+`X-Forwarded-For` to a single entry and `X-Real-IP` to the proxy's own value,
+and it keeps uvicorn's client address under `TRUST_PROXY_HEADERS` (the
+*left-most* entry) equal to the rate limiter's key (the *right-most* entry).
| Forwarded header | Used by LDR? | For |
|---|---|---|
@@ -53,9 +57,17 @@ This means:
withheld and the same-origin WebSocket check rejects the browser's `https`
origin.
- **Overwrite `X-Forwarded-For` and `X-Real-IP`** with the address observed by
- the one trusted proxy. Do not use an appending form: LDR's rate limiter reads
- the left-most forwarded value, so preserving a value supplied by the client
- lets that client choose its own rate-limit bucket.
+ the one trusted proxy. With the overwrite form shown below the header carries
+ a single entry. LDR's rate limiter keys on the right-most `X-Forwarded-For`
+ entry (the one added by the nearest proxy, also across repeated header
+ lines), so a single *appending* proxy cannot be steered by a client-supplied
+ prefix either. Overwriting remains the supported configuration: it also
+ pins `X-Real-IP`, and under `TRUST_PROXY_HEADERS` uvicorn takes the
+ *left-most* entry as the client address, which only the overwrite form makes
+ trustworthy. An entry that is not an IP address (an optional `:port`, or
+ `[IPv6]:port`, is accepted and dropped) is ignored, and the key falls back to
+ the request's client address. If that client address is itself not an IP
+ address, every such request shares one fixed `unparseable-peer` bucket.
- **`TRUST_PROXY_HEADERS=true` makes uvicorn trust forwarded request
metadata.** Only set it
when LDR is reachable *exclusively* through your proxy. If LDR is also
@@ -68,8 +80,14 @@ This means:
above applies even before you opt in.
- **Exactly one proxy hop is supported.** `TRUST_PROXY_HEADERS` is a boolean,
not a hop count, so a multi-proxy chain or a CDN/Cloudflare Tunnel *in
- addition* to your proxy is not supported without a code change (LDR would
- read the left-most forwarded entry, which an outer hop lets a client forge).
+ addition* to your proxy is not supported without a code change. LDR keys on
+ the right-most forwarded entry, which behind a chain (CDN → nginx) is the
+ outer hop's address: every client collapses into that one rate-limit bucket
+ unless the inner proxy overwrites the header with the real client IP it has
+ verified. (uvicorn's own client address under `TRUST_PROXY_HEADERS` is the
+ left-most entry; the rate limiter uses it only as the fallback when the
+ forwarded header it reads carries no usable address, and when that entry is
+ not an IP address either, the shared `unparseable-peer` bucket instead.)
- **HSTS and HTTPS redirect:** LDR sends `Strict-Transport-Security`
(`max-age=31536000; includeSubDomains`, no `preload`) itself on HTTPS
requests, so don't add a duplicate at the proxy. Do add an HTTP→HTTPS redirect
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 242bcfdace..639a5a92b2 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -331,8 +331,8 @@ This guide covers common issues and their solutions.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
- # LDR's limiter reads the left-most value, so overwrite rather than
- # append any client-supplied forwarding chain.
+ # Overwrite rather than append: LDR supports exactly one proxy hop and
+ # keys its rate limiter on the right-most X-Forwarded-For entry.
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
# Required when terminating TLS at the proxy: without X-Forwarded-Proto
diff --git a/src/local_deep_research/web/dependencies/rate_limit.py b/src/local_deep_research/web/dependencies/rate_limit.py
index 0a7f231cd5..dfa0b1e681 100644
--- a/src/local_deep_research/web/dependencies/rate_limit.py
+++ b/src/local_deep_research/web/dependencies/rate_limit.py
@@ -7,6 +7,7 @@ used by auth routes (login, register, change-password).
import asyncio
import inspect
+import ipaddress
import os
import re
from collections.abc import Callable
@@ -53,6 +54,46 @@ def _is_trusted_peer(host: str) -> bool:
return is_private_ip(host)
+_PORT_RE = re.compile(r"[0-9]{1,5}")
+
+
+def _forwarded_address(entry: str) -> str | None:
+ """The IP address in one forwarded-header entry, or ``None``.
+
+ Accepts a bare IPv4/IPv6 address, ``IPv4:port`` and ``[IPv6]`` or
+ ``[IPv6]:port`` (surrounding whitespace ignored) and returns the address
+ without the port, so one client cannot spread its attempts across
+ per-port buckets. Anything else -- empty, a hostname, free text, an
+ IPv6 zone ID -- returns ``None`` so the caller falls back instead of
+ keying the limiter on (and logging) client-chosen text.
+ """
+ candidate = entry.strip()
+ if candidate.startswith("["):
+ end = candidate.find("]")
+ if end == -1:
+ return None
+ host, rest = candidate[1:end], candidate[end + 1 :]
+ if rest and not (rest[0] == ":" and _PORT_RE.fullmatch(rest[1:])):
+ return None
+ elif candidate.count(":") == 1:
+ host, port = candidate.split(":")
+ if not _PORT_RE.fullmatch(port):
+ return None
+ else:
+ host = candidate
+ if "%" in host:
+ return None
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ return None
+ return host
+
+
+# Shared key for a direct peer that is not an address (see _get_client_ip).
+_UNPARSEABLE_PEER_KEY = "unparseable-peer"
+
+
def _get_client_ip(request: Request) -> str:
"""Get client IP, respecting X-Forwarded-For ONLY when the direct peer
is trusted (private network) or TRUST_PROXY_HEADERS=true.
@@ -64,24 +105,74 @@ def _get_client_ip(request: Request) -> str:
— matches the convention used by `web/app.py` for the uvicorn
`--proxy-headers` toggle.
"""
+ # NOTE: ``direct_peer`` is the TCP peer ONLY while TRUST_PROXY_HEADERS
+ # is off. When it is on, uvicorn runs with ``forwarded_allow_ips="*"``
+ # (web/app.py), and its ProxyHeaders middleware has already rewritten
+ # ``request.client.host`` to the LEFT-MOST X-Forwarded-For entry (the
+ # real peer is no longer visible in the scope). Under an appending proxy
+ # that entry is client-chosen. The header is re-read below and its
+ # RIGHT-MOST entry wins whenever it is a usable address, so
+ # ``direct_peer`` only decides the key when the forwarded header read
+ # below (X-Forwarded-For, else X-Real-IP) yields no usable address --
+ # and in that flag-on case the fallback is whatever uvicorn took from
+ # the left of the header, not a verified address.
direct_peer = request.client.host if request.client else "127.0.0.1"
+ # The fallback key. With the flag on, uvicorn copies the left-most entry
+ # into ``client.host`` without checking that it is an address, so a
+ # peer-sent "x, junk" would otherwise key -- and log -- free text (or a
+ # ``user:<name>`` string that collides with ``_user_key``'s namespace).
+ # Such values share one fixed bucket instead. "testclient" is Starlette's
+ # TestClient sentinel.
+ if direct_peer == "testclient" or _forwarded_address(direct_peer) == (
+ direct_peer
+ ):
+ fallback = direct_peer
+ else:
+ fallback = _UNPARSEABLE_PEER_KEY
trust = _TRUST_PROXY_HEADERS or _is_trusted_peer(direct_peer)
if trust:
- forwarded = request.headers.get("x-forwarded-for")
+ # getlist + join: Starlette's ``headers.get`` returns only the FIRST
+ # header line, and a proxy that adds its own SEPARATE
+ # X-Forwarded-For line (e.g. HAProxy ``option forwardfor``) leaves
+ # the client-sent line first. RFC 9110 5.3 makes repeated lines
+ # equivalent to one comma-joined value, so join them in order.
+ forwarded = ", ".join(request.headers.getlist("x-forwarded-for"))
if forwarded:
- return forwarded.split(",")[0].strip()
+ # Take the RIGHT-MOST entry: the one added by the nearest
+ # (trusted) proxy. The documented nginx config overwrites the
+ # header with $remote_addr, so it carries a single entry and
+ # left-most == right-most. A proxy that APPENDS instead
+ # ($proxy_add_x_forwarded_for, or a separate header line) puts
+ # the client's own header first, so reading the left-most
+ # entry would let a rotating forged prefix mint a fresh
+ # rate-limit bucket per request (#5787). Exactly ONE proxy hop
+ # is supported: behind a chain (CDN -> nginx) the right-most
+ # entry is the outer hop's address unless the inner proxy
+ # overwrites the header with the real client IP.
+ rightmost = _forwarded_address(forwarded.rsplit(",", 1)[-1])
+ # An empty key makes slowapi skip the limit entirely, and a
+ # non-address entry would be an unbounded, free-text key (it is
+ # also written to the 429 audit log). A trailing comma, a
+ # whitespace-only value or garbage therefore keys on the
+ # fallback -- see the NOTE above for what that is.
+ return rightmost or fallback
real_ip = request.headers.get("x-real-ip")
if real_ip:
- # .strip() to match the X-Forwarded-For branch above. main's
- # get_client_ip stripped both; the port dropped it here, so a
- # padded value keyed a DIFFERENT rate-limit bucket than the
- # same address unpadded -- a fresh brute-force budget per
- # padding variant. h11 normalises OWS before the ASGI scope,
- # so this is only reachable via transports that do not.
- return real_ip.strip()
-
- return direct_peer
+ # Parsed like the X-Forwarded-For entry above: padding is
+ # stripped (main's get_client_ip stripped both, and a padded
+ # value must not key a DIFFERENT bucket than the same address
+ # unpadded), and a value that is empty after stripping or is
+ # not an address falls back instead of becoming the key.
+ # uvicorn's HTTP parsers (httptools -- the default with
+ # uvicorn[standard] -- and h11) both pass obs-text (0x80-0xFF)
+ # through, so ``"\xa0"`` or ``"\x85"`` arrive intact, and
+ # ``str.strip()`` reduces them to ``""``, which slowapi treats
+ # as "no limit". h11 also passes the control bytes 0x01, 0x1b
+ # and 0x7f, which httptools rejects.
+ return _forwarded_address(real_ip) or fallback
+
+ return fallback
# Create the limiter instance.
@@ -564,7 +655,12 @@ def _api_user_key(request: Request) -> str:
username = (
request.session.get("username") if "session" in request.scope else None
)
- return f"api_user:{username or _get_client_ip(request)}"
+ # Separate prefixes for the two branches, as ``_user_key`` does: with one
+ # shared ``api_user:`` prefix a username shaped like an address was the
+ # same bucket as an anonymous caller from that address.
+ if username:
+ return f"api_user:{username}"
+ return f"api_ip:{_get_client_ip(request)}"
def _api_exempt() -> bool:
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index 1ce7efd39c..7d57244895 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -7,6 +7,7 @@ static files, and background services.
"""
import ipaddress
+import json
import logging
import os
import re
@@ -1893,6 +1894,7 @@ def _setup_rate_limiting(app: FastAPI) -> None:
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
+ from ..security.log_sanitizer import sanitize_for_log
from .dependencies.rate_limit import _get_client_ip, limiter
app.state.limiter = limiter
@@ -1918,10 +1920,25 @@ def _setup_rate_limiting(app: FastAPI) -> None:
# Audit logging for security monitoring — port of main's 429
# errorhandler. _get_client_ip resolves the real IP behind
# trusted proxies (raw request.client would log the proxy).
+ # Every field is client-influenced, so each goes through
+ # sanitize_for_log (control, format and line-break characters
+ # stripped, length capped). The line is space-delimited
+ # ``field=value``, so the free-text fields are also JSON-quoted:
+ # json.dumps always double-quotes and escapes ``"`` and ``\``, so a
+ # key=value reader cannot find a field boundary inside the value
+ # (repr() would switch to single quotes for a value containing
+ # ``"``, which such a reader does not honour). The ip value is
+ # always a validated address or a fixed token (_get_client_ip), so
+ # it stays unquoted.
+ path = sanitize_for_log(request.url.path, max_length=200)
+ user_agent = sanitize_for_log(
+ request.headers.get("User-Agent", "unknown"), max_length=200
+ )
logger.warning(
- f"Rate limit exceeded: endpoint={request.url.path} "
- f"ip={_get_client_ip(request)} "
- f"user_agent={request.headers.get('User-Agent', 'unknown')}"
+ "Rate limit exceeded: "
+ f"endpoint={json.dumps(path)} "
+ f"ip={sanitize_for_log(_get_client_ip(request), max_length=64)} "
+ f"user_agent={json.dumps(user_agent)}"
)
response = JSONResponse(
{
diff --git a/src/local_deep_research/web/routers/chat.py b/src/local_deep_research/web/routers/chat.py
index 65e477eca2..b5876dd5da 100644
--- a/src/local_deep_research/web/routers/chat.py
+++ b/src/local_deep_research/web/routers/chat.py
@@ -133,11 +133,16 @@ def _chat_user_key(request: Request) -> str:
Without this, users behind a shared NAT/proxy share one bucket and can
DoS each other for legitimate chat use. Falls back to the client IP for
any unauthenticated request that somehow reaches a limited route.
+
+ The username branch is prefixed (``user:<name>``, the shape
+ ``_user_key`` uses) so a username shaped like an address is not the
+ same bucket as an anonymous caller from that address; the IP branch is
+ always a validated address or a fixed token, never ``user:...``.
"""
username = (
request.session.get("username") if "session" in request.scope else None
)
- return username or _get_client_ip(request)
+ return f"user:{username}" if username else _get_client_ip(request)
async def _json_object_body(request: Request):
diff --git a/tests/chat/test_chat_route_helpers.py b/tests/chat/test_chat_route_helpers.py
index b55660181f..51e4efa170 100644
--- a/tests/chat/test_chat_route_helpers.py
+++ b/tests/chat/test_chat_route_helpers.py
@@ -108,4 +108,26 @@ class TestChatUserKey:
}
)
- assert _chat_user_key(request) == "alice"
+ assert _chat_user_key(request) == "user:alice"
+
+ def test_chat_user_key_keeps_usernames_out_of_the_ip_namespace(self):
+ """A username shaped like an address must not share the bucket of
+ an anonymous caller from that address."""
+ from local_deep_research.web.routers.chat import _chat_user_key
+
+ def request(**extra):
+ return Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/",
+ "headers": [],
+ "client": ("192.168.1.10", 12345),
+ **extra,
+ }
+ )
+
+ named = request(session={"username": "192.168.1.10"})
+ anonymous = request()
+ assert _chat_user_key(anonymous) == "192.168.1.10"
+ assert _chat_user_key(named) != _chat_user_key(anonymous)
diff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.py
index b50d9be8a7..24fea74719 100644
--- a/tests/deployment/test_deployment_surface_contracts.py
+++ b/tests/deployment/test_deployment_surface_contracts.py
@@ -1170,11 +1170,46 @@ class TestReverseProxyDoc:
"the doc's open-signup warning must track the actual default"
)
- def test_documented_xff_is_not_forgeable(self, nginx_directives):
- limiter = RATE_LIMIT_PY.read_text(encoding="utf-8")
- assert 'forwarded.split(",")[0].strip()' in limiter, (
- "the limiter no longer reads the left-most entry; re-derive "
- "which nginx directive is correct before changing this test"
+ def test_documented_xff_is_not_forgeable(
+ self, nginx_directives, monkeypatch
+ ):
+ """Behavioural, not source-text: under a forwarded chain the
+ limiter keys on the entry the nearest proxy added, never on a
+ client-supplied prefix -- and the documented nginx directives
+ overwrite the header so it carries that one entry only."""
+ from starlette.requests import Request
+
+ from local_deep_research.web.dependencies import rate_limit
+
+ monkeypatch.setattr(rate_limit, "_TRUST_PROXY_HEADERS", False)
+
+ def key(*xff_lines: str) -> str:
+ return rate_limit._get_client_ip(
+ Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/auth/login",
+ "query_string": b"",
+ "headers": [
+ (b"x-forwarded-for", line.encode())
+ for line in xff_lines
+ ],
+ "client": ("127.0.0.1", 51234),
+ }
+ )
+ )
+
+ observed = "93.184.216.34"
+ assert key(observed) == observed
+ assert key(f"203.0.113.7, {observed}") == observed, (
+ "the limiter keys on a client-supplied X-Forwarded-For prefix; "
+ "re-derive which nginx directive is correct before changing "
+ "this test"
+ )
+ assert key("203.0.113.7", observed) == observed, (
+ "a client-sent X-Forwarded-For line ahead of the proxy's own "
+ "line chose the rate-limit key"
)
values = _xff_values(nginx_directives)
assert len(values) == 2, values
@@ -1189,16 +1224,19 @@ class TestReverseProxyDoc:
offenders.append(str(path.relative_to(REPO_ROOT)))
assert not offenders, (
"these proxy examples preserve a client-supplied XFF prefix, "
- f"which the limiter trusts as its key: {offenders}"
+ f"which uvicorn takes as the client address: {offenders}"
)
def test_every_header_the_limiter_reads_is_documented(self):
limiter = RATE_LIMIT_PY.read_text(encoding="utf-8")
read_headers = set(
- re.findall(r'request\.headers\.get\("([\w-]+)"\)', limiter)
+ re.findall(
+ r'request\.headers\.(?:get|getlist)\("([\w-]+)"\)', limiter
+ )
)
- assert "x-real-ip" in read_headers, (
- "X-Real-IP is no longer read; drop this contract"
+ assert {"x-forwarded-for", "x-real-ip"} <= read_headers, (
+ "X-Forwarded-For or X-Real-IP is no longer read; drop this "
+ f"contract (found {sorted(read_headers)})"
)
doc = REVERSE_PROXY_DOC.read_text(encoding="utf-8").lower()
for header in sorted(read_headers):
diff --git a/tests/security/test_rate_limit_key_derivation.py b/tests/security/test_rate_limit_key_derivation.py
index 781b5ffb1b..8757366088 100644
--- a/tests/security/test_rate_limit_key_derivation.py
+++ b/tests/security/test_rate_limit_key_derivation.py
@@ -16,23 +16,17 @@ the bucket. That half is correct and this file does not re-litigate it.
What this file covers is the half the guard does not reach: WHICH ENTRY
of the header is taken once the peer IS trusted.
- forwarded = request.headers.get("x-forwarded-for")
- if forwarded:
- return forwarded.split(",")[0].strip()
-
-``[0]`` is the LEFT-MOST entry. In a forwarded chain the left-most entry
-can be supplied by the original client; an appending proxy puts the
-address it observed on the RIGHT. The shipped nginx guide now mitigates
-that ambiguity by overwriting both client-IP headers with ``$remote_addr``
-and explicitly forbidding the appending form. A contract below pins that
-safe deployment guidance.
-
-The parser remains fragile if an unsupported or misconfigured appending
-proxy passes a chain, and a private/LAN peer can still supply the header
-directly because ``_is_trusted_peer`` trusts private addresses. Those
-residual behaviours remain characterized here and tracked in #5787. A
-strict xfail expresses the safer result for a single appending proxy so
-an eventual parser hardening forces these expectations to be revisited.
+``_get_client_ip`` joins every ``X-Forwarded-For`` header line (Starlette's
+``headers.get`` would return only the first) and keys on the RIGHT-MOST
+entry: the one added by the nearest proxy. In a forwarded chain the
+left-most entry can be supplied by the original client; an appending proxy
+puts the address it observed on the RIGHT (#5787). The shipped nginx guide
+additionally overwrites both client-IP headers with ``$remote_addr``, so
+the header carries a single entry; a contract below pins that guidance.
+
+A private/LAN peer can still supply the header directly because
+``_is_trusted_peer`` trusts private addresses; that documented residual is
+characterized here too. Exactly one proxy hop is supported.
Scope note: the per-URL bucketing defect (slowapi's ``key_style="url"``)
is a separate, already-filed issue and is deliberately not touched here.
@@ -44,6 +38,7 @@ directly. No app boot, no TestClient, no database.
"""
import ast
+import re
from pathlib import Path
import pytest
@@ -61,6 +56,10 @@ from starlette.requests import Request
LOOPBACK_PEER = "127.0.0.1" # nginx on the same host, per the repo's own
# snippet: ``proxy_pass http://127.0.0.1:5000``
LAN_PEER = "192.168.1.50" # LAN / docker-bridge neighbour, no proxy
+# A proxy on a private network that is NOT the limiter's own last-resort
+# default ("127.0.0.1" when the scope has no client), so a fallback test can
+# tell "keyed on the direct peer" apart from "keyed on the default".
+PRIVATE_PROXY_PEER = "10.0.0.5"
PUBLIC_PEER = "8.8.8.8" # attacker connecting straight to the app
REAL_CLIENT = "93.184.216.34" # what an appending proxy observes and appends
@@ -94,16 +93,20 @@ def _default_trust_flag(rl, monkeypatch):
monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
-def make_request(peer=PUBLIC_PEER, headers=None, session=None):
- """Build a minimal Starlette Request from a raw ASGI scope dict."""
+def make_request(peer=PUBLIC_PEER, headers=None, session=None, raw=None):
+ """Build a minimal Starlette Request from a raw ASGI scope dict.
+
+ ``raw`` is a list of ``(name, value)`` pairs appended after ``headers``
+ in order, so the same header name can appear on several lines -- which
+ a dict cannot express.
+ """
+ pairs = list((headers or {}).items()) + list(raw or [])
scope = {
"type": "http",
"method": "POST",
"path": "/auth/login",
"query_string": b"",
- "headers": [
- (k.lower().encode(), v.encode()) for k, v in (headers or {}).items()
- ],
+ "headers": [(k.lower().encode(), v.encode()) for k, v in pairs],
"client": (peer, 51234),
}
if session is not None:
@@ -119,9 +122,8 @@ def appending_proxy_chain(forged, observed=REAL_CLIENT):
comma. So a client that sends ``X-Forwarded-For: <forged>`` from
address ``<observed>`` reaches the app as ``"<forged>, <observed>"``.
- The shipped nginx guide explicitly forbids this configuration and
- overwrites the header instead. This helper retains coverage of how
- ``_get_client_ip`` behaves if an unsupported proxy passes a chain.
+ The shipped nginx guide overwrites the header instead. This helper
+ covers how ``_get_client_ip`` behaves when a single proxy appends.
"""
return f"{forged}, {observed}"
@@ -129,9 +131,9 @@ def appending_proxy_chain(forged, observed=REAL_CLIENT):
class TestTheDocumentedProxyOverwritesRatherThanAppends:
"""Pin the deployment mitigation introduced by #6046.
- Because LDR reads the left-most value, the supported one-hop nginx
- configuration must overwrite client-supplied forwarding headers.
- Appending would make the first value attacker-controlled.
+ LDR keys on the right-most value, so one appending proxy is also safe
+ for the rate limiter; the guide still overwrites, which leaves a single
+ entry and gives uvicorn's left-most reader the real client address.
"""
def test_doc_exists_and_is_the_deployment_guide(self):
@@ -160,23 +162,30 @@ class TestTheDocumentedProxyOverwritesRatherThanAppends:
f"got: {directives}"
)
assert all("$proxy_add_x_forwarded_for" not in d for d in directives), (
- "the appending form reintroduces client control of the left-most "
- f"rate-limit key: {directives}"
+ "the appending form leaves a client-chosen left-most entry, "
+ f"which uvicorn reads as the client address: {directives}"
)
- def test_doc_states_that_ldr_reads_the_leftmost_entry(self):
- text = REVERSE_PROXY_DOC.read_text(encoding="utf-8").lower()
- assert "left-most" in text or "leftmost" in text, (
+ def test_doc_states_that_ldr_keys_on_the_rightmost_entry(self):
+ text = re.sub(
+ r"\s+", " ", REVERSE_PROXY_DOC.read_text(encoding="utf-8")
+ ).lower()
+ assert (
+ "rate limiter keys on the right-most `x-forwarded-for` entry"
+ in text
+ ), (
"the deployment guide no longer describes which forwarded "
- "entry LDR reads; this file's premise needs re-checking"
+ "entry LDR keys on; this file's premise needs re-checking"
)
+ assert "exactly one proxy hop is supported" in text
-class TestForgedLeftmostEntryBecomesTheKey:
- """Residual bypass under an unsupported appending-proxy topology.
+class TestForgedPrefixNeverBecomesTheKey:
+ """A client-supplied prefix under a single appending proxy.
- The shipped nginx guide prevents this by overwriting the header. These
- tests characterize LDR's behavior if another proxy appends instead.
+ The shipped nginx guide overwrites the header; these tests pin that a
+ proxy which appends instead -- on the same line or as a separate
+ header line -- still yields the address the proxy observed (#5787).
"""
def test_control_key_is_the_observed_client_without_a_forged_header(
@@ -185,7 +194,7 @@ class TestForgedLeftmostEntryBecomesTheKey:
"""CONTROL: an honest client keys on its real address.
The proxy still sends a single-entry X-Forwarded-For, so this is
- the same code path as the residual bypass below — the only
+ the same code path as the forged-prefix cases below — the only
difference is whether the client supplied a header of its own.
"""
request = make_request(
@@ -194,29 +203,13 @@ class TestForgedLeftmostEntryBecomesTheKey:
)
assert rl._get_client_ip(request) == REAL_CLIENT
- def test_forged_prefix_displaces_the_real_client(self, rl):
- """DEFECT: the key is the value the ATTACKER chose, and the
- address nginx observed is discarded."""
- forged = "203.0.113.77"
- request = make_request(
- peer=LOOPBACK_PEER,
- headers={"X-Forwarded-For": appending_proxy_chain(forged)},
- )
- derived = rl._get_client_ip(request)
- assert derived == forged
- assert derived != REAL_CLIENT, (
- "the address the trusted proxy actually observed never "
- "reaches the rate-limit key"
- )
-
- def test_rotating_the_forged_prefix_mints_a_fresh_key_each_request(
- self, rl
- ):
- """DEFECT paired with its CONTROL, in one test.
+ def test_rotating_the_forged_prefix_mints_no_new_keys(self, rl):
+ """FIXED behavior paired with its CONTROL, in one test.
Same peer, same real client, same route — the ONLY variable is
- whether the attacker prepends a value of their own.
- """
+ whether the attacker prepends a value of their own, and it must
+ change nothing: every attempt still lands in the one real
+ bucket."""
attempts = 32
control_keys = {
@@ -246,22 +239,11 @@ class TestForgedLeftmostEntryBecomesTheKey:
)
for i in range(attempts)
}
- assert len(forged_keys) == attempts, (
- "bypass: each forged prefix produced its own rate-limit key "
- f"({len(forged_keys)} distinct keys from {attempts} requests)"
- )
-
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "LIVE DEFECT: _get_client_ip takes X-Forwarded-For.split(',')"
- "[0] — the LEFT-MOST entry, which the original client "
- "controls under an appending proxy. The shipped nginx guide "
- "mitigates this by overwriting the header, but for a single "
- "appending proxy the correct entry is the RIGHT-MOST one: the "
- "address the proxy itself observed. See #5787."
- ),
- )
+ assert forged_keys == {REAL_CLIENT}, (
+ "bypass: rotating the forged prefix minted fresh rate-limit "
+ f"keys ({len(forged_keys)} distinct keys from {attempts} requests)"
+ )
+
def test_desired_key_is_the_address_the_trusted_proxy_observed(self, rl):
forged = "203.0.113.77"
request = make_request(
@@ -270,9 +252,61 @@ class TestForgedLeftmostEntryBecomesTheKey:
)
assert rl._get_client_ip(request) == REAL_CLIENT
+ def test_proxy_appending_a_separate_header_line_is_keyed_on_its_line(
+ self, rl
+ ):
+ """HAProxy's ``option forwardfor`` adds its OWN X-Forwarded-For
+ line rather than extending the client's. Starlette's
+ ``headers.get`` returns only the first line -- the client's -- so
+ every line must be considered, in order, and the last entry wins.
+ """
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer=LOOPBACK_PEER,
+ raw=[
+ ("X-Forwarded-For", f"203.0.113.{i}"),
+ ("X-Forwarded-For", REAL_CLIENT),
+ ],
+ )
+ )
+ for i in range(8)
+ }
+ assert keys == {REAL_CLIENT}, (
+ "a client-sent X-Forwarded-For line placed before the proxy's "
+ f"own line chose the rate-limit key: {sorted(keys)}"
+ )
+
+ def test_separate_lines_each_carrying_a_chain_use_the_last_entry(self, rl):
+ request = make_request(
+ peer=LOOPBACK_PEER,
+ raw=[
+ ("X-Forwarded-For", "203.0.113.1, 203.0.113.2"),
+ ("X-Forwarded-For", f"203.0.113.3, {REAL_CLIENT}"),
+ ],
+ )
+ assert rl._get_client_ip(request) == REAL_CLIENT
+
+ @pytest.mark.parametrize("value", ["203.0.113.9,", "203.0.113.9, ", " "])
+ def test_empty_rightmost_entry_falls_back_to_the_direct_peer(
+ self, rl, value
+ ):
+ """slowapi skips the limit when the key is falsy, so a trailing
+ comma or a whitespace-only value must never yield an empty key.
+
+ With ``TRUST_PROXY_HEADERS`` off (pinned by the autouse fixture) the
+ direct peer is the real TCP peer, so the left-most entry is not the
+ key either. The peer is deliberately not ``127.0.0.1``: that is
+ also the limiter's default, and a hard-coded fallback would pass.
+ """
+ request = make_request(
+ peer=PRIVATE_PROXY_PEER, headers={"X-Forwarded-For": value}
+ )
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+
class TestLoginBruteForceBudgetUnderAnAppendingProxy:
- """What the residual appending-proxy behavior costs in login attempts.
+ """Login attempts under an appending proxy with a rotating prefix.
The arithmetic runs against the real ``limits`` primitives with the
app's OWN configured limit string and strategy — not a local
@@ -316,11 +350,13 @@ class TestLoginBruteForceBudgetUnderAnAppendingProxy:
f"attempt {item.amount + 1} from one client must be refused"
)
- def test_forged_header_never_exhausts_the_budget(self, rl):
- """BYPASS: same client, same route, ten times the quota, zero
- refusals — because every attempt derives a different key."""
+ def test_forged_header_still_exhausts_the_budget(self, rl):
+ """FIXED: same client, same route, ten times the quota — the
+ refusals arrive on schedule, because every attempt derives the
+ SAME key no matter what prefix the attacker rotates."""
strategy, item = self._fresh_limiter(rl)
attempts = item.amount * 10 + 5
+ keys = set()
refused = []
for i in range(attempts):
key = rl._get_client_ip(
@@ -328,14 +364,19 @@ class TestLoginBruteForceBudgetUnderAnAppendingProxy:
peer=LOOPBACK_PEER,
headers={
"X-Forwarded-For": appending_proxy_chain(
- f"10.9.{i // 256}.{i % 256}"
+ f"203.0.113.{i}"
)
},
)
)
+ keys.add(key)
if not strategy.hit(item, "auth-login", key):
refused.append(i)
- assert refused == [], (
+ assert keys == {REAL_CLIENT}, (
+ "every forged-prefix attempt must land in the one real "
+ "client's bucket"
+ )
+ assert refused, (
f"{attempts} login attempts from ONE client against a "
f"'{rl.LOGIN_RATE_LIMIT}' limit produced no refusal; the "
"per-IP login limit is bypassed by varying a header"
@@ -370,50 +411,161 @@ class TestPrivatePeerWithNoProxyAtAll:
assert rl._get_client_ip(request) == PUBLIC_PEER
-class TestDerivedKeyIsNeverValidatedAsAnAddress:
- """Whatever is in the header becomes the key, verbatim.
+class TestDerivedKeyIsValidatedAsAnAddress:
+ """A forwarded entry becomes the key only if it parses as an IP address.
- ``_get_client_ip`` splits and strips; it never parses the entry as
- an IP. Two consequences, both reachable with printable-ASCII header
- values (h11 rejects control bytes in header values, so log-ANSI
- injection is NOT reachable — but structured-field forgery is):
-
- 1. Unbounded key cardinality in the limiter's storage. With the
- default in-memory backend each distinct key holds a window entry
- for the whole limit period.
- 2. The key is interpolated straight into the 429 audit log line in
- ``fastapi_app._rate_limit_exceeded`` as ``ip={...}`` with no
- ``sanitize_for_log()``, unlike the username in ``routers/auth.py``
- — so an attacker chooses the text of a security log line, spaces
- and ``=`` included. See ``TestFourTwoNineResponseDoesNotLeakTheKey
- ::test_audit_log_interpolates_the_unsanitised_key``.
+ Before this was enforced, whatever sat in the header became the key
+ verbatim: unbounded key cardinality in the limiter's storage, and --
+ because the key is written to the 429 audit line -- a client-chosen
+ ``field=value`` text in a security log. A non-address entry now falls
+ back to the direct peer, like an empty one.
"""
- def test_non_address_token_is_returned_verbatim(self, rl):
- token = "not-an-address-at-all"
+ @pytest.mark.parametrize(
+ "token",
+ [
+ "not-an-address-at-all",
+ "1.1.1.1 user_agent=trusted-monitor endpoint=/healthz",
+ "x" * 1000,
+ "user:alice",
+ "1.2.3.4:http",
+ "1.2.3.4:",
+ "[2001:db8::1",
+ "[2001:db8::1]x",
+ "fe80::1%eth0",
+ "999.1.1.1",
+ ],
+ )
+ def test_non_address_rightmost_entry_falls_back(self, rl, token):
request = make_request(
- peer=LOOPBACK_PEER,
- headers={"X-Forwarded-For": appending_proxy_chain(token)},
+ peer=PRIVATE_PROXY_PEER,
+ headers={
+ "X-Forwarded-For": appending_proxy_chain(
+ REAL_CLIENT, observed=token
+ )
+ },
)
- assert rl._get_client_ip(request) == token
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+
+ @pytest.mark.parametrize(
+ "entry, expected",
+ [
+ (REAL_CLIENT, REAL_CLIENT),
+ (f"{REAL_CLIENT}:443", REAL_CLIENT),
+ ("2001:db8::1", "2001:db8::1"),
+ ("[2001:db8::1]", "2001:db8::1"),
+ ("[2001:db8::1]:443", "2001:db8::1"),
+ ("::1", "::1"),
+ ("::ffff:8.8.8.8", "::ffff:8.8.8.8"),
+ ],
+ )
+ def test_address_forms_are_accepted_and_the_port_dropped(
+ self, rl, entry, expected
+ ):
+ """IPv4 with a port, bare and bracketed IPv6 (with or without a
+ port) all key on the address alone -- so varying the port cannot
+ spread one client across many buckets."""
+ request = make_request(
+ peer=PRIVATE_PROXY_PEER, headers={"X-Forwarded-For": entry}
+ )
+ assert rl._get_client_ip(request) == expected
- def test_key_can_carry_forged_log_fields(self, rl):
- """A printable value that reproduces the audit line's own
- space-delimited ``field=value`` shape."""
- token = "1.1.1.1 user_agent=trusted-monitor endpoint=/healthz"
+ def test_rotating_non_address_tokens_mint_no_new_keys(self, rl):
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer=PRIVATE_PROXY_PEER,
+ headers={"X-Forwarded-For": f"token-{i}"},
+ )
+ )
+ for i in range(32)
+ }
+ assert keys == {PRIVATE_PROXY_PEER}
+
+ def test_non_address_x_real_ip_falls_back(self, rl):
request = make_request(
- peer=LOOPBACK_PEER,
- headers={"X-Forwarded-For": appending_proxy_chain(token)},
+ peer=PRIVATE_PROXY_PEER,
+ headers={"X-Real-IP": "1.1.1.1 user_agent=trusted-monitor"},
)
- assert rl._get_client_ip(request) == token
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
- def test_key_length_is_unbounded(self, rl):
- token = "x" * 1000
+ def test_x_real_ip_with_port_keys_on_the_address(self, rl):
request = make_request(
- peer=LOOPBACK_PEER,
- headers={"X-Forwarded-For": appending_proxy_chain(token)},
+ peer=PRIVATE_PROXY_PEER,
+ headers={"X-Real-IP": f"{REAL_CLIENT}:8080"},
+ )
+ assert rl._get_client_ip(request) == REAL_CLIENT
+
+ @pytest.mark.parametrize("raw_value", [b"\xa0", b"\x85", b" \xa0 "])
+ def test_x_real_ip_that_strips_to_empty_falls_back(self, rl, raw_value):
+ """uvicorn's HTTP parsers (httptools -- the default with
+ uvicorn[standard] -- and h11) both pass obs-text (0x80-0xFF) in
+ header values through, and Starlette decodes it as latin-1. (h11
+ also passes the control bytes 0x01, 0x1b and 0x7f, which httptools
+ rejects.)
+ ``str.strip()`` treats U+00A0 and U+0085 as whitespace, so these
+ values strip to ``""`` -- a key that makes slowapi skip the limit.
+ The raw bytes are placed in the scope directly: ``make_request``
+ UTF-8-encodes, which would turn U+00A0 into two non-space bytes."""
+ request = Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/auth/login",
+ "query_string": b"",
+ "headers": [(b"x-real-ip", raw_value)],
+ "client": (PRIVATE_PROXY_PEER, 51234),
+ }
+ )
+ assert request.headers["x-real-ip"].strip() == "", (
+ "premise: the raw value must strip to empty"
+ )
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+
+ def test_unparseable_direct_peer_under_the_flag_shares_one_bucket(
+ self, rl, monkeypatch
+ ):
+ """With ``TRUST_PROXY_HEADERS`` on, uvicorn copies the LEFT-MOST
+ entry into ``client.host`` unvalidated, so the fallback itself can
+ be free text. Such a peer keys on one fixed value instead."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer=f"forged-{i} user_agent=x",
+ headers={"X-Forwarded-For": "junk"},
+ )
+ )
+ for i in range(8)
+ }
+ assert keys == {rl._UNPARSEABLE_PEER_KEY}
+
+ def test_unparseable_direct_peer_with_bad_x_real_ip_under_the_flag(
+ self, rl, monkeypatch
+ ):
+ """The X-Real-IP branch falls back to the same fixed value, not to
+ the unparseable peer text."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="forged user_agent=x", headers={"X-Real-IP": "junk"}
)
- assert len(rl._get_client_ip(request)) == 1000
+ assert rl._get_client_ip(request) == rl._UNPARSEABLE_PEER_KEY
+
+ def test_unparseable_direct_peer_without_the_flag(self, rl):
+ """Flag off: a peer that is not an address is untrusted, so no
+ header is read -- and the final return is still the fixed value,
+ not the peer text."""
+ request = make_request(
+ peer="forged user_agent=x",
+ headers={"X-Forwarded-For": REAL_CLIENT},
+ )
+ assert rl._get_client_ip(request) == rl._UNPARSEABLE_PEER_KEY
+
+ def test_address_direct_peer_is_kept_verbatim(self, rl):
+ """CONTROL for the test above: a real peer address is the key as
+ reported, including an IPv4-mapped IPv6 spelling."""
+ request = make_request(peer="::ffff:8.8.8.8")
+ assert rl._get_client_ip(request) == "::ffff:8.8.8.8"
def _rate_limit_exceeded_ast(rl):
@@ -496,38 +648,159 @@ class TestFourTwoNineResponseDoesNotLeakTheKey:
f"rate-limit set: {sorted(assigned - allowed)}"
)
- def test_audit_log_interpolates_the_unsanitised_key(self, rl):
- """Characterisation of the log-forgery surface described in
- ``TestDerivedKeyIsNeverValidatedAsAnAddress``.
-
- The key IS written server-side, which is intentional (it is the
- audit line main's Flask errorhandler had). What is pinned here
- is that it goes in raw: no ``sanitize_for_log`` wrapper, while
- ``routers/auth.py`` wraps the equally client-supplied username.
- If this ever fails, the value was wrapped — good; update the
- docstrings above.
- """
+ def test_audit_log_sanitises_and_quotes_every_field(self, rl):
+ """The 429 audit line is space-delimited ``field=value`` and every
+ field is client-influenced (the path, the derived key, the
+ User-Agent). Every other logger call in the handler must log
+ constants only, and the audit line must interpolate exactly three
+ plain fields:
+
+ * ``ip`` -- exactly ``sanitize_for_log(_get_client_ip(request),
+ max_length=<int <= 64>)``;
+ * the other two -- ``json.dumps(<name>)`` with no keyword arguments
+ (``ensure_ascii=False`` or ``default=str`` would change what a
+ reader sees), where ``<name>`` is bound exactly once in the
+ handler, before the logger call, by ``<name> =
+ sanitize_for_log(..., max_length=<int <= 256>)``.
+
+ ``sanitize_for_log`` is the helper ``routers/auth.py`` uses for the
+ equally client-supplied username; the JSON quoting keeps a
+ key=value reader from finding a field boundary inside a value. The
+ behavioural half is ``tests/web/test_rate_limit_coverage.py::
+ TestRateLimitExceededHandler::
+ test_429_audit_line_cannot_be_given_a_forged_ip_field``."""
handler = _rate_limit_exceeded_ast(rl)
- raw_key_interpolations = [
+
+ def root_name(node):
+ while isinstance(node, (ast.Attribute, ast.Call)):
+ node = node.func if isinstance(node, ast.Call) else node.value
+ return node.id if isinstance(node, ast.Name) else None
+
+ def constant_only(call):
+ return all(
+ isinstance(arg, ast.Constant)
+ for arg in [*call.args, *(kw.value for kw in call.keywords)]
+ )
+
+ # Every logger call except the audit line must log constants only
+ # (the handler's "could not attach headers" debug line); anything
+ # that interpolates request data has to be the one audited line.
+ logger_calls = [
node
for node in ast.walk(handler)
- if isinstance(node, ast.Call)
- and getattr(node.func, "id", None) == "_get_client_ip"
+ if isinstance(node, ast.Call) and root_name(node.func) == "logger"
]
- assert raw_key_interpolations, (
- "expected the 429 audit line to log the derived client key"
+ interpolating = [c for c in logger_calls if not constant_only(c)]
+ assert len(interpolating) == 1, (
+ "the 429 handler must have exactly one logger call that logs "
+ "anything but constants (the audit line); found "
+ f"{[ast.unparse(c) for c in interpolating]}"
)
- sanitised = [
- node
- for node in ast.walk(handler)
- if isinstance(node, ast.Call)
- and getattr(node.func, "id", None) == "sanitize_for_log"
+ (warning,) = interpolating
+ assert ast.unparse(warning.func) == "logger.warning", ast.unparse(
+ warning.func
+ )
+ assert len(warning.args) == 1 and not warning.keywords
+ (message,) = warning.args
+ assert isinstance(message, ast.JoinedStr), ast.unparse(message)
+ fields = [
+ part
+ for part in message.values
+ if isinstance(part, ast.FormattedValue)
+ ]
+ assert len(fields) == 3, [ast.unparse(f) for f in fields]
+ for field in fields:
+ assert field.conversion == -1 and field.format_spec is None, (
+ f"429 audit field {ast.unparse(field)!r} carries a "
+ "conversion or format spec"
+ )
+ values = [field.value for field in fields]
+
+ def max_length_at_most(call, limit):
+ if len(call.keywords) != 1 or call.keywords[0].arg != "max_length":
+ return False
+ cap = call.keywords[0].value
+ return (
+ isinstance(cap, ast.Constant)
+ and type(cap.value) is int
+ and 1 <= cap.value <= limit
+ )
+
+ def is_sanitize_call(node, limit):
+ return (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "sanitize_for_log"
+ and len(node.args) == 1
+ and max_length_at_most(node, limit)
+ )
+
+ ip_expected = ast.dump(
+ ast.parse("_get_client_ip(request)", mode="eval").body
+ )
+ ip_fields = [
+ value
+ for value in values
+ if is_sanitize_call(value, 64)
+ and ast.dump(value.args[0]) == ip_expected
]
- assert sanitised == [], (
- "sanitize_for_log now appears in the 429 handler — the "
- "log-forgery note in this file is stale and should be removed"
+ assert len(ip_fields) == 1, (
+ "expected exactly one field of the form "
+ "sanitize_for_log(_get_client_ip(request), max_length=<=64): "
+ f"{[ast.unparse(v) for v in values]}"
)
+ quoted_names = []
+ for value in values:
+ if value is ip_fields[0]:
+ continue
+ assert (
+ isinstance(value, ast.Call)
+ and ast.unparse(value.func) == "json.dumps"
+ and len(value.args) == 1
+ and not value.keywords
+ and isinstance(value.args[0], ast.Name)
+ ), (
+ f"429 audit field {ast.unparse(value)!r} is not "
+ "json.dumps(<sanitised name>) without keyword arguments"
+ )
+ quoted_names.append(value.args[0].id)
+ assert len(set(quoted_names)) == 2, quoted_names
+
+ for name in quoted_names:
+ bindings = [
+ node
+ for node in ast.walk(handler)
+ if isinstance(node, ast.Name)
+ and node.id == name
+ and isinstance(node.ctx, ast.Store)
+ ]
+ assert len(bindings) == 1, (
+ f"{name!r} must be bound exactly once in the 429 handler "
+ f"(found {len(bindings)} bindings, including augmented "
+ "assignments and walrus targets)"
+ )
+ assigns = [
+ node
+ for node in ast.walk(handler)
+ if isinstance(node, ast.Assign)
+ and len(node.targets) == 1
+ and node.targets[0] is bindings[0]
+ ]
+ assert len(assigns) == 1, (
+ f"{name!r} is bound by something other than a plain "
+ "single-target assignment"
+ )
+ (assign,) = assigns
+ assert is_sanitize_call(assign.value, 256), (
+ f"{name!r} is not assigned from "
+ "sanitize_for_log(..., max_length=<=256): "
+ f"{ast.unparse(assign.value)}"
+ )
+ assert assign.lineno < warning.lineno, (
+ f"{name!r} is assigned after the audit line"
+ )
+
class TestPerUserKeysInheritTheSameHeaderControl:
"""``_user_key`` / ``_api_user_key``: can a user move their own key?
@@ -535,18 +808,18 @@ class TestPerUserKeysInheritTheSameHeaderControl:
An AUTHENTICATED user cannot: the key is ``user:<session username>``,
and the session is server-signed, so the only way to change it is to
be a different account. The unauthenticated fallback, though, is
- ``_get_client_ip`` — so every per-user limit inherits the header
- control demonstrated above for anyone not logged in.
+ ``_get_client_ip`` — so every per-user limit inherits whatever that
+ key derivation yields for anyone not logged in.
"""
- def test_user_key_falls_back_to_the_forgeable_ip_key(self, rl):
+ def test_user_key_falls_back_to_the_observed_ip_key(self, rl):
forged = "203.0.113.88"
request = make_request(
peer=LOOPBACK_PEER,
session={},
headers={"X-Forwarded-For": appending_proxy_chain(forged)},
)
- assert rl._user_key(request) == forged
+ assert rl._user_key(request) == REAL_CLIENT
def test_user_prefix_keeps_a_username_out_of_the_ip_namespace(self, rl):
"""A user who registers a name shaped like an address cannot
@@ -563,27 +836,28 @@ class TestPerUserKeysInheritTheSameHeaderControl:
)
assert rl._user_key(request) != rl._user_key(anonymous)
- def test_api_user_key_collapses_username_and_ip_into_one_namespace(
- self, rl
- ):
- """DEFECT (latent): ``_api_user_key`` applies its ``api_user:``
- prefix to BOTH branches, so a username shaped like an address is
- the same key as an anonymous caller from that address.
-
- Impact is currently limited — ``/api/v1`` routes run
- ``require_api_access`` before the decorated endpoint, so the
- anonymous branch is close to unreachable — but the collision is
- one dependency-ordering change away from mattering, and
- ``_user_key`` right above it already shows the safe shape.
- """
+ def test_api_user_key_keeps_a_username_out_of_the_ip_namespace(self, rl):
+ """``_api_user_key`` prefixes the two branches differently, so a
+ username shaped like an address is NOT the same key as an
+ anonymous caller from that address."""
named = make_request(peer=PUBLIC_PEER, session={"username": LAN_PEER})
anonymous = make_request(
peer=LOOPBACK_PEER,
session={},
headers={"X-Forwarded-For": LAN_PEER},
)
- assert rl._api_user_key(named) == rl._api_user_key(anonymous), (
- "expected the documented collision; if this now fails the "
- "branches were namespaced apart and this test should be "
- "inverted"
+ assert rl._api_user_key(named) == f"api_user:{LAN_PEER}"
+ assert rl._api_user_key(anonymous) == f"api_ip:{LAN_PEER}"
+
+ def test_forwarded_value_cannot_enter_the_user_namespace(self, rl):
+ """``_user_key`` returns the bare IP key for anonymous callers, so
+ a forwarded ``user:<name>`` value would have shared that user's
+ bucket. Only an address can be an IP key now."""
+ victim = make_request(peer=LOOPBACK_PEER, session={"username": "alice"})
+ forged = make_request(
+ peer=PRIVATE_PROXY_PEER,
+ session={},
+ headers={"X-Forwarded-For": "user:alice"},
)
+ assert rl._user_key(victim) == "user:alice"
+ assert rl._user_key(forged) == PRIVATE_PROXY_PEER
diff --git a/tests/security/test_rate_limiter_fastapi.py b/tests/security/test_rate_limiter_fastapi.py
index d87725daf5..a5b9ab519a 100644
--- a/tests/security/test_rate_limiter_fastapi.py
+++ b/tests/security/test_rate_limiter_fastapi.py
@@ -593,8 +593,8 @@ class TestXRealIpWhitespaceDivergence:
main's ``get_client_ip`` did ``request.headers.get("X-Real-IP").strip()``
and had a dedicated test (``test_strips_whitespace_from_real_ip``).
- This branch's ``_get_client_ip`` strips the X-Forwarded-For entry
- (``.split(",")[0].strip()``) but returns ``X-Real-IP`` verbatim, so a
+ This branch's ``_get_client_ip`` stripped the X-Forwarded-For entry
+ it keyed on but returned ``X-Real-IP`` verbatim, so a
padded value produces a DIFFERENT bucket key than the same address
unpadded.
diff --git a/tests/test_known_defect_pattern_sweep.py b/tests/test_known_defect_pattern_sweep.py
index 3709e35a78..170ea5f6e6 100644
--- a/tests/test_known_defect_pattern_sweep.py
+++ b/tests/test_known_defect_pattern_sweep.py
@@ -2173,12 +2173,10 @@ def echo(request: Request):
)
"""
-P6_LOG_KNOWN = "src/local_deep_research/web/fastapi_app.py"
-P6_LOG_EXPECTED = {
- (P6_LOG_KNOWN, "_get_client_ip()"),
- (P6_LOG_KNOWN, "request.headers.get('User-Agent')"),
- (P6_LOG_KNOWN, "request.url.path"),
-}
+# The 429 audit line in web/fastapi_app.py was the only live instance; it now
+# wraps every field in sanitize_for_log (#5787), so the inventory is empty and
+# the positive control above is what keeps the scanner honest.
+P6_LOG_EXPECTED: set[tuple[str, str]] = set()
P6_HEADER_EXPECTED: set[tuple[str, str]] = set()
P6_CREDENTIAL_KNOWN = (
"src/local_deep_research/config/llm_config.py",
@@ -2222,10 +2220,6 @@ def test_p6_premise_scrub_error_does_not_strip_control_chars():
def test_p6_known_live_instances_are_refound():
- logs, _ = scan_pattern_6_logs(modules())
- assert (P6_LOG_KNOWN, "_get_client_ip()") in keys(logs), report(
- "pattern 6: the 429 ip= audit line must still be flagged", logs
- )
cred = scan_pattern_6_credential_only(modules())
assert P6_CREDENTIAL_KNOWN in keys(cred), report(
"pattern 6: _log_llm_error must still be flagged", cred[:20]
diff --git a/tests/web/dependencies/test_dependency_resolution_contracts.py b/tests/web/dependencies/test_dependency_resolution_contracts.py
index ead461aa96..8294b32d85 100644
--- a/tests/web/dependencies/test_dependency_resolution_contracts.py
+++ b/tests/web/dependencies/test_dependency_resolution_contracts.py
@@ -1282,5 +1282,5 @@ class TestErrorPathsInsideTheAuthDependencies:
assert response.status_code == 200
assert response.json() == {
"user": "testclient",
- "api": "api_user:testclient",
+ "api": "api_ip:testclient",
}
diff --git a/tests/web/dependencies/test_rate_limit_keys.py b/tests/web/dependencies/test_rate_limit_keys.py
index ac79714410..83da137d98 100644
--- a/tests/web/dependencies/test_rate_limit_keys.py
+++ b/tests/web/dependencies/test_rate_limit_keys.py
@@ -146,12 +146,14 @@ class TestGetClientIpTrustedPeer:
)
assert rl._get_client_ip(request) == "93.184.216.34"
- def test_xff_chain_uses_first_entry_stripped(self, rl):
+ def test_xff_chain_uses_last_entry_stripped(self, rl):
+ """The right-most entry — the address the appending proxy
+ observed — is the key (#5787); padding is still stripped."""
request = make_request(
peer="10.0.0.5",
headers={"X-Forwarded-For": " 93.184.216.34 , 10.0.0.1, 10.0.0.2"},
)
- assert rl._get_client_ip(request) == "93.184.216.34"
+ assert rl._get_client_ip(request) == "10.0.0.2"
def test_x_real_ip_used_when_no_xff(self, rl):
request = make_request(
@@ -269,13 +271,13 @@ class TestApiUserKey:
def test_anonymous_shape_uses_ip(self, rl):
request = make_request(peer="10.0.0.5", session={})
- assert rl._api_user_key(request) == "api_user:10.0.0.5"
+ assert rl._api_user_key(request) == "api_ip:10.0.0.5"
def test_no_session_scope_uses_ip(self, rl):
"""No SessionMiddleware in the stack: the scope guard must keep
Request.session from raising and key by IP instead."""
request = make_request(peer="10.0.0.5")
- assert rl._api_user_key(request) == "api_user:10.0.0.5"
+ assert rl._api_user_key(request) == "api_ip:10.0.0.5"
def test_api_and_user_buckets_are_namespaced_apart(self, rl):
"""The /api/v1 bucket and the settings/upload per-user bucket for
@@ -290,7 +292,7 @@ class TestApiUserKey:
session={},
headers={"X-Forwarded-For": "1.2.3.4"},
)
- assert rl._api_user_key(request) == "api_user:8.8.8.8"
+ assert rl._api_user_key(request) == "api_ip:8.8.8.8"
def test_anonymous_behind_trusted_proxy_uses_forwarded_ip(self, rl):
request = make_request(
@@ -298,7 +300,7 @@ class TestApiUserKey:
session={},
headers={"X-Forwarded-For": "93.184.216.34"},
)
- assert rl._api_user_key(request) == "api_user:93.184.216.34"
+ assert rl._api_user_key(request) == "api_ip:93.184.216.34"
class TestApiExempt:
diff --git a/tests/web/test_rate_limit_coverage.py b/tests/web/test_rate_limit_coverage.py
index 15be8b5fb5..f0a994a1cc 100644
--- a/tests/web/test_rate_limit_coverage.py
+++ b/tests/web/test_rate_limit_coverage.py
@@ -14,6 +14,7 @@ from unittest.mock import MagicMock, Mock, patch
import pytest
from fastapi import HTTPException
+from starlette.datastructures import Headers
# Importing the app registers every router's limits with the limiter.
from local_deep_research.web.fastapi_app import app
@@ -115,7 +116,7 @@ class TestUserKey:
request = Mock()
request.scope = {}
request.client = Mock(host="203.0.113.7")
- request.headers = {}
+ request.headers = Headers({})
assert _user_key(request) == "203.0.113.7"
@@ -176,7 +177,7 @@ class TestRateLimitExceededHandler:
request = Mock()
request.url.path = "/auth/login"
request.client = Mock(host="203.0.113.7")
- request.headers = {"User-Agent": "test-agent"}
+ request.headers = Headers({"User-Agent": "test-agent"})
with patch("local_deep_research.web.fastapi_app.logger") as mock_logger:
# Called directly, NOT via asyncio.run: the handler is deliberately
@@ -202,3 +203,25 @@ class TestRateLimitExceededHandler:
assert "/auth/login" in audit
assert "203.0.113.7" in audit
assert "test-agent" in audit
+
+ def test_429_audit_line_cannot_be_given_a_forged_ip_field(self):
+ """A User-Agent or path carrying `` ip=...`` -- including one that
+ mixes both quote characters -- must not add a second ``ip=`` field
+ for a key=value (logfmt-style) reader."""
+ import re
+
+ from slowapi.errors import RateLimitExceeded
+
+ handler = app.exception_handlers[RateLimitExceeded]
+ request = Mock()
+ request.url.path = "/a'\" ip=6.6.6.6 z="
+ request.client = Mock(host="8.8.8.8")
+ request.headers = Headers({"User-Agent": "x ip=6.6.6.6"})
+
+ with patch("local_deep_research.web.fastapi_app.logger") as mock_logger:
+ handler(request, Mock())
+
+ audit = mock_logger.warning.call_args[0][0]
+ fields = re.findall(r'(\w+)=("(?:[^"\\]|\\.)*"|\S+)', audit)
+ ips = [value for name, value in fields if name == "ip"]
+ assert ips == ["8.8.8.8"], (audit, fields)