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(security): port trusted proxy rate-limit identity to main (#7143)

LearningCircuit6f24cb4af9c9
diff --git a/README.md b/README.md
index 659b8daa2a..a975743f0a 100644
--- a/README.md
+++ b/README.md
@@ -478,6 +478,17 @@ attempt there also replaces that backup.
- **`llm.model` no longer has a default.** Pre-1.6.3 installs auto-filled `gemma3:12b` (Ollama) when no model was configured, which silently downloaded a multi-GB binary. The field is now empty by default — pick a model in Settings → LLM, or research will fail loudly with a clear error.
- **The `auto` and `parallel` meta search engines were removed.** The default langgraph-agent strategy selects engines dynamically per query, which replaces them. Stored settings are migrated automatically (removed values become `searxng`); update any explicit `search_tool="auto"` API calls or `LDR_SEARCH_TOOL=auto` env overrides to a concrete engine such as `searxng`.
+- **Behind a reverse proxy: the rate limiter reads the client address differently.** Up to v1.10.7 the login and registration rate limits keyed on the left-most `X-Forwarded-For` entry, or else `X-Real-IP`, sent by *any* peer, so any client could choose its own bucket. What happens now depends on your configuration:
+ - **`TRUST_PROXY_HEADERS` unset (the default):** those headers are read only when the direct peer is a private, loopback or link-local address (6to4, Teredo and NAT64 tunnel addresses do not count), or, once you set `LDR_SERVER_FORWARDED_ALLOW_IPS` to your proxy's address(es), only when it is listed there. The key is the **right-most** `X-Forwarded-For` entry, or `X-Real-IP` when no `X-Forwarded-For` is present.
+ - **`TRUST_PROXY_HEADERS=true` with `LDR_SERVER_FORWARDED_ALLOW_IPS` set to your proxy's address(es):** forwarded headers count only from a listed peer. uvicorn derives the client address from a listed peer's `X-Forwarded-For`, and `X-Real-IP` (used when no `X-Forwarded-For` is present) is read only from a listed peer. Any other peer is keyed on its own address.
+ - **`TRUST_PROXY_HEADERS=true` without `LDR_SERVER_FORWARDED_ALLOW_IPS`:** the key is the **right-most** `X-Forwarded-For` entry sent by **any** peer, public addresses included. That stops a client behind one appending proxy from choosing its bucket with a forged prefix, but a client that connects straight to LDR writes the whole header and still chooses its own key. `X-Real-IP` is read only from a private, loopback or link-local peer. LDR logs a startup warning for this configuration: set `LDR_SERVER_FORWARDED_ALLOW_IPS`.
+
+ What it means for an existing proxy setup:
+ - **Proxy reaching LDR from a public or carrier-grade-NAT address** (a cloud load balancer, a Tailscale `100.64.x.x` peer, a public nginx host): without `TRUST_PROXY_HEADERS` its forwarded headers are now ignored; with `TRUST_PROXY_HEADERS=true` and no allow-list its `X-Real-IP` is ignored, while its `X-Forwarded-For` still counts. When the header your proxy sends is ignored, every client shares the proxy's one rate-limit bucket and a few failed logins lock everyone out. Set `LDR_SERVER_FORWARDED_ALLOW_IPS` to the proxy's IP address(es).
+ - **Proxy on a private or Docker network:** (if you set a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`, only listed peers are trusted, so list this private proxy too.) With a single proxy, clients keep separate buckets, provided the proxy **overwrites** `X-Forwarded-For` with the address it observed (nginx: `$remote_addr`) and overwrites `X-Real-IP` the same way. A proxy that passes a client-sent header through unchanged still lets that client choose its key; a proxy that sets only `X-Real-IP` must also clear `X-Forwarded-For`, because LDR prefers it. Appending (`$proxy_add_x_forwarded_for`) gives the right rate-limit key, but under `TRUST_PROXY_HEADERS=true` without `LDR_SERVER_FORWARDED_ALLOW_IPS` uvicorn reports the left-most, client-written entry as the client address.
+ - **Two or more proxies in a chain** (CDN → nginx): by default every client is keyed on the outer proxy's address, so all of them share one rate-limit bucket and a few failed logins lock everyone out. Either have the inner proxy resolve the real client itself (nginx `realip`) and overwrite with that address, or make every inner proxy append and set a multi-hop setting: `LDR_SERVER_TRUSTED_PROXY_COUNT`, or, with `TRUST_PROXY_HEADERS=true`, every hop listed in `LDR_SERVER_FORWARDED_ALLOW_IPS`. See [Proxy chains](docs/deployment/reverse-proxy.md#proxy-chains).
+
+ With `TRUST_PROXY_HEADERS=true` but no `LDR_SERVER_FORWARDED_ALLOW_IPS`, LDR logs a startup warning naming the variable (or refuses to start if `LDR_SERVER_TRUSTED_PROXY_COUNT` is also set to a positive value, or if the allow-list is set explicitly to `*` or another value that trusts every peer). See [Reverse proxy configuration](docs/deployment/reverse-proxy.md).
- **The `llamacpp` provider now uses HTTP instead of in-process loading.** If you previously set `llm.llamacpp_model_path` to a local `.gguf` file, that setting is no longer read. Instead, run `llama-server -m <your-model.gguf>` (it ships with every modern llama.cpp build) and the default `llm.llamacpp.url` of `http://localhost:8080/v1` will pick it up. Optional API key support is available via `llm.llamacpp.api_key` if you put `llama-server` behind an auth proxy.
## 📚 Documentation
diff --git a/changelog.d/+proxy-warning-observation.bugfix.md b/changelog.d/+proxy-warning-observation.bugfix.md
index 68680e3033..6cb7c756d1 100644
--- a/changelog.d/+proxy-warning-observation.bugfix.md
+++ b/changelog.d/+proxy-warning-observation.bugfix.md
@@ -1 +1 @@
-Keep checking plain-HTTP requests for an untrusted HTTPS proxy header until the configuration warning is emitted, so an earlier health check or direct request cannot suppress the warning.
+Keep checking plain-HTTP requests for an untrusted HTTPS proxy header until the configuration warning is emitted. Track malformed forwarded-proto warnings separately, so an earlier health check, direct request, or spoofed noncanonical header cannot suppress the later private-proxy warning.
diff --git a/changelog.d/+proxy-warning-transition-peers.security.md b/changelog.d/+proxy-warning-transition-peers.security.md
new file mode 100644
index 0000000000..5697fc7890
--- /dev/null
+++ b/changelog.d/+proxy-warning-transition-peers.security.md
@@ -0,0 +1 @@
+The HTTP-cookie warnings no longer treat 6to4 (`2002::/16`), Teredo (`2001::/32`) or NAT64 (`64:ff9b::/96`, `64:ff9b:1::/48`) client addresses as private. Python's `ipaddress` module may report 6to4, Teredo and NAT64 local-use addresses as private (which ones depends on the Python version; LDR excludes these ranges on every version), so a remote client arriving over such a tunnel could send `X-Forwarded-Proto: https` and plant the "set `TRUST_PROXY_HEADERS=true`" advice meant for a local reverse proxy, and was never reported as a public client served over plain HTTP. The rate limiter's forwarding-trust check makes the same exclusion: without a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`, a direct peer with such an address is no longer treated as a private proxy, so it cannot choose its own rate-limit key with `X-Real-IP`, nor, while `TRUST_PROXY_HEADERS` is unset, with `X-Forwarded-For`. (With `TRUST_PROXY_HEADERS=true` and `LDR_SERVER_FORWARDED_ALLOW_IPS` unset, the right-most `X-Forwarded-For` entry is read from every peer, tunnelled or not; set `LDR_SERVER_FORWARDED_ALLOW_IPS` to close that.) Both the rate limiter's check and the HTTP-cookie warnings unwrap an IPv4-mapped peer (`::ffff:a.b.c.d`) themselves and judge it by the IPv4 address it wraps, so the result does not depend on the Python version: Python 3.12.0 to 3.12.3 report every mapped address private, which let a public IPv4 client on a dual-stack listener plant the same advice and stay unreported.
diff --git a/changelog.d/3299.breaking.md b/changelog.d/3299.breaking.md
index 4f17ab0507..ed7801079b 100644
--- a/changelog.d/3299.breaking.md
+++ b/changelog.d/3299.breaking.md
@@ -10,8 +10,14 @@ custom API clients should prepare for these compatibility changes:
`TRUST_PROXY_HEADERS=true` and prevent direct access to the backend.** This
lets LDR use the externally visible HTTPS scheme for secure cookies, HSTS,
and WebSocket origin checks. Rate-limit client-IP extraction has a separate
- trust rule for private or loopback proxy peers, so the proxy must overwrite,
- never append, `X-Forwarded-For` and `X-Real-IP`. See
+ trust rule for private or loopback proxy peers, so a single proxy must
+ overwrite, never append, `X-Forwarded-For` and `X-Real-IP`. A proxy that
+ connects from a public or carrier-grade-NAT address and sends `X-Real-IP`
+ without `X-Forwarded-For` is no longer trusted for it, because `X-Real-IP`
+ is now read only from a private, loopback or link-local peer (the previous
+ release read it from any peer): set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that
+ proxy's IP address, or all its clients share one rate-limit bucket. A chain of
+ proxies (CDN → nginx) needs more: see "Proxy chains" in
`docs/deployment/reverse-proxy.md`.
- **Socket.IO moved from `/socket.io` to `/ws/socket.io`.** Update custom clients
and explicit reverse-proxy `location` rules. The bundled UI is already updated.
diff --git a/changelog.d/4870.security.md b/changelog.d/4870.security.md
new file mode 100644
index 0000000000..3495528ddc
--- /dev/null
+++ b/changelog.d/4870.security.md
@@ -0,0 +1,10 @@
+**Breaking change for deployments behind a reverse proxy, whether or not they set `TRUST_PROXY_HEADERS`.** Up to v1.10.7 the rate limiter keyed on the left-most `X-Forwarded-For` entry, or else `X-Real-IP`, sent by *any* peer, so any client could choose its own rate-limit bucket. What it does now depends on the configuration. **With `TRUST_PROXY_HEADERS` unset/false** it reads those headers only from a direct peer that is private, loopback or link-local (6to4 `2002::/16`, Teredo `2001::/32` and NAT64 `64:ff9b::/96`/`64:ff9b:1::/48` peers do not count on any Python version, although Python's `ipaddress` may report some of them private, depending on the version), or, once `LDR_SERVER_FORWARDED_ALLOW_IPS` is set to a restricted list, only from a peer in that list; and it keys on the **right-most** `X-Forwarded-For` entry, or `X-Real-IP` when no `X-Forwarded-For` is present. **With `TRUST_PROXY_HEADERS=true` and a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`** only a listed peer's headers count: the key is the client address uvicorn derived from a listed peer's `X-Forwarded-For`, or, when no `X-Forwarded-For` is present, a listed peer's `X-Real-IP`; any other peer is keyed on its own address. **With `TRUST_PROXY_HEADERS=true` and `LDR_SERVER_FORWARDED_ALLOW_IPS` unset** the key is the **right-most** `X-Forwarded-For` entry from *any* peer, public addresses included. That is still an improvement on v1.10.7's left-most entry (a client behind one appending proxy can no longer choose its bucket with a forged prefix), but a client connecting straight to LDR writes the whole header and still chooses its key, so set `LDR_SERVER_FORWARDED_ALLOW_IPS`; LDR logs a startup warning saying so. In this mode `X-Real-IP` is read only from a private, loopback or link-local peer. What changes for an existing deployment that never set `TRUST_PROXY_HEADERS`: (1) a proxy that reaches LDR from a public or carrier-grade-NAT address — a cloud load balancer, a Tailscale/CGNAT peer in `100.64.0.0/10`, a public nginx host — has its forwarded headers ignored, collapsing every client behind it into one rate-limit bucket and making the login (5/15min) and registration (3/hour) lockouts deployment-global; set `LDR_SERVER_FORWARDED_ALLOW_IPS=<proxy address(es)>`. (2) A single proxy on a private or Docker network keeps per-client keying, provided it **overwrites** `X-Forwarded-For` and `X-Real-IP` with the address it observed: a client-sent header passed through unchanged still lets that client choose its key, and a proxy that sets only `X-Real-IP` must also clear `X-Forwarded-For`, which LDR prefers. An appending proxy now yields the address it observed rather than the client's forged left-most entry. (3) Behind a chain of proxies (CDN → nginx) the default settings key every client on the outer proxy's address, whether the inner proxy appends or overwrites with a plain `$remote_addr`, so all of them share one bucket and the login and registration lockouts become deployment-global. Either have the inner proxy resolve the real client itself (nginx `realip`) and overwrite with that address, or make every inner proxy append and set a multi-hop setting: `LDR_SERVER_TRUSTED_PROXY_COUNT` (below), or `TRUST_PROXY_HEADERS=true` with every hop listed in `LDR_SERVER_FORWARDED_ALLOW_IPS` (an allow-list without `TRUST_PROXY_HEADERS=true` still keys on the right-most entry). See "Proxy chains" in `docs/deployment/reverse-proxy.md`. What changes for a deployment with `TRUST_PROXY_HEADERS=true` and no `LDR_SERVER_FORWARDED_ALLOW_IPS`: points (2) and (3) apply (for an appending chain, list every hop in `LDR_SERVER_FORWARDED_ALLOW_IPS`; `LDR_SERVER_TRUSTED_PROXY_COUNT` has no effect in this mode, and setting it without the allow-list makes LDR refuse to start), but a public-address proxy's `X-Forwarded-For` is still honoured; only its `X-Real-IP` is ignored (v1.10.7 honoured it from any peer). So a proxy on a public or carrier-grade-NAT address that sends `X-Real-IP` and no `X-Forwarded-For` of its own, such as an nginx with only `proxy_set_header X-Real-IP $remote_addr`, is keyed on its own address and collapses all its clients into one bucket until you set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that proxy's IP address as LDR sees it; having the proxy overwrite `X-Forwarded-For` with the address it observed also restores per-client keys. Appending to `X-Forwarded-For` yields the right rate-limit key there too, but while `LDR_SERVER_FORWARDED_ALLOW_IPS` is unset uvicorn reports the left-most, client-written entry as the request's client address, so a single proxy should overwrite (for a chain, see (3)).
+
+Rate limiting can now derive the client IP from an explicit, admin-declared trusted-proxy hop count instead of only the pre-existing private-peer heuristic. Set `LDR_SERVER_TRUSTED_PROXY_COUNT` to the exact number of `X-Forwarded-For` entries your trusted proxies append (one per appending hop for an ordinary proxy); with `TRUST_PROXY_HEADERS` unset/false and the direct peer private/loopback or listed in a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`, the FastAPI rate limiter then reads the corresponding entry from the *right* end of `X-Forwarded-For` (the address appended by the outermost trusted hop), never the raw first (leftmost) entry — which a client can always forge, even through a real proxy. An `X-Forwarded-For` that is missing or has fewer entries than the configured count, or a direct peer that passes neither check (for example a cloud load balancer on a public address with no allow-list), falls back to the direct socket peer rather than trusting an ambiguous chain; such a public-address proxy must be listed in `LDR_SERVER_FORWARDED_ALLOW_IPS`, or every client behind it shares one rate-limit bucket. The value must be an ASCII decimal integer from 0 to 16. Surrounding whitespace (Unicode whitespace included) is ignored, and `-0` reads as `0`. Anything else (a negative value, `1_0`, `+3`, a non-ASCII digit, an out-of-range hop count) prevents startup instead of failing silently, and an empty or whitespace-only value counts as unset. The setting defaults to `0`, which keeps the pre-existing behaviour of trusting `X-Forwarded-For`/`X-Real-IP` when the direct peer is itself private/loopback (or, once a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS` is set, only when the direct peer is listed there); beyond the forwarding-trust change described above, deployments that do not set the new variable need no further action.
+
+A new `LDR_SERVER_FORWARDED_ALLOW_IPS` variable controls which direct peers uvicorn itself trusts to set `X-Forwarded-For` when `TRUST_PROXY_HEADERS=true` (mirrors uvicorn's own `--forwarded-allow-ips`). LDR's default is `*`, the value the FastAPI server hard-coded before this setting existed; note that this is not uvicorn's own default, which is `127.0.0.1` when uvicorn is launched directly. Existing deployments that only set `TRUST_PROXY_HEADERS=true` still boot: LDR starts normally and logs a startup warning describing the (unchanged, pre-existing) risk that `X-Forwarded-For` is spoofable by a client connecting directly to LDR, plus the forwarding-trust change above. LDR refuses to start only if the operator has additionally *adopted* one of this release's new settings — `LDR_SERVER_TRUSTED_PROXY_COUNT` set to a positive value, or `LDR_SERVER_FORWARDED_ALLOW_IPS` set explicitly (including to `*`) — while the allow-list still trusts every peer; that combination is unconditionally exploitable, so it hard-fails at import time. "Trusts every peer" is decided by uvicorn's own `_TrustedHosts` semantics rather than by the literal string `*`, so a whole-family CIDR (`0.0.0.0/0`, `::/0`, `0.0.0.0/0,::/0`, or the same range split as `0.0.0.0/1,128.0.0.0/1`) is caught too. Empty entries are dropped before the value is used, by both the launcher that passes uvicorn `--forwarded-allow-ips` and the rate limiter that classifies it, so uvicorn now receives `*` for `"*,"` (and for `","`) instead of a one-entry allow-list matching no peer. A value made up entirely of empty entries (e.g. `LDR_SERVER_FORWARDED_ALLOW_IPS=","`) therefore resolves to `*` too, and is warned about exactly like an unset allow-list. When a restricted allow-list contains a network broader than `/24` (IPv4) or `/64` (IPv6) — an entry overlapping the IPv4-mapped (`::ffff:0:0/96`), NAT64 well-known (`64:ff9b::/96`), NAT64 local-use (`64:ff9b:1::/48`) or Teredo (`2001::/32`) range is held to the IPv4 limit, since it embeds IPv4 addresses in its low 32 bits, so one that contains such a range (`64:ff9b::/64`) gets the broad-entry warning an over-wide IPv4 entry would get, rather than passing as an ordinary IPv6 `/64` — or an entry uvicorn keeps as an opaque literal because it parses as neither an IP nor a network (`nginx`, `10.0.0.5/8`), LDR logs a startup warning; neither is a hard failure. To silence the warning and lock this down, set `LDR_SERVER_FORWARDED_ALLOW_IPS` to your reverse proxy's real IP address(es). With `TRUST_PROXY_HEADERS=true` and such a restricted list, the rate limiter keys on the client address uvicorn computed from the list instead of the right-most `X-Forwarded-For` entry, so a multi-hop chain whose hops are all listed resolves to the real client. Together with the hop count above, this supersedes the earlier note (#6442) that only one proxy hop is supported. See `docs/deployment/reverse-proxy.md`. The one-shot warning for an `X-Forwarded-Proto: https` that is not being honoured now also points at `LDR_SERVER_FORWARDED_ALLOW_IPS`, and it distinguishes an untrusted proxy from a proxy sending a value uvicorn ignores (`HTTPS`, or a comma-separated `https, https`: uvicorn honours only a single exact lower-case value), telling the operator to fix the proxy's header in that case. It never names a client address as the one to allow-list: with `TRUST_PROXY_HEADERS=true` that address may be one uvicorn copied from a client-supplied `X-Forwarded-For`.
+
+Two hardening corrections ship with this: (1) whenever `LDR_SERVER_FORWARDED_ALLOW_IPS` is explicitly configured to a restricted list, that allow-list is the *only* source of application-level forwarding trust in the rate limiter — a merely-private direct peer outside the list (another container/pod on the same network, a LAN host) can no longer mint fresh rate-limit buckets by rotating a spoofed `X-Real-IP` or a crafted `X-Forwarded-For`, in any trust mode; private-ness alone confers forwarding trust only when no restricted allow-list is configured. (2) In trusted-hop-count mode, the selected `X-Forwarded-For` entry is now normalised by stripping an observed source port (`address:port` and `[v6]:port` forms, the same ones uvicorn's own forwarded parser accepts), so a proxy that appends the port it observed no longer hands the same client a fresh per-IP bucket on every new TCP connection.
+
+The startup error raised when the rate-limit storage backend cannot be initialised now also redacts credentials passed in the query string or fragment of `RATE_LIMIT_STORAGE_URI` / `RATELIMIT_STORAGE_URL` (for example `redis://cache:6379/0?password=...`), not only `user:pass@` userinfo; a value without `@` was previously echoed verbatim. When a `?` or `#` comes before the last `@`, the value is ambiguous (a password may contain a raw `?` or `#`, and a query value may contain a raw `@`, as in `?password=p@ss`), so everything after `scheme://` is replaced and the host is no longer shown. Credentials in other positions, such as a `;password=` path parameter, are not redacted.
+ The same redaction now also covers a storage URI that fails before `limits` builds the backend (a fullwidth `#`/`@`/`?` in the password, which Python rejects with an error quoting the whole host part, or a raw `/` in the password): a failure in parsing or initialising that URI, whether it came from the environment or from a `RATELIMIT_STORAGE_URL` line in a `.env` file in the working directory (which slowapi reads), is reported as a startup error carrying only the redacted URI, with the original error not chained or logged. Any other limiter construction failure (for example a stray `RATELIMIT_ENABLED=yes`) is reported under its real cause, with the text redacted. Fullwidth separators are folded to their ASCII forms before redacting. LDR looks that `.env` key up itself only so it can recognise and redact the URI; if the working directory or the file cannot be checked or read, that lookup treats it as having no `.env` instead of aborting the import (a `.env` that exists but cannot be read still makes slowapi's own read of it abort the import).
diff --git a/changelog.d/6442.security.md b/changelog.d/6442.security.md
index d306257056..d8285f4ebe 100644
--- a/changelog.d/6442.security.md
+++ b/changelog.d/6442.security.md
@@ -1 +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.
+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 by default: behind a chain such as CDN → nginx, every client shares the outer hop's bucket unless the inner proxy resolves the real client itself (nginx `realip`) and overwrites with that address, or every inner proxy appends and a multi-hop setting is configured (#4870); see "Proxy chains" in `docs/deployment/reverse-proxy.md`.
diff --git a/docker-compose.yml b/docker-compose.yml
index b2dbfaf138..d07b3bbaa4 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -88,6 +88,32 @@ services:
# ============================================================================
# - LDR_APP_ALLOW_REGISTRATIONS=false
+ # ============================================================================
+ # REVERSE PROXY: only if TLS terminates at a proxy in front of LDR
+ # (nginx, Caddy, Traefik, a cloud load balancer). See
+ # docs/deployment/reverse-proxy.md for the matching proxy config.
+ # LDR_SERVER_FORWARDED_ALLOW_IPS should list your proxy's IP(s) as
+ # LDR sees them: for a proxy on the Docker host that is this
+ # network's gateway (`docker network inspect`, "Gateway"), not
+ # 127.0.0.1; for a proxy container, its address on this network. Left
+ # unset with TRUST_PROXY_HEADERS=true, the rate limiter keys on the
+ # right-most X-Forwarded-For entry from ANY peer, so a client that
+ # reaches LDR directly picks its own key (LDR logs a startup warning).
+ # A proxy that connects from a public/CGNAT address needs it too:
+ # without TRUST_PROXY_HEADERS its forwarded headers are ignored, and
+ # with it only its X-Real-IP is; when the header it sends is ignored,
+ # all clients behind it share one rate-limit bucket.
+ # A single proxy must OVERWRITE X-Forwarded-For and X-Real-IP with
+ # the address it observed (nginx: $remote_addr), never pass a
+ # client-sent value through or append to one. Behind a chain (CDN ->
+ # nginx) these defaults key every client on the outer proxy's
+ # address (one shared rate-limit bucket): see "Proxy chains" in
+ # docs/deployment/reverse-proxy.md. When the inner proxies append,
+ # list every hop below, comma-separated, not just the nearest one.
+ # ============================================================================
+ # - TRUST_PROXY_HEADERS=true
+ # - LDR_SERVER_FORWARDED_ALLOW_IPS=<your-proxy-ip>
+
# ============================================================================
# ADVANCED: Uncomment ONLY if you need to enforce/lock these settings
# WARNING: This will disable UI configuration for these settings!
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 9d23eef82c..4cc28cc2a3 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -52,6 +52,7 @@ They are not available in the Web UI because they are needed to start the applic
| `LDR_SECURITY_CORS_ALLOWED_ORIGINS` | String | `None` | No | | Allowed CORS origins for API routes (comma-separated). Use '*' for all origins, empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | |
| `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Unset or empty means same-origin only (default); use '*' to allow all origins. Example: 'https://example.com,https://app.example.com' | Security | |
| `LDR_SERVER_MAX_CONCURRENT_RESEARCH` | Integer | `10` | No | 1..1000 | Server-wide maximum concurrent research operations. Requires restart. | Server | LDR_MAX_GLOBAL_CONCURRENT |
+| `LDR_SERVER_TRUSTED_PROXY_COUNT` | Integer | `0` | No | 0..16 | Number of X-Forwarded-For entries your trusted reverse proxies append -- one per appending hop for an ordinary proxy, so CDN -> nginx is 2. Used by the rate limiter only while TRUST_PROXY_HEADERS is NOT set: it then reads the N-th entry from the right, provided the direct peer is private/loopback or, once a restricted LDR_SERVER_FORWARDED_ALLOW_IPS is set, listed there (otherwise it keys on the direct peer). N must be exact: too small keys every client on a proxy's address, too large reads an entry the client wrote itself (or, when the header is shorter than N, keys on the direct peer). Zero (default) disables hop counting and keeps the single-proxy behaviour (the right-most entry). With TRUST_PROXY_HEADERS=true this value has no effect -- list every hop in LDR_SERVER_FORWARDED_ALLOW_IPS instead -- and setting it while that allow-list still trusts every peer (the default "*") makes LDR refuse to start. For N >= 2, every intermediate hop must be unreachable directly by clients, or a client connecting to an inner hop chooses the entry read. Does not affect X-Forwarded-Proto/scheme detection. See 'Proxy chains' in docs/deployment/reverse-proxy.md. Accepted values are ASCII decimal integers from 0 to 16 (surrounding whitespace is ignored and -0 reads as 0); an empty or whitespace-only value counts as unset, and any other invalid value prevents startup. | Server | |
| `LDR_TESTING_TEST_MODE` | Boolean | `False` | No | | Enable test mode (adds delays for testing concurrency) | Testing | |
| `LDR_VITE_DEV_MODE` | Boolean | `False` | No | | When true, templates link to the Vite dev server at http://localhost:5173 for HMR instead of the built manifest under static/dist. Set to true when running `npm run dev` alongside the Python server. | Server | |
| `LDR_WEB_QUEUE_PROCESSOR_ENABLED` | Boolean | `True` | No | | Enable or disable the background research queue processor | Queue Processor | |
diff --git a/docs/MIGRATION_GUIDE_v1.md b/docs/MIGRATION_GUIDE_v1.md
index 0dccc70ac5..f57b171849 100644
--- a/docs/MIGRATION_GUIDE_v1.md
+++ b/docs/MIGRATION_GUIDE_v1.md
@@ -287,9 +287,48 @@ still works.
Set `TRUST_PROXY_HEADERS=true` when TLS terminates at a trusted reverse proxy.
Without it, uvicorn keeps the request scheme as HTTP, so secure-cookie, HSTS,
and WebSocket same-origin behaviour will be wrong. Client-IP extraction for
-rate limiting follows a separate rule, so the proxy must overwrite forwarded
-client-IP headers even when this variable is unset. Use the hardened examples
-in [Reverse proxy configuration](deployment/reverse-proxy.md).
+rate limiting follows a separate rule, so a single proxy must overwrite
+forwarded client-IP headers even when this variable is unset. Behind a chain
+of proxies (CDN → nginx) the default settings key every client on the outer
+proxy's address, so all clients share one rate-limit bucket: either have the
+inner proxy resolve the real client itself (nginx `realip`) and overwrite
+with that address, or make every inner proxy append and set a multi-hop
+setting — see [Proxy chains](deployment/reverse-proxy.md#proxy-chains). Use
+the hardened examples in
+[Reverse proxy configuration](deployment/reverse-proxy.md).
+
+With `TRUST_PROXY_HEADERS=true`, also set `LDR_SERVER_FORWARDED_ALLOW_IPS` to
+your reverse proxy's IP address(es) as LDR sees them — every hop, for a
+chain whose inner proxies append. For LDR in Docker behind a proxy on the
+host, that is the Docker network's gateway, not `127.0.0.1` (see
+[Reverse proxy configuration](deployment/reverse-proxy.md)). It defaults to `*` (every peer, the value
+LDR used before), which keeps booting but logs a warning, because a client
+that reaches LDR directly can then forge `X-Forwarded-For`. Two cases need
+action:
+
+- **Your proxy connects from a public or carrier-grade-NAT address and sends
+ `X-Real-IP` without `X-Forwarded-For`** (a cloud load balancer, a Tailscale
+ `100.64.x.x` peer, a public nginx host). Without a restricted
+ `LDR_SERVER_FORWARDED_ALLOW_IPS`,
+ `X-Real-IP` is honoured only from a private, loopback or link-local peer;
+ once a restricted list is set, ONLY listed peers are trusted, so list the
+ proxy that connects to LDR even if its address is private (and, for a
+ chain, see [Proxy chains](deployment/reverse-proxy.md#proxy-chains)).
+ Without that,
+ every client shares one rate-limit bucket and the login and registration
+ lockouts apply to everyone at once. Set `LDR_SERVER_FORWARDED_ALLOW_IPS` to
+ that proxy's IP address as LDR sees it, or have a single proxy overwrite
+ `X-Forwarded-For` with the address it observed (`$remote_addr`), never pass
+ a client-sent one through. Without
+ `TRUST_PROXY_HEADERS`, only `LDR_SERVER_FORWARDED_ALLOW_IPS` helps: a
+ public-address proxy's `X-Forwarded-For` is ignored too.
+- **You set `LDR_SERVER_TRUSTED_PROXY_COUNT` or an explicit
+ `LDR_SERVER_FORWARDED_ALLOW_IPS`** while the allow-list still trusts every
+ peer (`*`, `0.0.0.0/0`, ...). LDR refuses to start, because that
+ combination is always exploitable. List your proxy's real IP(s) instead.
+
+The previous behaviour (trusting `X-Real-IP` from any peer) cannot be turned
+back on: it let any client choose its own rate-limit bucket.
### The Socket.IO endpoint moved to `/ws/socket.io`
diff --git a/docs/SearXNG-Setup.md b/docs/SearXNG-Setup.md
index 5550684f8d..335347a1a9 100644
--- a/docs/SearXNG-Setup.md
+++ b/docs/SearXNG-Setup.md
@@ -49,8 +49,9 @@ You have two ways to configure the SearXNG instance URL:
1. **Environment Variable (Recommended for self-hosted instances)**:
```bash
# Set in the server process's environment (export / docker -e / compose
- # environment: / systemd EnvironmentFile). LDR itself never loads a .env
- # file; hand such a file to whatever starts LDR instead.
+ # environment: / systemd EnvironmentFile). LDR's own code does not load a
+ # .env file for its LDR_* settings; hand such a file to whatever starts LDR
+ # instead.
LDR_SEARCH_ENGINE_WEB_SEARXNG_DEFAULT_PARAMS_INSTANCE_URL=http://localhost:8080
# Optional: Set custom delay between requests (in seconds)
diff --git a/docs/deployment/reverse-proxy.md b/docs/deployment/reverse-proxy.md
index 0a202aac0b..617eb6e70b 100644
--- a/docs/deployment/reverse-proxy.md
+++ b/docs/deployment/reverse-proxy.md
@@ -13,7 +13,10 @@ compression is intentionally the proxy's job, not the app's).
> you want behind a proxy on the same host. For Docker — where the container's
> loopback is not reachable from the host — set `LDR_WEB_HOST=0.0.0.0` and
> publish to loopback instead (`-p 127.0.0.1:5000:5000`), or use an internal
-> network. This matters for security — see the next section.
+> network. This matters for security — see the next section. Inside the
+> container the proxy's connections then arrive from the Docker network's
+> gateway, not from `127.0.0.1`; that gateway is the address to put in
+> `LDR_SERVER_FORWARDED_ALLOW_IPS` (see below).
The config below is **illustrative**; directive syntax evolves, so follow the
linked upstream docs for the current spelling. `5000` is LDR's default port
@@ -30,22 +33,111 @@ linked upstream docs for the current spelling. `5000` is LDR's default port
> `Secure` flag, HSTS is withheld, and the WebSocket same-origin check rejects
> `https` origins. Set it in the environment of the LDR process (note: no
> `LDR_` prefix — it is read at startup, before settings are loaded).
+>
+> Uvicorn only honours forwarded headers from peers listed in
+> **`LDR_SERVER_FORWARDED_ALLOW_IPS`** (LDR's default is `"*"`, any peer —
+> the value LDR previously hard-coded, so it is backward compatible; uvicorn's
+> own default when launched directly is `127.0.0.1`). With a restricted
+> allow-list, LDR's rate limiter trusts uvicorn's own computed client address
+> whenever `TRUST_PROXY_HEADERS=true` is set — regardless of whether you also
+> set `LDR_SERVER_TRUSTED_PROXY_COUNT` — and with `"*"` any client that can
+> reach LDR directly chooses its own key, so restrict this to your proxy's
+> real IP(s) whenever `TRUST_PROXY_HEADERS=true` is set. **Existing deployments
+> that only set `TRUST_PROXY_HEADERS=true` keep booting after upgrading —
+> LDR logs a startup warning instead of refusing to start.** LDR only
+> refuses to start over this if you've *also* set
+> `LDR_SERVER_TRUSTED_PROXY_COUNT` (to a positive value) or explicitly set
+> `LDR_SERVER_FORWARDED_ALLOW_IPS` (including to `"*"`) while
+> `LDR_SERVER_FORWARDED_ALLOW_IPS` still resolves to `"*"`. See "Combining
+> `TRUST_PROXY_HEADERS` with `LDR_SERVER_TRUSTED_PROXY_COUNT`" further down.
+> The startup warning also names the one behaviour change that can need action
+> on upgrade: a proxy on a public or carrier-grade-NAT address that sends
+> `X-Real-IP` without `X-Forwarded-For` is no longer trusted for it, so list that
+> proxy's IP address in `LDR_SERVER_FORWARDED_ALLOW_IPS` (the breaking-change
+> note under "`X-Real-IP` fallback" there).
-Rate-limit client-IP extraction is a separate application-level path. It reads
-`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).
+Rate-limit client-IP extraction is a separate application-level path. Which
+trust mode applies depends **first** on `TRUST_PROXY_HEADERS`, independent of
+`LDR_SERVER_TRUSTED_PROXY_COUNT`:
+
+- **`TRUST_PROXY_HEADERS=true` (at ANY `LDR_SERVER_TRUSTED_PROXY_COUNT`,
+ including its default of `0`/unset):** with a restricted
+ `LDR_SERVER_FORWARDED_ALLOW_IPS`, LDR never re-parses `X-Forwarded-For`
+ itself whenever that header is present. It trusts uvicorn's own computed
+ client address outright — uvicorn's `ProxyHeadersMiddleware` already ran,
+ as the outermost ASGI layer, before LDR's rate limiter ever saw the
+ request. With the unrestricted default `"*"`, uvicorn's client address is
+ the client-forgeable *left-most* entry, so the rate limiter keys on the
+ *right-most* entry instead, as in the default mode below. This is the
+ "combo" mode described in full under "Combining `TRUST_PROXY_HEADERS` with
+ `LDR_SERVER_TRUSTED_PROXY_COUNT`" below — safety comes entirely from
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` being restricted to your proxy's real
+ IP(s), **not** from `LDR_SERVER_TRUSTED_PROXY_COUNT`'s numeric value,
+ which has no effect at all while `TRUST_PROXY_HEADERS` is true. uvicorn's
+ `ProxyHeadersMiddleware` only ever looks at `X-Forwarded-For` — it has no
+ notion of `X-Real-IP` at all — so if a request carries no
+ `X-Forwarded-For` (or simply omits that header), `request.client` is still
+ the raw socket peer once uvicorn has run. LDR's rate limiter then falls
+ back to `X-Real-IP` itself, but only when that raw direct peer passes the
+ application-level forwarding-trust gate: membership in a **restricted,
+ explicitly configured
+`LDR_SERVER_FORWARDED_ALLOW_IPS`** when one is set (private-ness alone
+confers no trust then), or when the direct peer is private/loopback (or the
+test-suite sentinel) and no restricted allow-list is configured. Once a
+restricted allow-list is configured, no unlisted client — public or private —
+connecting straight to LDR can pick its own rate-limit bucket by sending its
+own `X-Real-IP`. Without one, the private/loopback test is Python's
+`ipaddress` classification (private, loopback or link-local) with two
+corrections: an IPv4-mapped peer (`::ffff:a.b.c.d`) is judged by the IPv4
+address it wraps, on every supported Python, and a 6to4 (`2002::/16`),
+Teredo (`2001::/32`) or NAT64 (`64:ff9b::/96`, `64:ff9b:1::/48`) peer never
+counts as private on any Python version, although Python may report some of
+those addresses as private, depending on the version: such a peer is a remote host arriving through a tunnel relay or
+translator. The test is still broader than "on your network" (it also
+accepts ranges such as the RFC 5737 documentation blocks, which are not
+routed on the public internet), so listing your proxy in
+`LDR_SERVER_FORWARDED_ALLOW_IPS` remains the precise configuration.
+- **`TRUST_PROXY_HEADERS` unset/false, `LDR_SERVER_TRUSTED_PROXY_COUNT=0`
+ (the overall default):** reads `X-Forwarded-For` when the direct peer
+ passes the application-level forwarding-trust gate — private/loopback
+ when no restricted `LDR_SERVER_FORWARDED_ALLOW_IPS` is explicitly
+ configured, allow-list membership when one is — so a local proxy works
+ before the uvicorn opt-in —
+ and
+ it takes the **right-most** entry (the one added by the nearest proxy).
+ This mode is for a single proxy, which must still **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).
+- **`TRUST_PROXY_HEADERS` unset/false, explicit trusted-hop count
+ (`LDR_SERVER_TRUSTED_PROXY_COUNT=N`, `N>0`):** LDR sees the raw socket peer
+ itself (uvicorn's proxy-header rewriting isn't installed), so it does its
+ own counting: declare exactly how many trusted proxies append to
+ `X-Forwarded-For` and LDR reads the entry counting from the **right** —
+ the one the outermost trusted hop appended — so a client-forged prefix
+ cannot spoof its IP even through a real proxy chain; this is one of the
+ multi-hop configurations in [Proxy chains](#proxy-chains). The counting
+ only runs when the direct peer passes the same application-level
+ forwarding-trust gate as above
+ (private/loopback, or allow-list membership when a restricted
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` is explicitly configured). The selected
+ entry is normalised by stripping an observed source port (`address:port`,
+ `[v6]:port` — the same forms uvicorn's own forwarded parser accepts), so
+ a proxy that appends the port it observed doesn't hand the same client a
+ fresh bucket on every connection. An invalid or negative
+ `LDR_SERVER_TRUSTED_PROXY_COUNT` value prevents startup rather than
+ silently falling back. See "Combining `TRUST_PROXY_HEADERS` with
+ `LDR_SERVER_TRUSTED_PROXY_COUNT`" further down for the different
+ (uvicorn-driven) algorithm that applies instead.
| Forwarded header | Used by LDR? | For |
|---|---|---|
-| `X-Forwarded-For` | yes | client IP for rate limiting; the trusted proxy must overwrite it |
-| `X-Real-IP` | fallback | client IP when `X-Forwarded-For` is absent; overwrite or clear it too |
+| `X-Forwarded-For` | yes | client IP for rate limiting; a single proxy overwrites it — for a chain see [Proxy chains](#proxy-chains) |
+| `X-Real-IP` | fallback | client IP when `X-Forwarded-For` is absent in combo/default modes, read only from a trusted peer (one listed in a restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`, otherwise a private, loopback or link-local one, so a proxy on a public or carrier-grade-NAT address must be listed); count-positive mode requires `X-Forwarded-For` and falls back to the direct peer when it is absent; overwrite or clear it too |
| `X-Forwarded-Proto` | with `TRUST_PROXY_HEADERS` | http/https detection → secure cookies, HSTS, the WebSocket same-origin check |
| `X-Forwarded-Host` | ignored | — |
| `X-Forwarded-Port` | ignored | — |
@@ -56,18 +148,26 @@ This means:
proxy makes LDR think the request is plain HTTP — secure cookies and HSTS are
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. 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.
+- **Default mode: overwrite `X-Forwarded-For` and `X-Real-IP`** with the
+ address observed by the one trusted proxy. With the overwrite form shown
+ below the header carries a single entry. In the default
+ (`LDR_SERVER_TRUSTED_PROXY_COUNT=0`) trust mode, 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.
+- **More than one proxy: see [Proxy chains](#proxy-chains).** The overwrite
+ rule above is for a single proxy. Behind a chain (CDN → nginx) the default
+ settings key every client on the outer hop's address — one shared
+ rate-limit bucket — unless the inner proxy resolves the real client itself
+ (nginx `realip`) and overwrites with it, or every inner proxy appends and
+ you set a multi-hop setting.
- **`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
@@ -78,21 +178,342 @@ This means:
ignored by uvicorn, but the rate limiter still honours client-IP headers
from a private/loopback peer. That distinction is why the overwrite rule
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 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
+- **Exactly one proxy hop is supported in the default mode.**
+ `TRUST_PROXY_HEADERS` is a boolean, not a hop count, and with
+ `LDR_SERVER_TRUSTED_PROXY_COUNT` unset LDR keys on the right-most forwarded
+ entry; [Proxy chains](#proxy-chains) covers deployments with more than one
+ proxy. (uvicorn's own client address
+ under `TRUST_PROXY_HEADERS` with the unrestricted `"*"` is the left-most
+ entry; the rate limiter then 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.)
+- **`LDR_SERVER_TRUSTED_PROXY_COUNT` applies only while
+ `TRUST_PROXY_HEADERS` is unset/false**, and it does not affect
+ `X-Forwarded-Proto`/scheme trust. How to choose its value, and the
+ firewalling every hop needs, are in [Proxy chains](#proxy-chains).
- **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
at the proxy (shown below).
+### Proxy chains
+
+This section is the reference for every deployment with more than one proxy
+in front of LDR — a CDN, tunnel or cloud load balancer in front of nginx, say.
+The rest of the documentation, the changelog and LDR's startup warnings only
+summarise it.
+
+**One proxy.** It must **overwrite** `X-Forwarded-For` and `X-Real-IP` with
+the address it observed (nginx: `$remote_addr`, as in the nginx example
+below). Nothing else is needed: in the default mode the rate limiter keys on
+that single entry, provided the proxy connects from a private/loopback
+address, or is listed in `LDR_SERVER_FORWARDED_ALLOW_IPS` when you set that.
+
+**Why a chain needs more.** By default the rate limiter keys on the
+right-most `X-Forwarded-For` entry — the one written by the proxy nearest to
+LDR. In a chain that is the *inner* proxy, and what it writes is the outer
+hop's address: if it appends, the right-most entry is the outer hop's
+address; if it overwrites with a plain `$remote_addr`, that address is the
+only entry. Either way every client is keyed on the outer hop and shares one
+rate-limit bucket, so a few failed logins or registrations lock everyone out
+of the whole deployment. Setting `LDR_SERVER_FORWARDED_ALLOW_IPS` does not
+change this while `TRUST_PROXY_HEADERS` is unset: the allow-list only decides
+which direct peers may send forwarded headers, and the right-most entry is
+still the key. Pick **one** of the two configurations below.
+
+**Option 1 — the inner proxy resolves the client itself.** Configure the
+inner proxy to trust the outer hop and recover the client's address from the
+header the outer hop sent, then overwrite both client-IP headers with that
+verified address. With nginx this is the
+[`realip` module](https://nginx.org/en/docs/http/ngx_http_realip_module.html):
+
+```conf
+# inner nginx, http or server context
+set_real_ip_from 198.51.100.0/24; # the outer hop's address(es), nothing wider
+real_ip_header X-Forwarded-For;
+```
+
+For a request from a `set_real_ip_from` address, nginx replaces
+`$remote_addr` with the right-most `X-Forwarded-For` entry the outer hop sent
+(with `real_ip_recursive on`, the right-most one not itself in
+`set_real_ip_from` — use that, and list every outer address, when the outer
+layer is several hops). The unchanged single-proxy directives in the nginx
+example below then forward the real client, and LDR's default single-proxy
+mode keys on it (so does `TRUST_PROXY_HEADERS=true` with only the inner proxy
+in `LDR_SERVER_FORWARDED_ALLOW_IPS`) — set **no** multi-hop setting here (with
+`LDR_SERVER_TRUSTED_PROXY_COUNT=2`, the one-entry header is shorter than the
+count and every client is keyed on the inner proxy instead). Without
+`realip`, the inner proxy's `$remote_addr` is the outer hop's address and you
+are back to one shared bucket. `set_real_ip_from` must list exactly the outer
+hop's addresses: any address it covers can name its own client address.
+
+**Option 2 — inner proxies append, and LDR is told about the chain.** Every
+inner proxy **appends** its peer's address to `X-Forwarded-For` (nginx's
+appending variable in place of the `$remote_addr` overwrite in the example
+below; the outermost proxy may append or overwrite). Appending is not enough
+on its own — **one of these multi-hop settings is required**, or the chain
+behaves as in "Why a chain needs more" above:
+
+- **`TRUST_PROXY_HEADERS` unset/false:** set
+ `LDR_SERVER_TRUSTED_PROXY_COUNT=N`, where `N` is the number of
+ `X-Forwarded-For` entries your proxies add — one per appending hop for an
+ ordinary proxy, so CDN → nginx is `2`. LDR reads the `N`-th entry from the
+ right. `N` must be exact: too small keys every client on a proxy's address,
+ too large reads an entry the client wrote itself (or, when the header has
+ fewer than `N` entries, keys on the direct peer). The count is only applied
+ when the direct peer is trusted — private/loopback, or listed in
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` once that is set — so a proxy that reaches
+ LDR from a public address must be listed there. This setting has **no
+ effect** while `TRUST_PROXY_HEADERS=true`.
+- **`TRUST_PROXY_HEADERS=true`** (needed anyway when TLS terminates in front
+ of LDR, for secure cookies, HSTS and the WebSocket origin check): list
+ **every** hop in `LDR_SERVER_FORWARDED_ALLOW_IPS` — the inner proxy LDR
+ sees as its direct peer *and* each outer hop's address as it appears in
+ `X-Forwarded-For`. uvicorn walks the header from the right and returns the
+ first address that is not listed, so a hop missing from the list is
+ returned as the client and every client behind it shares its bucket.
+
+**Load balancers that add more than one entry.** Some load balancers append
+more than one address — for example the client's address followed by an
+address of their own. Treat each added entry like a hop: count all of them
+in `LDR_SERVER_TRUSTED_PROXY_COUNT`, or, with `TRUST_PROXY_HEADERS=true`,
+list the addresses the load balancer adds as well as the one it connects
+from. Check your load balancer's documentation for exactly what it appends,
+and list it in `LDR_SERVER_FORWARDED_ALLOW_IPS` if it connects from a public
+address.
+
+**Every hop must be unreachable directly.** LDR can only check its direct
+peer. If a client can connect straight to an intermediate proxy (it also has
+a public listener, or the firewall only protects the edge), that proxy
+records the client's real address at its own position, and every entry to
+its left — including the one Option 2 reads — is the client's own text. This
+mirrors [Werkzeug `ProxyFix`'s documented
+limitation](https://werkzeug.palletsprojects.com/en/stable/middleware/proxy_fix/).
+Firewall **every** hop so it only accepts connections from the hop in front
+of it, not just the edge-facing one.
+
+### Combining `TRUST_PROXY_HEADERS` with `LDR_SERVER_TRUSTED_PROXY_COUNT`
+
+**Setting `TRUST_PROXY_HEADERS=true` *recommends* restricting
+`LDR_SERVER_FORWARDED_ALLOW_IPS` to your proxy's IP(s) — required only
+if you've also adopted `LDR_SERVER_TRUSTED_PROXY_COUNT` or set
+`LDR_SERVER_FORWARDED_ALLOW_IPS` explicitly, see below. With a restricted
+list it hands client-IP resolution to uvicorn (with `"*"` the rate limiter
+keys on the right-most entry instead); either way LDR's own hop-counting is
+never used, whatever `LDR_SERVER_TRUSTED_PROXY_COUNT` is set to
+(including left at its default of `0`/unset).**
+`TRUST_PROXY_HEADERS=true` makes `web/app.py` launch uvicorn with
+`proxy_headers=True`, which installs uvicorn's `ProxyHeadersMiddleware`
+as the *outermost* ASGI layer, wrapping the whole FastAPI app, running
+before any of LDR's own code (including the rate limiter) ever sees the
+request. For a direct peer matching `forwarded_allow_ips` (uvicorn's own
+`--forwarded-allow-ips`, which `web/app.py` sets from
+`LDR_SERVER_FORWARDED_ALLOW_IPS`, default `"*"` for backward
+compatibility), that middleware walks `X-Forwarded-For` from the
+**right** and rewrites the request's client address to the first entry
+that is *not itself* one of the allow-list's trusted IPs; for a direct
+peer that does *not* match, it leaves the client address untouched (the
+real raw socket peer). Because this walk is IP-membership-based rather
+than a plain hop count, LDR's rate limiter takes advantage of it:
+whenever `TRUST_PROXY_HEADERS=true`, a restricted
+`LDR_SERVER_FORWARDED_ALLOW_IPS` is configured, **and the request carries
+an `X-Forwarded-For` header**, it trusts uvicorn's already-computed client
+address directly and does **not** re-parse `X-Forwarded-For` or apply
+`LDR_SERVER_TRUSTED_PROXY_COUNT`'s own counting at all — at any
+`LDR_SERVER_TRUSTED_PROXY_COUNT`, including `0`/unset. With the
+unrestricted `"*"` it keys on the right-most entry instead (see the
+`"*"` case below); hop counting does not run in either case.
+- **`X-Real-IP` fallback.** uvicorn's `ProxyHeadersMiddleware` rewrites
+ `scope["client"]` only inside its `if x_forwarded_for_values:` branch
+ — it has no concept of `X-Real-IP` whatsoever, in any
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` configuration. So a request with
+ **no** `X-Forwarded-For` at all leaves `request.client` as the raw
+ socket peer, exactly as if `TRUST_PROXY_HEADERS` were unset — this is
+ the case for a reverse proxy set up with only
+ `proxy_set_header X-Real-IP $remote_addr` and no
+ `X-Forwarded-For` directive, a common nginx pattern. Such a proxy
+ must still **clear** any `X-Forwarded-For` the client sent (in
+ nginx, set that header to `""`, which drops it; or overwrite it
+ with `$remote_addr` as the example below does): nginx passes
+ request headers through by default, so a client-sent value would
+ reach uvicorn, become the client address, and suppress the
+ `X-Real-IP` fallback
+ ([#6849](https://github.com/LearningCircuit/local-deep-research/issues/6849)).
+ Without a
+ fallback, every client behind such a proxy would land in one
+ shared rate-limit bucket. LDR's rate limiter restores that fallback
+ itself: when no `X-Forwarded-For` is present, it reads `X-Real-IP`,
+ but **only** when the raw direct peer passes the application-level
+ forwarding-trust gate — with a restricted, explicitly configured
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` that means **membership in the
+ allow-list** (a merely-private peer outside the list gets no trust:
+ it is a direct-connecting client, exactly what the restricted
+ configuration exists to defend against); with no restricted
+ allow-list configured it means private/loopback (or the test-suite's
+ `testclient` sentinel) — the same check used by the
+ `TRUST_PROXY_HEADERS=false` heuristic above. uvicorn provides no
+ equivalent gate for `X-Real-IP`, so this check is the *only* thing
+ standing between an arbitrary direct-connecting client's `X-Real-IP`
+ header and the rate limiter; an untrusted direct peer's `X-Real-IP`
+ is always ignored.
+ > **Breaking change in this release.** Before it, `X-Real-IP` was
+ > trusted unconditionally whenever `TRUST_PROXY_HEADERS=true`. Now, with
+ > no restricted `LDR_SERVER_FORWARDED_ALLOW_IPS`, it is read only from a
+ > private, loopback or link-local peer. If your proxy reaches LDR from
+ > any other address — a cloud load balancer, a CGNAT/Tailscale peer in
+ > `100.64.0.0/10`, a public nginx host — and sends `X-Real-IP` without
+ > `X-Forwarded-For`, that header is now ignored and every client behind
+ > it shares the proxy's single bucket, making the login and registration
+ > lockouts deployment-global. Set
+ > `LDR_SERVER_FORWARDED_ALLOW_IPS=<your proxy's address(es)>` (its IP
+ > address as LDR sees it) to restore per-client keying.
+ >
+ > **Dual-stack listeners.** Matching is by parsed IP address, with
+ > no IPv4-mapped normalisation — the same as uvicorn's own
+ > `_TrustedHosts`. A proxy that reaches a dual-stack listener over
+ > IPv6 shows up as `::ffff:10.0.0.5`, which does **not** match a
+ > plain `10.0.0.5` entry; list the mapped form (or both) when your
+ > listener accepts IPv6.
+- **`LDR_SERVER_FORWARDED_ALLOW_IPS` unset / `"*"` (any peer trusted) —
+ SPOOFABLE.** With `"*"`, uvicorn treats every direct peer as trusted
+ and takes a shortcut: it returns the **left-most** `X-Forwarded-For`
+ entry verbatim — the one a client fully controls — for *any* request
+ carrying that header, including one from an attacker connecting
+ directly to LDR, and irrespective of hop count. It does not touch the
+ raw headers, only the derived client address, so this cannot be
+ detected or undone downstream: an attacker who reaches LDR directly
+ gets to choose their own rate-limit bucket outright by sending any
+ `X-Forwarded-For` value they like. (LDR's rate limiter keys on the
+ *right-most* entry in this case, which stops a client behind a single
+ appending proxy from steering its bucket with a forged prefix — but a
+ client connecting directly writes the whole header, right-most entry
+ included.) This is the *same* exposure
+ `TRUST_PROXY_HEADERS=true` has always had, going back to before
+ `LDR_SERVER_FORWARDED_ALLOW_IPS`/`LDR_SERVER_TRUSTED_PROXY_COUNT`
+ existed — this release does not make it worse.
+ - **Legacy deployments — `TRUST_PROXY_HEADERS=true` set, and
+ *neither* new variable touched — boot normally, with a startup
+ warning** naming the risk and the fix, so upgrading never breaks a
+ pre-existing deployment on its own.
+ - **Deployments that have *adopted* this release's new settings —
+ `LDR_SERVER_TRUSTED_PROXY_COUNT` set to a positive value, or
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` set explicitly (including
+ explicitly to `"*"`) — while `LDR_SERVER_FORWARDED_ALLOW_IPS`
+ still resolves to `"*"`: LDR raises a `RuntimeError` at import
+ time, before uvicorn ever binds a port, and refuses to start.**
+ Once you've opted into these settings this is an unconditionally
+ exploitable combination, not merely a risky one, so it fails
+ closed the same way a malformed or negative
+ `LDR_SERVER_TRUSTED_PROXY_COUNT` does, rather than only logging a
+ warning an operator could miss.
+ - **"Resolves to `"*"`" means uvicorn's semantics, not the literal
+ string.** A list that covers an entire address family is exactly
+ as permissive and is refused (or warned about) identically:
+ `0.0.0.0/0`, `::/0`, `0.0.0.0/0,::/0`, and the same range split
+ into pieces such as `0.0.0.0/1,128.0.0.0/1`. Once every hop in a
+ chain is trusted, uvicorn falls back to the left-most (forgeable)
+ `X-Forwarded-For` entry, so these spell `"*"` in CIDR. A trailing
+ comma is ignored rather than silently producing an allow-list
+ that matches nothing (`"*,"` is normalised to `"*"` before
+ uvicorn is handed it). `::/0` on its own counts too: wherever the
+ listener accepts IPv6 it trusts every peer arriving over it. So
+ does `::ffff:0.0.0.0/96`, the IPv4-mapped range every IPv4 peer
+ arrives inside on such a listener.
+- **`LDR_SERVER_FORWARDED_ALLOW_IPS` set to your proxy's address(es) —
+ the recommended, safe configuration.** Set it to the exact IP(s) of
+ your reverse proxy (comma-separated; same syntax as uvicorn's
+ `--forwarded-allow-ips`), e.g.
+ `LDR_SERVER_FORWARDED_ALLOW_IPS=10.0.0.5`. With a restricted list,
+ uvicorn only rewrites the client address for connections that
+ actually arrived from that trusted proxy, by walking `X-Forwarded-For`
+ for the first entry it doesn't recognise as one of those trusted
+ IPs — an attacker connecting directly to LDR (bypassing the proxy)
+ keeps their real raw socket peer **provided every entry in
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` names a proxy's exact address**,
+ whatever address the attacker themselves connects from (public
+ *or* private): in restricted mode the allow-list is also the only
+ source of application-level forwarding trust, so the rate
+ limiter's own gates (the `X-Real-IP` fallback and the hop-count
+ direct-peer check) ignore forwarding headers from any peer outside
+ the list — private-ness alone confers nothing. This guarantee is
+ scoped to exact addresses: a *network* entry instead trusts every
+ peer inside it (see the warning below), so an attacker whose own
+ address falls inside a broader entry is not "outside the list" and
+ keeps the ability to supply their own client address. The rate
+ limiter keys on uvicorn's computed client address in this mode,
+ validated as an IP address (anything else shares the fixed
+ `unparseable-peer` bucket). That address is only as trustworthy as
+ the peers on the list: uvicorn takes a listed peer's
+ `X-Forwarded-For` at face value, and when every entry in the header
+ is itself a listed address it returns the left-most one. So a client
+ that reaches LDR *from* an allow-listed address (the proxy host
+ itself, or any address inside a network entry) chooses its own
+ rate-limit key, just as it chooses the scheme `TRUST_PROXY_HEADERS`
+ sees. A trusted proxy that sends a trailing empty entry
+ (`X-Forwarded-For: 203.0.113.7,`) makes uvicorn return the proxy's
+ own address, so every client behind it shares one bucket. This is how to get **both** HTTPS-behind-proxy detection
+ (only `TRUST_PROXY_HEADERS` provides secure cookies, HSTS, and the
+ WebSocket same-origin check) **and** correct multi-hop client-IP
+ resolution at the same time — LDR permits this combination and boots
+ normally (it logs an info line confirming the restricted allow-list
+ rather than raising). Each entry is a peer allowed to pick a
+ client's rate-limit bucket, so list exact addresses: a network
+ entry extends that trust to everything inside it, and an entry
+ uvicorn cannot parse as an IP or a network (a hostname such as
+ `nginx`, or a CIDR with host bits set such as `10.0.0.5/8`) is kept
+ as an opaque literal that matches no peer at all. LDR logs a
+ startup warning for each, but does not refuse to start.
+ **Not over a unix socket.** A request that arrives over a UDS has
+ no peer address at all — `request.client` is `None`, and the rate
+ limiter substitutes `"127.0.0.1"` — so with a restricted allow-list
+ that synthetic peer is outside the list and every client behind the
+ proxy lands in a single bucket. Reach LDR over TCP when you set
+ `LDR_SERVER_FORWARDED_ALLOW_IPS`, or leave the allow-list unset for
+ a UDS deployment (`127.0.0.1` is private, so the pre-existing
+ heuristic trusts it).
+ **List the address LDR sees, not the one the proxy dials.** The entry
+ must match the direct peer of the TCP connection as it arrives at
+ LDR. With LDR in Docker and the proxy on the host (the
+ `-p 127.0.0.1:5000:5000` setup above), the proxy connects to
+ `127.0.0.1`, but inside the container the connection arrives from
+ the Docker network's gateway (often `172.17.0.1` on the default
+ bridge; a Compose network has its own, e.g. `172.18.0.1`). Find it
+ with `docker network inspect <network>` (the `Gateway` field) and list
+ that address. With a proxy container on the same Docker network, list
+ that container's address, and pin it with a static `ipv4_address` so
+ it survives a restart. Listing `127.0.0.1` here instead matches no
+ peer: uvicorn and the rate limiter then ignore the proxy's headers,
+ every client shares one rate-limit bucket, and the login and
+ registration lockouts become deployment-global. Listing the whole
+ Docker subnet (`172.18.0.0/16`) works but trusts every container on
+ it, and LDR logs a broad-entry warning for it at every start.
+ **Behind a chain whose inner proxies append, list *every* hop, not
+ just the nearest one** — uvicorn trusts by IP membership, not hop
+ count, so `LDR_SERVER_TRUSTED_PROXY_COUNT` plays no part here; see
+ [Proxy chains](#proxy-chains).
+- **Running LDR behind a different ASGI server** (not `ldr-web` /
+ `web/app.py` — e.g. a custom `gunicorn -k uvicorn.workers.UvicornWorker`
+ invocation) that already passes its own restricted
+ `--forwarded-allow-ips` on the command line: set
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` to that *same* value too. The
+ startup check above only sees the env var, not your ASGI server's
+ actual CLI flags, so this tells it your deployment is genuinely
+ restricted instead of tripping the `"*"` failure over an unrelated
+ default. Unless you enable LDR's logging yourself (only `ldr-web`
+ does), LDR writes its startup warnings about these settings straight
+ to stderr.
+
+For the same-host nginx, Caddy and Traefik examples below, set these
+variables in the **LDR** service environment. The proxy connects over IPv4
+loopback. This allow-list trusts any local process connecting from
+`127.0.0.1`, so use it only on a host without untrusted local users:
+
+```dotenv
+LDR_WEB_HOST=127.0.0.1
+TRUST_PROXY_HEADERS=true
+LDR_SERVER_FORWARDED_ALLOW_IPS=127.0.0.1
+```
+
## nginx
```nginx
@@ -201,6 +622,56 @@ inbound ports 80 and 443 reachable for the ACME challenge and a writable data
directory. For an internal/non-public hostname Caddy falls back to its
locally-trusted internal CA (browsers warn unless you trust its root).
+## Traefik (same host, one proxy)
+
+This example uses Traefik's [file provider](https://doc.traefik.io/traefik/reference/install-configuration/providers/others/file/).
+Traefik connects to `127.0.0.1:5000`, matching the LDR allow-list above. In
+Traefik's static configuration, redirect HTTP to HTTPS and load the route below:
+
+```yaml
+# /etc/traefik/traefik.yml
+entryPoints:
+ web:
+ address: ":80"
+ http:
+ redirections:
+ entryPoint:
+ to: websecure
+ websecure:
+ address: ":443"
+providers:
+ file:
+ filename: /etc/traefik/ldr.yml
+```
+
+```yaml
+# /etc/traefik/ldr.yml
+http:
+ routers:
+ ldr:
+ rule: Host(`ldr.example.com`)
+ entryPoints: [websecure]
+ service: ldr
+ tls: {}
+ services:
+ ldr:
+ loadBalancer:
+ servers:
+ - url: http://127.0.0.1:5000
+```
+
+Configure a valid TLS certificate or certificate resolver in Traefik; `tls: {}`
+enables TLS for the route but does not provision a trusted certificate. When
+Traefik receives requests directly from clients, leave its
+[`forwardedHeaders.trustedIPs`](https://doc.traefik.io/traefik/reference/install-configuration/entrypoints/#forwarded-headers)
+unset and do not use `forwardedHeaders.insecure`: Traefik then discards
+client-supplied forwarding headers and supplies its own. If another trusted
+proxy sits in front of Traefik, list **only** that proxy's IP/CIDR in Traefik's
+`forwardedHeaders.trustedIPs`, then configure LDR for the resulting chain as
+described in [Proxy chains](#proxy-chains). If Traefik and LDR run in separate
+containers, use an internal network and put Traefik's address **as seen by
+LDR** in `LDR_SERVER_FORWARDED_ALLOW_IPS`; container loopback is not shared.
+
## Notes
- **Single backend only.** LDR doesn't support horizontal scaling — multiple
@@ -229,9 +700,19 @@ locally-trusted internal CA (browsers warn unless you trust its root).
but `LDR_APP_ALLOW_REGISTRATIONS` defaults to **true** (open self-signup). Set
`LDR_APP_ALLOW_REGISTRATIONS=false` after creating your accounts. Proxy-level
basic-auth is usually unnecessary given the built-in auth.
-- **Other proxies:** Traefik (set its forwarded-headers trusted IPs),
- [Nginx Proxy Manager](unraid.md), or a tunnel. Note **Cloudflare Tunnel adds a
- second hop**, which conflicts with the fixed one-proxy trust model above.
+- **Other proxies:** [Nginx Proxy Manager](unraid.md), or a tunnel. With **Cloudflare Tunnel**,
+ the Cloudflare edge appends the visitor's address to `X-Forwarded-For`, but
+ `cloudflared` itself does not append anything. When `cloudflared` connects
+ straight to LDR, that is a single appending hop: use
+ `LDR_SERVER_TRUSTED_PROXY_COUNT=1` (or leave it unset — `cloudflared` on
+ the same host or container network is a private peer, so the default
+ right-most rule already picks the visitor), or, with
+ `TRUST_PROXY_HEADERS=true`, list `cloudflared`'s own address in
+ `LDR_SERVER_FORWARDED_ALLOW_IPS`. Do **not** set a count of 2 for a
+ tunnel-only setup: LDR would then key on the entry to the left of the
+ visitor's address, which the visitor can forge. Only when another proxy
+ (such as nginx) sits between `cloudflared` and LDR is it a two-hop chain
+ (see [Proxy chains](#proxy-chains)).
## Related
diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md
index ea3a36d0de..f7ac21841e 100644
--- a/docs/deployment/upgrading.md
+++ b/docs/deployment/upgrading.md
@@ -53,7 +53,17 @@ See the [configuration reference](../CONFIGURATION.md).
Socket.IO now uses `/ws/socket.io`. A trusted TLS-terminating proxy requires
`TRUST_PROXY_HEADERS=true` and must be the only way to reach the backend.
Follow the [reverse-proxy guide](reverse-proxy.md), including its header
- overwrite and single-proxy requirements.
+ overwrite requirements and, behind more than one proxy, its
+ [proxy chains](reverse-proxy.md#proxy-chains) section. If the proxy
+ connects to LDR from a public or carrier-grade-NAT address (a cloud load
+ balancer, a Tailscale `100.64.x.x` peer, a public nginx host), set
+ `LDR_SERVER_FORWARDED_ALLOW_IPS` to its IP address as LDR sees it before you
+ upgrade. Without a restricted allow-list, LDR now reads `X-Real-IP` only from
+ a private, loopback or link-local peer (the previous release read it from
+ any peer), so a proxy that sends `X-Real-IP` without `X-Forwarded-For` is
+ otherwise keyed on its own address: all its clients share one rate-limit
+ bucket and a few failed logins lock everyone out. Without
+ `TRUST_PROXY_HEADERS`, such a proxy's `X-Forwarded-For` is ignored too.
## Upgrade and verify
diff --git a/docs/docker-compose-guide.md b/docs/docker-compose-guide.md
index 5901bec23d..74c7ddb6aa 100644
--- a/docs/docker-compose-guide.md
+++ b/docs/docker-compose-guide.md
@@ -62,6 +62,8 @@ Most settings can be configured through the web UI at http://localhost:5000/sett
| `LDR_WEB_PORT` | Internal port (default: `5000`) |
| `LDR_DATA_DIR` | Data directory (default: `/data`) |
| `LDR_APP_ALLOW_REGISTRATIONS` | Allow new user registration (default: `true`). Set to `false` for public deployments after creating your initial account. |
+| `TRUST_PROXY_HEADERS` | Set to `true` only when TLS terminates at a reverse proxy in front of LDR. See [Reverse proxy configuration](deployment/reverse-proxy.md). |
+| `LDR_SERVER_FORWARDED_ALLOW_IPS` | With `TRUST_PROXY_HEADERS=true`: your reverse proxy's IP address(es) as LDR sees them. For a proxy on the Docker host that is the Docker network's gateway (`docker network inspect`, `Gateway`), not `127.0.0.1`; an address the proxy does not connect from puts every client in one rate-limit bucket. Unset means the rate limiter keys on the right-most `X-Forwarded-For` entry from any peer, so a client that reaches LDR directly picks its own key (startup warning). Also needed if the proxy connects from a public/CGNAT address: without `TRUST_PROXY_HEADERS` its forwarded headers are ignored, and with it only its `X-Real-IP` is; when the header it sends is ignored, all clients behind it share one rate-limit bucket. A single proxy must overwrite `X-Forwarded-For` and `X-Real-IP` with the address it observed. Behind a chain (CDN → nginx) the defaults key every client on the outer proxy's address (one shared bucket): see [Proxy chains](deployment/reverse-proxy.md#proxy-chains). |
| `LDR_LLM_PROVIDER` | LLM provider (`ollama`, `openai`, `anthropic`, etc.) |
| `LDR_LLM_MODEL` | Model name (e.g., `gemma3:12b`) |
diff --git a/docs/env_configuration.md b/docs/env_configuration.md
index 6e5d6c9ded..1b0c9dbe19 100644
--- a/docs/env_configuration.md
+++ b/docs/env_configuration.md
@@ -34,10 +34,21 @@ For the complete list of all settings, their environment variable names, and def
## Getting Variables Into LDR (and Making Them Persistent)
-**LDR itself never loads a `.env` file** — it reads only the environment of
-the server process. (The bundled `.env.template` is a reference of available
-names, not a file LDR opens by itself.) Keeping your values in a file is
-still perfectly fine: hand the file to whatever *starts* LDR rather than to
+**LDR's own code never loads a `.env` file into its settings** — it reads
+only the environment of the server process. Two things can still involve a
+`.env` file, neither of which is LDR loading one for its settings:
+
+- Rate limiting: the bundled `slowapi` library reads its own `RATELIMIT_*`
+ keys from a `.env` file in the server's working directory, and LDR looks
+ up the legacy rate-limit storage URL key there the same way, only to
+ report and redact it.
+- A dependency can put a stray `.env` file's keys into the process
+ environment, where LDR then reads them like any other variable (see
+ [the caveat below](#caveat-a-dependency-may-pull-in-a-stray-env-pip-installs)).
+
+The bundled `.env.template` is a reference of available names, not a
+file LDR opens by itself. Keeping your values in a file is still perfectly
+fine: hand the file to whatever *starts* LDR rather than to
LDR — `docker run --env-file <file>`, Compose `env_file:`, or systemd
`EnvironmentFile=` all read a key=value file and put its contents into the
process environment, which is what LDR then sees.
diff --git a/docs/faq.md b/docs/faq.md
index f068f508ee..a9929a7bdf 100644
--- a/docs/faq.md
+++ b/docs/faq.md
@@ -148,7 +148,7 @@ services:
### Where should I configure settings?
-**Important**: LDR itself never loads a `.env` file — it reads only the environment of the server process. To keep values in a file, hand the file to whatever starts LDR rather than to LDR: `docker run --env-file <file>`, Compose `env_file:`, or systemd `EnvironmentFile=`. (The bundled `.env.template` is a reference of available variable names, not a file LDR opens by itself.) For most users the web UI is the simplest option:
+**Important**: LDR's own code never loads a `.env` file into its settings — it reads `LDR_*` and other settings only from the environment of the server process. (Two things can still involve a `.env` file: the bundled `slowapi` library reads its own `RATELIMIT_*` keys from a `.env` file in the server's working directory, and LDR looks up the legacy rate-limit storage URL key there the same way, only to report and redact it; and a dependency can put a stray `.env` file's keys into the process environment, as described in the caveat below.) To keep values in a file, hand the file to whatever starts LDR rather than to LDR: `docker run --env-file <file>`, Compose `env_file:`, or systemd `EnvironmentFile=`. (The bundled `.env.template` is a reference of available variable names, not a file LDR opens by itself.) For most users the web UI is the simplest option:
1. Run the web app: `python -m local_deep_research.web.app`
2. Navigate to Settings
3. Configure your preferences
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index 639a5a92b2..89f281b6ed 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -331,8 +331,11 @@ This guide covers common issues and their solutions.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
- # Overwrite rather than append: LDR supports exactly one proxy hop and
- # keys its rate limiter on the right-most X-Forwarded-For entry.
+ # Overwrite rather than append when this is the only proxy: LDR's
+ # default mode supports exactly one proxy hop and keys its rate limiter
+ # on the right-most X-Forwarded-For entry. If this nginx sits behind
+ # another proxy (a CDN), these lines alone key every client on the
+ # CDN's address: see "Proxy chains" in docs/deployment/reverse-proxy.md.
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/defaults/.env.template b/src/local_deep_research/defaults/.env.template
index 71b3a1ef80..b88a01bbc3 100644
--- a/src/local_deep_research/defaults/.env.template
+++ b/src/local_deep_research/defaults/.env.template
@@ -6,9 +6,14 @@
# Example: app.debug -> LDR_APP_DEBUG
#
# IMPORTANT — how these variables reach LDR: this file is a REFERENCE of
-# available names. LDR itself never loads a .env file; it reads only the
-# environment of the server process. To keep your values in a file, hand
-# the file to whatever STARTS LDR rather than to LDR:
+# available names. LDR's own code never loads a .env file into its settings;
+# it reads only the environment of the server process. (Two things can still
+# involve a .env: the bundled slowapi library reads its own RATELIMIT_* keys
+# from a .env in the server's working directory, and LDR looks up the legacy
+# rate-limit storage URL key there the same way, only to report and redact
+# it; and a dependency can put a stray .env's keys into the process
+# environment, see docs/env_configuration.md.) To keep your
+# values in a file, hand the file to whatever STARTS LDR rather than to LDR:
# - docker compose: put them under the service's `environment:` section,
# or point the service's `env_file:` at your copy
# - docker run: pass them with -e NAME=value, or load the whole file
diff --git a/src/local_deep_research/security/network_utils.py b/src/local_deep_research/security/network_utils.py
index f998785a48..4c75dd0c9f 100644
--- a/src/local_deep_research/security/network_utils.py
+++ b/src/local_deep_research/security/network_utils.py
@@ -6,6 +6,69 @@ as private/local vs public. Used for URL normalization and security validation.
import ipaddress
+#: IPv6 transition ranges whose addresses stand for a host beyond a tunnel
+#: relay or translator, never for a peer on this host or LAN. CPython's
+#: ``is_private`` may nonetheless report addresses in 6to4 (``2002::/16``),
+#: Teredo (``2001::/32``, inside the private ``2001::/23`` block) and the
+#: RFC 8215 NAT64 local-use prefix (``64:ff9b:1::/48``) as private on some
+#: Python versions -- including ones wrapping a public IPv4 such as
+#: ``2002:808:808::1`` -- since which ranges ``ipaddress`` treats as
+#: private has changed between releases. The well-known NAT64 prefix
+#: (``64:ff9b::/96``) reads as public. LDR excludes all four ranges on
+#: every version, so the rule does not depend on either behaviour.
+#:
+#: The single definition shared by every PEER-classification decision (who
+#: is talking to this server). It deliberately does not feed
+#: ``is_private_ip``, whose outbound callers (URL normalisation, egress
+#: classification) answer a different question.
+IPV6_TRANSITION_NETWORKS = tuple(
+ ipaddress.ip_network(net)
+ for net in ("2002::/16", "2001::/32", "64:ff9b::/96", "64:ff9b:1::/48")
+)
+
+
+def is_ipv6_transition_address(
+ ip: ipaddress.IPv4Address | ipaddress.IPv6Address,
+) -> bool:
+ """Whether ``ip`` lies in one of ``IPV6_TRANSITION_NETWORKS``."""
+ return ip.version == 6 and any(
+ ip in net for net in IPV6_TRANSITION_NETWORKS
+ )
+
+
+def is_private_peer_ip(host: str) -> bool:
+ """Whether a direct peer address is private/loopback/link-local.
+
+ ``is_private_ip`` for an inbound peer (``request.client.host``), used
+ where the answer confers trust -- e.g. whether that peer may supply
+ ``X-Forwarded-For``. It differs from ``is_private_ip`` only for IP
+ addresses:
+
+ * 6to4, Teredo and NAT64 addresses (``IPV6_TRANSITION_NETWORKS``) are
+ NOT private: such a peer is a remote host arriving through a relay
+ or translator, whatever ``ipaddress`` says.
+ * An IPv4-mapped IPv6 address (``::ffff:a.b.c.d``, how an IPv4 client
+ appears on a dual-stack listener) is judged by the IPv4 address it
+ wraps. CPython's ``ipaddress`` does the same from 3.12.4, but 3.12.0
+ to 3.12.3 answer from their IPv6 table, which lists
+ ``::ffff:0:0/96`` as private, so the unwrap here keeps this trust
+ decision from depending on the interpreter.
+
+ Non-IP strings fall through to ``is_private_ip`` unchanged.
+ """
+ candidate = host
+ if candidate.startswith("[") and candidate.endswith("]"):
+ candidate = candidate[1:-1]
+ try:
+ ip = ipaddress.ip_address(candidate)
+ except ValueError:
+ return is_private_ip(host)
+ if ip.version == 6 and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ if is_ipv6_transition_address(ip):
+ return False
+ return ip.is_private or ip.is_loopback or ip.is_link_local
+
def is_private_ip(hostname: str) -> bool:
"""Check if hostname is a private/local IP address.
diff --git a/src/local_deep_research/settings/env_definitions/server.py b/src/local_deep_research/settings/env_definitions/server.py
index 24298d6832..e1a7fba622 100644
--- a/src/local_deep_research/settings/env_definitions/server.py
+++ b/src/local_deep_research/settings/env_definitions/server.py
@@ -7,6 +7,50 @@ to take effect. They are not editable via the UI.
from ..env_settings import BooleanSetting, IntegerSetting
+TRUSTED_PROXY_COUNT = IntegerSetting(
+ key="server.trusted_proxy_count",
+ description=(
+ "Number of X-Forwarded-For entries your trusted reverse proxies "
+ "append -- one per appending hop for an ordinary proxy, so CDN -> "
+ "nginx is 2. Used by the rate limiter only while "
+ "TRUST_PROXY_HEADERS is NOT set: it then reads the N-th entry from "
+ "the right, provided the direct peer is private/loopback or, once "
+ "a restricted LDR_SERVER_FORWARDED_ALLOW_IPS is set, listed there "
+ "(otherwise it keys on the direct peer). N must be exact: too "
+ "small keys every client on a proxy's address, too large reads an "
+ "entry the client wrote itself (or, when the header is shorter "
+ "than N, keys on the direct peer). Zero (default) disables hop "
+ "counting and keeps the single-proxy behaviour (the right-most "
+ "entry). With TRUST_PROXY_HEADERS=true this value has no effect -- "
+ "list every hop in LDR_SERVER_FORWARDED_ALLOW_IPS instead -- and "
+ "setting it while that allow-list still trusts every peer (the "
+ 'default "*") makes LDR refuse to start. For N >= 2, every '
+ "intermediate hop must be unreachable directly by clients, or a "
+ "client connecting to an inner hop chooses the entry read. Does not "
+ "affect X-Forwarded-Proto/scheme detection. See 'Proxy chains' in "
+ "docs/deployment/reverse-proxy.md. Accepted values are ASCII "
+ "decimal integers from 0 to 16 (surrounding whitespace is ignored "
+ "and -0 reads as 0); an empty or whitespace-only value counts as "
+ "unset, and any other invalid value prevents startup."
+ ),
+ min_value=0,
+ # A real deployment has one or two hops in front of LDR; a CDN plus a
+ # tunnel plus an ingress is three or four. 16 sits far above anything
+ # operationally sensible while still turning a fat-fingered value (a
+ # pasted port number, a year) into a startup failure that names the
+ # variable -- instead of a hop count no X-Forwarded-For chain can
+ # satisfy, which would silently collapse every client behind the proxy
+ # into the direct peer's single rate-limit bucket.
+ max_value=16,
+ default=0,
+ raise_on_validation_error=True,
+ # Reject "1_0" (int() reads that as 10), "+3", and non-ASCII decimal
+ # digits such as "٣": a trust-boundary count must mean what it
+ # looks like.
+ strict_digits=True,
+)
+
+
SERVER_SETTINGS = [
IntegerSetting(
key="server.max_concurrent_research",
@@ -42,4 +86,5 @@ SERVER_SETTINGS = [
),
default=False,
),
+ TRUSTED_PROXY_COUNT,
]
diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.py
index e06ad50a05..a4aa6c397c 100644
--- a/src/local_deep_research/settings/env_settings.py
+++ b/src/local_deep_research/settings/env_settings.py
@@ -21,6 +21,7 @@ to access persisted settings.
"""
import os
+import re
from pathlib import Path
from typing import Any, Dict, Optional, List, Set, TypeVar, Generic
from abc import ABC, abstractmethod
@@ -146,8 +147,34 @@ class StringSetting(EnvSetting[str]):
return raw
+#: Plain ASCII decimal integer, optionally negative. Deliberately NOT what
+#: ``int()`` accepts: ``int`` also takes underscore separators (``"1_0"``
+#: -> 10), a leading ``"+"``, surrounding whitespace, and any Unicode
+#: decimal digit (``"٣"`` -> 3). For a setting that defines a trust
+#: boundary those spellings are a review hazard -- ``"1_0"`` reads as one
+#: hop and means ten -- so ``strict_digits`` settings reject them. The
+#: optional ``-`` is matched (rather than rejected outright) so a negative
+#: value still reaches the ``min_value`` check and gets the specific
+#: "below minimum" range error instead of a generic parse error.
+_STRICT_INTEGER_LITERAL = re.compile(r"-?[0-9]+")
+
+
class IntegerSetting(EnvSetting[int]):
- """Integer environment setting."""
+ """Integer environment setting.
+
+ ``raise_on_validation_error`` makes malformed and out-of-range values
+ propagate instead of falling back through ``SettingsRegistry``.
+
+ ``strict_digits`` restricts accepted spellings to a plain ASCII
+ decimal literal (see ``_STRICT_INTEGER_LITERAL``).
+
+ An empty value is treated as UNSET in every mode: ``LDR_X=""`` falls
+ back to the default rather than failing, because orchestrators
+ (Compose, k8s manifests, Unraid templates) routinely emit an empty
+ string for an unconfigured variable -- the repo-wide contract pinned
+ by ``tests/test_config_env_var_contracts.py::
+ test_empty_env_var_is_treated_as_unset_not_as_false``.
+ """
def __init__(
self,
@@ -157,18 +184,48 @@ class IntegerSetting(EnvSetting[int]):
min_value: Optional[int] = None,
max_value: Optional[int] = None,
deprecated_env_var: Optional[str] = None,
+ raise_on_validation_error: bool = False,
+ strict_digits: bool = False,
):
super().__init__(
- key, description, default, deprecated_env_var=deprecated_env_var
+ key,
+ description,
+ default,
+ deprecated_env_var=deprecated_env_var,
)
self.min_value = min_value
self.max_value = max_value
+ self.raise_on_validation_error = raise_on_validation_error
+ self.strict_digits = strict_digits
def _convert_value(self, raw: str) -> Optional[int]:
"""Convert string to integer with validation."""
- try:
- value = int(raw)
- except ValueError:
+ candidate = raw.strip()
+ if not candidate:
+ logger.warning(
+ f"Empty value for {self.env_var}, treating it as unset and using default: {self.default}"
+ )
+ return self.default
+
+ value: Optional[int] = None
+ parse_error: Optional[ValueError] = None
+ if self.strict_digits and not _STRICT_INTEGER_LITERAL.fullmatch(
+ candidate
+ ):
+ parse_error = ValueError(
+ f"invalid literal for int() with base 10: {raw!r}"
+ )
+ else:
+ try:
+ value = int(candidate)
+ except ValueError as exc:
+ parse_error = exc
+
+ if parse_error is not None:
+ if self.raise_on_validation_error:
+ raise InvalidEnvironmentValueError(
+ self.env_var, raw, expected_type="integer"
+ ) from parse_error
logger.warning(
f"Invalid integer value '{raw}' for {self.env_var}, using default: {self.default}"
)
@@ -332,6 +389,11 @@ class SettingsRegistry:
# Use provided default if setting returns None
return value if value is not None else default
except ValueError:
+ if (
+ isinstance(setting, IntegerSetting)
+ and setting.raise_on_validation_error
+ ):
+ raise
logger.warning(
"Validation error for setting '{}', using default", key
)
diff --git a/src/local_deep_research/settings/exceptions.py b/src/local_deep_research/settings/exceptions.py
index 492da151f0..967b3101d9 100644
--- a/src/local_deep_research/settings/exceptions.py
+++ b/src/local_deep_research/settings/exceptions.py
@@ -43,9 +43,23 @@ class EnvironmentPathNotFoundError(EnvSettingError):
class InvalidEnvironmentValueError(EnvSettingError):
- """Raised when an environment variable value is not among the allowed values."""
+ """Raised when an environment variable value fails its typed validation."""
- def __init__(self, env_var: str, value: str, allowed_values: Sequence):
- super().__init__(
- env_var, f"value '{value}' not in allowed values: {allowed_values}"
- )
+ def __init__(
+ self,
+ env_var: str,
+ value: str,
+ allowed_values: Sequence[str] | None = None,
+ expected_type: str | None = None,
+ ):
+ if expected_type is not None:
+ message = "value '{}' is not a valid {}".format(
+ value, expected_type
+ )
+ elif allowed_values is not None:
+ message = "value '{}' not in allowed values: {}".format(
+ value, allowed_values
+ )
+ else:
+ message = "value '{}' is invalid".format(value)
+ super().__init__(env_var, message)
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index ebf0c8d257..fc3f82b2ab 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -103,6 +103,24 @@ def main():
_run_with_uvicorn(config["host"], config["port"], config["debug"])
+def _normalise_forwarded_allow_ips(raw: str) -> str:
+ """The allow-list string uvicorn is handed for ``raw``.
+
+ TWIN of ``web/dependencies/rate_limit.py``'s
+ ``_normalise_forwarded_allow_ips`` -- duplicated rather than
+ imported because importing that module here would run its
+ import-time startup guard and freeze its view of the allow-list
+ before uvicorn has started, and would pull slowapi/limits and the
+ server config into this launcher. The two are pinned together by
+ tests/security/test_middleware_and_proxy_trust_fastapi.py::
+ TestTrustProxyHeadersUvicornWiring::
+ test_app_and_rate_limit_normalise_identically.
+ """
+ return (
+ ",".join(item.strip() for item in raw.split(",") if item.strip()) or "*"
+ )
+
+
def _run_with_uvicorn(host: str, port: int, debug: bool) -> None:
"""Launch the FastAPI app via uvicorn.
@@ -125,6 +143,39 @@ def _run_with_uvicorn(host: str, port: int, debug: bool) -> None:
"yes",
)
+ # Which direct peers uvicorn's ProxyHeadersMiddleware will trust forwarded
+ # headers from -- passed straight through to uvicorn's own
+ # `--forwarded-allow-ips`. Defaults to "*" (any peer) for backward
+ # compatibility with every deployment that has only ever set
+ # TRUST_PROXY_HEADERS=true.
+ #
+ # This default is exactly what makes TRUST_PROXY_HEADERS=true UNSAFE to
+ # combine with `web/dependencies/rate_limit.py`'s
+ # LDR_SERVER_TRUSTED_PROXY_COUNT hop-count mode: with "*", the middleware
+ # rewrites `scope["client"]` to the client-forgeable left-most
+ # X-Forwarded-For entry for ANY direct connection, not just ones from the
+ # real proxy -- poisoning the hop-count logic's fallback-to-direct-peer
+ # safety net before it ever runs (see rate_limit.py's import-time check).
+ # Restricting this to the actual reverse-proxy IP(s) closes that hole:
+ # uvicorn then only rewrites `scope["client"]` for connections whose
+ # DIRECT peer is one of these addresses, so an attacker connecting
+ # straight to LDR keeps their real socket peer and the rate limiter's
+ # trust boundary stays intact. See "Combining TRUST_PROXY_HEADERS with
+ # LDR_SERVER_TRUSTED_PROXY_COUNT" in docs/deployment/reverse-proxy.md
+ # for the recommended value here.
+ #
+ # Normalised per entry, not as one string: `web/dependencies/
+ # rate_limit.py` classifies the SAME value and names it in the
+ # RuntimeError, the startup warning and the info line it logs, so a
+ # value the two read differently would make every one of those
+ # messages describe an allow-list uvicorn was never handed. `","`
+ # used to arrive here as the literal `","` (one entry matching
+ # nothing, every client in one bucket) while rate_limit.py read it
+ # as unset.
+ forwarded_allow_ips = _normalise_forwarded_allow_ips(
+ os.environ.get("LDR_SERVER_FORWARDED_ALLOW_IPS", "")
+ )
+
uvicorn.run(
"local_deep_research.web.fastapi_app:app",
host=host,
@@ -145,7 +196,7 @@ def _run_with_uvicorn(host: str, port: int, debug: bool) -> None:
# long-running streams (research SSE) and the process never exits.
timeout_graceful_shutdown=10,
proxy_headers=trust_proxy,
- forwarded_allow_ips="*" if trust_proxy else None,
+ forwarded_allow_ips=forwarded_allow_ips if trust_proxy else None,
)
diff --git a/src/local_deep_research/web/dependencies/rate_limit.py b/src/local_deep_research/web/dependencies/rate_limit.py
index dfa0b1e681..175745fcdb 100644
--- a/src/local_deep_research/web/dependencies/rate_limit.py
+++ b/src/local_deep_research/web/dependencies/rate_limit.py
@@ -3,29 +3,122 @@ Rate limiting for FastAPI via slowapi.
Replaces Flask-Limiter. Provides the same rate limit decorators
used by auth routes (login, register, change-password).
+
+Client-IP trust model (see docs/deployment/reverse-proxy.md for the
+operator-facing version):
+
+* ``TRUST_PROXY_HEADERS=true``: uvicorn's ``ProxyHeadersMiddleware``
+ (the outermost ASGI layer) is the authority on ``request.client``
+ when a restricted ``LDR_SERVER_FORWARDED_ALLOW_IPS`` is configured;
+ ``_get_client_ip`` then never re-parses X-Forwarded-For itself. With
+ the legacy unrestricted ``"*"`` it keys on the right-most
+ X-Forwarded-For entry instead of uvicorn's left-most one. Werkzeug's
+ ``ProxyFix`` is NOT installed anywhere in the FastAPI stack. When no X-Forwarded-For header is present at all,
+ uvicorn leaves the raw socket peer in place, so this module falls
+ back to X-Real-IP itself -- gated by
+ ``_peer_may_supply_forwarding_headers`` (allow-list membership when
+ a restricted ``LDR_SERVER_FORWARDED_ALLOW_IPS`` is explicitly
+ configured, private/loopback peer otherwise).
+* ``TRUST_PROXY_HEADERS=false`` + ``LDR_SERVER_TRUSTED_PROXY_COUNT=N``
+ (> 0): hop-count mode -- reads the Nth entry from the right of
+ X-Forwarded-For, port-stripped, gated by the same peer check.
+* ``TRUST_PROXY_HEADERS=false`` + count 0 (default): pre-existing
+ heuristic -- right-most X-Forwarded-For entry / X-Real-IP honoured
+ when the direct peer passes the same check.
+
+Rate-limit VALUES (default/login/registration/...) load from
+``web.server_config.load_server_config()`` (env var > legacy
+server_config.json > built-in default) -- this module deliberately
+still depends on that sibling web module for its configuration.
"""
+import unicodedata
import asyncio
import inspect
import ipaddress
import os
import re
+import sys
from collections.abc import Callable
from contextvars import ContextVar
-from functools import wraps
+from functools import lru_cache, wraps
+from pathlib import Path
from typing import Any
from limits.errors import ConfigurationError
from loguru import logger
from slowapi import Limiter
+from starlette.config import Config as StarletteConfig
from starlette.requests import Request
from starlette.responses import Response
+from ...security.log_sanitizer import redact_secrets
from ..server_config import load_server_config
-from ...security.network_utils import is_private_ip
+from ...security.network_utils import is_private_peer_ip
+from ...settings.env_definitions.server import TRUSTED_PROXY_COUNT
from ...settings.env_registry import is_rate_limiting_enabled
+def _log_startup(level: str, message: str) -> None:
+ """Log one forwarding-trust startup line where the operator sees it.
+
+ ``local_deep_research/__init__.py`` disables the package's loguru
+ namespace, and only ``config_logger()`` enables it again. The
+ ``ldr-web`` launcher calls that before uvicorn imports the app, but
+ an external ASGI server (``uvicorn
+ local_deep_research.web.fastapi_app:app``, gunicorn's
+ ``UvicornWorker``) never does, so there a plain ``logger.warning``
+ from this module's import is dropped without a trace. A temporary
+ loguru handler records whether loguru delivered the line; when it
+ did not, the line goes to stderr instead. Each line is emitted once
+ either way.
+
+ That stderr write is a CodeQL ``py/clear-text-logging-sensitive-data``
+ sink, and the query treats any value held under a name containing
+ "trusted" (or "secret", "password" and the like) as a secret. So
+ ``message`` must never interpolate such a value, directly or through
+ another variable: ``_TRUSTED_PROXY_COUNT`` tripped it, although it
+ only holds a hop count.
+
+ Two limits of the probe, both accepted:
+
+ * "Delivered" means the probe handler saw the record, which happens
+ exactly when the package's namespace is enabled. It does not mean a
+ sink displayed the line: an embedder that enabled the namespace but
+ installed no sink, or only sinks that filter the line out, sees
+ nothing and gets no stderr fallback. ``config_logger()`` installs
+ INFO-level sinks, so ``ldr-web`` shows these lines.
+ * The probe is removed by its id. A bare ``logger.remove()`` (which
+ drops every handler) from another thread between the add and the
+ remove would make the remove raise ``ValueError`` and abort the
+ import. ``config_logger()`` is the only such call on the web
+ start-up path and ``ldr-web`` runs it before the app is imported,
+ so nothing does this today.
+ """
+ delivered: list[str] = []
+ probe = logger.add(
+ delivered.append,
+ level=0,
+ format="{message}",
+ filter=lambda record: (
+ record["function"] == "_log_startup" and record["name"] == __name__
+ ),
+ )
+ try:
+ logger.log(level, message)
+ finally:
+ logger.remove(probe)
+ if delivered or sys.stderr is None:
+ return
+ try:
+ sys.stderr.write(f"{level}:{__name__}:{message}\n")
+ sys.stderr.flush()
+ except (OSError, ValueError):
+ # A closed or broken stderr must not abort the import that is
+ # starting the server; there is nowhere left to report it.
+ pass
+
+
# When the app is reachable over the public internet without a reverse
# proxy, X-Forwarded-For is attacker-controlled and must NOT be trusted.
# Operators behind a real proxy (nginx, caddy, traefik) should set
@@ -41,17 +134,997 @@ _TRUST_PROXY_HEADERS = os.environ.get("TRUST_PROXY_HEADERS", "").lower() in (
"yes",
)
+# Which direct peers uvicorn trusts forwarded headers from when
+# TRUST_PROXY_HEADERS=true -- mirrors `web/app.py`'s `--forwarded-allow-ips`
+# read exactly (same env var, same default, read the same way at import
+# time) so this module's view of the setting matches what uvicorn was
+# actually launched with. Defaults to "*" (any peer), the value web/app.py
+# hard-coded before this variable existed, so every deployment that predates
+# it behaves as before. (That is NOT uvicorn's own default, which is
+# "127.0.0.1" when uvicorn is launched directly.)
+#
+# This is the setting that determines whether TRUST_PROXY_HEADERS=true is
+# safe or exploitable, independent of LDR_SERVER_TRUSTED_PROXY_COUNT below
+# -- see the check immediately following.
+#
+# Empty entries are dropped before anything else looks at the value, so a
+# stray trailing comma cannot turn the wildcard into a "restricted" list
+# that matches nothing: `"*,"` normalises to `"*"` (and therefore trips the
+# unrestricted check below) rather than silently collapsing every client
+# into one bucket while logging a "safe combination" line.
+#
+# `web/app.py`'s `_normalise_forwarded_allow_ips` is the TWIN of the two
+# helpers below and the thing that actually hands uvicorn its
+# `--forwarded-allow-ips`. Both must turn the same raw value into the same
+# string, or every message this module logs describes a different
+# allow-list from the one uvicorn was launched with (`","` used to reach
+# uvicorn verbatim while this module read it as unset). The two are pinned
+# together by tests/security/test_middleware_and_proxy_trust_fastapi.py::
+# TestTrustProxyHeadersUvicornWiring::
+# test_app_and_rate_limit_normalise_identically; they are duplicated rather
+# than shared because `web/app.py` must not import this module before
+# uvicorn starts (importing it runs the startup guard, freezes the
+# allow-list at that moment, and drags slowapi/limits and the server
+# config in with it).
+
+
+def _forwarded_allow_entries(raw: str) -> tuple[str, ...]:
+ """The non-empty, whitespace-stripped entries of ``raw``."""
+ return tuple(item.strip() for item in raw.split(",") if item.strip())
+
+
+def _normalise_forwarded_allow_ips(raw: str) -> str:
+ """The exact allow-list string uvicorn is handed for ``raw``."""
+ return ",".join(_forwarded_allow_entries(raw)) or "*"
+
+
+_FORWARDED_ALLOW_IPS_RAW = os.environ.get("LDR_SERVER_FORWARDED_ALLOW_IPS", "")
+_FORWARDED_ALLOW_ENTRIES_CONFIGURED: tuple[str, ...] = _forwarded_allow_entries(
+ _FORWARDED_ALLOW_IPS_RAW
+)
+_FORWARDED_ALLOW_IPS = _normalise_forwarded_allow_ips(_FORWARDED_ALLOW_IPS_RAW)
+
+# Stronger, explicit alternative to the peer heuristic above: the exact
+# number of trusted reverse-proxy hops that append to X-Forwarded-For
+# (`LDR_SERVER_TRUSTED_PROXY_COUNT`, ported from PR #4870's Flask-side
+# design). Defaults to 0, which is treated as "unset" below, so a
+# deployment that never configures this setting gets byte-identical
+# behaviour to before this setting existed (see the `else` branch of
+# `_get_client_ip`). IntegerSetting reads straight from the environment
+# (no DB/SettingsManager needed, safe at import time) and
+# `raise_on_validation_error=True` makes a malformed, non-numeric,
+# negative or absurdly large value abort startup instead of silently
+# degrading the trust boundary; an EMPTY value is treated as unset (the
+# repo-wide `LDR_X=""` contract, see
+# tests/test_config_env_var_contracts.py::
+# test_empty_env_var_is_treated_as_unset_not_as_false).
+#
+# The raw `os.environ` read next to it is deliberate and not merely
+# duplicated work: it is what makes this import-time read visible to the
+# AST sweeps that pin the port's frozen-at-import configuration
+# (tests/web/test_startup_ordering_contracts.py's `_IMPORT_TIME_CONFIG`
+# and tests/test_config_env_var_contracts.py's `_KNOWN_IMPORT_TIME_READS`,
+# both of which match `os.environ.get`/`os.getenv` call sites and cannot
+# see a typed setting object's `.get_value()`).
+_TRUSTED_PROXY_COUNT_RAW = os.environ.get("LDR_SERVER_TRUSTED_PROXY_COUNT", "")
+_TRUSTED_PROXY_COUNT: int = TRUSTED_PROXY_COUNT.get_value() or 0
+
+# Whether the operator has actually touched either of the two NEW knobs
+# this PR introduces, as opposed to only ever having set the pre-existing
+# `TRUST_PROXY_HEADERS=true` (which predates this PR and is documented on
+# its own). Checked against what the operator actually WROTE rather than
+# the resolved `_FORWARDED_ALLOW_IPS`/`_TRUSTED_PROXY_COUNT` values,
+# because an operator who explicitly writes
+# `LDR_SERVER_FORWARDED_ALLOW_IPS="*"` has made a deliberate (unsafe)
+# choice and must still hard-fail below, even though "*" is also what an
+# *unset* var resolves to. An EMPTY value (`LDR_SERVER_FORWARDED_ALLOW_
+# IPS=""`, which orchestrators such as Compose/k8s emit routinely for an
+# unconfigured variable) contributes no entries and therefore does NOT
+# count as explicitly set -- same `LDR_X=""` means unset contract as the
+# hop count above.
+_FORWARDED_ALLOW_IPS_EXPLICIT = bool(_FORWARDED_ALLOW_ENTRIES_CONFIGURED)
+_PROXY_TRUST_OPTED_IN = (
+ _TRUSTED_PROXY_COUNT > 0 or _FORWARDED_ALLOW_IPS_EXPLICIT
+)
+
+# uvicorn's own trusted-host container, used below to decide -- by uvicorn's
+# semantics rather than by string comparison against the literal "*" --
+# whether the configured allow-list actually restricts anything. It is
+# PRIVATE API (leading underscore): pyproject requires
+# `uvicorn[standard]~=0.34` and pdm.lock resolves 0.54.0, where
+# `_TrustedHosts.__init__(trusted_hosts)` / `.always_trust` /
+# `.trusted_hosts` / `.trusted_networks` all exist, but that pin admits any
+# 0.x, and a RENAME in a future one raises AttributeError or TypeError --
+# not ImportError -- at construction or at attribute-read time. So BOTH the
+# import and every use of the class are guarded with a bare `Exception`,
+# and the failure degrades to `_LocalTrustedHosts` below instead of
+# aborting import with a raw traceback.
+
+
+def _warn_uvicorn_parser_unavailable(detail: str) -> None:
+ """Name the fallback classifier taking over.
+
+ Emitted from exactly one of the two guarded paths per process: if
+ the import failed there is nothing left to construct, and if it
+ succeeded the import never warned.
+ """
+ _log_startup(
+ "WARNING",
+ f"uvicorn's private _TrustedHosts class is unusable ({detail}), so "
+ "LDR cannot classify LDR_SERVER_FORWARDED_ALLOW_IPS with uvicorn's "
+ "own parser. Falling back to LDR's own allow-list parser, which "
+ "fails CLOSED: a list counts as unrestricted only if the whole "
+ 'value is literally "*" or the entries cover a whole address '
+ "family, so an explicitly restricted allow-list STAYS restricted (no "
+ "private/loopback peer silently regains forwarding trust) and "
+ "TRUST_PROXY_HEADERS=true with an exact proxy address still "
+ "starts. Please report this against the uvicorn version in "
+ "pdm.lock.",
+ )
+
+
+# The except branch is reached only by a module reload with the import
+# broken -- see TestUvicornParserFallback in
+# tests/web/dependencies/test_rate_limit_restricted_allow_list.py -- never
+# at real import time, which is what the pragma records.
+try:
+ from uvicorn.middleware.proxy_headers import (
+ _TrustedHosts as _UvicornTrustedHosts,
+ )
+except Exception as exc: # pragma: no cover - TestUvicornParserFallback
+ _UvicornTrustedHosts = None
+ _warn_uvicorn_parser_unavailable(f"import failed: {exc!r}")
+
+
+class _LocalTrustedHosts:
+ """LDR's own parse of an allow-list, shaped like uvicorn's.
+
+ Exposes exactly the three attributes
+ ``_allow_list_covers_whole_families`` and
+ ``_describe_unrestricted_allow_list`` read, parsed the same way
+ ``_peer_in_forwarded_allow_list`` already parses the same entries
+ (``ipaddress``: an entry containing ``/`` is a network, otherwise an
+ address, otherwise an opaque literal). Used only when uvicorn's
+ private class cannot be imported or cannot be used.
+
+ Matches uvicorn's ``always_trust`` exactly: it is the whole
+ (normalised) value being ``"*"``, not any entry spelled ``"*"``.
+ ``"*,*"`` and ``"10.0.0.5,*"`` are therefore restricted here just as
+ they are under uvicorn's own parser -- a stray ``*`` among other
+ entries is neither a network nor a valid address, so it becomes an
+ opaque literal that matches no peer (the existing "matches no peer"
+ warning from ``_warn_about_imprecise_allow_list_entries`` already
+ covers it) rather than silently widening the list.
+ """
+
+ __slots__ = ("always_trust", "trusted_hosts", "trusted_networks")
+
+ def __init__(self, allow_ips: str) -> None:
+ entries = _forwarded_allow_entries(allow_ips)
+ self.always_trust: bool = entries == ("*",)
+ self.trusted_hosts: set = set()
+ self.trusted_networks: set = set()
+ if self.always_trust:
+ return
+ for entry in entries:
+ if "/" in entry:
+ try:
+ self.trusted_networks.add(ipaddress.ip_network(entry))
+ except ValueError:
+ continue
+ else:
+ try:
+ self.trusted_hosts.add(ipaddress.ip_address(entry))
+ except ValueError:
+ continue
+
+
+#: The IPv6 range every IPv4 address is reachable through on a listener
+#: that accepts IPv6 (``8.8.8.8`` arrives as ``::ffff:8.8.8.8``). An entry
+#: spanning it therefore trusts the whole IPv4 family there, even though
+#: 2**32 addresses out of 2**128 never reach the family-coverage sum below.
+_IPV4_MAPPED_RANGE = ipaddress.ip_network("::ffff:0.0.0.0/96")
+
+#: The NAT64 well-known prefix (RFC 6052). Behind a NAT64/SIIT translator an
+#: IPv4 peer reaches an IPv6 listener as ``64:ff9b::<ipv4>``, so a /96 entry
+#: here trusts every IPv4 host coming through the translator -- the same
+#: breadth as ``0.0.0.0/0`` for that path, though only a /96 in IPv6 terms.
+_NAT64_WELL_KNOWN_RANGE = ipaddress.ip_network("64:ff9b::/96")
+
+#: The NAT64 local-use prefix (RFC 8215). An operator carves their own
+#: translator prefix out of it, and every IPv4 host coming through that
+#: translator is embedded under it just as under the well-known /96.
+_NAT64_LOCAL_USE_RANGE = ipaddress.ip_network("64:ff9b:1::/48")
+
+#: Teredo (RFC 4380). The low 32 bits of a Teredo address are its
+#: client's (obfuscated) public IPv4 address, and the 32 bits above them
+#: its port and flags, so a /64 inside this range is one relay server with
+#: every client behind it, not one host.
+_TEREDO_RANGE = ipaddress.ip_network("2001::/32")
+
+#: IPv6 ranges whose addresses stand for IPv4 hosts in their low 32 bits.
+#: An allow-list entry that overlaps any of them -- whether it sits inside
+#: one or contains it -- is judged by the IPv4 breadth limit, not the IPv6
+#: one.
+_IPV4_EMBEDDING_RANGES = (
+ _IPV4_MAPPED_RANGE,
+ _NAT64_WELL_KNOWN_RANGE,
+ _NAT64_LOCAL_USE_RANGE,
+ _TEREDO_RANGE,
+)
+
+
+def _strip_v6_scope(network):
+ """``network`` with its zone/scope id (``%eth0``) discarded.
+
+ ``ipaddress`` compares a scoped ``IPv6Network`` by scope id as well as
+ address range, so ``::ffff:0:0%eth0/96`` is neither equal to nor a
+ superset/subset of the unscoped ``::ffff:0:0/96`` even though they
+ denote the exact same range: a scope id only disambiguates which
+ interface a link-local address is reachable on, it is not part of the
+ address itself, and uvicorn's own matching (``get_trusted_client_address``
+ compares the integer address) ignores it entirely. Family-coverage and
+ mapped-range containment checks must therefore compare the
+ scope-stripped range, or a scoped spelling of an otherwise-covering
+ entry silently evades them.
+ """
+ if network.version != 6 or network.network_address.scope_id is None:
+ return network
+ return ipaddress.IPv6Network(
+ (int(network.network_address), network.prefixlen)
+ )
+
+
+def _family_blocks(trusted, version: int) -> list:
+ """Every entry of ``trusted`` in ``version``, as networks."""
+ blocks = [
+ ipaddress.ip_network(host)
+ for host in trusted.trusted_hosts
+ if host.version == version
+ ]
+ blocks += [
+ network
+ for network in trusted.trusted_networks
+ if network.version == version
+ ]
+ if version == 6:
+ blocks = [_strip_v6_scope(b) for b in blocks]
+ return blocks
+
+
+def _family_is_fully_covered(blocks: list, bits: int) -> bool:
+ """Whether ``blocks`` span every address of a ``bits``-wide family.
+
+ True when any entry is a zero-length prefix OR when the entries,
+ merged, span the whole family -- ``0.0.0.0/1,128.0.0.0/1`` is
+ ``0.0.0.0/0`` written in two pieces and uvicorn treats it
+ identically. Merging with ``collapse_addresses`` first is what makes
+ the sum exact: three overlapping entries such as
+ ``0.0.0.0/1,0.0.0.0/2,64.0.0.0/2`` sum to 2**31 + 2**30 + 2**30 ==
+ 2**32 uncollapsed -- a false "whole family" positive for a
+ configuration that in fact only restricts to ``0.0.0.0/1`` -- while
+ ``collapse_addresses`` merges the three into that single
+ ``0.0.0.0/1`` (2**31 addresses, correctly short of 2**32).
+ """
+ if not blocks:
+ return False
+ if any(network.prefixlen == 0 for network in blocks):
+ return True
+ merged = sum(
+ network.num_addresses
+ for network in ipaddress.collapse_addresses(blocks)
+ )
+ return merged >= 1 << bits
+
+
+def _allow_list_covers_whole_families(trusted) -> tuple[str, ...]:
+ """Address families ``trusted`` trusts in their entirety.
+
+ Returns the canonical CIDR spelling of each fully covered family
+ (``0.0.0.0/0`` / ``::/0``), or an empty tuple.
+
+ IPv4 is also fully covered by any IPv6 entry (or entries) that
+ together span ``::ffff:0.0.0.0/96``: on a listener that accepts
+ IPv6 every IPv4 peer arrives IPv4-mapped, so ``::ffff:0.0.0.0/96``
+ trusts all of them (verified against the real middleware:
+ ``peer="::ffff:8.8.8.8"`` has its forged X-Forwarded-For honoured)
+ while contributing only 2**32 of the 2**128 addresses the IPv6 sum
+ needs. Checked against ``collapse_addresses(v6_blocks)`` rather
+ than each entry alone, so a split pair such as
+ ``::ffff:0.0.0.0/97,::ffff:128.0.0.0/97`` -- two entries, neither
+ of which alone contains the mapped range -- is recognised exactly
+ like the single ``::ffff:0.0.0.0/96`` it merges into. Reported
+ under the covering range's own canonical spelling (``::ffff:0.0.0.0/96``),
+ not the literal entry the operator wrote -- ``::/1``, ``::/80`` and the
+ ``::ffff:0.0.0.0/97,::ffff:128.0.0.0/97`` split pair are all reported as
+ ``::ffff:0.0.0.0/96`` -- and only when ``::/0`` is not already being
+ reported. The RuntimeError this feeds
+ (``_describe_unrestricted_allow_list`` /
+ ``_ALLOW_LIST_UNRESTRICTED_REASON``) separately names the raw configured
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` value verbatim, so an operator sees
+ both: which range made the list unrestricted, and exactly what they set.
+
+ The NAT64 (``64:ff9b::/96``, ``64:ff9b:1::/48``) and Teredo
+ (``2001::/32``) ranges are not counted the same way, although each is
+ as broad as ``0.0.0.0/0`` on its own path: a peer arrives inside one
+ only through a translator or relay in front of LDR, which this module
+ cannot see, never merely by connecting over IPv4. An entry covering
+ one therefore gets the broad-entry warning from
+ ``_warn_about_imprecise_allow_list_entries``, not the startup refusal.
+ """
+ v4_blocks = _family_blocks(trusted, 4)
+ v6_blocks = _family_blocks(trusted, 6)
+ v6_covered = _family_is_fully_covered(v6_blocks, 128)
+
+ covered: list[str] = []
+ if _family_is_fully_covered(v4_blocks, 32):
+ covered.append("0.0.0.0/0")
+ elif not v6_covered and any(
+ _IPV4_MAPPED_RANGE.subnet_of(network)
+ for network in ipaddress.collapse_addresses(v6_blocks)
+ ):
+ covered.append("::ffff:0.0.0.0/96")
+ if v6_covered:
+ covered.append("::/0")
+ return tuple(covered)
+
+
+def _describe_unrestricted_allow_list(allow_ips: str) -> str | None:
+ """Why ``allow_ips`` lets uvicorn trust an entire address family.
+
+ Returns a human-readable reason, or ``None`` when the allow-list
+ genuinely restricts which direct peers uvicorn honours forwarded
+ headers from. This is the SEMANTIC replacement for comparing the
+ configured value against the literal ``"*"``: uvicorn's
+ ``_TrustedHosts.get_trusted_client_address`` returns the LEFT-most
+ (client-forgeable) X-Forwarded-For entry whenever ``always_trust`` is
+ set, and falls through to the same left-most entry when every entry
+ in the chain is trusted -- so ``0.0.0.0/0``, ``::/0``,
+ ``0.0.0.0/0,::/0`` and ``0.0.0.0/1,128.0.0.0/1`` are all exactly as
+ exploitable as ``"*"`` while spelling nothing like it.
+
+ ``::/0`` alone is reported as unrestricted even though uvicorn keeps
+ the raw peer for an IPv4 connection (an ``IPv4Address`` is never
+ ``in`` an IPv6 network). LDR's own listener is NOT dual-stack by
+ default: ``web/server_config.py``'s ``_DEFAULTS`` sets
+ ``"host": "127.0.0.1"``, and binding wider is an explicit opt-in via
+ ``LDR_WEB_HOST=0.0.0.0`` (which the Dockerfile sets) -- both IPv4
+ only. The classification deliberately does not depend on that:
+ wherever the listener DOES accept IPv6 (``LDR_WEB_HOST=::``, an
+ external ASGI server, a v6-capable ingress), ``::/0`` trusts every
+ peer arriving over it, and an operator who wrote it meant
+ "everything". Fail closed rather than ship a trust boundary whose
+ safety depends on the bind address.
+
+ When uvicorn's private class cannot be imported or cannot be used,
+ the same questions are answered from ``_LocalTrustedHosts`` -- LDR's
+ own parse of the same entries -- rather than by declaring every
+ allow-list unrestricted, which fails OPEN in the
+ ``TRUST_PROXY_HEADERS=false`` modes (``_ALLOW_LIST_IS_RESTRICTED``
+ would go silently False and private peers would regain forwarding
+ trust) and refuses to boot the recommended configuration.
+ """
+ if _UvicornTrustedHosts is not None:
+ try:
+ return _classify_allow_list(_UvicornTrustedHosts(allow_ips))
+ except Exception as exc:
+ _warn_uvicorn_parser_unavailable(
+ f"{type(exc).__name__} while classifying {allow_ips!r}: {exc}"
+ )
+ return _classify_allow_list(_LocalTrustedHosts(allow_ips))
+
+
+def _classify_allow_list(trusted) -> str | None:
+ """Why ``trusted`` trusts an entire address family, or ``None``."""
+ if trusted.always_trust:
+ return (
+ '"*" -- uvicorn\'s _TrustedHosts.always_trust shortcut, which '
+ "trusts every direct peer"
+ )
+ covered = _allow_list_covers_whole_families(trusted)
+ if covered:
+ return (
+ "entries covering an entire address family ("
+ + ", ".join(covered)
+ + '), which uvicorn trusts exactly as broadly as "*"'
+ )
+ return None
+
+
+# Whether the resolved allow-list restricts ANYTHING at all, decided once
+# and reused by both consumers (the startup guard below and
+# `_ALLOW_LIST_IS_RESTRICTED`) so the two can never disagree about the
+# same configuration -- the defect that let `0.0.0.0/0` boot while being
+# logged as "a safe combination".
+_ALLOW_LIST_UNRESTRICTED_REASON = _describe_unrestricted_allow_list(
+ _FORWARDED_ALLOW_IPS
+)
+_ALLOW_LIST_IS_UNRESTRICTED = _ALLOW_LIST_UNRESTRICTED_REASON is not None
+
+# Restricted mode: the operator has EXPLICITLY configured
+# LDR_SERVER_FORWARDED_ALLOW_IPS to something that really does restrict
+# which direct peers uvicorn trusts. In this mode the allow-list is the
+# ONLY source of application-level forwarding trust -- a merely-private
+# direct peer outside the list must NOT get to choose its rate-limit
+# bucket via X-Real-IP or a crafted X-Forwarded-For, exactly as
+# docs/deployment/reverse-proxy.md promises for the restricted
+# combination ("an attacker connecting directly to LDR keeps their real
+# raw socket peer"). An explicit "*" -- or any spelling of it, see
+# `_describe_unrestricted_allow_list` -- is treated as unrestricted (it
+# only reaches request handling when TRUST_PROXY_HEADERS is false, since
+# the startup guard below already refuses TRUST_PROXY_HEADERS=true plus
+# an explicit unrestricted list), preserving the documented
+# private/loopback heuristic for legacy configurations.
+_ALLOW_LIST_IS_RESTRICTED = (
+ _FORWARDED_ALLOW_IPS_EXPLICIT and not _ALLOW_LIST_IS_UNRESTRICTED
+)
+
+# Comma-separated entries of the allow-list above (same shapes
+# uvicorn's --forwarded-allow-ips accepts: exact IPs, CIDR networks,
+# and non-IP literals). Parsed once per distinct tuple and cached by
+# _parsed_forwarded_allow_entries, which _peer_in_forwarded_allow_list
+# consults on every lookup.
+_FORWARDED_ALLOW_ENTRIES: tuple[str, ...] = (
+ _FORWARDED_ALLOW_ENTRIES_CONFIGURED if _ALLOW_LIST_IS_RESTRICTED else ()
+)
+
+#: Longest prefix that is still "a few addresses" rather than "a network".
+#: An entry broader than this trusts peers the operator never enumerated:
+#: on a Kubernetes pod CIDR or a Docker bridge subnet, every co-tenant
+#: workload can pick its own rate-limit bucket. uvicorn's semantics, not a
+#: defect -- but the startup line used to call it "a safe combination".
+_BROAD_PREFIX_LIMIT = {4: 24, 6: 64}
+
+
+def _warn_about_imprecise_allow_list_entries(entries: tuple[str, ...]) -> None:
+ """Warn per entry that is not one proxy's exact address.
+
+ Two shapes, both legal for uvicorn and both silently wrong for most
+ deployments. Neither is a hard failure: a pod CIDR is sometimes the
+ only stable identifier an operator has, and a hostname entry is
+ merely useless rather than dangerous.
+
+ * A NETWORK broader than /24 (v4) or /64 (v6). uvicorn trusts every
+ peer inside it, so any co-tenant of that network can send a
+ forged X-Forwarded-For and choose its own bucket. An IPv6 entry
+ that is itself a subnet of ``::ffff:0.0.0.0/96`` is really an
+ IPv4-mapped IPv4 network in disguise (``::ffff:10.0.0.0/104`` is
+ ``10.0.0.0/8`` written for a dual-stack listener), so it is held
+ to the /24 IPv4 limit against its mapped prefix length rather
+ than the /64 IPv6 one -- otherwise a mapped ``/8``-equivalent
+ entry would stay silent for being "only" a /104. The NAT64
+ well-known prefix ``64:ff9b::/96`` and the RFC 8215 local-use
+ prefix ``64:ff9b:1::/48`` embed IPv4 the same way and are judged
+ the same way, as is Teredo ``2001::/32``, whose low 32 bits are
+ each client's (obfuscated) IPv4 address, so a Teredo ``/64`` is
+ one relay server with every client behind it. The test is OVERLAP, not containment: an entry that
+ contains one of these ranges (``64:ff9b::/64``, ``64:ff9b::/95``)
+ trusts every IPv4 host embedded in it -- as broad as ``0.0.0.0/0``
+ on that path -- yet its raw prefix length is not below the /64
+ IPv6 limit, so it would otherwise stay silent. Its effective IPv4
+ prefix length comes out negative and it warns. The embedded IPv4
+ is assumed to occupy the last 32 bits (the well-known prefix's
+ fixed layout, and the usual /96 local-use layout); under a shorter
+ RFC 6052 local-use layout this can only over-warn, never stay
+ silent about an entry that spans a whole translator prefix.
+ * An entry uvicorn parses as an opaque LITERAL -- a hostname
+ (``nginx``), a network with host bits set (``10.0.0.5/8``), a
+ stray ``*`` in a multi-entry list. ``_TrustedHosts`` compares
+ those verbatim against the peer string, which for a TCP
+ connection is always an IP address, so they match no peer: the
+ proxy itself is untrusted and every client behind it collapses
+ into one bucket (availability, not spoofing).
+ """
+ for entry in dict.fromkeys(entries):
+ if "/" in entry:
+ try:
+ network = ipaddress.ip_network(entry)
+ except ValueError:
+ pass
+ else:
+ if network.version == 6 and any(
+ _strip_v6_scope(network).overlaps(embedded)
+ for embedded in _IPV4_EMBEDDING_RANGES
+ ):
+ # A mapped, NAT64-translated or Teredo IPv4 network,
+ # or an entry spanning one of those ranges: judge it by
+ # the IPv4 limit against the prefix length within the
+ # low 32 bits, not the raw (IPv6-scaled) prefix length. An
+ # entry containing a whole range yields a negative
+ # effective length and always warns.
+ effective_prefixlen = network.prefixlen - 96
+ limit = _BROAD_PREFIX_LIMIT[4]
+ else:
+ effective_prefixlen = network.prefixlen
+ limit = _BROAD_PREFIX_LIMIT[network.version]
+ if effective_prefixlen < limit:
+ _log_startup(
+ "WARNING",
+ "LDR_SERVER_FORWARDED_ALLOW_IPS entry "
+ f"{entry!r} trusts every peer inside {network}; "
+ "name the proxy's exact addresses instead. "
+ "uvicorn honours a forwarded client address from "
+ "any direct peer in that range, so anything else "
+ "sharing the network (another container, pod or "
+ "LAN host) can choose its own rate-limit bucket.",
+ )
+ continue
+ else:
+ try:
+ ipaddress.ip_address(entry)
+ except ValueError:
+ pass
+ else:
+ continue
+ _log_startup(
+ "WARNING",
+ f"LDR_SERVER_FORWARDED_ALLOW_IPS entry {entry!r} is neither an "
+ "IP address nor a network, so uvicorn keeps it as an opaque "
+ "literal and it matches no peer; clients behind the proxy "
+ "share one bucket, making the login and registration lockouts "
+ "deployment-global. Use the proxy's resolved IP address(es) "
+ "(a hostname is never compared, a network needs its host bits "
+ "cleared, e.g. 10.0.0.0/8 rather than 10.0.0.5/8).",
+ )
+
+
+if _ALLOW_LIST_IS_RESTRICTED:
+ _warn_about_imprecise_allow_list_entries(_FORWARDED_ALLOW_ENTRIES)
+
+if _TRUST_PROXY_HEADERS:
+ # Whether this is safe hinges entirely on `_FORWARDED_ALLOW_IPS` above,
+ # which controls uvicorn's `--forwarded-allow-ips` (see `web/app.py`).
+ # `TRUST_PROXY_HEADERS=true` makes `web/app.py` launch uvicorn with
+ # `proxy_headers=True`, which installs uvicorn's
+ # ProxyHeadersMiddleware as the OUTERMOST ASGI layer -- wrapping this
+ # entire FastAPI app, so it runs before any code here ever sees the
+ # request. For a direct peer that matches `forwarded_allow_ips`, that
+ # middleware walks X-Forwarded-For from the RIGHT and rewrites
+ # `scope["client"]` to the first entry that is NOT itself one of
+ # `forwarded_allow_ips`'s trusted hosts (uvicorn
+ # `_TrustedHosts.get_trusted_client_address`) -- i.e. it skips over
+ # every entry it recognises as a trusted proxy's own address and
+ # returns the first one it doesn't. For a direct peer that does NOT
+ # match `forwarded_allow_ips`, `scope["client"]` is left completely
+ # alone: it stays the raw socket peer, exactly as if `proxy_headers`
+ # were off.
+ #
+ # With a RESTRICTED allow-list, `_get_client_ip` below trusts
+ # uvicorn's computed `request.client` when `TRUST_PROXY_HEADERS` is
+ # true -- it never re-parses X-Forwarded-For itself in that case,
+ # regardless of `LDR_SERVER_TRUSTED_PROXY_COUNT` (which only takes
+ # effect when `TRUST_PROXY_HEADERS` is false; see `_get_client_ip`).
+ # With the unrestricted "*" it keys on the RIGHT-MOST X-Forwarded-For
+ # entry instead (#6442), which defeats a rotating forged prefix under
+ # an appending proxy but not a client connecting straight to LDR, who
+ # writes the whole header. That is what makes the allow-list below
+ # the ENTIRE trust boundary here:
+ #
+ # * `forwarded_allow_ips == "*"` (the default, unset): EVERY direct
+ # peer matches `forwarded_allow_ips`, so the middleware ALWAYS
+ # takes the "always_trust" shortcut (uvicorn's own
+ # `_TrustedHosts.always_trust`) and returns the LEFT-most
+ # X-Forwarded-For entry verbatim, for ANY request carrying that
+ # header -- including one from an attacker connecting straight to
+ # LDR, and irrespective of hop count. It does not touch
+ # `scope["headers"]`, so it cannot be detected or undone from
+ # here, and the original raw socket peer is gone by the time this
+ # module's `_get_client_ip` runs -- there is no `request.scope`
+ # field left to recover it from. `_get_client_ip` therefore keys
+ # on the RIGHT-most X-Forwarded-For entry in this mode rather
+ # than on `direct_peer`, but an attacker connecting straight to
+ # LDR writes the whole header, right-most entry included, so they
+ # still choose their key outright by sending any X-Forwarded-For
+ # value they like. This is an unconditionally exploitable,
+ # genuinely poisoned configuration.
+ # Whether that is a hard-fail or a warning depends on whether the
+ # operator has actually opted into the NEW knobs this PR adds --
+ # see `_PROXY_TRUST_OPTED_IN` and the tri-state branch below.
+ # * A restricted `forwarded_allow_ips` (the reverse proxy's actual
+ # IP(s)): the middleware only rewrites `scope["client"]` for
+ # connections that arrive directly from that trusted proxy, and it
+ # does so by walking X-Forwarded-For for the first entry it does
+ # NOT recognise as one of those trusted IPs -- so `request.client`
+ # (== `direct_peer` in `_get_client_ip`) is the client address the
+ # listed proxies reported once uvicorn has run (correct as long as
+ # no client connects from a listed address itself), for both
+ # cases: an attacker connecting straight to LDR (bypassing the
+ # proxy) is not in the allow-list, so their raw socket peer is
+ # preserved end to end; a request that actually came through the
+ # trusted proxy chain gets uvicorn's own computed answer.
+ # `_get_client_ip` below takes advantage of this: whenever
+ # `TRUST_PROXY_HEADERS` is true it does NOT hop-count
+ # X-Forwarded-For itself at all -- it keys on `direct_peer`
+ # (validated as an address), because uvicorn has already done the
+ # (more precise, IP-membership-based rather than blind
+ # position-based) equivalent computation as the outermost ASGI
+ # layer. This is the RECOMMENDED way to get both
+ # HTTPS-behind-proxy detection (which only TRUST_PROXY_HEADERS
+ # provides -- see Secure cookies / HSTS / WebSocket same-origin
+ # checks) and correct client-IP resolution at once — permitted,
+ # not hard-failed. IMPORTANT: because uvicorn trusts by IP
+ # membership rather than counting hops,
+ # `LDR_SERVER_FORWARDED_ALLOW_IPS` must list EVERY trusted proxy
+ # hop in a multi-hop chain whose inner hops append (see "Proxy
+ # chains" in docs/deployment/reverse-proxy.md), not just the
+ # nearest one -- otherwise
+ # uvicorn's walk stops one hop too early and returns an
+ # intermediate proxy's own address instead of the true client.
+ # `LDR_SERVER_TRUSTED_PROXY_COUNT`'s own hop-count value is UNUSED
+ # whenever TRUST_PROXY_HEADERS is true, whatever it is set to
+ # (including its default of 0/unset) -- it only takes effect when
+ # TRUST_PROXY_HEADERS is false (see `_get_client_ip`).
+ #
+ # Whether the "*" case above is a hard startup error or only a warning
+ # is gated by `_PROXY_TRUST_OPTED_IN`:
+ #
+ # * The operator has ADOPTED one of the two new knobs this PR adds
+ # (a positive LDR_SERVER_TRUSTED_PROXY_COUNT, or an explicitly-set
+ # LDR_SERVER_FORWARDED_ALLOW_IPS -- including one explicitly set
+ # to "*", a deliberate unsafe choice): they are relying on this
+ # PR's guarantees, so the unconditionally exploitable "*" case
+ # must hard-fail exactly like the module's other trust-boundary
+ # inputs already do (a malformed/negative
+ # LDR_SERVER_TRUSTED_PROXY_COUNT, see TRUSTED_PROXY_COUNT's
+ # raise_on_validation_error=True above) -- fail loudly rather than
+ # rely on an operator noticing a log line.
+ # * The operator has NOT touched either new knob -- i.e. this is a
+ # deployment that only ever set `TRUST_PROXY_HEADERS=true`, the
+ # original, documented opt-in that predates this PR entirely.
+ # Hard-failing THIS case on a plain upgrade would break every such
+ # deployment at import time with no config change on the
+ # operator's part, contradicting this PR's own changelog promise
+ # that "no action is required" for deployments that don't touch
+ # the new variables. Warn instead: `_get_client_ip` below already
+ # makes this configuration no worse than before this PR existed
+ # (see its comment), so it is safe to boot -- merely still
+ # spoofable exactly as far as it always was.
+ #
+ # The restricted-allow-list case (the `else` below) is not exploitable
+ # in the same way (an attacker cannot reach the trusted-peer code path
+ # at all), so it boots normally -- logged, not raised or warned.
+ #
+ # "Trusts every peer" is decided by `_ALLOW_LIST_IS_UNRESTRICTED` --
+ # uvicorn's OWN _TrustedHosts semantics -- not by comparing the
+ # configured string to the literal "*": `0.0.0.0/0`, `::/0`,
+ # `0.0.0.0/0,::/0` and `0.0.0.0/1,128.0.0.0/1` all trust every peer
+ # just as completely, and the same predicate decides
+ # `_ALLOW_LIST_IS_RESTRICTED` above, so the guard and the request-time
+ # trust gate cannot disagree about one configuration.
+ if _ALLOW_LIST_IS_UNRESTRICTED:
+ if _PROXY_TRUST_OPTED_IN:
+ raise RuntimeError(
+ "TRUST_PROXY_HEADERS=true is set together with "
+ "LDR_SERVER_TRUSTED_PROXY_COUNT and/or an explicit "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS, and "
+ f"LDR_SERVER_FORWARDED_ALLOW_IPS={_FORWARDED_ALLOW_IPS!r} "
+ "leaves uvicorn trusting forwarded headers from ANY direct "
+ f"peer: {_ALLOW_LIST_UNRESTRICTED_REASON}. Note that "
+ 'this is NOT only the literal "*" -- a whole-family CIDR '
+ "such as 0.0.0.0/0 or ::/0 (including the two written as "
+ "0.0.0.0/0,::/0, or split into 0.0.0.0/1,128.0.0.0/1) is "
+ "exactly as permissive, because uvicorn returns the "
+ "left-most X-Forwarded-For entry once every hop in the "
+ "chain is trusted. This combination is UNSAFE and LDR "
+ "refuses to "
+ "start, regardless of LDR_SERVER_TRUSTED_PROXY_COUNT "
+ f"(currently {_TRUSTED_PROXY_COUNT}): uvicorn's "
+ "--proxy-headers rewrites the request's client address "
+ "from the left-most (client-forgeable) X-Forwarded-For "
+ "entry before the rate limiter ever sees the request, "
+ "and with an unrestricted allow-list the rate limiter "
+ "keys on an X-Forwarded-For entry the direct peer wrote "
+ "-- which lets a client connecting straight to LDR "
+ "bypass per-IP rate limits by sending a short "
+ "X-Forwarded-For header. Fix by setting "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS to your reverse proxy's "
+ "IP address(es) as LDR sees them (comma-separated; same "
+ "syntax as uvicorn's --forwarded-allow-ips), e.g. "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS=10.0.0.5. With LDR in "
+ "Docker behind a proxy on the host, that is the Docker "
+ "network's gateway address (e.g. 172.17.0.1), not "
+ "127.0.0.1 -- this makes "
+ "uvicorn only rewrite the client address for connections "
+ "that actually came from that proxy, which is safe. If "
+ "LDR is started by an external ASGI server (not "
+ "`ldr-web` / web/app.py) that already passes its own "
+ "restricted --forwarded-allow-ips on the command line, "
+ "set LDR_SERVER_FORWARDED_ALLOW_IPS to that SAME value "
+ "here so this check reflects your actual deployment "
+ "instead of the unrelated default. See 'Combining "
+ "TRUST_PROXY_HEADERS with LDR_SERVER_TRUSTED_PROXY_COUNT' "
+ "in docs/deployment/reverse-proxy.md."
+ )
+ _log_startup(
+ "WARNING",
+ "TRUST_PROXY_HEADERS=true is set with no "
+ "LDR_SERVER_TRUSTED_PROXY_COUNT and no "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS configured -- LDR will start, "
+ "but this is a SPOOFABLE configuration: uvicorn's "
+ "--proxy-headers is launched with --forwarded-allow-ips=* (the "
+ "default), so it trusts the left-most (client-forgeable) "
+ "X-Forwarded-For entry from ANY direct peer, including an "
+ "attacker connecting straight to LDR without going through "
+ "your reverse proxy at all -- letting them choose the "
+ "rate-limit key on every request and bypass per-IP login/"
+ "register lockouts. This is the SAME exposure this "
+ "configuration has always had; this version does not make it "
+ "worse. BREAKING CHANGE in this release, though: X-Real-IP is "
+ "now honoured only from a private, loopback or link-local "
+ "direct peer (before this release, from any peer). It is the "
+ "fallback used when a request carries no X-Forwarded-For at "
+ "all, as from an nginx that sets only "
+ "`proxy_set_header X-Real-IP $remote_addr`. So if your proxy "
+ "reaches LDR from a public or carrier-grade-NAT address (a "
+ "cloud load balancer, a Tailscale/CGNAT peer in "
+ "100.64.0.0/10, a public nginx host) and sends X-Real-IP "
+ "without X-Forwarded-For, its X-Real-IP is now IGNORED and "
+ "every client behind it shares ONE rate-limit bucket -- which "
+ "makes the login and registration lockouts deployment-global. "
+ "To restore per-client keying, set "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS to that proxy's IP address as "
+ "LDR sees it. That also closes the spoofing exposure above: "
+ "set it to your reverse proxy's IP address(es), e.g. "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS=10.0.0.5 (with LDR in Docker "
+ "behind a proxy on the host, the Docker network's gateway "
+ "address such as 172.17.0.1, not 127.0.0.1: listing an "
+ "address the proxy does not connect from makes uvicorn and "
+ "the rate limiter ignore its headers, so every client shares "
+ "one rate-limit bucket). Either way a single "
+ "proxy must OVERWRITE X-Forwarded-For with the address it "
+ "observed (nginx: proxy_set_header X-Forwarded-For "
+ "$remote_addr), and X-Real-IP likewise, never pass a "
+ "client-sent value through: an unchanged client header lets "
+ "that client choose its key, and an appended one leaves the "
+ "client's own entries on the left, which uvicorn reports as "
+ "the client address while LDR_SERVER_FORWARDED_ALLOW_IPS is "
+ "unset. Behind a chain of proxies (CDN -> nginx) that setup keys "
+ "every client on the outer proxy's address, so all clients "
+ "share one rate-limit bucket, unless the inner proxy resolves "
+ "the real client itself (nginx realip) and overwrites with it, "
+ "or every inner proxy appends and every hop is listed in "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS -- see 'Proxy chains' in "
+ "docs/deployment/reverse-proxy.md.",
+ )
+ else:
+ _log_startup(
+ "INFO",
+ "TRUST_PROXY_HEADERS=true is set, with "
+ f"LDR_SERVER_FORWARDED_ALLOW_IPS={_FORWARDED_ALLOW_IPS!r} "
+ "restricting which direct peers uvicorn trusts. This is the "
+ "recommended combination, and it is safe exactly to the "
+ "extent that every entry above is one proxy's exact address "
+ "-- each entry is a peer allowed to choose a client's "
+ "rate-limit bucket, so a network entry extends that to "
+ "everything inside it (warned about separately above). "
+ "uvicorn computes the client address "
+ "itself, as the outermost ASGI layer, before this module "
+ "ever sees the request -- so _get_client_ip trusts "
+ "request.client directly in this mode instead of "
+ "re-deriving it from X-Forwarded-For, and "
+ "LDR_SERVER_TRUSTED_PROXY_COUNT's own hop-count logic does "
+ "not run (whatever it is set to has no effect while "
+ "TRUST_PROXY_HEADERS is true). Behind a chain "
+ "of proxies whose inner hops append, "
+ "LDR_SERVER_FORWARDED_ALLOW_IPS must list EVERY hop, not just "
+ "the nearest one -- uvicorn trusts by IP membership, not hop "
+ "count, so an incomplete list makes it stop its walk one hop "
+ "too early (see 'Proxy chains' in "
+ "docs/deployment/reverse-proxy.md).",
+ )
+
def _is_trusted_peer(host: str) -> bool:
"""Whether to trust X-Forwarded-For from this direct peer.
Trusted peers: private/loopback IPs and Starlette TestClient's
"testclient" sentinel (lets the test suite use unique IPs to avoid
- sharing rate-limit buckets across modules).
+ sharing rate-limit buckets across modules). 6to4, Teredo and NAT64
+ peers are NOT trusted, on any Python version, although Python's
+ ``is_private`` may report them private on some versions: they are remote hosts arriving through a tunnel relay or
+ translator (see ``network_utils.is_private_peer_ip``).
+
+ This is the UNRESTRICTED-mode heuristic: it applies whenever no
+ restricted LDR_SERVER_FORWARDED_ALLOW_IPS is explicitly configured.
+ Restricted mode uses _peer_may_supply_forwarding_headers instead,
+ which consults the allow-list alone.
"""
if host == "testclient":
return True
- return is_private_ip(host)
+ return is_private_peer_ip(host)
+
+
+@lru_cache(maxsize=8)
+def _parsed_forwarded_allow_entries(entries: tuple[str, ...]) -> tuple:
+ """``entries`` parsed once, not on every request.
+
+ Networks for ``/`` entries, addresses for the rest; an entry that
+ parses as neither is dropped here (it can only ever match verbatim,
+ which the caller checks for a non-IP host). Keyed on the tuple itself,
+ so a reassigned ``_FORWARDED_ALLOW_ENTRIES`` is re-parsed.
+ """
+ parsed: list = []
+ for entry in entries:
+ try:
+ parsed.append(
+ ipaddress.ip_network(entry)
+ if "/" in entry
+ else ipaddress.ip_address(entry)
+ )
+ except ValueError:
+ continue
+ return tuple(parsed)
+
+
+def _peer_in_forwarded_allow_list(host: str) -> bool:
+ """Whether ``host`` matches the configured allow-list.
+
+ Mirrors uvicorn's ``_TrustedHosts`` membership semantics
+ (uvicorn/middleware/proxy_headers.py): compare by parsed IP address
+ so IPv6's many spellings agree, honour CIDR network entries, and
+ compare non-IP literals verbatim. Only meaningful when
+ ``_ALLOW_LIST_IS_RESTRICTED`` is true.
+ """
+ try:
+ ip = ipaddress.ip_address(host)
+ except ValueError:
+ return host in _FORWARDED_ALLOW_ENTRIES
+ for trusted in _parsed_forwarded_allow_entries(_FORWARDED_ALLOW_ENTRIES):
+ if isinstance(trusted, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
+ if ip in trusted:
+ return True
+ elif ip == trusted:
+ return True
+ return False
+
+
+def _peer_may_supply_forwarding_headers(host: str) -> bool:
+ """Whether this direct peer's forwarding headers may be trusted.
+
+ Application-level gate for every trust decision ``_get_client_ip``
+ makes on its own (the X-Real-IP fallback, hop-count mode's direct-
+ peer check, and the default right-most heuristic):
+
+ * Restricted mode (an explicit LDR_SERVER_FORWARDED_ALLOW_IPS other
+ than "*"): the allow-list is the ONLY source of forwarding
+ trust. Private-ness alone must not confer trust here -- a peer on
+ the same private network as LDR but outside the allow-list is
+ exactly the direct-connecting client the restricted
+ configuration exists to defend against, so it keeps its raw
+ socket peer as its rate-limit key no matter what spoofed
+ forwarding header it sends.
+ * Otherwise (allow-list unset, or explicitly "*"): the pre-existing
+ private/loopback heuristic (``_is_trusted_peer``) applies,
+ unchanged.
+
+ The "testclient" sentinel stays trusted in both modes so the test
+ suite can hand out unique IPs (it never appears as a real network
+ peer).
+ """
+ if host == "testclient":
+ return True
+ if _ALLOW_LIST_IS_RESTRICTED:
+ return _peer_in_forwarded_allow_list(host)
+ return _is_trusted_peer(host)
+
+
+def _strip_forwarded_port(entry: str) -> str:
+ """Strip an observed source port from a forwarded address entry.
+
+ X-Forwarded-For entries may legitimately carry the port the
+ appending proxy observed (``address:port``), and uvicorn's own
+ forwarded parser normalises that form away before the address
+ reaches ``scope["client"]``. Rate-limit keys must do the same, or a
+ proxy that appends the observed address WITH its TCP source port
+ hands the same client a DIFFERENT bucket on every connection --
+ connection churn alone would replenish per-IP quotas.
+
+ Mirrors uvicorn's ``_parse_host_port``
+ (uvicorn/middleware/proxy_headers.py) exactly, including its
+ conservative treatment of malformed values -- anything unparseable
+ is returned unchanged so trust checks never silently normalise
+ arbitrary input:
+
+ * ``198.51.100.20:41000`` -> ``198.51.100.20`` (bare IPv4 + port)
+ * ``[2001:db8::1]:443`` -> ``2001:db8::1`` (bracketed IPv6 + port;
+ the brackets are dropped, as uvicorn drops them)
+ * ``2001:db8::1`` -> unchanged (bare IPv6 has multiple colons and
+ is never treated as host:port)
+ * ``198.51.100.20:notaport`` -> unchanged (uvicorn keeps the raw
+ value when the IPv4 port does not parse)
+ """
+ if entry.startswith("["):
+ bracket_end = entry.find("]")
+ if bracket_end == -1:
+ return entry
+ host = entry[1:bracket_end]
+ remainder = entry[bracket_end + 1 :]
+ if not remainder:
+ return host
+ if not remainder.startswith(":"):
+ return entry
+ try:
+ int(remainder[1:])
+ except ValueError:
+ return host
+ return host
+ if entry.count(":") == 1:
+ host, port = entry.rsplit(":", 1)
+ try:
+ int(port)
+ except ValueError:
+ return entry
+ return host
+ return entry
+
+
+def _select_trusted_hop(header_value: str, hop_count: int) -> str | None:
+ """Return the address appended by the outermost trusted proxy.
+
+ Mirrors Werkzeug's ``ProxyFix`` hop-counting: with ``hop_count``
+ trusted proxies each appending their peer's address, the value the
+ *first* trusted proxy saw is the ``hop_count``-th entry counting from
+ the right (index ``-hop_count``) -- never the raw first (leftmost)
+ entry. That position is always attacker-controlled: a client can
+ prepend arbitrary fake entries to its own X-Forwarded-For header
+ before the first trusted hop ever sees the request. Returns ``None``
+ if the header has fewer entries than the configured hop count (a
+ missing or under-filled chain), so the caller falls back to the
+ direct socket peer instead of trusting a short, ambiguous list.
+
+ The selected entry is normalised through ``_strip_forwarded_port``
+ before being returned, so an appending proxy that includes the
+ observed source port (``address:port``, a form uvicorn's own
+ forwarded parser accepts) still keys the client by address alone --
+ a fresh TCP source port per connection must not mint a fresh
+ rate-limit bucket.
+
+ Caveat for ``hop_count >= 2`` (mirrors Werkzeug ``ProxyFix``'s
+ documented limitation): this only verifies that the DIRECT peer is
+ trusted -- it has no way to verify that every hop in between is also
+ unreachable directly. If an attacker can connect straight to an
+ INTERMEDIATE proxy in the chain (skipping the outer hops), that
+ proxy appends the attacker's real address at its own position, and
+ the attacker fully controls every entry to the left of it -- which
+ can include the position this function reads. Trusting a hop count
+ > 1 is only sound when EVERY intermediate hop, not just the
+ outermost one, is unreachable except from the hop immediately in
+ front of it (e.g. firewalled to that peer only). See "Every hop must
+ be unreachable directly" under "Proxy chains" in
+ docs/deployment/reverse-proxy.md.
+ """
+ entries = [
+ entry.strip() for entry in header_value.split(",") if entry.strip()
+ ]
+ if hop_count <= 0 or len(entries) < hop_count:
+ return None
+ return _strip_forwarded_port(entries[-hop_count])
+
+
+def _get_forwarded_for(request: Request) -> str:
+ """Join every X-Forwarded-For header line into one comma-separated value.
+
+ Starlette's ``Headers.get()`` returns only the FIRST matching header
+ line. A proxy chain that APPENDS its own X-Forwarded-For line rather
+ than editing the existing one (e.g. HAProxy's ``option forwardfor``
+ without ``if-none``, or the multi-hop CDN/tunnel setups this module's
+ docs bless) produces a request with MULTIPLE X-Forwarded-For header
+ lines -- the client's own forged line first, the proxy-appended line
+ after. ``.get()`` would silently hand hop-counting the client's fully
+ attacker-controlled first line and never see the proxy-appended one,
+ letting a forged entry become the rate-limit key even under a
+ trusted-hop-count >= 1. WSGI-based stacks (Werkzeug's ``ProxyFix``
+ included) never see this ambiguity: the WSGI spec requires the server
+ to comma-join repeated header lines into a single
+ ``HTTP_X_FORWARDED_FOR`` value before handing it to the app. Do the
+ same here explicitly via ``getlist`` so ASGI/Starlette's per-line
+ header model doesn't silently drop the proxy-appended lines.
+ """
+ return ",".join(
+ value
+ for value in request.headers.getlist("x-forwarded-for")
+ if value.strip()
+ )
_PORT_RE = re.compile(r"[0-9]{1,5}")
@@ -95,27 +1168,122 @@ _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.
+ """Get client IP, respecting X-Forwarded-For ONLY when trusted.
Without this guard, slowapi's per-IP rate limit can be bypassed by
sending X-Forwarded-For: <random> on every request.
+ Which trust model applies depends FIRST on ``TRUST_PROXY_HEADERS``,
+ independent of ``LDR_SERVER_TRUSTED_PROXY_COUNT``:
+
+ - ``TRUST_PROXY_HEADERS=true`` (the startup guard above hard-fails
+ this only when the operator has ALSO opted into
+ ``LDR_SERVER_TRUSTED_PROXY_COUNT`` or an explicit
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` while the latter still resolves
+ to "*"; a legacy deployment that sets only
+ ``TRUST_PROXY_HEADERS=true`` boots with a warning instead -- see
+ the guard's comment above): uvicorn's ``ProxyHeadersMiddleware``
+ runs as the outermost ASGI layer, before this function ever sees
+ the request, and already computed ``request.client``. With a
+ RESTRICTED ``LDR_SERVER_FORWARDED_ALLOW_IPS`` that is correct, by
+ walking X-Forwarded-For for the first entry that is not itself one
+ of the allow-list's trusted hosts, and leaving it untouched (the
+ raw socket peer) for a direct peer outside that allow-list. At the
+ default ``LDR_SERVER_FORWARDED_ALLOW_IPS="*"`` (the legacy,
+ warned-about case) uvicorn instead ALWAYS rewrites
+ ``request.client`` from the left-most (spoofable)
+ X-Forwarded-For entry, so in that case this function re-reads the
+ header and keys on its RIGHT-MOST entry -- the one the nearest
+ proxy added (#6442) -- exactly as the ``TRUST_PROXY_HEADERS=false``
+ heuristic below does. With a RESTRICTED allow-list this function
+ does NOT re-parse X-Forwarded-For, AT ANY
+ ``LDR_SERVER_TRUSTED_PROXY_COUNT`` VALUE (including its default of
+ 0/unset) -- doing so would only let a direct-connecting attacker
+ reintroduce a forged entry uvicorn had no reason to trust. It
+ simply trusts ``direct_peer`` whenever an X-Forwarded-For header
+ was present at all (uvicorn has then already had its say, one way
+ or the other -- see the startup guard's comment above for its
+ exact algorithm). ``LDR_SERVER_TRUSTED_PROXY_COUNT``'s hop-counting
+ logic below never runs while this is true.
+
+ X-Real-IP fallback: uvicorn's ``ProxyHeadersMiddleware`` ONLY ever
+ inspects X-Forwarded-For -- it has no knowledge of X-Real-IP and
+ never rewrites ``scope["client"]`` because of it. So when a
+ request carries NO X-Forwarded-For header at all, uvicorn had
+ nothing to rewrite from and ``direct_peer`` is still the raw
+ socket peer, exactly as if ``TRUST_PROXY_HEADERS`` were false. A
+ reverse proxy configured with only
+ ``proxy_set_header X-Real-IP $remote_addr`` (a common nginx
+ pattern) never sends X-Forwarded-For, so without a fallback here
+ every client behind such a proxy would collapse into ONE shared
+ rate-limit bucket -- turning the login/registration limits into a
+ global lockout switch reachable by any visitor. This function
+ restores that fallback, gated the way the hop-count and
+ heuristic branches below gate X-Forwarded-For: only when
+ ``direct_peer`` passes ``_peer_may_supply_forwarding_headers``
+ -- allow-list membership when a restricted
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` is explicitly configured,
+ private/loopback (or the testclient sentinel) otherwise. With a
+ restricted allow-list an unlisted direct peer -- an attacker
+ connecting straight to LDR, including a merely-PRIVATE one --
+ must not be able to pick its own rate-limit bucket by sending an
+ arbitrary X-Real-IP; since uvicorn does not gate X-Real-IP for us
+ the way it gates X-Forwarded-For, this function is the ONLY thing
+ standing between that header and the rate limiter. With the
+ legacy unrestricted ``"*"`` the gate protects nothing a direct
+ peer could not do anyway -- that mode reads X-Forwarded-For from
+ every peer, so it can still choose its key with that -- and its
+ only effect is the deliberate breaking change recorded in
+ docs/deployment/reverse-proxy.md (the previous release honoured
+ X-Real-IP from any peer): a proxy on a public or
+ carrier-grade-NAT address that sends X-Real-IP without
+ X-Forwarded-For is keyed on its own address, ONE shared bucket,
+ until ``LDR_SERVER_FORWARDED_ALLOW_IPS`` is set to that proxy's
+ address.
+ - ``TRUST_PROXY_HEADERS=false`` and ``LDR_SERVER_TRUSTED_PROXY_COUNT``
+ > 0, AND the direct peer passes
+ ``_peer_may_supply_forwarding_headers`` (allow-list membership
+ when a restricted LDR_SERVER_FORWARDED_ALLOW_IPS is explicitly
+ configured; private/loopback or the testclient sentinel
+ otherwise): LDR sees the RAW socket peer (uvicorn's
+ proxy-headers middleware is not installed), so the operator has
+ declared exactly how many trusted proxy hops sit in front of LDR
+ and this function does its own hop-counting: it reads the
+ corresponding hop's entry from the right of X-Forwarded-For --
+ port-stripped, never the spoofable leftmost entry. Declaring a
+ hop count is not,
+ by itself, authorisation to trust whoever is directly connected --
+ an untrusted direct peer still gets ``direct_peer`` back regardless
+ of what its X-Forwarded-For says.
+ - ``TRUST_PROXY_HEADERS=false`` and ``LDR_SERVER_TRUSTED_PROXY_COUNT
+ == 0`` (the default): the pre-existing heuristic applies instead:
+ trust the right-most X-Forwarded-For entry (#6442), else
+ X-Real-IP, when the direct peer passes the same
+ ``_peer_may_supply_forwarding_headers`` gate (private/loopback
+ when no restricted allow-list is explicitly configured). Unchanged
+ from before the hop-count setting existed, so deployments that
+ never configure either setting see identical behaviour.
+
+ In every mode a forwarded value that is not an IP address (empty, a
+ hostname, free text), and a direct peer that is not one, keys on a
+ fixed fallback rather than on client-chosen text (#6442).
+
Note: the env var is `TRUST_PROXY_HEADERS`, not `LDR_TRUST_PROXY_HEADERS`
— 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.
+ # is off, or while it is on but the request carries no X-Forwarded-For.
+ # When the flag is on and the header is present, uvicorn's
+ # ProxyHeaders middleware has already rewritten ``request.client.host``
+ # (the real peer is no longer visible in the scope): with a RESTRICTED
+ # LDR_SERVER_FORWARDED_ALLOW_IPS to the first entry, from the right,
+ # that is not a listed address (or left it as the raw peer for a peer
+ # outside the list), but
+ # with the legacy unrestricted ``"*"`` to the LEFT-MOST X-Forwarded-For
+ # entry, which under an appending proxy is client-chosen. The
+ # unrestricted case therefore re-reads the header below and keys on
+ # its RIGHT-MOST entry (#6442).
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
@@ -130,14 +1298,140 @@ def _get_client_ip(request: Request) -> str:
else:
fallback = _UNPARSEABLE_PEER_KEY
- trust = _TRUST_PROXY_HEADERS or _is_trusted_peer(direct_peer)
- if trust:
- # 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 _TRUST_PROXY_HEADERS:
+ forwarded = _get_forwarded_for(request)
+ if forwarded:
+ if _ALLOW_LIST_IS_RESTRICTED:
+ # RESTRICTED allow-list: uvicorn's ProxyHeadersMiddleware --
+ # the OUTERMOST ASGI layer, already run by the time this
+ # function sees the request -- is the authority on the
+ # client address. For a direct peer in
+ # LDR_SERVER_FORWARDED_ALLOW_IPS it rewrote request.client to
+ # the first X-Forwarded-For entry, walking from the right,
+ # that is not itself a listed address (the left-most entry
+ # when every one is listed); for a direct peer outside it (an
+ # attacker connecting straight to LDR) it left request.client
+ # as that attacker's raw socket peer, which is the correct
+ # answer. uvicorn verifies only that the DIRECT peer is
+ # listed, not what that peer wrote: a client that itself
+ # connects from a listed address (the proxy host, or inside
+ # a network entry) still chooses its key. Do NOT re-parse
+ # X-Forwarded-For here, at any LDR_SERVER_TRUSTED_PROXY_COUNT
+ # (including its default of 0/unset): re-parsing would let a
+ # direct-connecting attacker reintroduce a forged entry
+ # uvicorn had no reason to trust, and for a trusted multi-hop
+ # chain would disagree with uvicorn's more precise walk. See
+ # the startup guard's comment above for uvicorn's exact
+ # algorithm. ``fallback`` is ``direct_peer`` whenever that is
+ # an address.
+ return fallback
+ # Unrestricted allow-list (the legacy, warned-about "*" -- the
+ # startup guard refuses it whenever the operator opted into
+ # either new knob): uvicorn has already rewritten request.client
+ # from the LEFT-MOST, client-forgeable entry, so ``direct_peer``
+ # carries no information uvicorn verified. Key on the RIGHT-MOST
+ # entry instead -- the one added by the nearest proxy (#6442).
+ # 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 the left-most entry would
+ # let a rotating forged prefix mint a fresh rate-limit bucket
+ # per request (#5787). This does not make the configuration
+ # safe against a client connecting straight to LDR -- such a
+ # client writes the whole header -- which is what the startup
+ # warning is about. A trailing comma, a whitespace-only value or
+ # a non-address entry keys on the fallback (an empty key makes
+ # slowapi skip the limit, and free text would be an unbounded
+ # key that is also written to the 429 audit log).
+ return _forwarded_address(forwarded.rsplit(",", 1)[-1]) or fallback
+
+ # No X-Forwarded-For at all: uvicorn's ProxyHeadersMiddleware had
+ # nothing to rewrite scope["client"] from (see the `if
+ # x_forwarded_for_values:` guard in its source -- it never even
+ # looks at X-Real-IP), so `direct_peer` above is still the RAW
+ # socket peer, exactly as when TRUST_PROXY_HEADERS is false. A
+ # reverse proxy set up with only
+ # `proxy_set_header X-Real-IP $remote_addr` (a common nginx
+ # pattern) never sends X-Forwarded-For, so stopping here would
+ # collapse every client behind such a proxy into ONE rate-limit
+ # bucket -- keep main's pre-PR X-Real-IP fallback to avoid that.
+ # Unlike main, which trusted it unconditionally whenever
+ # TRUST_PROXY_HEADERS was true, gate it here with
+ # _peer_may_supply_forwarding_headers -- the same gate this
+ # module uses for X-Forwarded-For everywhere else it hop-counts
+ # or heuristically trusts a header: allow-list membership when a
+ # restricted LDR_SERVER_FORWARDED_ALLOW_IPS is explicitly
+ # configured, private/loopback (or the testclient sentinel)
+ # otherwise. uvicorn provides no equivalent guard for X-Real-IP
+ # -- unlike X-Forwarded-For, an untrusted direct peer's X-Real-IP
+ # reaches this function completely unfiltered. In restricted mode
+ # this check is what keeps an unlisted peer from choosing its own
+ # rate-limit bucket with an arbitrary X-Real-IP: the allow-list
+ # alone decides, and a merely-private peer outside the list keeps
+ # its raw socket peer as its key. With the legacy unrestricted
+ # "*" it protects nothing a direct peer could not do anyway (that
+ # mode reads X-Forwarded-For from every peer, so a direct peer
+ # still chooses its key with it, as the startup warning says);
+ # there it only stops a public or carrier-grade-NAT peer's
+ # X-Real-IP from counting, the breaking change documented in
+ # docs/deployment/reverse-proxy.md; naming that proxy in
+ # LDR_SERVER_FORWARDED_ALLOW_IPS undoes it.
+ # The value is parsed like the heuristic branch's X-Real-IP below.
+ if _peer_may_supply_forwarding_headers(direct_peer):
+ real_ip = request.headers.get("x-real-ip")
+ if real_ip:
+ return _forwarded_address(real_ip) or fallback
+ return fallback
+
+ if _TRUSTED_PROXY_COUNT > 0:
+ # TRUST_PROXY_HEADERS is false: LDR sees the raw socket peer (no
+ # uvicorn header rewriting happens), so a declared hop count is
+ # not, on its own, permission to trust X-Forwarded-For: it only
+ # says how many entries to count from the right IF the request
+ # actually arrived through that trusted proxy chain. A client
+ # that reaches this process directly (bypassing the proxy
+ # entirely -- e.g. the origin is also reachable on a secondary
+ # interface/port) is not behind ANY proxy hop, so nothing has
+ # verified its X-Forwarded-For. Without this check, such a
+ # client could send a crafted header with >= count entries and
+ # have entries[-count] (fully attacker-controlled) trusted as
+ # its identity, spoofing the rate-limit key. The gate is
+ # _peer_may_supply_forwarding_headers: allow-list membership
+ # when a restricted LDR_SERVER_FORWARDED_ALLOW_IPS is explicitly
+ # configured, private/loopback otherwise -- a merely-private
+ # peer outside an explicit allow-list is a direct-connecting
+ # client the restricted configuration exists to defend against.
+ if _peer_may_supply_forwarding_headers(direct_peer):
+ forwarded = _get_forwarded_for(request)
+ if forwarded:
+ trusted_hop = _select_trusted_hop(
+ forwarded, _TRUSTED_PROXY_COUNT
+ )
+ if trusted_hop is not None:
+ # The selected hop must still be an address: a
+ # non-address entry would be a free-text key that is
+ # also written to the 429 audit log (#6442).
+ return _forwarded_address(trusted_hop) or fallback
+ # Header missing, empty, or shorter than the configured hop
+ # count: do NOT fall back to an untrustworthy entry. Keep the
+ # direct peer (the nearest proxy's own address) as the
+ # identity -- this collapses clients behind that proxy into
+ # one bucket, which is safe (if operationally noisy) rather
+ # than exploitable.
+ return fallback
+ # Direct peer is untrusted: the connection did not come through
+ # the declared proxy chain at all, so X-Forwarded-For is
+ # attacker-controlled. The direct connection IS the client.
+ return fallback
+
+ # TRUST_PROXY_HEADERS is false and LDR_SERVER_TRUSTED_PROXY_COUNT is
+ # 0/unset: the pre-existing heuristic (right-most entry, #6442) --
+ # except that a RESTRICTED, explicitly configured allow-list overrides
+ # the private/loopback peer check (see
+ # _peer_may_supply_forwarding_headers).
+ if _peer_may_supply_forwarding_headers(direct_peer):
+ forwarded = _get_forwarded_for(request)
if forwarded:
# Take the RIGHT-MOST entry: the one added by the nearest
# (trusted) proxy. The documented nginx config overwrites the
@@ -147,9 +1441,14 @@ def _get_client_ip(request: Request) -> str:
# 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.
+ # is supported here: behind a chain (CDN -> nginx) the
+ # right-most entry is the outer hop's address unless the inner
+ # proxy overwrites the header with the client address it
+ # resolved itself (nginx's realip module trusting the outer
+ # hop makes $remote_addr that address; without realip it is
+ # the outer hop's). Appending chains need
+ # LDR_SERVER_TRUSTED_PROXY_COUNT (above) instead -- see "Proxy
+ # chains" in docs/deployment/reverse-proxy.md.
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
@@ -206,20 +1505,158 @@ if not _RATE_LIMITING_ENABLED:
# https://limits.readthedocs.io/en/stable/storage.html for options.
_RATE_LIMIT_STORAGE_URI = os.environ.get("RATE_LIMIT_STORAGE_URI", "").strip()
-# slowapi reads the Flask-Limiter-era name itself, straight from the
-# environment: `Limiter.__init__` falls back to
+# slowapi reads the Flask-Limiter-era name itself, from the environment
+# or, failing that, from a `.env` file in the working directory:
+# `Limiter.__init__` builds `starlette.config.Config(".env")` when
+# `os.path.isfile(".env")` and falls back to
# `get_app_config(C.STORAGE_URL, "memory://")` where `C.STORAGE_URL` is
-# "RATELIMIT_STORAGE_URL" (slowapi/extension.py:49,244). That is the name
-# `main` documented, so it is the only one an existing deployment will
-# have set — and it keeps working here, silently, without ever appearing
-# in `_limiter_kwargs`.
+# "RATELIMIT_STORAGE_URL" (slowapi/extension.py:49,159-163,244). That is
+# the name `main` documented, so it is the only one an existing deployment
+# will have set — and it keeps working here, silently, without ever
+# appearing in `_limiter_kwargs`.
#
# Tracked purely so this module can tell the truth about such a
# deployment: without it, the "storage is in-memory" warning below fires
# at an operator whose Redis backend is in fact active, and the
# ConfigurationError handler below cannot redact a credential it does not
-# know exists.
-_LEGACY_STORAGE_URI = os.environ.get("RATELIMIT_STORAGE_URL", "").strip()
+# know exists. To know what slowapi will see, this module repeats that
+# one lookup — the only `.env` read anywhere in LDR, limited to this one
+# key; nothing from the file is ever applied to `os.environ`.
+#
+# The environment half is read here at module scope (frozen at import,
+# like the rest of this block) and handed to the resolver.
+_LEGACY_STORAGE_URI_ENV = os.environ.get("RATELIMIT_STORAGE_URL", "")
+
+
+def _resolve_legacy_storage_uri(environ_value: str) -> tuple[str, str]:
+ """Return (value, source) for RATELIMIT_STORAGE_URL, as slowapi sees it.
+
+ ``environ_value`` is the variable's ``os.environ`` value. slowapi
+ builds ``starlette.config.Config(".env")`` when
+ ``os.path.isfile(".env")`` is true and reads this key through it, so
+ the value can come from a file as well as from the environment
+ (environment wins, as in starlette). Resolving it the same way is what
+ lets the construction-failure handler know a credential-bearing URI is
+ in play.
+
+ The existence check sits inside the ``try``: on Python 3.12
+ ``Path.is_file`` re-raises EACCES when the working directory is not
+ searchable, where slowapi's ``os.path.isfile`` just returns False. Any
+ failure while checking for or reading the file is therefore treated
+ as "no .env", as slowapi treats it, and logged at DEBUG by exception
+ type only, so this lookup can never abort the import — not even with
+ rate limiting disabled. If slowapi cannot read the file either, it
+ fails on it when the ``Limiter`` is constructed (enabled or not; that
+ is slowapi's own behaviour), and the handler below reports that
+ failure under its real cause.
+ """
+ value = environ_value.strip()
+ if value:
+ return value, "environment"
+ try:
+ if not (Path.cwd() / ".env").is_file():
+ return "", ""
+ value = str(
+ StarletteConfig(".env")("RATELIMIT_STORAGE_URL", default="")
+ ).strip()
+ except Exception as exc:
+ # Type only: the exception text can quote the file, and the file
+ # can hold a credential.
+ logger.debug(
+ "Could not read RATELIMIT_STORAGE_URL from ./.env "
+ f"({type(exc).__name__}); treating it as unset"
+ )
+ return "", ""
+ if value:
+ return value, ".env file"
+ return "", ""
+
+
+_LEGACY_STORAGE_URI, _LEGACY_STORAGE_SOURCE = _resolve_legacy_storage_uri(
+ _LEGACY_STORAGE_URI_ENV
+)
+
+# An RFC 3986 scheme followed by "://". A scheme can contain neither
+# ":" nor "@", so this prefix can never carry userinfo.
+_STORAGE_URI_SCHEME_RE = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*://")
+
+
+def _redact_storage_uri(uri: str) -> str:
+ """Strip embedded credentials from a storage URI.
+
+ Used ONLY to keep credentials configured via RATE_LIMIT_STORAGE_URI
+ out of logs/exception text — never pass the raw value to logger or
+ a raised exception.
+
+ This runs precisely when the URI failed to parse, so nothing about
+ its shape can be trusted: a userinfo password may hold any delimiter
+ raw ("redis://u:p@ss@h", "redis://u:Pa#ss@h", "redis://u:a/b@h",
+ "redis://u:pa?ss@h"), and a query value may hold a raw "@"
+ ("redis://h/0?password=p@ss", which RFC 3986 allows and redis-py
+ reads as the password). Two places can carry a credential: the
+ userinfo (``user:pass@``) and the query string or fragment
+ (``?password=...``, ``?ssl_password=...``). Let "@" be the LAST "@"
+ in the value and "delimiter" the FIRST "?" or "#":
+
+ * Neither "@" nor a delimiter: returned unchanged.
+ * "@" only: everything between the scheme's "://" and the "@" is
+ replaced by "***" (``redis://***@host:6379/0``). The "@" is the
+ last one because a password may contain "@", "/", "?" or "#", so
+ any earlier stopping point would emit part of it.
+ * A delimiter only: everything after the delimiter is replaced by
+ "***" (``redis://host:6379/0?***``). Without an "@" there is no
+ userinfo, so the text before the delimiter holds no credential.
+ * Both, delimiter after the "@": the userinfo and the query are both
+ replaced (``redis://***@host:6379?***``). No "@" follows the last
+ "@" and no delimiter precedes the first, so the host shown between
+ them can hold neither a userinfo nor a query credential.
+ * Both, delimiter before the "@": userinfo with a raw "?" or "#" and
+ a query with a raw "@" cannot be told apart, so the host cannot be
+ located and everything after the scheme's "://" is replaced
+ (``redis://***``).
+
+ When a value contains an "@" but no well-formed "scheme://" prefix,
+ the text before the "@" (in the ambiguous case, the whole value) is
+ redacted rather than guessed at (``redis:u:pw@h`` gives ``***@h``).
+ The result can over-redact (an "@" in a path
+ hides the host too), which only costs diagnostic detail; it never
+ emits any part of the userinfo, query or fragment. Credentials in
+ other places (for example a ``;password=`` path parameter) are not
+ recognised.
+ """
+ # urlparse() rejects (and quotes) any netloc that NFKC-normalises to a
+ # delimiter, so a fullwidth "@" / "#" / "?" is a real separator
+ # for the code that failed. Fold to NFKC first so the redactor sees
+ # the same boundaries; this only runs on the failure path, where
+ # over-redaction costs nothing.
+ uri = unicodedata.normalize("NFKC", uri)
+ at = uri.rfind("@")
+ delimiters = [i for i in (uri.find("?"), uri.find("#")) if i != -1]
+ cut = min(delimiters) if delimiters else -1
+ if at == -1 and cut == -1:
+ return uri
+ scheme = _STORAGE_URI_SCHEME_RE.match(uri)
+ if at != -1 and cut != -1 and cut < at:
+ # Ambiguous boundary: redact everything after the scheme.
+ return f"{scheme.group(0)}***" if scheme else "***"
+ if at == -1:
+ return f"{uri[: cut + 1]}***"
+ prefix = scheme.group(0) if scheme and scheme.end() <= at else ""
+ rest = uri[at + 1 :]
+ if cut != -1:
+ rest = "{}***".format(rest[: cut - at])
+ return f"{prefix}***@{rest}"
+
+
+def _storage_uri_scheme(uri: str) -> str:
+ """Return only ``scheme://...`` for an info log line, never userinfo.
+
+ ``uri.split("://", 1)[0]`` echoes the whole value, password included,
+ when an operator drops the "//" (``redis:user:pass@host``).
+ """
+ scheme = _STORAGE_URI_SCHEME_RE.match(uri)
+ return f"{scheme.group(0)}..." if scheme else "<unrecognised scheme>"
+
_limiter_kwargs: dict = {
"key_func": _get_client_ip,
@@ -273,7 +1710,7 @@ if not _RATE_LIMITING_ENABLED:
#
# Passing storage_uri explicitly is also what stops slowapi falling
# back to `get_app_config(C.STORAGE_URL, "memory://")`, i.e. reading
- # main's RATELIMIT_STORAGE_URL straight out of the environment.
+ # main's RATELIMIT_STORAGE_URL from the environment or a ./.env file.
_limiter_kwargs["storage_uri"] = "memory://"
if _RATE_LIMIT_STORAGE_URI or _LEGACY_STORAGE_URI:
_ignored_var = (
@@ -289,15 +1726,16 @@ if not _RATE_LIMITING_ENABLED:
elif _RATE_LIMIT_STORAGE_URI:
_limiter_kwargs["storage_uri"] = _RATE_LIMIT_STORAGE_URI
logger.info(
- f"Rate-limit storage configured: {_RATE_LIMIT_STORAGE_URI.split('://', 1)[0]}://..."
+ "Rate-limit storage configured: "
+ f"{_storage_uri_scheme(_RATE_LIMIT_STORAGE_URI)}"
)
elif _LEGACY_STORAGE_URI:
# Backend IS shared — slowapi picked the legacy name up on its own.
# Say so rather than warning about in-memory storage that isn't in use.
logger.info(
"Rate-limit storage configured via the legacy "
- f"RATELIMIT_STORAGE_URL: {_LEGACY_STORAGE_URI.split('://', 1)[0]}://"
- "... (read directly by slowapi). Prefer RATE_LIMIT_STORAGE_URI, "
+ f"RATELIMIT_STORAGE_URL: {_storage_uri_scheme(_LEGACY_STORAGE_URI)}"
+ f" (read directly by slowapi from the {_LEGACY_STORAGE_SOURCE}). Prefer RATE_LIMIT_STORAGE_URI, "
"which this application manages explicitly."
)
else:
@@ -331,68 +1769,84 @@ _limiter_kwargs["default_limits"] = [DEFAULT_RATE_LIMIT]
# are keyed by their own scope and are unaffected either way.
_limiter_kwargs["key_style"] = "endpoint"
-# Matches "://user:pass@host" (and bare "://user@host") userinfo, stopping
-# at the first "/" so a path segment is never mistaken for it.
-_URI_CREDENTIAL_RE = re.compile(r"://[^@/]+@")
-
-
-def _redact_storage_uri(uri: str) -> str:
- """Strip embedded userinfo (``user:pass@``) from a storage URI.
-
- Used ONLY to keep credentials configured via RATE_LIMIT_STORAGE_URI
- out of logs/exception text — never pass the raw value to logger or
- a raised exception.
- """
- return _URI_CREDENTIAL_RE.sub("://***@", uri)
-
+_limiter_init_failed = False
+_limiter_init_from_uri = False
+_limiter_init_cause = ""
+_limiter_init_config_error = False
try:
limiter = Limiter(**_limiter_kwargs)
-except ConfigurationError:
- # Whichever name supplied the URI, the credential in it is equally
- # sensitive. Deferring to the original exception when the legacy name
- # was used — as this handler previously did, on the reasoning that
- # there was "nothing to redact" — leaks exactly the password the
- # redaction below exists to protect, and does so for the *only*
- # variable name a deployment upgrading from main will have set.
+except Exception as _init_exc:
+ # ANY construction failure, not just limits' ConfigurationError.
+ # storage_from_string() calls urlparse() first, which raises a bare
+ # ValueError on a netloc containing a character that NFKC-normalises
+ # to one of / ? # @ : (e.g. a fullwidth U+FF03 in the password), and
+ # that message quotes the WHOLE netloc, password included. redis-py's
+ # ``.port`` ValueError on a raw "/" in the password does the same.
+ # Nothing here may let the original exception, its message or its
+ # traceback reach the log, so only redacted strings are recorded; the
+ # new exception is raised below, OUTSIDE this block, because raising
+ # inside it would keep the original reachable as ``__context__``
+ # (``from None`` only suppresses its display).
+ _limiter_init_failed = True
+ # Only a failure inside limits' storage_from_string() is a problem
+ # with the URI. Anything else (a RATELIMIT_ENABLED=yes cast error, a
+ # NotImplementedError for memcached with moving-window, an unreadable
+ # .env) is reported under its real cause.
+ _limiter_init_config_error = isinstance(_init_exc, ConfigurationError)
+ _tb = _init_exc.__traceback__
+ while _tb is not None:
+ if _tb.tb_frame.f_code.co_name == "storage_from_string":
+ _limiter_init_from_uri = True
+ _tb = _tb.tb_next
+ _limiter_init_cause = f"{type(_init_exc).__name__}: " + _redact_storage_uri(
+ redact_secrets(
+ str(_init_exc),
+ _RATE_LIMIT_STORAGE_URI,
+ _LEGACY_STORAGE_URI,
+ min_length=1,
+ )
+ )
+
+if _limiter_init_failed:
+ # Whichever name or source (environment or a ./.env that slowapi
+ # reads) supplied the URI, the credential in it is equally sensitive.
_configured_uri = _RATE_LIMIT_STORAGE_URI or _LEGACY_STORAGE_URI
_configured_var = (
"RATE_LIMIT_STORAGE_URI"
if _RATE_LIMIT_STORAGE_URI
else "RATELIMIT_STORAGE_URL"
)
- if not _configured_uri:
- # No URI from either name: the failure is not attributable to a
- # value we can identify, so there is nothing to redact and the
- # original exception and traceback are the most useful output.
- raise
- # storage_from_string() (called inside Limiter.__init__) echoes the
- # full, unredacted URI back in ConfigurationError.args. Left
- # unhandled, that credential is logged TWICE at startup: once by
- # loguru's `@logger.catch` on web/app.py:main(), and again in the
- # raw stderr traceback when the process exits. Build a brand-new
- # exception carrying only the redacted URI, and use `from None` so
- # neither the log nor the traceback ever renders the original
- # (credential-bearing) exception or its frames.
- _redacted_uri = _redact_storage_uri(_configured_uri)
- _message = (
- "Rate-limit storage backend could not be initialised "
- f"({_configured_var}={_redacted_uri}). Install the required "
- "client package for this backend (e.g. `pip install redis` for "
- f"redis:// URIs) or unset {_configured_var} to use "
- "per-process in-memory limits."
- )
- # Deliberately NOT logged here before raising. The RuntimeError carries
- # the identical (redacted) message and is raised at import time, so it
- # aborts startup and is reported by the `@logger.catch` on web/app.py's
- # main() -- logging it first would only duplicate the line.
- #
- # It must also not become logger.exception(): that renders the ORIGINAL
- # ConfigurationError, whose args contain the RAW storage URI including
- # any password. Redacting the message and then logging the unredacted
- # cause would defeat the whole point. `from None` severs the chain for
- # the same reason.
- raise RuntimeError(_message) from None
+ if _limiter_init_from_uri and _configured_uri:
+ _redacted_uri = _redact_storage_uri(_configured_uri)
+ if _limiter_init_config_error:
+ _message = (
+ "Rate-limit storage backend could not be initialised "
+ f"({_configured_var}={_redacted_uri}). Install the "
+ "required client package for this backend (e.g. `pip "
+ "install redis` for redis:// URIs) or unset "
+ f"{_configured_var} to use per-process in-memory limits."
+ )
+ else:
+ _message = (
+ "Rate-limit storage URI could not be parsed or "
+ f"initialised ({_configured_var}={_redacted_uri}). Check "
+ "that it is a well-formed URI (percent-encode special "
+ f"characters in the password) or unset {_configured_var} "
+ "to use per-process in-memory limits."
+ )
+ else:
+ _message = (
+ "Rate limiter could not be initialised "
+ f"({_limiter_init_cause}). Check the RATELIMIT_* / "
+ "RATE_LIMIT_* settings and any ./.env file in the working "
+ "directory."
+ )
+ # Deliberately NOT logged here before raising: the RuntimeError aborts
+ # startup and is reported once by the `@logger.catch` on web/app.py's
+ # main(). It must also not become logger.exception(), and it is raised
+ # outside the `except` so there is no __context__/__cause__ to render.
+ raise RuntimeError(_message)
# slowapi's Limiter.__init__ consults the Flask-era RATELIMIT_ENABLED env
# var (starlette Config) and overrides the `enabled` kwarg with its RAW
# STRING value. Re-assert the resolved flag so the canonical
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index 8cb9772bb3..cb9c47201d 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -25,6 +25,7 @@ from starlette.middleware.sessions import SessionMiddleware
from ..__version__ import __version__
from ..security import get_security_default
+from ..security.network_utils import is_ipv6_transition_address
from ..utilities.type_utils import to_bool
from ..utilities.log_utils import InterceptHandler
@@ -590,14 +591,34 @@ def _is_private_ip(ip_str: str) -> bool:
Returns True for private IPs (RFC 1918), localhost, and non-parseable
strings (e.g. 'testclient' from TestClient). Non-parseable strings
are treated as private to avoid adding Secure flag in test/dev contexts.
+
+ A 6to4, Teredo or NAT64 peer is NOT private, whatever ``ipaddress``
+ says: such an address reaches this server through a relay or
+ translator from somewhere else entirely. Both consumers depend on
+ that -- the forwarded-proto advice must not be plantable by a remote
+ client arriving over a tunnel, and the "serving HTTP to a public
+ client" warning must not stay silent for one. The ranges are the
+ shared ``network_utils.IPV6_TRANSITION_NETWORKS``, the same ones the
+ rate limiter's proxy-trust decision excludes.
+
+ An IPv4-mapped address (``::ffff:a.b.c.d``, how an IPv4 client appears
+ on a dual-stack listener) is judged by the IPv4 address it wraps,
+ unwrapped here as ``network_utils.is_private_peer_ip`` does. CPython
+ 3.12.0 to 3.12.3 answer from their IPv6 table instead, which lists
+ ``::ffff:0:0/96`` as private, so a public IPv4 client would read as
+ private on those versions.
"""
if not ip_str:
return True
try:
ip = ipaddress.ip_address(ip_str)
- return ip.is_private or ip.is_loopback
except ValueError:
return True # Non-IP strings (e.g. "testclient") treated as private
+ if ip.version == 6 and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ if is_ipv6_transition_address(ip):
+ return False
+ return ip.is_private or ip.is_loopback
class SecurityHeadersMiddleware:
@@ -1052,6 +1073,7 @@ class SecureCookieMiddleware:
self.testing = testing
self._warned_insecure_public = False
self._warned_untrusted_forwarded_proto = False
+ self._warned_noncanonical_forwarded_proto = False
def _maybe_warn_untrusted_forwarded_proto(
self, scope, remote_addr: str
@@ -1071,38 +1093,95 @@ class SecureCookieMiddleware:
The tell is a request that carries ``X-Forwarded-Proto: https`` while
the connection is not being treated as HTTPS. Cheap: this only runs on
the not-https path (a correctly configured deployment never reaches
- it), and stops checking headers after the first warning. Until then,
- each request must be checked: a headerless health check or an
- untrusted direct client must not conceal a later proxy request.
+ it), and logs each distinct misconfiguration once. Until both warnings
+ have been emitted, each request must be checked: a headerless health
+ check or an untrusted direct client must not conceal a later proxy
+ request.
"""
- if self._warned_untrusted_forwarded_proto:
- return
-
- # Only meaningful from a proxy on the loopback/private network. This
- # header is untrusted client input: any remote client could otherwise
- # send `X-Forwarded-Proto: https` once and plant a log line telling
- # the operator to set TRUST_PROXY_HEADERS=true — advice that, followed
- # on a host NOT behind a proxy, would hand that same client control of
- # the scheme and therefore of the Secure-cookie and HSTS decisions.
- if not remote_addr or not _is_private_ip(remote_addr):
+ if (
+ self._warned_untrusted_forwarded_proto
+ and self._warned_noncanonical_forwarded_proto
+ ):
return
+ # Mirror uvicorn's ProxyHeadersMiddleware exactly (0.52.x): it reads
+ # the LAST X-Forwarded-Proto header line, decodes it as latin-1,
+ # strips it, and honours it only on an exact match against
+ # {"http", "https", "ws", "wss"}. A value LDR would read as https
+ # but uvicorn would not ("HTTPS", "https, https" from a proxy that
+ # appends, "https,http") is a different misconfiguration from an
+ # untrusted proxy and needs different advice -- in that case
+ # uvicorn may well trust the proxy and have rewritten
+ # scope["client"] from X-Forwarded-For already.
+ proto_value = None
for name, value in scope.get("headers", []):
- if name != b"x-forwarded-proto":
- continue
- # Left-most value is the original client protocol when a chain of
- # proxies has appended to the header.
- if value.split(b",")[0].strip().lower() == b"https":
- self._warned_untrusted_forwarded_proto = True
- logger.warning(
- "Received X-Forwarded-Proto: https but this connection is "
- "not being treated as HTTPS, so session cookies will NOT "
- "get the Secure flag and HSTS will NOT be sent. If this "
- "server sits behind a TLS-terminating reverse proxy, set "
- "TRUST_PROXY_HEADERS=true so forwarded headers are "
- "honoured."
- )
- break
+ if name == b"x-forwarded-proto":
+ proto_value = value
+ if proto_value is None:
+ return
+ uvicorn_view = proto_value.decode("latin-1").strip()
+
+ # No client address is ever interpolated into this advice. The
+ # address in scope["client"] is not necessarily the proxy: with
+ # TRUST_PROXY_HEADERS=true uvicorn may already have replaced it with
+ # an X-Forwarded-For entry (under "*" the client-forgeable left-most
+ # one, unvalidated -- "8.8.8.8/32" or free text), and even when it
+ # is the raw socket peer, that peer may be an unlisted co-tenant
+ # rather than the operator's proxy. Naming it as "the address to
+ # allow-list" would let a client plant its own address into the
+ # operator's forwarding trust.
+ if uvicorn_view == "https":
+ if self._warned_untrusted_forwarded_proto:
+ return
+ # uvicorn would have honoured this exact value had it trusted
+ # the peer, so it did not: TRUST_PROXY_HEADERS is off, or the
+ # peer is outside LDR_SERVER_FORWARDED_ALLOW_IPS. This header is
+ # untrusted client input, and the advice here widens forwarding
+ # trust, so give it only for a loopback/private peer: any remote
+ # client could otherwise send `X-Forwarded-Proto: https` once
+ # and plant a log line telling the operator to set
+ # TRUST_PROXY_HEADERS=true -- advice that, followed on a host
+ # NOT behind a proxy, would hand that same client control of the
+ # scheme and therefore of the Secure-cookie and HSTS decisions.
+ if not remote_addr or not _is_private_ip(remote_addr):
+ return
+ self._warned_untrusted_forwarded_proto = True
+ logger.warning(
+ "Received X-Forwarded-Proto: https but this connection is "
+ "not being treated as HTTPS, so session cookies will NOT "
+ "get the Secure flag and HSTS will NOT be sent. If this "
+ "server sits behind a TLS-terminating reverse proxy, set "
+ "TRUST_PROXY_HEADERS=true so forwarded headers are "
+ "honoured. If it is already set, uvicorn does not trust the "
+ "proxy that sent this request: add your reverse proxy's own "
+ "address as LDR sees it (the address the proxy connects "
+ "from, not a client address; with LDR in Docker behind a "
+ "proxy on the host, the Docker network's gateway, not "
+ "127.0.0.1) to LDR_SERVER_FORWARDED_ALLOW_IPS, which must "
+ "list every proxy hop in front of LDR."
+ )
+ elif uvicorn_view.split(",")[0].strip().lower() == "https":
+ if self._warned_noncanonical_forwarded_proto:
+ return
+ # uvicorn ignores this value whether or not it trusts the peer,
+ # so neither TRUST_PROXY_HEADERS nor the allow-list is the fix,
+ # and the advice (reconfigure the proxy) widens no trust -- it
+ # is safe to give for any peer, including one uvicorn has
+ # already rewritten to a public client address.
+ self._warned_noncanonical_forwarded_proto = True
+ logger.warning(
+ "Received an X-Forwarded-Proto header claiming https in a "
+ "form uvicorn does not accept, so this connection is not "
+ "being treated as HTTPS: session cookies will NOT get the "
+ "Secure flag and HSTS will NOT be sent. uvicorn honours "
+ "only a single exact lower-case value (http, https, ws or "
+ "wss) in the last X-Forwarded-Proto header, so 'HTTPS' or "
+ "a comma-separated list such as 'https, https' is "
+ "ignored. If a TLS-terminating reverse proxy sets this "
+ "header, configure it to overwrite X-Forwarded-Proto with "
+ "exactly 'https' rather than appending to it (nginx: "
+ "proxy_set_header X-Forwarded-Proto $scheme;)."
+ )
def _maybe_warn_insecure_public(self, remote_addr: str) -> None:
"""One-shot warning when serving HTTP to a non-private client IP —
@@ -1118,12 +1197,12 @@ class SecureCookieMiddleware:
"are NOT marked Secure (marking them Secure over HTTP would "
"make the browser drop them). Put LDR behind HTTPS, and if "
"using a TLS proxy set TRUST_PROXY_HEADERS=true.",
- # (#6938: under TRUST_PROXY_HEADERS this is the client's
- # unvalidated X-Forwarded-For entry, so it is bounded. A
- # plain string cap, not the quoted value preview, so a real
- # address logs exactly as before, like the ``ip=`` field of
- # the rate-limit-exceeded line below.)
- redact_and_bound_for_log(remote_addr, 64),
+ # remote_addr parsed as an IP (non-IPs count as private),
+ # but ipaddress accepts an IPv6 zone id of arbitrary text
+ # ("2001:db8::1%any words"), and with TRUST_PROXY_HEADERS
+ # uvicorn may have copied it from X-Forwarded-For. Log the
+ # address alone.
+ redact_and_bound_for_log(remote_addr.partition("%")[0], 64),
)
async def __call__(self, scope, receive, send):
diff --git a/tests/deployment/test_deployment_surface_contracts.py b/tests/deployment/test_deployment_surface_contracts.py
index 9ae52f83a5..e66bc3d56b 100644
--- a/tests/deployment/test_deployment_surface_contracts.py
+++ b/tests/deployment/test_deployment_surface_contracts.py
@@ -1002,7 +1002,15 @@ class TestRunCommand:
def test_trust_proxy_headers_opens_forwarded_ips(self, monkeypatch):
"""Execution-verified: opting in trusts forwarded headers from any
- peer, which is why the docs demand loopback/internal binding."""
+ peer at the default allow-list, which is why the docs demand
+ loopback/internal binding.
+
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` narrows that, so it is cleared
+ here (as the sibling fixture in
+ ``tests/security/test_middleware_and_proxy_trust_fastapi.py``
+ does): a value exported by CI or a dev shell would otherwise make
+ the assertion below observe someone else's proxy list.
+ """
import uvicorn
from local_deep_research.web.app import _run_with_uvicorn
@@ -1011,6 +1019,11 @@ class TestRunCommand:
monkeypatch.setattr(
uvicorn, "run", lambda app, **kw: captured.update(kw)
)
+ for name in (
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+ "LDR_SERVER_TRUSTED_PROXY_COUNT",
+ ):
+ monkeypatch.delenv(name, raising=False)
for value in TRUSTY_VALUES:
captured.clear()
monkeypatch.setenv("TRUST_PROXY_HEADERS", value)
@@ -1645,9 +1658,29 @@ class TestReverseProxyDoc:
def test_proxy_header_trust_scope_is_described_consistently(self):
limiter = RATE_LIMIT_PY.read_text(encoding="utf-8")
- assert "_TRUST_PROXY_HEADERS or _is_trusted_peer(direct_peer)" in (
- limiter
- ), "the limiter trust rule changed; re-derive this documentation test"
+ # _get_client_ip's trust rule became a tri-state gate (PR #4870):
+ # TRUST_PROXY_HEADERS is checked FIRST and, when set with
+ # X-Forwarded-For present, never consults the peer gate: with a
+ # restricted LDR_SERVER_FORWARDED_ALLOW_IPS it keys on uvicorn's
+ # own answer, with the unrestricted "*" on the right-most
+ # X-Forwarded-For entry (#6442), both validated as addresses;
+ # LDR_SERVER_TRUSTED_PROXY_COUNT is the second gate;
+ # every application-level trust decision now goes through
+ # _peer_may_supply_forwarding_headers, which resolves to the
+ # restricted LDR_SERVER_FORWARDED_ALLOW_IPS alone when one is
+ # explicitly configured and to the private/loopback heuristic
+ # otherwise. Pin all three branches so a future edit that
+ # collapses or reorders them re-triggers this documentation check.
+ get_client_ip = limiter[limiter.index("def _get_client_ip(") :]
+ for rule in (
+ "if _TRUST_PROXY_HEADERS:",
+ "if _TRUSTED_PROXY_COUNT > 0:",
+ "if _peer_may_supply_forwarding_headers(direct_peer):",
+ ):
+ assert rule in get_client_ip, (
+ "the limiter trust rule changed; re-derive this "
+ f"documentation test (missing: {rule!r})"
+ )
doc = REVERSE_PROXY_DOC.read_text(encoding="utf-8")
changelog = (REPO_ROOT / "changelog.d" / "3299.breaking.md").read_text(
diff --git a/tests/security/test_fastapi_app_ip_classification_edges.py b/tests/security/test_fastapi_app_ip_classification_edges.py
index 1262ffe689..3f795797f1 100644
--- a/tests/security/test_fastapi_app_ip_classification_edges.py
+++ b/tests/security/test_fastapi_app_ip_classification_edges.py
@@ -4,10 +4,10 @@ The repo carries three private-IP classifiers. The two that matter here
differ in fallback behaviour — this is not a hardened/unhardened pair:
- ``local_deep_research.security.network_utils.is_private_ip`` — it first
- short-circuits ``return True`` (``network_utils.py:39``) on a small set
+ short-circuits ``return True`` on a small set
of known localhost spellings (``localhost``, ``127.0.0.1``, ``[::1]``,
- ``0.0.0.0``) checked at ``:38``, BEFORE any bracket handling; only then does
- it strip the brackets off a ``[...]``-wrapped literal (``:42``) and
+ ``0.0.0.0``), BEFORE any bracket handling; only then does
+ it strip the brackets off a ``[...]``-wrapped literal and
hand everything else straight to ``ipaddress``'s own ``is_private`` /
``is_loopback`` / ``is_link_local``, falling back to a ``.local``-suffix
check when the string does not parse as an IP at all. It does no
@@ -17,15 +17,15 @@ differ in fallback behaviour — this is not a hardened/unhardened pair:
prefixes, which ``ipaddress`` answers from its network table rather
than from the embedded IPv4, that answer is not always right. A
NAT64-wrapped RFC1918/link-local address (e.g. ``64:ff9b::c0a8:1``, or
- the metadata-address case) is classified public, while every 6to4
- address is classified private regardless of what it wraps, because
- ``2002::/16`` is an entry in Python's private-networks table with no
- matching exception. Both classes are covered by the deep classification
+ the metadata-address case) is classified public, while on a CPython
+ build whose private-networks table lists ``2002::/16`` (older builds
+ that lack that entry do not), every 6to4 address is classified private
+ regardless of what it wraps. Both classes are covered by the deep classification
suite in ``tests/security/test_middleware_and_proxy_trust_fastapi.py``,
but not on the same footing:
- ``test_6to4_wrapping_a_private_address_counts_as_private`` (:752) is
+ ``test_6to4_wrapping_a_private_address_counts_as_private`` is
explicitly labelled CURRENT BEHAVIOUR, not desired behaviour, while
- ``test_nat64_wrapped_addresses_are_not_private`` (:678) is framed as
+ ``test_nat64_wrapped_addresses_are_not_private`` is framed as
load-bearing — its docstring says ``security/egress/policy.py`` relies
on this classification (plus its own ``_is_nat64_wrapped_metadata``
check) so a NAT64-wrapped cloud metadata address cannot pose as a local
@@ -33,12 +33,17 @@ differ in fallback behaviour — this is not a hardened/unhardened pair:
``64:ff9b::169.254.169.254`` (the metadata address); the RFC1918
example above, ``64:ff9b::c0a8:1``, is not itself asserted there — the
public class is pinned via a link-local metadata address instead. For
- IPv4-mapped inputs — the one of these three shapes whose answer CPython
- changed inside the supported version range — this function is exactly as
- version-dependent as the copy below; see the CGNAT ``xfail`` keyed to
- this same function in ``tests/security/test_guard_internals.py``.
+ IPv4-mapped inputs this function takes whatever the running
+ interpreter's ``ipaddress`` answers: from CPython 3.12.4 that follows
+ the IPv4 address the mapped form wraps, while 3.12.0 to 3.12.3 report
+ every mapped address private.
- ``web.fastapi_app._is_private_ip`` — a local copy that does the same kind
- of non-unwrapping delegation, but with different edges: no bracket
+ of delegation, except that it first unwraps an IPv4-mapped address to
+ the IPv4 address it wraps, and classifies every 6to4
+ (``2002::/16``), Teredo (``2001::/32``) and NAT64 (``64:ff9b::/96``,
+ ``64:ff9b:1::/48``) address as NOT private before consulting
+ ``ipaddress`` (a transition address stands for a host beyond a relay
+ or translator), and with different edges: no bracket
stripping, no localhost-string shortcut, and "non-parseable (including
empty string) counts as private" so TestClient peers behave like
loopback — where the module above instead falls back to a
@@ -53,7 +58,7 @@ differ in fallback behaviour — this is not a hardened/unhardened pair:
its only reference).
The third classifier, ``NotificationURLValidator._is_private_ip``
-(``security/notification_validator.py:460``), is a different animal: it
+(``security/notification_validator.py``), is a different animal: it
resolves a hostname and screens the resolved addresses as an SSRF gate
on the notification egress path, with its own knobs
(``allow_private_ips``, ``allow_nat64``, ``block_link_local``) and its
@@ -69,7 +74,7 @@ paths inside ``SecureCookieMiddleware`` —
— and never the ``Secure``-flag decision itself: that decision is
``should_add_secure = not self.testing and is_https`` where ``is_https``
-is ``scope.get("scheme") == "https"`` (``fastapi_app.py:938-942``). It is
+is ``scope.get("scheme") == "https"`` (in ``SecureCookieMiddleware``). It is
gated on the testing flag as well as the scheme, and the peer address is
not an input to it at all; it is pinned in
``tests/web/test_secure_cookie_middleware.py``. A misclassification here
@@ -79,28 +84,25 @@ What this file pins:
1. The honest classification table (RFC 1918, loopback, IPv6 ULA/link-local,
public v4/v6, empty, non-parseable).
-2. The CPython dependence this copy shares with
- ``network_utils.is_private_ip`` (neither unwraps IPv4-mapped forms
- itself): for IPv4-mapped peers this copy inherits whatever
- ``ipaddress`` says — CPython before 3.12.4 classified
- ``::ffff:8.8.8.8`` as PRIVATE (the ``::ffff:0:0/96``-is-private era),
- and gh-113171 (landed in 3.12.4 / 3.13) made ``is_private`` delegate
- to the embedded IPv4 instead. Both interpreters are inside this
- project's ``>=3.12,<3.15`` range, so the secure direction (mapped
- public stays public) is pinned under a runtime-probed ``strict=True``
- xfail — the same guard shape ``tests/security/test_guard_internals.py``
- uses for the CGNAT half of that same CPython change — and a runtime
- flip fails loudly instead of silently degrading the operator warnings
- this feeds.
+2. IPv4-mapped peers (``::ffff:a.b.c.d``) are judged by the IPv4 address
+ they wrap, unwrapped by this copy itself as
+ ``network_utils.is_private_peer_ip`` does, so ``::ffff:8.8.8.8``
+ classifies public on every interpreter. CPython 3.12.0 to 3.12.3
+ answer a mapped address from their IPv6 private-networks table, where
+ ``::ffff:0:0/96`` is listed private outright, and would classify every
+ mapped address private; one test simulates that table answer so the
+ unwrap is what its assertions observe.
3. NAT64 (``64:ff9b::/96``) peers never get mapped-address treatment
from CPython: a NAT64-wrapped public IPv4 classifies public.
-4. 6to4 (``2002::/16``) peers, in the INSECURE direction: a 6to4-wrapped
- PUBLIC IPv4 classifies PRIVATE here, because ``2002::/16`` is a
- private-networks entry and nothing unwraps the embedded IPv4. That is
- the direction that costs an operator the "serving HTTP to a public
- client" warning (``_maybe_warn_insecure_public`` warns only when the
- peer is NOT private), so it is pinned as an explicitly inverted pin —
- see the disclosure on the test itself.
+4. 6to4 (``2002::/16``), Teredo (``2001::/32``) and NAT64 local-use
+ (``64:ff9b:1::/48``) peers classify NOT private, although CPython's
+ network table may list them as private, depending on the build
+ (Teredo through ``2001::/23``; 6to4 and NAT64 local-use only on
+ builds whose table carries those entries, where a 6to4-wrapped
+ PUBLIC IPv4 such as ``2002:808:808::1`` reads private; older builds
+ that lack them do not). Classifying them private cost an operator the
+ "serving HTTP to a public client" warning, and let a remote client
+ arriving over a tunnel plant the forwarded-proto advice.
Deliberately NOT pinned: the ``or ip.is_loopback`` half of the classifier.
It is unreachable as a *decision* — ``127.0.0.0/8`` and ``::1/128`` are
@@ -131,16 +133,6 @@ import pytest
from local_deep_research.web.fastapi_app import _is_private_ip
-#: True on interpreters that still answer IPv4-mapped addresses from the
-#: IPv6 network table (``::ffff:0:0/96`` listed private outright) instead
-#: of delegating to the embedded IPv4 — i.e. CPython before gh-113171
-#: (3.12.4 / 3.13). Probed at import time rather than compared against
-#: ``sys.version_info`` so a backport or a vendored ``ipaddress`` is
-#: judged by what it actually does.
-_MAPPED_ADDRESSES_ARE_BLANKET_PRIVATE = ipaddress.ip_address(
- "::ffff:8.8.8.8"
-).is_private
-
class TestPrivateClassification:
def test_rfc1918_blocks_are_private(self):
@@ -171,12 +163,12 @@ class TestPrivateClassification:
def test_empty_and_non_parseable_are_private(self):
# "" and "testclient" (the Starlette TestClient peer) classify
- # private. The SUT docstring (fastapi_app.py:462-464) gives the
+ # private. The SUT docstring (``_is_private_ip``) gives the
# reason as "Non-parseable strings are treated as private to
# avoid adding Secure flag in test/dev contexts" — quoted here
# exactly because that rationale is STALE: this classifier is not
# an input to the Secure-flag decision at all (that decision is
- # `not self.testing and is_https`, fastapi_app.py:938-942, as the
+ # `not self.testing and is_https` in SecureCookieMiddleware, as the
# module docstring above records). What the fallback actually
# buys today is quiet operator-warning paths. Tracked in #6263.
#
@@ -191,36 +183,43 @@ class TestPrivateClassification:
class TestMappedAddressSemantics:
- @pytest.mark.xfail(
- _MAPPED_ADDRESSES_ARE_BLANKET_PRIVATE,
- strict=True,
- reason=(
- "CPython before gh-113171 (landed in 3.12.4 / 3.13) listed "
- "::ffff:0:0/96 among the IPv6 private networks outright, so "
- "EVERY mapped address — including one wrapping a public IPv4 "
- "— reported is_private=True; that interpreter is inside this "
- "project's requires-python >=3.12,<3.15 range. The change "
- "made is_private delegate to the embedded IPv4 instead. This "
- "local copy does no unwrapping of its own and inherits "
- "whichever semantics the running CPython has, so the "
- "assertion below is xfailed rather than dropped on the older "
- "interpreters — same guard shape as the CGNAT half of the "
- "same CPython change in tests/security/test_guard_internals.py"
- ),
- )
def test_ipv4_mapped_public_peer_classifies_public(self):
- # The SECURE direction, pinned: on an interpreter that derives
- # the answer from the embedded IPv4, a mapped PUBLIC peer must
- # classify public. strict=True on the xfail above means this also
- # fails loudly if an interpreter reports blanket-private yet this
- # assertion somehow passes, so neither direction can drift
- # silently and degrade the operator warnings this feeds. (The
- # other copy, security.network_utils.is_private_ip, does no
- # unwrapping either and shares this exact CPython dependence for
- # the mapped case — see the CGNAT xfail keyed to that function in
- # tests/security/test_guard_internals.py.)
+ # The SECURE direction: a mapped PUBLIC peer classifies public,
+ # so it gets the "serving HTTP to a public client" warning and
+ # cannot plant the forwarded-proto advice.
assert not _is_private_ip("::ffff:8.8.8.8")
+ def test_mapped_address_follows_the_wrapped_ipv4_on_any_interpreter(
+ self, monkeypatch
+ ):
+ """Decided by unwrapping, not by the interpreter's table.
+
+ A stock CPython 3.12.4 or later already delegates a mapped address
+ to the IPv4 it wraps, so there deleting the unwrap changes no
+ verdict. This simulates CPython 3.12.0 to 3.12.3, which answer
+ from the IPv6 network table where ``::ffff:0:0/96`` is listed
+ private outright, so the unwrap is what the assertions observe.
+ """
+ mapped_range = ipaddress.ip_network("::ffff:0:0/96")
+ table_answer = ipaddress.IPv6Address.is_private
+
+ def is_private_from_table(self):
+ if self in mapped_range:
+ return True
+ return table_answer.fget(self)
+
+ monkeypatch.setattr(
+ ipaddress.IPv6Address,
+ "is_private",
+ property(is_private_from_table),
+ )
+ # The simulation is in effect: the stdlib now says "private".
+ assert ipaddress.ip_address("::ffff:8.8.8.8").is_private is True
+
+ assert _is_private_ip("::ffff:8.8.8.8") is False
+ assert _is_private_ip("::ffff:10.0.0.1") is True
+ assert _is_private_ip("::ffff:127.0.0.1") is True
+
def test_ipv4_mapped_loopback_classifies_private(self):
assert _is_private_ip("::ffff:127.0.0.1")
@@ -234,14 +233,11 @@ class TestMappedAddressSemantics:
# never consulted. A NAT64-wrapped PUBLIC peer therefore
# classifies public.
#
- # This is NOT where the asymmetry with the mapped range lives —
- # at least on CPython >= 3.12.4 (gh-113171): there, a mapped
- # public peer also classifies public
- # (test_ipv4_mapped_public_peer_classifies_public above, xfailed
- # on the older interpreters where the mapped range is
- # blanket-private regardless of what it wraps — see the
- # strict=True xfail on that test). The asymmetry is on the
- # PRIVATE-wrapped side —
+ # This is NOT where the asymmetry with the mapped range lives:
+ # _is_private_ip unwraps a mapped address to the IPv4 it wraps, so
+ # a mapped public peer also classifies public
+ # (test_ipv4_mapped_public_peer_classifies_public above). The
+ # asymmetry is on the PRIVATE-wrapped side —
# `::ffff:192.168.1.10` and `::ffff:127.0.0.1` classify private
# via the embedded IPv4, while `64:ff9b::c0a8:1` (RFC1918
# 192.168.0.1 wrapped for NAT64) classifies PUBLIC. That
@@ -251,28 +247,60 @@ class TestMappedAddressSemantics:
# other classifier; the module docstring above records it.
assert not _is_private_ip("64:ff9b::808:808")
- def test_6to4_wrapping_a_public_ipv4_classifies_private(self):
- # 2002:808:808::1 is 8.8.8.8 wrapped in the 6to4 prefix. Unlike
- # both cases above this is the INSECURE direction: 2002::/16 is a
- # plain entry in CPython's IPv6 private-networks table with no
- # matching exception, and nothing here unwraps the embedded
- # IPv4 — so a PUBLIC peer arriving over a 6to4 tunnel is
- # classified PRIVATE. The cost is exactly one lost operator
- # warning: _maybe_warn_insecure_public warns only when the peer
- # is NOT private (fastapi_app.py:910), so a 6to4 public peer
- # served over plain HTTP silently gets no "serving HTTP to a
- # public client" line. (The other warning path runs the test the
- # other way round — _maybe_warn_untrusted_forwarded_proto
- # proceeds only for a private peer, fastapi_app.py:886 — so there
- # the same misclassification merely widens who can plant that
- # one-shot hint.)
- #
- # INVERTED PIN: this test FAILS if the classifier is ever
- # hardened to unwrap 6to4 (or to drop 2002::/16 from whatever
- # table it consults). That is deliberate — update this test then,
- # it is not a regression. It exists so the hardening is a
- # conscious edit rather than an unnoticed behaviour change.
- assert _is_private_ip("2002:808:808::1")
+ @pytest.mark.parametrize(
+ "peer",
+ [
+ # 6to4 wrapping a public IPv4 (8.8.8.8) and a private one
+ # (10.0.0.1): neither is a peer on this host or LAN.
+ "2002:808:808::1",
+ "2002:a00:1::1",
+ # Teredo: 2001::/32 sits inside the private 2001::/23 block.
+ "2001:0:4136:e378:8000:63bf:3fff:fdd2",
+ # RFC 8215 NAT64 local-use prefix, private in CPython's table
+ # on builds that carry that entry.
+ "64:ff9b:1::808:808",
+ # Well-known NAT64 wrapping an RFC1918 address.
+ "64:ff9b::a00:1",
+ # A zone id does not change the classification.
+ "2002:808:808::1%eth0",
+ ],
+ )
+ def test_transition_addresses_classify_public(self, peer):
+ # Each of these may read is_private=True in CPython, depending on
+ # the build (the well-known NAT64 row is listed so the rule does
+ # not depend on the network table). Classified private, a
+ # 6to4/Teredo client silently got no "serving HTTP to a public client" warning and
+ # could plant the forwarded-proto advice meant for a local
+ # reverse proxy.
+ assert not _is_private_ip(peer)
+
+ def test_transition_rule_is_needed_on_this_interpreter(self):
+ # Guards the test above against passing for the wrong reason: on an
+ # interpreter whose ipaddress lists these ranges as private, the
+ # rule in _is_private_ip is what keeps them public. Which ranges
+ # are listed depends on the CPython build (6to4 and NAT64
+ # local-use are missing from older builds' private table), so
+ # the guard needs at least one of them to be listed here and skips
+ # otherwise: there the rule is redundant rather than wrong.
+ listed = [
+ peer
+ for peer in (
+ "2002:808:808::1",
+ "2001:0:4136:e378::1",
+ "64:ff9b:1::808:808",
+ )
+ if ipaddress.ip_address(peer).is_private
+ ]
+ if not listed:
+ pytest.skip("this interpreter lists no transition range as private")
+ for peer in listed:
+ assert not _is_private_ip(peer)
+
+ def test_neighbours_of_the_transition_ranges_are_unaffected(self):
+ # 2001:db8::/32 (documentation) is outside Teredo's 2001::/32 and
+ # keeps CPython's private verdict.
+ assert _is_private_ip("2001:db8::1")
+ assert not _is_private_ip("2001:4860:4860::8888")
class TestConsumerBoundary:
@@ -281,6 +309,7 @@ class TestConsumerBoundary:
[
("127.0.0.1", True),
("8.8.8.8", False),
+ # The secure mapped direction, on every interpreter.
("::ffff:8.8.8.8", False),
],
)
diff --git a/tests/security/test_guard_internals.py b/tests/security/test_guard_internals.py
index 72dfcaef20..9afeb35394 100644
--- a/tests/security/test_guard_internals.py
+++ b/tests/security/test_guard_internals.py
@@ -1267,8 +1267,9 @@ class TestGuardConsistency:
(``ip.is_private or ip.is_loopback or ip.is_link_local``).
``ip_ranges.PRIVATE_IP_RANGES`` is a hand-maintained table consumed
by the SSRF validator and the egress PDP. They are not the same
- predicate, and ``is_private_ip`` is what decides whether
- ``X-Forwarded-For`` is trusted (``rate_limit._is_trusted_peer``) and
+ predicate, and ``is_private_ip`` is the base of what decides whether
+ ``X-Forwarded-For`` is trusted (``rate_limit._is_trusted_peer``, via
+ ``is_private_peer_ip``) and
whether a URL is downgraded to plaintext http
(``utilities.url_utils.normalize_url``).
"""
@@ -1289,24 +1290,24 @@ class TestGuardConsistency:
not ipaddress.ip_address(CGNAT_V4).is_private,
strict=True,
reason=(
- "DEFECT (consistency): CPython removed 100.64.0.0/10 from "
- "IPv4Address.is_private (gh-113171, landed in 3.12.4 / "
- "3.13). ip_ranges.PRIVATE_IP_RANGES and ssrf_validator's "
- "PRIVATE_RANGES both still list it, and both docstrings call "
- "it out as 'used by Podman/rootless containers'. So on the "
- "newer interpreters this project supports "
- "(requires-python >=3.12,<3.15) the same CGNAT address is "
+ "DEFECT (consistency): CPython's IPv4Address.is_private does "
+ "not cover 100.64.0.0/10 (RFC 6598 shared address space, "
+ "which ipaddress reports as neither private nor global). "
+ "ip_ranges.PRIVATE_IP_RANGES and ssrf_validator's "
+ "PRIVATE_RANGES both list it, and both docstrings call "
+ "it out as 'used by Podman/rootless containers'. So on an "
+ "interpreter whose is_private leaves it out (probed above) "
+ "the same CGNAT address is "
"private to the SSRF validator and public to is_private_ip. "
- "The observable split: rate_limit._is_trusted_peer stops "
- "trusting X-Forwarded-For from a rootless-container proxy "
+ "The observable split: rate_limit._is_trusted_peer does not "
+ "trust X-Forwarded-For from a rootless-container proxy "
"(all clients collapse into one rate-limit bucket), and "
"egress/policy._classify_host labels an on-box CGNAT Ollama "
"as an EXPOSING public sink. Both directions fail closed, "
"which is why nothing has caught it -- but the existing "
"coverage at test_network_utils_behavior.py::"
"TestIsPrivateCarrierGradeNAT asserts only "
- "isinstance(result, bool), so the behaviour is unpinned and "
- "silently version-dependent."
+ "isinstance(result, bool), so the behaviour is unpinned."
),
)
def test_cgnat_is_classified_the_same_by_both_guards(self):
diff --git a/tests/security/test_middleware_and_proxy_trust_fastapi.py b/tests/security/test_middleware_and_proxy_trust_fastapi.py
index 6e485f9820..132b32c0d0 100644
--- a/tests/security/test_middleware_and_proxy_trust_fastapi.py
+++ b/tests/security/test_middleware_and_proxy_trust_fastapi.py
@@ -36,7 +36,9 @@ pin the call site, not that split.
COVERAGE AREA 2 — ``is_private_ip`` mapped-IPv6 and multicast
--------------------------------------------------------
-``security/network_utils.is_private_ip`` feeds
+``security/network_utils.is_private_ip`` is the base of
+``is_private_peer_ip`` (which additionally unwraps IPv4-mapped addresses
+and rejects the 6to4/Teredo/NAT64 transition ranges), and that feeds
``web/dependencies/rate_limit._is_trusted_peer``, which decides whether
``X-Forwarded-For`` from a given direct peer is honoured — i.e. whether a
client may choose its own rate-limit bucket and apparent source address. An
@@ -750,9 +752,18 @@ class TestIsPrivateIpOtherClasses:
assert is_private_ip(address) is True
def test_6to4_wrapping_a_private_address_counts_as_private(self):
- """CURRENT BEHAVIOUR: 2002::/16 is non-globally-reachable in Python's
- table, so every 6to4 address is private regardless of what it wraps."""
- assert is_private_ip("2002:0a00:0001::1") is True
+ """CURRENT BEHAVIOUR: this helper follows the running interpreter.
+ On a CPython build whose table lists 2002::/16 as
+ non-globally-reachable, every 6to4 address is private regardless
+ of what it wraps; older builds that lack that entry report this
+ address as not private (the test name describes the former). The
+ proxy-trust decision does not inherit either answer:
+ ``_is_trusted_peer`` goes through ``is_private_peer_ip``, which
+ rejects 6to4 peers (``tests/web/dependencies/test_rate_limit_keys.py``)."""
+ import ipaddress
+
+ expected = ipaddress.ip_address("2002:0a00:0001::1").is_private
+ assert is_private_ip("2002:0a00:0001::1") is expected
@pytest.mark.parametrize("address", ["100.64.0.1", "100.127.255.255"])
def test_carrier_grade_nat_is_not_private(self, address):
@@ -890,9 +901,21 @@ def uvicorn_run_kwargs(monkeypatch):
``web/app.py`` does ``import uvicorn`` inside the function, so patching
the attribute on the already-imported module is what the call resolves.
+
+ The two proxy-trust variables are cleared first: ``web/app.py`` now
+ derives ``forwarded_allow_ips`` from ``LDR_SERVER_FORWARDED_ALLOW_IPS``
+ rather than hard-coding ``"*"``, so a value exported ambiently by CI or
+ a dev shell would silently change what every assertion below observes.
+ Each test that cares sets its own value.
"""
import uvicorn
+ for name in (
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+ "LDR_SERVER_TRUSTED_PROXY_COUNT",
+ ):
+ monkeypatch.delenv(name, raising=False)
+
calls: list[tuple[tuple, dict]] = []
monkeypatch.setattr(uvicorn, "run", lambda *a, **kw: calls.append((a, kw)))
@@ -942,8 +965,35 @@ class TestTrustProxyHeadersUvicornWiring:
assert kwargs["proxy_headers"] is True, (
f"TRUST_PROXY_HEADERS={value!r} did not reach uvicorn"
)
+ # The backward-compatible DEFAULT, not a coupling: with
+ # LDR_SERVER_FORWARDED_ALLOW_IPS unset (the fixture clears it) the
+ # opt-in still launches uvicorn with its own "*" default, exactly
+ # as it did before that variable existed.
assert kwargs["forwarded_allow_ips"] == "*"
+ def test_restricted_forwarded_allow_ips_reaches_uvicorn(
+ self, monkeypatch, uvicorn_run_kwargs
+ ):
+ """The two kwargs are deliberately INDEPENDENT.
+
+ ``proxy_headers`` is the operator's on/off switch; the allow-list
+ is a separate axis that narrows which direct peers uvicorn honours
+ forwarded headers from. Pinned together here so the pairing cannot
+ silently regress to the old "``proxy_headers`` implies ``*``"
+ equivalence, which is exactly the spoofable configuration the
+ rate limiter's startup guard now refuses.
+ """
+ configured_allow_ips = "10.0.0.5,2001:db8::/64"
+ monkeypatch.setenv(
+ "LDR_SERVER_FORWARDED_ALLOW_IPS", configured_allow_ips
+ )
+
+ _, kwargs = uvicorn_run_kwargs("true")
+
+ assert kwargs["proxy_headers"] is True
+ assert kwargs["forwarded_allow_ips"] == configured_allow_ips
+ assert kwargs["forwarded_allow_ips"] != "*"
+
@pytest.mark.parametrize(
"value",
["", "false", "False", "0", "no", "off", "maybe", " true ", "true "],
@@ -964,16 +1014,26 @@ class TestTrustProxyHeadersUvicornWiring:
def test_forwarded_allow_ips_never_widens_without_proxy_headers(
self, uvicorn_run_kwargs, value
):
- """The two kwargs are one decision and must not drift apart.
-
- ``forwarded_allow_ips="*"`` tells uvicorn to accept ``X-Forwarded-*``
- from ANY peer; it is only safe paired with the operator's explicit
- opt-in. Pinned as an equivalence so neither half can be flipped alone.
+ """An allow-list is only ever passed together with the opt-in.
+
+ The two kwargs are no longer one decision -- ``forwarded_allow_ips``
+ is now operator-configurable and can be narrower than ``"*"`` while
+ ``proxy_headers`` is on (see
+ ``test_restricted_forwarded_allow_ips_reaches_uvicorn``). What must
+ still hold in BOTH directions is the gating: ``forwarded_allow_ips``
+ is ``None`` -- uvicorn's middleware is not installed at all --
+ exactly when ``proxy_headers`` is False, so no allow-list can widen
+ anything without the explicit opt-in, and the opt-in never arrives
+ without one. With ``LDR_SERVER_FORWARDED_ALLOW_IPS`` unset (the
+ fixture clears it), the value passed on the opt-in side is uvicorn's
+ own backward-compatible ``"*"``.
"""
_, kwargs = uvicorn_run_kwargs(value)
- assert (kwargs["forwarded_allow_ips"] == "*") is (
- kwargs["proxy_headers"] is True
+ assert (kwargs["forwarded_allow_ips"] is None) is (
+ kwargs["proxy_headers"] is False
)
+ if kwargs["proxy_headers"]:
+ assert kwargs["forwarded_allow_ips"] == "*"
def test_ldr_prefixed_variable_does_not_enable_proxy_trust(
self, monkeypatch, uvicorn_run_kwargs
@@ -1015,6 +1075,48 @@ class TestTrustProxyHeadersUvicornWiring:
assert 'os.environ.get("LDR_TRUST_PROXY_HEADERS"' not in app_source
assert 'os.environ.get("LDR_TRUST_PROXY_HEADERS"' not in rl_source
+ @pytest.mark.parametrize(
+ "raw",
+ ["*,", ",", " 10.0.0.5 , ", "", "*", "10.0.0.5,,10.0.0.6", " "],
+ )
+ def test_app_and_rate_limit_normalise_identically(self, raw):
+ """Both halves must hand uvicorn, and describe, the same string.
+
+ ``web/app.py`` sets ``--forwarded-allow-ips``; ``rate_limit.py``
+ classifies the same variable and quotes its own resolved value in
+ the RuntimeError, the startup warning and the info line. When the
+ two normalised differently, those messages described an allow-list
+ uvicorn was never given: ``","`` reached uvicorn verbatim (one
+ literal entry matching no peer, so every client shared a bucket)
+ while the rate limiter read it as unset.
+
+ Duplicated rather than shared because ``web/app.py`` must not
+ import ``rate_limit`` before uvicorn starts -- that would run its
+ import-time startup guard and freeze its allow-list early. This
+ test is what keeps the twins in step.
+ """
+ from local_deep_research.web import app as web_app
+ from local_deep_research.web.dependencies import rate_limit
+
+ assert web_app._normalise_forwarded_allow_ips(
+ raw
+ ) == rate_limit._normalise_forwarded_allow_ips(raw)
+
+ def test_normalised_allow_list_is_what_reaches_uvicorn(
+ self, monkeypatch, uvicorn_run_kwargs
+ ):
+ """Execution-verified end of the same contract."""
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", " 10.0.0.5 , ")
+ _, kwargs = uvicorn_run_kwargs("true")
+ assert kwargs["forwarded_allow_ips"] == "10.0.0.5"
+
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", ",")
+ _, kwargs = uvicorn_run_kwargs("true")
+ assert kwargs["forwarded_allow_ips"] == "*", (
+ "a comma-only value used to reach uvicorn verbatim as a single "
+ "literal entry matching no peer"
+ )
+
def test_other_security_relevant_server_kwargs_are_forwarded(
self, uvicorn_run_kwargs
):
diff --git a/tests/security/test_network_utils.py b/tests/security/test_network_utils.py
index 6326bcaebf..4912c50ec9 100644
--- a/tests/security/test_network_utils.py
+++ b/tests/security/test_network_utils.py
@@ -1,6 +1,15 @@
"""Tests for network_utils module - IP address classification."""
-from local_deep_research.security.network_utils import is_private_ip
+import ipaddress
+
+import pytest
+
+from local_deep_research.security.network_utils import (
+ IPV6_TRANSITION_NETWORKS,
+ is_ipv6_transition_address,
+ is_private_ip,
+ is_private_peer_ip,
+)
class TestIsPrivateIPLocalhost:
@@ -159,3 +168,102 @@ class TestIsPrivateIPEdgeCases:
assert is_private_ip("not.an.ip.address") is False
assert is_private_ip("256.256.256.256") is False
assert is_private_ip("192.168.1") is False
+
+
+class TestIsPrivatePeerIp:
+ """The inbound-peer variant used for proxy-trust decisions."""
+
+ @pytest.mark.parametrize(
+ "addr",
+ [
+ "2002:808:808::1", # 6to4 wrapping 8.8.8.8
+ "2002:a00:1::1", # 6to4 wrapping 10.0.0.1: still a remote relay
+ "2001:0:4136:e378:8000:63bf:3fff:fdd2", # Teredo
+ "64:ff9b:1::808:808", # RFC 8215 NAT64 local-use
+ "64:ff9b::808:808", # RFC 6052 NAT64 well-known
+ "[2002:808:808::1]",
+ ],
+ )
+ def test_transition_addresses_are_not_private_peers(self, addr):
+ assert is_private_peer_ip(addr) is False
+
+ @pytest.mark.parametrize(
+ "addr",
+ [
+ "127.0.0.1",
+ "10.1.2.3",
+ "192.168.0.1",
+ "::1",
+ "[::1]",
+ "fd00::1",
+ "fe80::1",
+ "::ffff:10.0.0.1",
+ ],
+ )
+ def test_private_peers_stay_private(self, addr):
+ assert is_private_peer_ip(addr) is True
+
+ @pytest.mark.parametrize(
+ "addr", ["8.8.8.8", "2001:4860:4860::8888", "::ffff:8.8.8.8"]
+ )
+ def test_public_peers_are_not_private(self, addr):
+ assert is_private_peer_ip(addr) is False
+
+ def test_mapped_address_follows_the_wrapped_ipv4(self, monkeypatch):
+ """Decided by unwrapping, not by the interpreter's table.
+
+ From CPython 3.12.4, ``IPv6Address.is_private`` delegates a mapped
+ address to the IPv4 it wraps, so there deleting the unwrap in
+ ``is_private_peer_ip`` changes no verdict. This simulates CPython
+ 3.12.0 to 3.12.3, which answer mapped addresses from their IPv6
+ network table instead, where ``::ffff:0:0/96`` is listed private
+ outright, so the unwrap is what the assertions observe.
+ """
+ mapped_range = ipaddress.ip_network("::ffff:0:0/96")
+ table_answer = ipaddress.IPv6Address.is_private
+
+ def is_private_from_table(self):
+ if self in mapped_range:
+ return True
+ return table_answer.fget(self)
+
+ monkeypatch.setattr(
+ ipaddress.IPv6Address,
+ "is_private",
+ property(is_private_from_table),
+ )
+ # The simulation is in effect: the stdlib now says "private".
+ assert ipaddress.ip_address("::ffff:8.8.8.8").is_private is True
+
+ assert is_private_peer_ip("::ffff:8.8.8.8") is False
+ assert is_private_peer_ip("[::ffff:8.8.8.8]") is False
+ assert is_private_peer_ip("::ffff:10.0.0.1") is True
+
+ @pytest.mark.parametrize("host", ["localhost", "printer.local", "x.com"])
+ def test_non_ip_hosts_defer_to_is_private_ip(self, host):
+ assert is_private_peer_ip(host) is is_private_ip(host)
+
+ def test_is_private_ip_itself_is_unchanged(self):
+ """The outbound callers (egress policy, URL normalisation) keep the
+ interpreter's classification; only the peer variant excludes the
+ transition ranges. Teredo is used because CPython lists it private
+ (through ``2001::/23``; the first assertion checks that on the
+ running interpreter), so this fails if ``is_private_ip`` starts
+ excluding transition ranges itself."""
+ teredo = "2001:0:4136:e378:8000:63bf:3fff:fdd2"
+ assert ipaddress.ip_address(teredo).is_private is True
+ assert is_private_ip(teredo) is True
+ assert is_private_peer_ip(teredo) is False
+
+ def test_transition_networks_are_the_four_prefixes(self):
+ assert {str(n) for n in IPV6_TRANSITION_NETWORKS} == {
+ "2002::/16",
+ "2001::/32",
+ "64:ff9b::/96",
+ "64:ff9b:1::/48",
+ }
+
+ def test_transition_membership_ignores_ipv4(self):
+ assert is_ipv6_transition_address(ipaddress.ip_address("8.8.8.8")) is (
+ False
+ )
diff --git a/tests/security/test_rate_limit_key_derivation.py b/tests/security/test_rate_limit_key_derivation.py
index 8757366088..8f1dbdefb3 100644
--- a/tests/security/test_rate_limit_key_derivation.py
+++ b/tests/security/test_rate_limit_key_derivation.py
@@ -447,6 +447,60 @@ class TestDerivedKeyIsValidatedAsAnAddress:
)
assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+ @pytest.mark.parametrize("hop_count", [1, 2])
+ @pytest.mark.parametrize(
+ "token",
+ [
+ "user:alice",
+ "proxy.internal.example",
+ "1.1.1.1 user_agent=trusted-monitor endpoint=/healthz",
+ "unknown",
+ "1.2.3.4:http",
+ ],
+ )
+ def test_non_address_selected_hop_falls_back(
+ self, rl, monkeypatch, hop_count, token
+ ):
+ """``LDR_SERVER_TRUSTED_PROXY_COUNT`` mode: the entry at the
+ configured hop is validated too, so a proxy that appends a
+ hostname, ``unknown`` or other text keys on the direct peer rather
+ than on that text. The token sits exactly at index ``-hop_count``;
+ the entries to its right are what the inner proxies appended."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", hop_count)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ inner_hops = ["10.0.0.9"] * (hop_count - 1)
+ header = ", ".join([REAL_CLIENT, token, *inner_hops])
+ request = make_request(
+ peer=PRIVATE_PROXY_PEER, headers={"X-Forwarded-For": header}
+ )
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+
+ @pytest.mark.parametrize("hop_count", [1, 2])
+ @pytest.mark.parametrize(
+ "raw_value", [b"", b" ", b"\xa0", b" \xa0 ", b",", b" , \xa0"]
+ )
+ def test_blank_forwarded_entries_at_the_hop_fall_back(
+ self, rl, monkeypatch, hop_count, raw_value
+ ):
+ """Hop-count mode with a header made only of empty, whitespace or
+ NBSP entries: nothing is selected, so the key is the direct peer,
+ never ``""`` (which would make slowapi skip the limit). Raw bytes
+ go in the scope because ``make_request`` UTF-8-encodes, which would
+ turn U+00A0 into two non-space bytes."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", hop_count)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ request = Request(
+ {
+ "type": "http",
+ "method": "POST",
+ "path": "/auth/login",
+ "query_string": b"",
+ "headers": [(b"x-forwarded-for", raw_value)],
+ "client": (PRIVATE_PROXY_PEER, 51234),
+ }
+ )
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+
@pytest.mark.parametrize(
"entry, expected",
[
@@ -522,6 +576,80 @@ class TestDerivedKeyIsValidatedAsAnAddress:
)
assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+ @pytest.fixture(params=["unrestricted", "restricted"])
+ def trusted_proxy_mode(self, request, rl, monkeypatch):
+ """``TRUST_PROXY_HEADERS=true`` with no X-Forwarded-For: the
+ X-Real-IP fallback that keeps per-client keys behind an
+ X-Real-IP-only proxy. The flag-on branch has its OWN copy of the
+ address validation, which the flag-off tests above never reach.
+ Run it in both allow-list modes, with ``PRIVATE_PROXY_PEER``
+ entitled to supply the header in each: private in the
+ unrestricted case, listed in the restricted one."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ restricted = request.param == "restricted"
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", restricted)
+ if restricted:
+ monkeypatch.setattr(
+ rl, "_FORWARDED_ALLOW_ENTRIES", (PRIVATE_PROXY_PEER,)
+ )
+ return request.param
+
+ @pytest.mark.parametrize(
+ "token",
+ [
+ "1.1.1.1 user_agent=trusted-monitor",
+ "user:alice",
+ "not-an-address-at-all",
+ ],
+ )
+ def test_non_address_x_real_ip_falls_back_under_the_flag(
+ self, rl, trusted_proxy_mode, token
+ ):
+ request = make_request(
+ peer=PRIVATE_PROXY_PEER, headers={"X-Real-IP": token}
+ )
+ assert rl._get_client_ip(request) == PRIVATE_PROXY_PEER
+
+ def test_x_real_ip_with_port_keys_on_the_address_under_the_flag(
+ self, rl, trusted_proxy_mode
+ ):
+ request = make_request(
+ 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_under_the_flag(
+ self, rl, trusted_proxy_mode, raw_value
+ ):
+ """An empty key makes slowapi skip the limit; see the flag-off
+ version above for why these bytes reach the header verbatim."""
+ 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_valid_x_real_ip_is_honoured_under_the_flag(
+ self, rl, trusted_proxy_mode
+ ):
+ """CONTROL: the fallbacks above come from validation, not from
+ the header being ignored altogether in this branch."""
+ request = make_request(
+ peer=PRIVATE_PROXY_PEER, headers={"X-Real-IP": REAL_CLIENT}
+ )
+ assert rl._get_client_ip(request) == REAL_CLIENT
+
def test_unparseable_direct_peer_under_the_flag_shares_one_bucket(
self, rl, monkeypatch
):
@@ -655,16 +783,17 @@ class TestFourTwoNineResponseDoesNotLeakTheKey:
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>)``;
+ * ``ip`` -- one reviewed bounded wrapper around
+ ``_get_client_ip(request)``, with ``max_length <= 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(..., max_length=<int <= 256>)`` (or the
+ redact-before-bound successor).
- ``sanitize_for_log`` is the helper ``routers/auth.py`` uses for the
- equally client-supplied username; the JSON quoting keeps a
+ Both reviewed wrappers bound the value; the successor also redacts
+ credentials before truncation. 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::
@@ -726,11 +855,12 @@ class TestFourTwoNineResponseDoesNotLeakTheKey:
and 1 <= cap.value <= limit
)
- def is_sanitize_call(node, limit):
+ def is_bounded_log_call(node, limit):
return (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
- and node.func.id == "sanitize_for_log"
+ and node.func.id
+ in {"sanitize_for_log", "redact_and_bound_for_log"}
and len(node.args) == 1
and max_length_at_most(node, limit)
)
@@ -741,12 +871,13 @@ class TestFourTwoNineResponseDoesNotLeakTheKey:
ip_fields = [
value
for value in values
- if is_sanitize_call(value, 64)
+ if is_bounded_log_call(value, 64)
and ast.dump(value.args[0]) == ip_expected
]
assert len(ip_fields) == 1, (
"expected exactly one field of the form "
- "sanitize_for_log(_get_client_ip(request), max_length=<=64): "
+ "bounded log wrapper around _get_client_ip(request), "
+ "max_length=<=64: "
f"{[ast.unparse(v) for v in values]}"
)
@@ -792,9 +923,9 @@ class TestFourTwoNineResponseDoesNotLeakTheKey:
"single-target assignment"
)
(assign,) = assigns
- assert is_sanitize_call(assign.value, 256), (
+ assert is_bounded_log_call(assign.value, 256), (
f"{name!r} is not assigned from "
- "sanitize_for_log(..., max_length=<=256): "
+ "a bounded log wrapper (..., max_length=<=256): "
f"{ast.unparse(assign.value)}"
)
assert assign.lineno < warning.lineno, (
diff --git a/tests/settings/test_trusted_proxy_setting.py b/tests/settings/test_trusted_proxy_setting.py
new file mode 100644
index 0000000000..8cfb8efcc0
--- /dev/null
+++ b/tests/settings/test_trusted_proxy_setting.py
@@ -0,0 +1,248 @@
+import pytest
+
+from local_deep_research.settings.env_registry import get_env_setting
+from local_deep_research.settings.env_settings import (
+ IntegerSetting,
+ SettingsRegistry,
+)
+from local_deep_research.settings.exceptions import (
+ EnvironmentValueRangeError,
+ InvalidEnvironmentValueError,
+)
+
+
+_TRUSTED_PROXY_ENV_VAR = "LDR_SERVER_TRUSTED_PROXY_COUNT"
+
+
+def test_trusted_proxy_count_raises_specific_error_for_malformed_value(
+ monkeypatch,
+):
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, "not-an-integer")
+
+ # When / Then
+ with pytest.raises(InvalidEnvironmentValueError) as error:
+ get_env_setting("server.trusted_proxy_count", 0)
+ assert error.value.env_var == _TRUSTED_PROXY_ENV_VAR
+ assert str(error.value) == (
+ "LDR_SERVER_TRUSTED_PROXY_COUNT: value 'not-an-integer' is not a valid integer"
+ )
+ assert isinstance(error.value.__cause__, ValueError)
+
+
+def test_trusted_proxy_count_raises_range_error_for_negative_value(monkeypatch):
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, "-1")
+
+ # When / Then
+ with pytest.raises(EnvironmentValueRangeError) as error:
+ get_env_setting("server.trusted_proxy_count", 0)
+ assert error.value.env_var == _TRUSTED_PROXY_ENV_VAR
+ assert str(error.value) == (
+ "LDR_SERVER_TRUSTED_PROXY_COUNT: value -1 is below minimum 0"
+ )
+
+
[email protected]("configured_count", ["0", "2"])
+def test_trusted_proxy_count_returns_valid_non_negative_value(
+ monkeypatch, configured_count
+):
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, configured_count)
+
+ # When
+ value = get_env_setting("server.trusted_proxy_count", 0)
+
+ # Then
+ assert value == int(configured_count)
+
+
+def test_trusted_proxy_count_uses_zero_default_when_unset(monkeypatch):
+ # Given
+ monkeypatch.delenv(_TRUSTED_PROXY_ENV_VAR, raising=False)
+
+ # When
+ value = get_env_setting("server.trusted_proxy_count", 0)
+
+ # Then
+ assert value == 0
+
+
+def test_non_strict_integer_setting_keeps_malformed_value_fallback(monkeypatch):
+ # Given
+ setting = IntegerSetting(
+ key="testing.non_strict_integer",
+ description="Test-only non-strict integer setting.",
+ default=7,
+ )
+ monkeypatch.setenv("LDR_TESTING_NON_STRICT_INTEGER", "not-an-integer")
+
+ # When
+ value = setting.get_value()
+
+ # Then
+ assert value == 7
+
+
[email protected]("raw_value", ["not-an-integer", "-1"])
+def test_registry_propagates_opted_in_integer_validation_errors(
+ monkeypatch, raw_value
+):
+ # Given
+ registry = SettingsRegistry()
+ setting = IntegerSetting(
+ key="testing.opted_in_integer",
+ description="Test-only opted-in integer setting.",
+ default=7,
+ min_value=0,
+ raise_on_validation_error=True,
+ )
+ registry.register_category("testing", [setting])
+ monkeypatch.setenv("LDR_TESTING_OPTED_IN_INTEGER", raw_value)
+
+ # When / Then
+ with pytest.raises(
+ (InvalidEnvironmentValueError, EnvironmentValueRangeError)
+ ):
+ registry.get("testing.opted_in_integer", 7)
+
+
[email protected]("raw_value", ["not-an-integer", "-1"])
+def test_registry_keeps_non_opted_in_integer_validation_fallback(
+ monkeypatch, raw_value
+):
+ # Given
+ registry = SettingsRegistry()
+ setting = IntegerSetting(
+ key="testing.non_opted_in_integer",
+ description="Test-only non-opted-in integer setting.",
+ default=7,
+ min_value=0,
+ )
+ registry.register_category("testing", [setting])
+ monkeypatch.setenv("LDR_TESTING_NON_OPTED_IN_INTEGER", raw_value)
+
+ # When
+ value = registry.get("testing.non_opted_in_integer", 7)
+
+ # Then
+ assert value == 7
+
+
+def test_trusted_proxy_count_treats_empty_value_as_unset(monkeypatch):
+ """``LDR_SERVER_TRUSTED_PROXY_COUNT=""`` must fall back to the default.
+
+ The repo-wide contract, pinned by
+ ``tests/test_config_env_var_contracts.py::
+ test_empty_env_var_is_treated_as_unset_not_as_false``: "``LDR_X=""`` must
+ fall back to the DB/default, not override it. Orchestrators (Unraid,
+ Compose, k8s manifests) frequently emit an empty string for an
+ unconfigured variable." Opting a setting into
+ ``raise_on_validation_error`` must not turn that routine emission into a
+ refusal to boot -- every other IntegerSetting warns and defaults.
+ """
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, "")
+
+ # When
+ value = get_env_setting("server.trusted_proxy_count", 0)
+
+ # Then
+ assert value == 0
+
+
+ "raw_value",
+ [
+ "1_0", # int() reads 10; reviewers read "one hop"
+ "+3", # int() reads 3
+ "٣", # ARABIC-INDIC DIGIT THREE; int() reads 3
+ "1", # FULLWIDTH DIGIT ONE; int() reads 1
+ " 2x ",
+ ],
+)
+def test_trusted_proxy_count_rejects_non_plain_ascii_spellings(
+ monkeypatch, raw_value
+):
+ """A trust-boundary hop count must mean what it looks like.
+
+ ``int()`` accepts underscore separators, a leading ``+`` and any Unicode
+ decimal digit, so a value that reads as one hop in review can resolve to
+ ten at runtime -- silently shifting which X-Forwarded-For entry is
+ believed. Reject the lot rather than normalising them.
+ """
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, raw_value)
+
+ # When / Then
+ with pytest.raises(InvalidEnvironmentValueError) as error:
+ get_env_setting("server.trusted_proxy_count", 0)
+ assert error.value.env_var == _TRUSTED_PROXY_ENV_VAR
+
+
[email protected]("raw_value", ["17", "5000", "99999999999999999999"])
+def test_trusted_proxy_count_rejects_values_above_the_hop_bound(
+ monkeypatch, raw_value
+):
+ """An absurd hop count is a typo, and silently accepting it collapses
+ every client behind the proxy into the direct peer's single bucket: no
+ real X-Forwarded-For chain has that many entries, so ``_select_trusted_
+ hop`` returns None on every request and the limiter falls back to the
+ peer. Fail at startup, naming the variable, instead."""
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, raw_value)
+
+ # When / Then
+ with pytest.raises(EnvironmentValueRangeError) as error:
+ get_env_setting("server.trusted_proxy_count", 0)
+ assert error.value.env_var == _TRUSTED_PROXY_ENV_VAR
+ assert "above maximum 16" in str(error.value)
+
+
[email protected]("raw_value", ["0", "1", "16", " 4 "])
+def test_trusted_proxy_count_accepts_plain_values_in_range(
+ monkeypatch, raw_value
+):
+ """Positive control for the two rejections above: the ordinary
+ spellings, including the upper bound and surrounding whitespace, still
+ resolve."""
+ # Given
+ monkeypatch.setenv(_TRUSTED_PROXY_ENV_VAR, raw_value)
+
+ # When / Then
+ assert get_env_setting("server.trusted_proxy_count", 0) == int(
+ raw_value.strip()
+ )
+
+
+def test_non_strict_integer_setting_still_accepts_int_spellings(monkeypatch):
+ """The strict parse is opt-in, not a change to every IntegerSetting.
+
+ Negative control for the parametrized rejection above: a setting that
+ did not ask for ``strict_digits`` keeps ``int()``'s own grammar.
+ """
+ # Given
+ setting = IntegerSetting(
+ key="testing.lenient_integer",
+ description="Test-only lenient integer setting.",
+ default=7,
+ )
+ monkeypatch.setenv("LDR_TESTING_LENIENT_INTEGER", "1_0")
+
+ # When / Then
+ assert setting.get_value() == 10
+
+
+def test_non_strict_integer_setting_treats_empty_value_as_unset(monkeypatch):
+ """The ``LDR_X=""`` contract applies to every IntegerSetting, not just
+ the opted-in one."""
+ # Given
+ setting = IntegerSetting(
+ key="testing.lenient_empty_integer",
+ description="Test-only lenient integer setting.",
+ default=7,
+ )
+ monkeypatch.setenv("LDR_TESTING_LENIENT_EMPTY_INTEGER", "")
+
+ # When / Then
+ assert setting.get_value() == 7
diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.py
index ec311ff121..3df7c35b65 100644
--- a/tests/test_config_env_var_contracts.py
+++ b/tests/test_config_env_var_contracts.py
@@ -419,6 +419,12 @@ _KNOWN_DEAD_REGISTRY_KEYS = {
"bootstrap.encryption_key",
"bootstrap.log_dir",
"bootstrap.secret_key",
+ # Read directly via TRUSTED_PROXY_COUNT.get_value() at
+ # web/dependencies/rate_limit.py import time (must be resolved before
+ # SettingsManager exists, like TRUST_PROXY_HEADERS above), never
+ # through a SettingsManager/registry lookup by string key -- so the
+ # generic "is this key ever read" scan can't see it.
+ "server.trusted_proxy_count",
}
@@ -936,7 +942,22 @@ _KNOWN_IMPORT_TIME_READS = {
# slowapi limiter is built at import, so all three freeze
("web/dependencies/rate_limit.py", "TRUST_PROXY_HEADERS"),
("web/dependencies/rate_limit.py", "RATE_LIMIT_STORAGE_URI"),
+ # Read at module scope and handed to ``_resolve_legacy_storage_uri()``,
+ # which (also at import) falls back to the same key in ./.env, as
+ # slowapi does; keep the environ read at module scope so this sweep,
+ # which stops at function bodies, still sees the freeze.
("web/dependencies/rate_limit.py", "RATELIMIT_STORAGE_URL"),
+ # Decides, alongside TRUSTED_PROXY_COUNT, whether the startup guard
+ # above raises or only warns; must be read at import time for the
+ # same reason TRUST_PROXY_HEADERS is.
+ ("web/dependencies/rate_limit.py", "LDR_SERVER_FORWARDED_ALLOW_IPS"),
+ # The other half of that guard's input. Its VALUE is resolved through
+ # the typed ``TRUSTED_PROXY_COUNT`` setting (which validates it and
+ # aborts startup on a malformed/out-of-range one); the plain
+ # ``os.environ.get`` beside it exists so this sweep -- which matches
+ # ``os.getenv``/``os.environ.get`` call sites and cannot see a
+ # settings object's ``.get_value()`` -- records the freeze.
+ ("web/dependencies/rate_limit.py", "LDR_SERVER_TRUSTED_PROXY_COUNT"),
}
diff --git a/tests/web/dependencies/test_rate_limit_keys.py b/tests/web/dependencies/test_rate_limit_keys.py
index 83da137d98..548a2ae1d5 100644
--- a/tests/web/dependencies/test_rate_limit_keys.py
+++ b/tests/web/dependencies/test_rate_limit_keys.py
@@ -6,9 +6,11 @@ register brute-force limits on ``_get_client_ip``. If X-Forwarded-For were
honored from an arbitrary public peer, an attacker could rotate the header
value on every request and get a fresh rate-limit bucket each time,
nullifying the login lockout. The guard trusts forwarding headers only when
-the DIRECT peer is a private/loopback address (typical reverse-proxy or
-Docker/k8s deployment), the Starlette TestClient sentinel, or when the
-operator opted in via TRUST_PROXY_HEADERS.
+the DIRECT peer passes ``_peer_may_supply_forwarding_headers``:
+membership in an explicitly configured, restricted
+``LDR_SERVER_FORWARDED_ALLOW_IPS`` allow-list; otherwise (allow-list
+unset or "*") the pre-existing private/loopback heuristic, plus the
+Starlette TestClient sentinel and the TRUST_PROXY_HEADERS opt-in.
These are pure unit tests: minimal Starlette ``Request`` objects are built
from raw ASGI scope dicts — no server, no TestClient, no app import.
@@ -38,16 +40,43 @@ def rl():
return rate_limit
+def restrict_allow_list(rl, monkeypatch, allow_ips):
+ """Put the module in restricted-allow-list mode for ``allow_ips``.
+
+ Mirrors a deployment where ``LDR_SERVER_FORWARDED_ALLOW_IPS`` names the
+ proxy: ``web/app.py`` hands the same value to uvicorn, so a test that
+ stands ``peer`` in for uvicorn's computed client address describes this
+ mode. With the unrestricted ``"*"`` the flag-on branch keys on the
+ right-most X-Forwarded-For entry instead (#6442).
+ """
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", True)
+ monkeypatch.setattr(
+ rl,
+ "_FORWARDED_ALLOW_ENTRIES",
+ tuple(e.strip() for e in allow_ips.split(",") if e.strip()),
+ )
+
+
def make_request(peer="8.8.8.8", headers=None, session=None, no_client=False):
- """Build a minimal Starlette Request from a raw ASGI scope dict."""
+ """Build a minimal Starlette Request from a raw ASGI scope dict.
+
+ ``headers`` is normally a dict (one value per header name). Pass a
+ list of ``(name, value)`` pairs instead to emit MULTIPLE header lines
+ for the same name -- e.g. two separate ``X-Forwarded-For`` lines, as a
+ proxy that appends (rather than edits) the header produces. A dict
+ can only ever represent one line per name; ASGI's ``headers`` list
+ (and therefore ``Headers.getlist()``) can represent several, which is
+ exactly the case the multi-line XFF tests below need to construct.
+ """
+ header_pairs = (
+ headers.items() if isinstance(headers, dict) else (headers or [])
+ )
scope = {
"type": "http",
"method": "GET",
"path": "/",
"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 header_pairs],
}
if not no_client:
scope["client"] = (peer, 51234)
@@ -86,6 +115,73 @@ class TestIsTrustedPeer:
assert rl._is_trusted_peer("some-random-host") is False
+#: One address per IPv6 transition range, each wrapping a PUBLIC IPv4 or
+#: standing for a remote Teredo client. Python's ``is_private`` may report
+#: the first three as private on some Python versions (which ranges it
+#: treats as private has changed between releases); the well-known NAT64
+#: one reads public. LDR excludes all four on every version, and all four
+#: are pinned so the exclusion does not depend on ``ipaddress``.
+TRANSITION_PEERS = [
+ pytest.param("2002:808:808::1", id="6to4"),
+ pytest.param("2001:0:4136:e378:8000:63bf:3fff:fdd2", id="teredo"),
+ pytest.param("64:ff9b:1::808:808", id="nat64-local-use"),
+ pytest.param("64:ff9b::808:808", id="nat64-well-known"),
+]
+
+
+class TestTransitionPeersAreNotTrusted:
+ """A 6to4 / Teredo / NAT64 peer is a remote host arriving through a
+ relay or translator, so in unrestricted mode it must not be treated as
+ a private proxy -- otherwise it could pick its own rate-limit key with
+ X-Forwarded-For or X-Real-IP."""
+
+ @pytest.mark.parametrize("peer", TRANSITION_PEERS)
+ def test_transition_peer_is_not_trusted(self, rl, peer):
+ assert rl._is_trusted_peer(peer) is False
+
+ @pytest.mark.parametrize("peer", TRANSITION_PEERS)
+ def test_transition_peer_cannot_supply_forwarding_headers(
+ self, rl, monkeypatch, peer
+ ):
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ assert rl._peer_may_supply_forwarding_headers(peer) is False
+
+ @pytest.mark.parametrize("peer", TRANSITION_PEERS)
+ @pytest.mark.parametrize("header", ["X-Forwarded-For", "X-Real-IP"])
+ def test_transition_peer_cannot_choose_its_key(
+ self, rl, monkeypatch, peer, header
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ request = make_request(peer=peer, headers={header: "10.0.0.99"})
+ assert rl._get_client_ip(request) == peer
+
+ def test_positive_control_private_peer_still_chooses_its_key(
+ self, rl, monkeypatch
+ ):
+ """Without this, the tests above would also pass against a trust
+ check that rejected every peer."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ request = make_request(
+ peer="fd00::5", headers={"X-Forwarded-For": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+ @pytest.mark.parametrize(
+ "peer", ["2003::1", "2001:db8::1", "2001:1::1", "64:ff9b:2::1"]
+ )
+ def test_neighbours_of_the_transition_ranges_keep_their_classification(
+ self, rl, peer
+ ):
+ """Range boundaries: the exclusion must not reach past the four
+ transition prefixes. Each neighbour keeps whatever
+ ``is_private_ip`` says about it."""
+ from local_deep_research.security.network_utils import is_private_ip
+
+ assert rl._is_trusted_peer(peer) is is_private_ip(peer)
+
+
class TestGetClientIpSpoofGuard:
"""X-Forwarded-For / X-Real-IP from an untrusted PUBLIC direct peer
must be ignored — otherwise per-IP limits are trivially bypassed."""
@@ -199,7 +295,26 @@ class TestGetClientIpTrustedPeer:
class TestTrustProxyHeadersOverride:
"""TRUST_PROXY_HEADERS=true (operator opt-in for a public-facing
- reverse proxy) makes forwarded headers trusted from ANY peer.
+ reverse proxy) means uvicorn's own ``ProxyHeadersMiddleware`` --
+ running as the OUTERMOST ASGI layer, before this module's code ever
+ sees the request -- is the sole authority on the client address.
+ ``_get_client_ip`` must NOT re-parse X-Forwarded-For itself whenever
+ this flag is true, at ANY ``LDR_SERVER_TRUSTED_PROXY_COUNT`` value
+ (including its default of 0/unset) -- see the module-level tri-state
+ guard's comment and ``_get_client_ip``'s docstring.
+
+ Regression coverage for the defect fixed here: the combo-mode "trust
+ uvicorn's request.client, don't re-parse XFF" rule was originally
+ wired ONLY inside the ``if _TRUSTED_PROXY_COUNT > 0:`` branch, so a
+ deployment with ``TRUST_PROXY_HEADERS=true`` + a restricted
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` (the documented, recommended
+ combination) but ``LDR_SERVER_TRUSTED_PROXY_COUNT`` left at its
+ default of 0 fell through to the legacy branch below, which honored
+ the left-most (client-forgeable) X-Forwarded-For entry -- exploitable
+ even though uvicorn itself was already computing the correct client
+ address one layer up. The fix hoists the "trust direct_peer" rule
+ above the ``_TRUSTED_PROXY_COUNT`` check so it is unconditional on
+ ``TRUST_PROXY_HEADERS`` alone.
The env var is evaluated once at module import into
``_TRUST_PROXY_HEADERS``; ``_get_client_ip`` reads that module global
@@ -208,8 +323,61 @@ class TestTrustProxyHeadersOverride:
out from under concurrently-running tests.
"""
- def test_flag_makes_public_peer_xff_trusted(self, rl, monkeypatch):
+ def test_flag_trusts_direct_peer_and_ignores_xff(self, rl, monkeypatch):
+ """``peer`` here stands in for whatever uvicorn's
+ ProxyHeadersMiddleware already resolved ``request.client`` to (the
+ real client, once uvicorn has run) -- this function must return it
+ as-is and must NOT let a forged X-Forwarded-For entry override it,
+ at the default LDR_SERVER_TRUSTED_PROXY_COUNT of 0. That holds for a
+ RESTRICTED allow-list, the only mode in which uvicorn's answer is
+ verified."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ restrict_allow_list(rl, monkeypatch, "10.0.0.5")
+ request = make_request(
+ peer="8.8.8.8", headers={"X-Forwarded-For": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_flag_with_unrestricted_allow_list_keys_on_rightmost_entry(
+ self, rl, monkeypatch
+ ):
+ """With the unrestricted ``"*"``, uvicorn rewrote ``request.client``
+ from the LEFT-most (client-forgeable) entry, so the key is the
+ RIGHT-most entry -- the one the nearest proxy appended (#6442) --
+ not ``direct_peer``. A rotating forged prefix under an appending
+ proxy therefore mints no new buckets.
+
+ The peers are PUBLIC addresses (``8.8.{i}.1``), as uvicorn produces
+ them here: it copies the forged left-most entry into
+ ``request.client``, and a forger picks public addresses. The
+ right-most rule must hold without any private/loopback peer check
+ -- the RFC 5737 ranges would pass that check and hide a regression
+ that gates this branch on it."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer=f"8.8.{i}.1",
+ headers={"X-Forwarded-For": f"8.8.{i}.1, 93.184.216.34"},
+ )
+ )
+ for i in range(5)
+ }
+ assert keys == {"93.184.216.34"}
+
+ def test_flag_with_unrestricted_allow_list_trusts_public_peer_xff(
+ self, rl, monkeypatch
+ ):
+ """With the unrestricted ``"*"`` a PUBLIC direct peer's single-entry
+ X-Forwarded-For is the key, exactly as before the allow-list setting
+ existed: under ``TRUST_PROXY_HEADERS`` the header is not gated on
+ the peer being private or loopback."""
monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
request = make_request(
peer="8.8.8.8", headers={"X-Forwarded-For": "93.184.216.34"}
)
@@ -223,6 +391,121 @@ class TestTrustProxyHeadersOverride:
assert rl._get_client_ip(request) == "8.8.8.8"
+class TestTrustProxyHeadersXRealIpFallback:
+ """Regression coverage for the defect fixed here: ``_get_client_ip``'s
+ ``TRUST_PROXY_HEADERS=true`` branch unconditionally trusted
+ ``direct_peer`` and never looked at ``X-Real-IP`` at all, even when no
+ X-Forwarded-For was present.
+
+ uvicorn's ``ProxyHeadersMiddleware`` ONLY ever inspects
+ X-Forwarded-For (see ``uvicorn/middleware/proxy_headers.py`` --
+ ``scope["client"]`` is rewritten only inside
+ ``if x_forwarded_for_values:``); it has no notion of X-Real-IP
+ whatsoever. So a reverse proxy configured with only
+ ``proxy_set_header X-Real-IP $remote_addr`` (a common nginx pattern)
+ or any request that simply arrives without X-Forwarded-For leaves
+ ``request.client`` as the proxy's own raw socket address -- collapsing
+ every client behind that proxy into ONE shared rate-limit bucket
+ unless this module restores the X-Real-IP fallback itself.
+
+ Restoring it naively (main's pre-PR behaviour: trust X-Real-IP
+ unconditionally whenever ``TRUST_PROXY_HEADERS`` is true) would reopen
+ the exact spoof this PR closes, because uvicorn provides no
+ equivalent gate for X-Real-IP the way it does for X-Forwarded-For --
+ so the fallback must be gated by
+ ``_peer_may_supply_forwarding_headers(direct_peer)``, the SAME
+ allow-list-aware trust check used for every other forwarding
+ decision in this module (restricted LDR_SERVER_FORWARDED_ALLOW_IPS
+ membership when explicitly configured; the private/loopback
+ heuristic otherwise). These tests build real Starlette
+ ``Request``/``Headers`` objects via ``make_request`` (not dict mocks)
+ since ``_get_forwarded_for`` depends on ``Headers.getlist``, which a
+ dict does not have.
+ """
+
+ def test_real_ip_used_when_no_xff_and_peer_trusted(self, rl, monkeypatch):
+ """Direct peer is a trusted proxy (private/loopback) and the
+ request carries no X-Forwarded-For at all -- uvicorn had nothing
+ to rewrite ``request.client`` from, so it is still the proxy's
+ own raw address here. The X-Real-IP fallback must kick in."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="10.0.0.5", headers={"X-Real-IP": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+ def test_real_ip_ignored_when_no_xff_and_peer_untrusted(
+ self, rl, monkeypatch
+ ):
+ """Direct peer is a public (untrusted) address -- an attacker
+ connecting straight to LDR without going through any reverse
+ proxy. uvicorn does not gate X-Real-IP the way it gates
+ X-Forwarded-For, so this function is the ONLY thing standing
+ between an attacker-supplied X-Real-IP and the rate limiter; it
+ must be ignored, and the client must not get to pick its own
+ rate-limit bucket."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="8.8.8.8", headers={"X-Real-IP": "203.0.113.99"}
+ )
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_rotating_real_ip_from_untrusted_peer_never_changes_key(
+ self, rl, monkeypatch
+ ):
+ """The actual bypass attempt: a new spoofed X-Real-IP value per
+ request must keep landing in the same (direct-peer) bucket."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer="8.8.8.8",
+ headers={"X-Real-IP": f"203.0.113.{i}"},
+ )
+ )
+ for i in range(5)
+ }
+ assert keys == {"8.8.8.8"}
+
+ def test_xff_present_takes_precedence_over_real_ip(self, rl, monkeypatch):
+ """When X-Forwarded-For IS present, uvicorn has already had its
+ say (rewriting ``request.client`` for a trusted peer, or leaving
+ it alone for an untrusted one) -- either way this function must
+ trust ``direct_peer`` as-is and must NOT fall through to
+ X-Real-IP, even though both headers are present here. (Restricted
+ allow-list: with ``"*"`` the right-most entry would be the key.)
+
+ ``peer`` is the allow-listed proxy itself with a header uvicorn
+ would have rewritten it from, so this is not a request uvicorn
+ produces. The construct is deliberate: it is the case in which
+ this function's answer (``direct_peer``) differs from what the
+ header-reading branches would return, so it fails if the
+ restricted-mode rule is moved back under
+ ``_TRUSTED_PROXY_COUNT > 0`` (the legacy branch would key on
+ ``203.0.113.7``) or if X-Real-IP is consulted (``8.8.4.4``)."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ restrict_allow_list(rl, monkeypatch, "10.0.0.5")
+ request = make_request(
+ peer="10.0.0.5",
+ headers={
+ "X-Forwarded-For": "203.0.113.7",
+ "X-Real-IP": "8.8.4.4",
+ },
+ )
+ assert rl._get_client_ip(request) == "10.0.0.5"
+
+ def test_real_ip_used_when_no_xff_and_peer_is_testclient_sentinel(
+ self, rl, monkeypatch
+ ):
+ """The testclient sentinel is trusted like a private-network peer
+ -- lets the test suite hand out unique IPs via X-Real-IP too."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="testclient", headers={"X-Real-IP": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+
class TestUserKey:
"""Per-user bucket key on REAL Starlette requests.
@@ -303,6 +586,493 @@ class TestApiUserKey:
assert rl._api_user_key(request) == "api_ip:93.184.216.34"
+class TestSelectTrustedHop:
+ """Pure tests for the hop-counting helper -- the core of the
+ explicit-hop-count trust mode (LDR_SERVER_TRUSTED_PROXY_COUNT > 0).
+ """
+
+ def test_hop_count_zero_returns_none(self, rl):
+ assert rl._select_trusted_hop("1.2.3.4, 5.6.7.8", 0) is None
+
+ def test_hop_count_negative_returns_none(self, rl):
+ assert rl._select_trusted_hop("1.2.3.4, 5.6.7.8", -1) is None
+
+ def test_fewer_entries_than_hop_count_returns_none(self, rl):
+ assert rl._select_trusted_hop("1.2.3.4", 2) is None
+
+ def test_missing_header_returns_none(self, rl):
+ assert rl._select_trusted_hop("", 1) is None
+
+ def test_hop_count_one_picks_rightmost_entry(self, rl):
+ assert (
+ rl._select_trusted_hop("1.2.3.4, 5.6.7.8, 9.9.9.9", 1) == "9.9.9.9"
+ )
+
+ def test_hop_count_two_picks_second_from_right(self, rl):
+ assert (
+ rl._select_trusted_hop("1.2.3.4, 5.6.7.8, 9.9.9.9", 2) == "5.6.7.8"
+ )
+
+ def test_entry_count_equal_to_hop_count_picks_leftmost(self, rl):
+ assert rl._select_trusted_hop("1.2.3.4, 5.6.7.8", 2) == "1.2.3.4"
+
+ def test_extra_leftmost_forged_entries_are_ignored(self, rl):
+ """The whole point of hop counting: a prefix the client prepends
+ before the trusted chain ever sees the request must never be
+ selectable, no matter how many fake entries are prepended."""
+ assert (
+ rl._select_trusted_hop("forged-1, forged-2, forged-3, 9.9.9.9", 1)
+ == "9.9.9.9"
+ )
+
+ def test_whitespace_around_entries_is_stripped(self, rl):
+ assert rl._select_trusted_hop(" 1.2.3.4 , 5.6.7.8 ", 1) == "5.6.7.8"
+
+
+class TestGetClientIpTrustedProxyCount:
+ """LDR_SERVER_TRUSTED_PROXY_COUNT > 0: explicit hop-count selection.
+
+ Still gated on the direct peer being trusted (private/loopback, the
+ testclient sentinel, or TRUST_PROXY_HEADERS=true) -- a declared count
+ is not itself permission to trust whoever connects directly; see the
+ _get_client_ip docstring.
+ """
+
+ def test_count_one_from_trusted_peer_picks_rightmost_entry(
+ self, rl, monkeypatch
+ ):
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ request = make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": "93.184.216.34, 10.0.0.9"},
+ )
+ assert rl._get_client_ip(request) == "10.0.0.9"
+
+ def test_count_two_from_trusted_peer_picks_second_from_right(
+ self, rl, monkeypatch
+ ):
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ request = make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": "93.184.216.34, 10.0.0.8, 10.0.0.9"},
+ )
+ assert rl._get_client_ip(request) == "10.0.0.8"
+
+ def test_count_mode_ignores_client_forged_leftmost_prefix(
+ self, rl, monkeypatch
+ ):
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ request = make_request(
+ peer="10.0.0.5",
+ headers={
+ "X-Forwarded-For": "forged-1, forged-2, forged-3, 10.0.0.9"
+ },
+ )
+ assert rl._get_client_ip(request) == "10.0.0.9"
+
+ def test_count_mode_untrusted_direct_peer_ignores_forged_xff(
+ self, rl, monkeypatch
+ ):
+ """A public direct peer isn't behind ANY declared proxy hop -- the
+ connection reaching this process directly IS the client, so a
+ crafted XFF with >= count entries must not be honored even though
+ it satisfies the length check."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ request = make_request(
+ peer="8.8.8.8",
+ headers={"X-Forwarded-For": "1.2.3.4, 5.6.7.8"},
+ )
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_count_mode_short_xff_falls_back_to_direct_peer(
+ self, rl, monkeypatch
+ ):
+ """Fewer entries than the declared hop count is a missing/under-
+ filled chain -- fall back to the direct peer rather than trust an
+ ambiguous, possibly attacker-supplied short list."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ request = make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": "93.184.216.34"},
+ )
+ assert rl._get_client_ip(request) == "10.0.0.5"
+
+ def test_count_mode_missing_xff_falls_back_to_direct_peer(
+ self, rl, monkeypatch
+ ):
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ request = make_request(peer="10.0.0.5")
+ assert rl._get_client_ip(request) == "10.0.0.5"
+
+ def test_count_mode_trust_proxy_headers_true_ignores_xff_and_trusts_peer(
+ self, rl, monkeypatch
+ ):
+ """Combo mode (TRUST_PROXY_HEADERS=true + count > 0): this
+ function must NOT hop-count X-Forwarded-For itself -- uvicorn's
+ ProxyHeadersMiddleware already ran as the outermost ASGI layer
+ and computed the correct `request.client` before this code ever
+ saw the request (see the tri-state guard's module-level comment
+ and `_get_client_ip`'s docstring). This is an
+ application-level unit test of that combo-mode branch only; it
+ does NOT exercise uvicorn's own --proxy-headers rewrite (a
+ separate, outer ASGI layer these pure Request-object tests never
+ go through) -- see ``TestComboModeAgainstRealUvicornMiddleware``
+ below for that. Here, `peer` stands in for whatever
+ `request.client.host` uvicorn already resolved it to (whether
+ that's a direct attacker's own raw IP, left untouched because
+ they're outside LDR_SERVER_FORWARDED_ALLOW_IPS, or a
+ proxy-computed address for a trusted peer) -- either way this
+ function must return it as-is and must NOT let the forged
+ X-Forwarded-For header override it with entries[-N]. (A positive
+ count with the unrestricted ``"*"`` refuses to start, so this mode
+ always has a restricted allow-list.)"""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ restrict_allow_list(rl, monkeypatch, "10.0.0.5")
+ request = make_request(
+ peer="8.8.8.8",
+ headers={"X-Forwarded-For": "1.2.3.4, 9.9.9.9"},
+ )
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_count_zero_is_pre_existing_heuristic_untrusted_peer(
+ self, rl, monkeypatch
+ ):
+ """count == 0 is the documented 'unset' sentinel -- an untrusted
+ public peer's forged XFF must still be ignored regardless of entry
+ count (no hop-counting kicks in)."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ request = make_request(
+ peer="8.8.8.8",
+ headers={"X-Forwarded-For": "1.2.3.4, 5.6.7.8"},
+ )
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_count_zero_is_pre_existing_heuristic_trusted_peer(
+ self, rl, monkeypatch
+ ):
+ """count == 0 from a trusted peer honors the RIGHT-most entry (the
+ pre-existing heuristic since #6442), whatever the chain length --
+ no hop counting kicks in."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ request = make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": "93.184.216.34, 10.0.0.8, 10.0.0.9"},
+ )
+ assert rl._get_client_ip(request) == "10.0.0.9"
+
+
+class TestComboModeAgainstRealUvicornMiddleware:
+ """Drives requests through uvicorn's OWN ``ProxyHeadersMiddleware`` --
+ not a stand-in -- before handing the resulting scope to
+ ``_get_client_ip``, to verify the premise behind combo mode
+ (``TRUST_PROXY_HEADERS=true``, at ANY ``LDR_SERVER_TRUSTED_PROXY_COUNT``
+ value): that uvicorn, not this module, is the authority on
+ ``request.client`` in that mode, and that authority already accounts
+ for whether the direct peer is in ``LDR_SERVER_FORWARDED_ALLOW_IPS``.
+
+ Regression coverage for two defects fixed here, at different times:
+
+ - Originally, the count-mode branch's ``if _TRUST_PROXY_HEADERS or
+ _is_trusted_peer(direct_peer):`` gate short-circuited on the global
+ flag alone, so -- in exactly the combination a restricted
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` is meant to make safe -- a
+ direct-connecting attacker's forged X-Forwarded-For was still
+ hop-counted and ``entries[-N]`` (fully attacker-chosen) became the
+ rate-limit key, because this module never consulted
+ ``request.client`` before parsing the header itself. Fixed by
+ returning ``direct_peer`` unconditionally inside the
+ ``_TRUSTED_PROXY_COUNT > 0`` branch, trusting only what uvicorn
+ already computed. Covered by the ``count_one``/``count_two``/
+ ``multi_hop`` tests below.
+ - That fix was then wired ONLY inside ``if _TRUSTED_PROXY_COUNT > 0:``,
+ so a deployment with the recommended combo (``TRUST_PROXY_HEADERS=
+ true`` + a restricted allow-list) but ``LDR_SERVER_TRUSTED_PROXY_
+ COUNT`` left at its default of 0 fell through to the legacy branch,
+ which honored the left-most (forgeable) XFF entry -- exploitable
+ even though uvicorn itself was already computing the correct client
+ address one layer up. Fixed by hoisting the "trust direct_peer" rule
+ so it is unconditional on ``TRUST_PROXY_HEADERS`` alone, independent
+ of the hop count. Since #6442 the legacy branch keys on the
+ RIGHT-most entry, which for a single trusted hop is uvicorn's answer
+ too, so ``test_count_zero_proxied_request_gets_uvicorn_computed_client``
+ passes either way and is a characterisation test. The multi-hop
+ tests below set a hop count of 2, so they never reach the branch the
+ hoist moved and do not fence it either. What fails if the hoist is
+ reverted: with the legacy gate's ``_TRUST_PROXY_HEADERS or``
+ short-circuit restored as well,
+ ``test_count_zero_direct_attacker_outside_allow_list_keeps_raw_peer``
+ here, ``TestTrustProxyHeadersOverride.test_flag_trusts_direct_peer_and_ignores_xff``,
+ ``TestTrustProxyHeadersXRealIpFallback``'s
+ ``test_real_ip_ignored_when_no_xff_and_peer_untrusted``,
+ ``test_rotating_real_ip_from_untrusted_peer_never_changes_key`` and
+ ``test_xff_present_takes_precedence_over_real_ip``, and in
+ ``test_rate_limit_restricted_allow_list.py``
+ ``test_private_non_allowlisted_peer_varying_real_ip_mints_no_new_keys``,
+ ``test_private_non_allowlisted_peer_xff_present_keeps_raw_peer`` and
+ ``test_non_private_proxy_x_real_ip_is_ignored``. With the gate left
+ as it is, ``test_xff_present_takes_precedence_over_real_ip`` and the
+ two unrestricted-allow-list tests in ``TestTrustProxyHeadersOverride``.
+ """
+
+ @staticmethod
+ async def _run_through_uvicorn(peer, headers, trusted_hosts):
+ """Wrap a capturing ASGI app in uvicorn's real
+ ``ProxyHeadersMiddleware`` and drive one HTTP request through it,
+ returning the ``scope`` the inner app observed (post-middleware).
+ """
+ from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
+
+ captured = {}
+
+ async def inner_app(scope, receive, send):
+ captured["scope"] = scope
+
+ middleware = ProxyHeadersMiddleware(
+ inner_app, trusted_hosts=trusted_hosts
+ )
+ scope = {
+ "type": "http",
+ "method": "GET",
+ "path": "/",
+ "query_string": b"",
+ "client": (peer, 51234),
+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers],
+ }
+
+ async def receive():
+ return {"type": "http.disconnect"}
+
+ async def send(message):
+ pass
+
+ await middleware(scope, receive, send)
+ return captured["scope"]
+
+ @pytest.fixture(autouse=True)
+ def _module_mirrors_uvicorn_allow_list(self, rl, monkeypatch):
+ """Keep the module's allow-list in step with the one each test hands
+ uvicorn, as ``web/app.py`` does from one env var."""
+ self._rl = rl
+ self._monkeypatch = monkeypatch
+
+ def _request_after_uvicorn(self, peer, headers, trusted_hosts):
+ restrict_allow_list(self._rl, self._monkeypatch, trusted_hosts)
+ scope = asyncio.run(
+ self._run_through_uvicorn(peer, headers, trusted_hosts)
+ )
+ return Request(scope)
+
+ def test_direct_attacker_outside_allow_list_keeps_raw_peer(
+ self, rl, monkeypatch
+ ):
+ """A restricted LDR_SERVER_FORWARDED_ALLOW_IPS (the trusted
+ proxy's real IP, ``10.0.0.5``): an attacker connecting straight
+ to LDR is NOT in that allow-list, so uvicorn's own middleware --
+ exercised here for real -- leaves ``scope["client"]`` untouched.
+ ``_get_client_ip``'s combo branch must return that raw attacker
+ peer, never a forged ``entries[-N]`` picked out of their XFF."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = self._request_after_uvicorn(
+ peer="8.8.8.8",
+ headers=[
+ (
+ "X-Forwarded-For",
+ "1.2.3.4, 5.6.7.8, 9.9.9.9, 6.6.6.6",
+ ),
+ ],
+ trusted_hosts="10.0.0.5",
+ )
+ assert request.client.host == "8.8.8.8"
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_proxied_request_gets_uvicorn_computed_client(
+ self, rl, monkeypatch
+ ):
+ """The trusted proxy (``10.0.0.5``) connects directly to LDR and
+ appends the client it observed to X-Forwarded-For. uvicorn's
+ real middleware rewrites ``scope["client"]`` to that upstream
+ client (``203.0.113.7``); ``_get_client_ip``'s combo branch must
+ return exactly that computed value, never re-deriving anything
+ from the header itself."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = self._request_after_uvicorn(
+ peer="10.0.0.5",
+ headers=[("X-Forwarded-For", "203.0.113.7")],
+ trusted_hosts="10.0.0.5",
+ )
+ assert request.client.host == "203.0.113.7"
+ assert rl._get_client_ip(request) == "203.0.113.7"
+
+ def test_count_zero_direct_attacker_outside_allow_list_keeps_raw_peer(
+ self, rl, monkeypatch
+ ):
+ """Same as ``test_direct_attacker_outside_allow_list_keeps_raw_peer``
+ but at ``LDR_SERVER_TRUSTED_PROXY_COUNT``'s default of 0/unset --
+ the exact configuration the fixed defect left exploitable: an
+ operator following the documented, recommended combo (restricted
+ allow-list) who never touches the count setting at all."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = self._request_after_uvicorn(
+ peer="8.8.8.8",
+ headers=[
+ (
+ "X-Forwarded-For",
+ "1.2.3.4, 5.6.7.8, 9.9.9.9, 6.6.6.6",
+ ),
+ ],
+ trusted_hosts="10.0.0.5",
+ )
+ assert request.client.host == "8.8.8.8"
+ assert rl._get_client_ip(request) == "8.8.8.8"
+
+ def test_count_zero_proxied_request_gets_uvicorn_computed_client(
+ self, rl, monkeypatch
+ ):
+ """Same as ``test_proxied_request_gets_uvicorn_computed_client``
+ but at ``LDR_SERVER_TRUSTED_PROXY_COUNT=0`` (default/unset): the
+ real client the trusted proxy observed and appended to XFF must
+ still be returned -- never the request's own left-most
+ (client-forgeable) XFF entry, which is what the pre-fix legacy
+ branch would have returned here.
+
+ The header carries a forged left-most entry (``1.2.3.4``) ahead of
+ the address the trusted proxy appended. uvicorn walks from the
+ right and hands back ``203.0.113.7``; since #6442 the legacy branch
+ keys on the right-most entry and returns the same address, so this
+ test no longer fences the hoist (see the class docstring for the
+ tests that do)."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = self._request_after_uvicorn(
+ peer="10.0.0.5",
+ headers=[("X-Forwarded-For", "1.2.3.4, 203.0.113.7")],
+ trusted_hosts="10.0.0.5",
+ )
+ assert request.client.host == "203.0.113.7"
+ assert rl._get_client_ip(request) == "203.0.113.7"
+
+ def test_proxied_multi_hop_requires_every_trusted_hop_listed(
+ self, rl, monkeypatch
+ ):
+ """Two trusted hops (``10.0.0.5`` nearest to LDR, ``10.0.0.6``
+ further out) each append the peer they observed. With BOTH IPs
+ in ``forwarded_allow_ips``, uvicorn's right-to-left walk skips
+ both trusted entries and returns the true client -- confirming
+ the docs' claim that ``LDR_SERVER_FORWARDED_ALLOW_IPS`` must
+ list EVERY trusted hop, not just the nearest one."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = self._request_after_uvicorn(
+ peer="10.0.0.5",
+ headers=[("X-Forwarded-For", "203.0.113.7, 10.0.0.6")],
+ trusted_hosts="10.0.0.5,10.0.0.6",
+ )
+ assert request.client.host == "203.0.113.7"
+ assert rl._get_client_ip(request) == "203.0.113.7"
+
+ def test_proxied_multi_hop_missing_inner_hop_from_allow_list_is_wrong(
+ self, rl, monkeypatch
+ ):
+ """Negative control for the claim above: if
+ LDR_SERVER_FORWARDED_ALLOW_IPS lists only the NEAREST hop
+ (``10.0.0.5``), uvicorn's reverse walk stops at the first entry
+ it doesn't recognise -- the inner proxy's own address
+ (``10.0.0.6``) -- and returns THAT instead of the true client.
+ Not a security hole (``10.0.0.6`` is still not
+ attacker-controlled), but operationally wrong, which is exactly
+ why the docs and the tri-state guard's comment insist on listing
+ every trusted hop."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = self._request_after_uvicorn(
+ peer="10.0.0.5",
+ headers=[("X-Forwarded-For", "203.0.113.7, 10.0.0.6")],
+ trusted_hosts="10.0.0.5", # missing 10.0.0.6
+ )
+ assert request.client.host == "10.0.0.6"
+ assert rl._get_client_ip(request) == "10.0.0.6"
+
+
+class TestMultiLineXForwardedFor:
+ """A proxy chain that APPENDS its own X-Forwarded-For line (rather
+ than editing the client-sent one) produces a request with MULTIPLE
+ X-Forwarded-For header lines -- e.g. HAProxy's ``option forwardfor``
+ without ``if-none``, or any of the multi-hop CDN/tunnel setups this
+ module's docs bless. Starlette's ``Headers.get()`` returns only the
+ FIRST such line, so naive code sees just the client's own (fully
+ forgeable) line and never the proxy-appended one. ``_get_client_ip``
+ must instead comma-join every line (mirroring WSGI's
+ ``HTTP_X_FORWARDED_FOR`` semantics, which Werkzeug's ``ProxyFix``
+ relies on) before hop-counting or taking the legacy right-most entry.
+ """
+
+ def test_hop_count_one_resolves_to_proxy_appended_line_not_forged_first_line(
+ self, rl, monkeypatch
+ ):
+ """The attacker sends their own X-Forwarded-For line first; the
+ trusted proxy appends a SECOND, separate X-Forwarded-For line
+ rather than editing the first. Under N=1, the rate-limit key must
+ be the entry from the proxy-appended line -- never the forged
+ first line, no matter how many entries it contains."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ request = make_request(
+ peer="10.0.0.5",
+ headers=[
+ ("X-Forwarded-For", "9.9.9.9, forged-2, forged-3"),
+ ("X-Forwarded-For", "10.0.0.9"),
+ ],
+ )
+ assert rl._get_client_ip(request) == "10.0.0.9"
+
+ def test_hop_count_two_resolves_across_both_header_lines(
+ self, rl, monkeypatch
+ ):
+ """Hop counting must operate on the FULL comma-joined chain
+ spanning every X-Forwarded-For line, not just whichever line
+ Headers.get() happens to return first."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ request = make_request(
+ peer="10.0.0.5",
+ headers=[
+ ("X-Forwarded-For", "forged, 93.184.216.34"),
+ ("X-Forwarded-For", "10.0.0.8, 10.0.0.9"),
+ ],
+ )
+ assert rl._get_client_ip(request) == "10.0.0.8"
+
+ def test_legacy_heuristic_mode_also_joins_multiple_header_lines(
+ self, rl, monkeypatch
+ ):
+ """count == 0 (the pre-existing heuristic) reads the right-most
+ entry of the joined chain (#6442) -- i.e. the proxy-appended second
+ line, not the client's own forged first line. This pins that a
+ second header line is no longer silently dropped."""
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ request = make_request(
+ peer="10.0.0.5",
+ headers=[
+ ("X-Forwarded-For", "93.184.216.34, forged-2"),
+ ("X-Forwarded-For", "10.0.0.9"),
+ ],
+ )
+ assert rl._get_client_ip(request) == "10.0.0.9"
+
+ def test_forwarded_for_helper_joins_all_lines_and_skips_empties(self, rl):
+ request = make_request(
+ peer="10.0.0.5",
+ headers=[
+ ("X-Forwarded-For", "1.2.3.4"),
+ ("X-Forwarded-For", ""),
+ ("X-Forwarded-For", "5.6.7.8"),
+ ],
+ )
+ assert rl._get_forwarded_for(request) == "1.2.3.4,5.6.7.8"
+
+
class TestApiExempt:
"""app.api_rate_limit = 0 disables the /api/v1 limit via the
request-scoped contextvar (parity with main's exempt_when)."""
diff --git a/tests/web/dependencies/test_rate_limit_regressions.py b/tests/web/dependencies/test_rate_limit_regressions.py
index 832fed4c57..01f91c1b1e 100644
--- a/tests/web/dependencies/test_rate_limit_regressions.py
+++ b/tests/web/dependencies/test_rate_limit_regressions.py
@@ -32,6 +32,10 @@ Each class below is independent and can be read/run on its own.
"""
import importlib
+import io
+import os
+import subprocess
+import sys
import uuid
from contextlib import contextmanager
@@ -246,6 +250,17 @@ _LEAKY_URI = (
)
_SECRET = "SuperSecretPW123"
+# RFC 3986 (and urllib.parse) split userinfo from host at the LAST
+# "@", so this password genuinely parses as "Top@Secret" and a redactor
+# stopping at the first "@" strips only its prefix, emitting the
+# "Secret" suffix into the startup error.
+_RAW_AT_LEAKY_URI = (
+ "rediss-bogus://rateuser:Top@Secret@evil-internal-host:6379/0"
+)
+# Every fragment the password could disclose through: the whole value
+# plus each raw-@-separated piece on either side of it.
+_RAW_AT_SECRET_FRAGMENTS = ("Top@Secret", "Top", "Secret")
+
class TestStorageUriRedaction:
def test_redact_helper_strips_credentials(self):
@@ -264,6 +279,299 @@ class TestStorageUriRedaction:
== "redis://localhost:6379/0"
)
+ def test_redact_helper_strips_password_containing_raw_at(self):
+ """The whole userinfo segment goes, not just up to the first "@".
+
+ Reverting to a first-"@" regex redacts this URI to
+ "rediss-bogus://***@Secret@evil-internal-host:6379/0", which
+ still carries the password's suffix -- this test pins the
+ last-"@" split so that revert fails.
+ """
+ mod = _rl()
+ redacted = mod._redact_storage_uri(_RAW_AT_LEAKY_URI)
+ for fragment in _RAW_AT_SECRET_FRAGMENTS:
+ assert fragment not in redacted
+ assert "rateuser" not in redacted
+ # Host/port/path stay diagnosable.
+ assert redacted == "rediss-bogus://***@evil-internal-host:6379/0"
+ # A well-formed single-"@" authority must redact identically.
+ assert mod._redact_storage_uri(_LEAKY_URI) == (
+ "rediss-bogus://***@evil-internal-host:6379/0"
+ )
+
+ @pytest.mark.parametrize(
+ ("uri", "secret_fragments", "expected"),
+ [
+ pytest.param(
+ "redis://default:Pa#ss@redis:6379/0",
+ ("Pa#ss", "Pa", "default"),
+ "redis://***",
+ id="raw-hash-in-password",
+ ),
+ pytest.param(
+ "redis://default:pa?ss@redis:6379/0",
+ ("pa?ss", "default"),
+ "redis://***",
+ id="raw-question-mark-in-password",
+ ),
+ pytest.param(
+ "memcached://u:pa?ss@mc:11211",
+ ("pa?ss", "u:"),
+ "memcached://***",
+ id="memcached-raw-question-mark",
+ ),
+ pytest.param(
+ "redis://u:ab/cd@redis:6379/0",
+ ("ab/cd", "u:ab"),
+ "redis://***@redis:6379/0",
+ id="raw-slash-in-password",
+ ),
+ pytest.param(
+ "redis://u:ab/cd#ef?gh@ij@[::1]:6379/0",
+ ("ab/cd", "#ef", "?gh", "ij@"),
+ "redis://***",
+ id="every-delimiter-in-password-ipv6-host",
+ ),
+ pytest.param(
+ "redis://u:pw@[2001:db8::1]:6379/0",
+ ("u:pw",),
+ "redis://***@[2001:db8::1]:6379/0",
+ id="ipv6-host",
+ ),
+ pytest.param(
+ "redis+unix://:s3cr3t@/var/run/redis.sock",
+ ("s3cr3t",),
+ "redis+unix://***@/var/run/redis.sock",
+ id="unix-socket-with-password",
+ ),
+ pytest.param(
+ "redis+sentinel://u:pw#1@h1:26379,h2:26379/mymaster",
+ ("pw#1",),
+ "redis+sentinel://***",
+ id="sentinel-host-list",
+ ),
+ pytest.param(
+ "redis:u:s3cr3t@h:6379",
+ ("s3cr3t", "u:"),
+ "***@h:6379",
+ id="missing-double-slash",
+ ),
+ ],
+ )
+ def test_redact_helper_strips_password_with_uri_delimiters(
+ self, uri, secret_fragments, expected
+ ):
+ """This redaction runs precisely when the URI failed to parse,
+ so the password may hold any delimiter raw. main's
+ ``://[^@/]+@`` stopped at "/" and at the first "@", and a
+ ``://[^/?#]*@`` variant stopped matching altogether at "#" or
+ "?" -- both returned such a URI with the password intact. A raw
+ "?" or "#" before the last "@" could equally open a query holding
+ a raw "@", so those rows redact everything after the scheme."""
+ mod = _rl()
+ redacted = mod._redact_storage_uri(uri)
+ for fragment in secret_fragments:
+ assert fragment not in redacted
+ assert redacted == expected
+
+ @pytest.mark.parametrize(
+ "uri",
+ [
+ "memory://",
+ "redis://[::1]:6379/0",
+ "redis+unix:///var/run/redis.sock",
+ "memcached://h1:11211,h2:11211",
+ ],
+ )
+ def test_redact_helper_leaves_userinfo_free_uris_unchanged(self, uri):
+ assert _rl()._redact_storage_uri(uri) == uri
+
+ @pytest.mark.parametrize(
+ ("uri", "secret_fragments", "expected"),
+ [
+ pytest.param(
+ "redis://cache:6379/0?password=hunter2",
+ ("hunter2", "password="),
+ "redis://cache:6379/0?***",
+ id="password-query-no-userinfo",
+ ),
+ pytest.param(
+ "redis://:pw@h:6379?ssl_password=kp&db=1",
+ ("pw", "ssl_password", "kp"),
+ "redis://***@h:6379?***",
+ id="userinfo-and-query",
+ ),
+ pytest.param(
+ "rediss://h:6380/0#token=abc",
+ ("token", "abc"),
+ "rediss://h:6380/0#***",
+ id="fragment-no-userinfo",
+ ),
+ pytest.param(
+ "redis+unix:///run/redis.sock?db=0&password=s3cr3t",
+ ("s3cr3t",),
+ "redis+unix:///run/redis.sock?***",
+ id="unix-socket-query-password",
+ ),
+ pytest.param(
+ "redis:h?password=s3cr3t",
+ ("s3cr3t",),
+ "redis:h?***",
+ id="no-scheme-slashes-query",
+ ),
+ ],
+ )
+ def test_redact_helper_strips_query_string_credentials(
+ self, uri, secret_fragments, expected
+ ):
+ """Storage clients take credentials as query parameters too
+ (redis-py reads ``password`` and ``ssl_password`` from the
+ query), and a value with no "@" used to come back verbatim --
+ into the startup RuntimeError the ``@logger.catch`` on
+ ``main()`` logs."""
+ redacted = _rl()._redact_storage_uri(uri)
+ for fragment in secret_fragments:
+ assert fragment not in redacted
+ assert redacted == expected
+
+ @pytest.mark.parametrize(
+ ("uri", "secret_fragments", "expected"),
+ [
+ pytest.param(
+ "redis://h:6379/0?password=p@ssw0rd",
+ ("p@ssw0rd", "ssw0rd"),
+ "redis://***",
+ id="at-in-query-password",
+ ),
+ pytest.param(
+ "rediss://h/0?ssl_password=Sup3r@Secret#frag",
+ ("Sup3r", "Secret", "frag"),
+ "rediss://***",
+ id="at-in-ssl-password-with-fragment",
+ ),
+ pytest.param(
+ "redis://u:pw@h:6379/0?password=x@tail",
+ ("pw", "x@tail", "tail"),
+ "redis://***",
+ id="userinfo-and-at-in-query-password",
+ ),
+ pytest.param(
+ "redis+sentinel://h:26379/m?sentinel_kwargs=x&password=s3@cr3t",
+ ("s3@cr3t", "cr3t"),
+ "redis+sentinel://***",
+ id="sentinel-at-in-query-password",
+ ),
+ pytest.param(
+ "redis://h:6379/0?username=ops@corp&password=S3cret",
+ ("S3cret", "corp"),
+ "redis://***",
+ id="at-in-earlier-parameter-then-password",
+ ),
+ pytest.param(
+ "rediss://h:6380/0#token=a@bcdef",
+ ("bcdef",),
+ "rediss://***",
+ id="at-in-fragment",
+ ),
+ pytest.param(
+ "redis:h?password=p@ss",
+ ("p@ss", "ss"),
+ "***",
+ id="at-in-query-no-scheme-slashes",
+ ),
+ ],
+ )
+ def test_redact_helper_strips_query_credentials_containing_raw_at(
+ self, uri, secret_fragments, expected
+ ):
+ """RFC 3986 allows a raw "@" in a query, and redis-py reads the
+ password from the query. Splitting at the last "@" first put the
+ "?" in the redacted part and printed the password's tail as the
+ host ("redis://***@ssw0rd")."""
+ redacted = _rl()._redact_storage_uri(uri)
+ for fragment in secret_fragments:
+ assert fragment not in redacted
+ assert redacted == expected
+
+ def test_redact_helper_never_emits_a_secret_substring_fuzz(self):
+ """Seeded fuzz over the shapes a credential can take: userinfo,
+ query, fragment, each with raw delimiters. No 3+ character piece
+ of the secret may survive (each piece checked carries one of the
+ marker letters, so structural text like "://" cannot match)."""
+ import random
+
+ rl = _rl()
+ rng = random.Random(4870)
+ markers = "QZXJ"
+ special = "@?#/:;&=[]%"
+ filler = "abcdefghij0123456789" + special
+
+ def word(k):
+ return "".join(rng.choice(filler) for _ in range(k))
+
+ for _ in range(3000):
+ pw = "".join(
+ rng.choice(markers + special) for _ in range(rng.randint(4, 12))
+ )
+ scheme = rng.choice(
+ ["redis://", "rediss://", "redis+sentinel://", "redis:", ""]
+ )
+ host = rng.choice(["h", "cache:6379", "[::1]:6379", "h1:1,h2:2"])
+ path = rng.choice(["", "/0", "/a@b", "/x?y"])
+ user = rng.choice(["", "u", "ops@corp"])
+ uri = rng.choice(
+ [
+ f"{scheme}{user}:{pw}@{host}{path}",
+ f"{scheme}{host}{path}?{word(4)}&password={pw}&db=0",
+ f"{scheme}{user}:{word(5)}@{host}{path}"
+ f"?ssl_password={pw}#{word(3)}",
+ f"{scheme}{host}{path}#{pw}",
+ f"{scheme}{user}:{pw}@{host}{path}?password={pw}",
+ ]
+ )
+ redacted = rl._redact_storage_uri(uri)
+ for i in range(len(pw)):
+ for j in range(i + 3, len(pw) + 1):
+ piece = pw[i:j]
+ if any(c in markers for c in piece):
+ assert piece not in redacted, (uri, redacted)
+
+ def test_storage_scheme_log_never_echoes_a_scheme_less_value(self):
+ """The "storage configured" info line logs only the scheme. A
+ ``split("://")[0]`` returned the whole value, password and all,
+ when the "//" was missing."""
+ mod = _rl()
+ assert mod._storage_uri_scheme("redis://u:pw@h:6379/0") == (
+ "redis://..."
+ )
+ assert "s3cr3t" not in mod._storage_uri_scheme("redis:u:s3cr3t@h")
+
+ def test_malformed_uri_with_raw_hash_password_never_leaks_secret(
+ self, clean_env
+ ):
+ """End-to-end: ``limits`` rejects this URI (unknown scheme) and
+ the startup error must not carry any part of the password."""
+ clean_env.setenv(
+ "RATE_LIMIT_STORAGE_URI",
+ "rediss-bogus://rateuser:Pa#ss?wd@evil-internal-host:6379/0",
+ )
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+ exc = exc_info.value
+ import traceback
+
+ formatted = "".join(
+ traceback.format_exception(type(exc), exc, exc.__traceback__)
+ )
+ for surface in (str(exc), formatted):
+ assert "Pa#ss" not in surface
+ assert "ss?wd" not in surface
+ assert "rateuser" not in surface
+ # "#" and "?" precede the last "@", so the host cannot be told
+ # apart from a query tail and everything after the scheme goes.
+ assert "rediss-bogus://***" in str(exc)
+ assert "evil-internal-host" not in str(exc)
+
def test_malformed_credentialed_uri_never_leaks_secret(self, clean_env):
"""End-to-end: reload the module with a broken, credential-bearing
RATE_LIMIT_STORAGE_URI (the reported PoC value) and confirm the
@@ -293,7 +601,37 @@ class TestStorageUriRedaction:
# handling of the above exception ...", secret and all) even
# though the outer exception's own text is clean.
assert exc.__cause__ is None
- assert exc.__suppress_context__ is True
+ assert exc.__context__ is None
+
+ def test_malformed_uri_with_raw_at_password_never_leaks_secret(
+ self, clean_env
+ ):
+ """End-to-end raw-"@" variant of the test above: no fragment of a
+ multi-"@" password may reach the raised message or the fully
+ formatted traceback — the two surfaces loguru's ``@logger.catch``
+ and the raw interpreter traceback actually print.
+ """
+ clean_env.setenv("RATE_LIMIT_STORAGE_URI", _RAW_AT_LEAKY_URI)
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ exc = exc_info.value
+ for fragment in _RAW_AT_SECRET_FRAGMENTS:
+ assert fragment not in str(exc)
+
+ import traceback
+
+ formatted = "".join(
+ traceback.format_exception(type(exc), exc, exc.__traceback__)
+ )
+ for fragment in _RAW_AT_SECRET_FRAGMENTS:
+ assert fragment not in formatted
+ assert "rateuser" not in formatted
+
+ # The credential-bearing ConfigurationError must stay severed.
+ assert exc.__cause__ is None
+ assert exc.__context__ is None
def test_malformed_uri_still_fails_fast(self, clean_env):
"""The redaction must not degrade into a silent in-memory
@@ -369,6 +707,45 @@ class TestStorageUriRedaction:
assert exc_info.value.__cause__ is None
assert not isinstance(exc_info.value, ConfigurationError)
+ def test_legacy_name_raw_at_password_is_wrapped_and_redacted(
+ self, clean_env
+ ):
+ """The same malformed-authority attack through the legacy
+ RATELIMIT_STORAGE_URL name: every fragment of a raw-"@"
+ password must be absent from the wrapped RuntimeError's message
+ and its formatted traceback.
+
+ Unlike the single-"@" legacy test above this needs no
+ installed-client skip: the ``rediss-bogus`` scheme is not a
+ registered limits storage scheme, so construction fails with
+ ConfigurationError regardless of which clients are installed.
+ """
+ clean_env.setenv(
+ "RATELIMIT_STORAGE_URL",
+ "rediss-bogus://legacy-admin:Zed@[email protected]:6379",
+ )
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ exc = exc_info.value
+ for fragment in ("Zed@Marsh", "Zed", "Marsh"):
+ assert fragment not in str(exc)
+ assert "legacy-admin" not in str(exc)
+ assert "RATELIMIT_STORAGE_URL" in str(exc)
+
+ import traceback
+
+ formatted = "".join(
+ traceback.format_exception(type(exc), exc, exc.__traceback__)
+ )
+ for fragment in ("Zed@Marsh", "Zed", "Marsh"):
+ assert fragment not in formatted
+
+ # `from None` keeps the original (credential-bearing) exception
+ # out of the traceback chain as well.
+ assert exc.__cause__ is None
+ assert exc.__context__ is None
+
# ---------------------------------------------------------------------------
# Regression 4 — storage is not resolved at all when rate limiting is OFF
@@ -393,6 +770,145 @@ class TestStorageUriRedaction:
# The module now forces `storage_uri="memory://"` when disabled, which both
# skips the broken backend and stops the legacy-name fallback being consulted
# at all. See issue #5964.
+_URLPARSE_LEAK_CASES = [
+ # fullwidth U+FF03 NFKC-normalises to "#": urlparse() raises a bare
+ # ValueError quoting the WHOLE netloc, password included.
+ ("redis://:Hunter2\uff03xyz@cache:6379/0", ("Hunter2", "xyz")),
+ # fullwidth U+FF20 NFKC-normalises to "@"; there is no ASCII "@" at
+ # all, so a redactor that does not fold NFKC would emit it unchanged.
+ ("redis://:Hunter2\uff20cache:6379/0", ("Hunter2",)),
+ # raw "/" ends the netloc early; redis-py's ``.port`` ValueError and
+ # limits' ConfigurationError both can quote the URI.
+ ("redis://:Hun/ter2@cache:6379/0", ("Hun/ter2", "ter2")),
+]
+
+
+class TestStorageUriParseErrorsNeverLeak:
+ """Any Limiter() construction failure -- not only ConfigurationError --
+ must surface as a RuntimeError carrying the redacted URI only."""
+
+ @pytest.mark.parametrize(
+ "uri,fragments",
+ _URLPARSE_LEAK_CASES,
+ ids=["fullwidth-hash", "fullwidth-at", "raw-slash"],
+ )
+ @pytest.mark.parametrize(
+ "var", ["RATE_LIMIT_STORAGE_URI", "RATELIMIT_STORAGE_URL"]
+ )
+ def test_no_leak_anywhere(self, clean_env, uri, fragments, var):
+ import traceback
+
+ from loguru import logger
+
+ clean_env.setenv(var, uri)
+ captured = []
+ sink_id = logger.add(
+ lambda m: captured.append(str(m)), diagnose=False, backtrace=True
+ )
+ try:
+
+ @logger.catch(reraise=False)
+ def _boom():
+ _reload_rate_limit()
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+ _boom()
+ finally:
+ logger.remove(sink_id)
+
+ exc = exc_info.value
+ formatted = "".join(
+ traceback.format_exception(type(exc), exc, exc.__traceback__)
+ )
+ logged = "".join(captured)
+ assert logged, "logger.catch produced no output; test is vacuous"
+ for fragment in fragments:
+ assert fragment not in str(exc)
+ assert fragment not in formatted
+ assert fragment not in logged
+ assert exc.__cause__ is None
+ assert exc.__context__ is None
+ assert var in str(exc)
+
+ @pytest.mark.parametrize(
+ "uri,fragments",
+ _URLPARSE_LEAK_CASES
+ + [
+ (
+ "rediss-bogus://u:SuperSecret@h:6379",
+ ("SuperSecret",),
+ )
+ ],
+ )
+ def test_uri_supplied_only_via_dotenv_never_leaks(
+ self, clean_env, tmp_path, uri, fragments
+ ):
+ """slowapi reads RATELIMIT_STORAGE_URL from ./.env when it is not
+ in os.environ; the handler must still know a URI is in play."""
+ import traceback
+
+ (tmp_path / ".env").write_text(f"RATELIMIT_STORAGE_URL={uri}\n")
+ clean_env.chdir(tmp_path)
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+ exc = exc_info.value
+ formatted = "".join(
+ traceback.format_exception(type(exc), exc, exc.__traceback__)
+ )
+ for fragment in fragments:
+ assert fragment not in str(exc)
+ assert fragment not in formatted
+ assert "RATELIMIT_STORAGE_URL" in str(exc)
+ assert exc.__cause__ is None and exc.__context__ is None
+
+ def test_non_uri_failure_names_real_cause(self, clean_env):
+ """A bool-cast error in a stray RATELIMIT_ENABLED is not a URI
+ problem and must not be reported as one."""
+ clean_env.setenv("RATELIMIT_ENABLED", "yes")
+ clean_env.setenv("RATE_LIMIT_STORAGE_URI", "memory://")
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+ message = str(exc_info.value)
+ assert "RATELIMIT_ENABLED" in message
+ assert "ValueError" in message
+ assert "percent-encode" not in message
+ assert exc_info.value.__context__ is None
+
+ def test_memcached_moving_window_reports_real_cause(self, clean_env):
+ """limits' MemcachedStorage has no moving-window support, so the
+ strategy constructor raises NotImplementedError (simulated here
+ so the test does not need pymemcache installed)."""
+ import slowapi
+
+ def _raise(self, *args, **kwargs):
+ raise NotImplementedError(
+ "MovingWindowRateLimiting is not implemented for storage "
+ "of type MemcachedStorage"
+ )
+
+ clean_env.setattr(slowapi.Limiter, "__init__", _raise)
+ clean_env.setenv(
+ "RATE_LIMIT_STORAGE_URI", "memcached://u:Pw123456@h:11211"
+ )
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+ message = str(exc_info.value)
+ assert "NotImplementedError" in message
+ assert "MovingWindowRateLimiting" in message
+ assert "percent-encode" not in message
+ assert "Pw123456" not in message
+
+ def test_redactor_folds_nfkc_separators(self):
+ rl = _rl()
+ assert "Hunter2" not in rl._redact_storage_uri(
+ "redis://:Hunter2\uff20cache:6379/0"
+ )
+ assert "Hunter2" not in rl._redact_storage_uri(
+ "redis://cache:6379/0\uff1fpassword=Hunter2"
+ )
+
+
# ---------------------------------------------------------------------------
@@ -474,3 +990,394 @@ class TestStorageValidationSkippedWhenDisabled:
assert mod.limiter.enabled is True
assert mod._limiter_kwargs["storage_uri"] == "memory://explicit"
+
+
+# ---------------------------------------------------------------------------
+# The legacy RATELIMIT_STORAGE_URL ./.env lookup must never abort the import
+#
+# The module looks the legacy key up in ./.env itself (as slowapi does), at
+# import, whether or not rate limiting is enabled. Whatever goes wrong with
+# that lookup has to degrade to "no .env", as slowapi's own
+# ``os.path.isfile(".env")`` does -- not stop the server from starting.
+# ---------------------------------------------------------------------------
+
+
+class TestLegacyDotenvLookupFailsSafe:
+ @pytest.mark.parametrize("disabled", ["true", "false"])
+ def test_unsearchable_working_directory_does_not_abort_import(
+ self, clean_env, disabled
+ ):
+ """On CPython 3.12 ``Path(".env").is_file()`` re-raises EACCES when
+ the working directory is not searchable (e.g. ``sudo -u ldr ldr-web``
+ from /root); ``os.path.isfile`` returns False there. Emulate the
+ 3.12 behaviour so the test bites on every interpreter."""
+ import pathlib
+
+ original_is_file = pathlib.Path.is_file
+
+ denied_paths = []
+
+ def _is_file(self, *args, **kwargs):
+ if self.name == ".env":
+ denied_paths.append(self)
+ raise PermissionError(13, "Permission denied", str(self))
+ return original_is_file(self, *args, **kwargs)
+
+ clean_env.setattr(pathlib.Path, "is_file", _is_file)
+ clean_env.setenv("LDR_DISABLE_RATE_LIMITING", disabled)
+
+ mod = _reload_rate_limit()
+
+ assert denied_paths, "The test must inject a .env permission failure"
+ assert mod._LEGACY_STORAGE_URI == ""
+ assert mod._LEGACY_STORAGE_SOURCE == ""
+ assert mod.limiter.enabled is (disabled == "false")
+
+ def test_unreadable_dotenv_is_logged_at_debug_without_contents(
+ self, clean_env, tmp_path, loguru_caplog
+ ):
+ """A ./.env the lookup cannot parse is treated as absent and noted
+ at DEBUG by exception type only -- the exception text can quote
+ the file, and the file can hold a credential."""
+ import starlette.config
+
+ def _unreadable(*args, **kwargs):
+ raise ValueError("line 1: RATELIMIT_STORAGE_URL=redis://:Hunter2@h")
+
+ (tmp_path / ".env").write_text(
+ "RATELIMIT_STORAGE_URL=redis://:Hunter2@h:6379/0\n"
+ )
+ clean_env.chdir(tmp_path)
+ clean_env.setattr(starlette.config, "Config", _unreadable)
+ clean_env.setenv("LDR_DISABLE_RATE_LIMITING", "true")
+
+ with loguru_caplog.at_level("DEBUG"):
+ mod = _reload_rate_limit()
+
+ assert mod._LEGACY_STORAGE_URI == ""
+ debug_lines = [
+ r.getMessage()
+ for r in loguru_caplog.records
+ if r.levelname == "DEBUG" and ".env" in r.getMessage()
+ ]
+ assert debug_lines, "the unreadable .env was swallowed silently"
+ assert any("ValueError" in line for line in debug_lines)
+ assert "Hunter2" not in loguru_caplog.text
+
+ def test_failed_lookup_still_redacts_slowapi_unknown_scheme_error(
+ self, clean_env, tmp_path
+ ):
+ """Fail closed: if this module's own .env lookup fails while
+ slowapi still reads an unknown-scheme URI from the same file,
+ limits' ``unknown storage scheme : <uri>`` text must not reach the
+ startup error unredacted."""
+ import traceback
+
+ import starlette.config
+
+ def _unreadable(*args, **kwargs):
+ raise OSError("simulated")
+
+ (tmp_path / ".env").write_text(
+ "RATELIMIT_STORAGE_URL=bogus://u:Pw0rdX9@h:6379\n"
+ )
+ clean_env.chdir(tmp_path)
+ # Only the module's lookup sees the failure: slowapi bound its own
+ # ``Config`` when it was imported.
+ clean_env.setattr(starlette.config, "Config", _unreadable)
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ exc = exc_info.value
+ formatted = "".join(
+ traceback.format_exception(type(exc), exc, exc.__traceback__)
+ )
+ assert "Pw0rdX9" not in str(exc)
+ assert "Pw0rdX9" not in formatted
+ assert exc.__cause__ is None and exc.__context__ is None
+
+
+# ---------------------------------------------------------------------------
+# Regression 5 — TRUST_PROXY_HEADERS + LDR_SERVER_TRUSTED_PROXY_COUNT is a
+# TRI-STATE check, not a blanket hard-fail
+#
+# Round 4 escalated the combination of TRUST_PROXY_HEADERS=true and
+# LDR_SERVER_TRUSTED_PROXY_COUNT>0 to an unconditional import-time
+# RuntimeError. That over-corrected: the actual poisoning source is
+# uvicorn's `--forwarded-allow-ips`, which `web/app.py` used to hardcode to
+# "*" whenever TRUST_PROXY_HEADERS was set. With "*", uvicorn's
+# ProxyHeadersMiddleware rewrites `scope["client"]` from the client-forgeable
+# left-most X-Forwarded-For entry for ANY direct peer -- but uvicorn's own
+# contract only does that rewrite for peers matching `--forwarded-allow-ips`.
+# `LDR_SERVER_FORWARDED_ALLOW_IPS` (new; read identically by both
+# `web/app.py` and this module) makes that allow-list configurable, so a
+# RESTRICTED value (the proxy's real IP) makes the combination safe: an
+# attacker connecting directly to LDR is not in the allow-list and keeps
+# their real socket peer. Only "*" (the backward-compatible default) with
+# both settings on remains unconditionally exploitable and hard-fails.
+#
+# Round 7 (commit f5db1daab) hoisted this guard to fire on
+# `TRUST_PROXY_HEADERS` alone, independent of `LDR_SERVER_TRUSTED_PROXY_
+# COUNT` -- which was correct for the rate-limiter's own trust logic (see
+# ``_get_client_ip``) but, applied to the *startup guard*, meant EVERY
+# pre-existing deployment that only ever set `TRUST_PROXY_HEADERS=true`
+# (the original, documented opt-in that predates this PR) started hitting
+# `RuntimeError` at import time after a plain upgrade -- with no config
+# change on the operator's part, and no way to know they needed one until
+# the server refused to start. This round restores the RuntimeError to an
+# OPT-IN condition: it fires only when the operator has ALSO adopted one of
+# this PR's new settings (`LDR_SERVER_TRUSTED_PROXY_COUNT > 0`, or an
+# explicitly-set `LDR_SERVER_FORWARDED_ALLOW_IPS`, checked on the value the
+# operator wrote having at least one non-empty entry, so an explicit `="*"`
+# still counts and an empty `=""` or `=","` does not) while
+# `LDR_SERVER_FORWARDED_ALLOW_IPS` still resolves to "*". The legacy,
+# not-opted-in case now boots with a `logger.warning` instead of raising --
+# see ``TestLegacyTrustProxyHeadersWarns`` below.
+# ---------------------------------------------------------------------------
+
+
+def clean_proxy_trust_env(monkeypatch):
+ """Isolate the three env vars the tri-state check reads, on top of
+ ``clean_env``'s rate-limiting/storage isolation -- CI or a dev shell
+ could plausibly have any of ``TRUST_PROXY_HEADERS``,
+ ``LDR_SERVER_TRUSTED_PROXY_COUNT``, or ``LDR_SERVER_FORWARDED_ALLOW_IPS``
+ exported ambiently, and every case below depends on starting from a
+ known-clean baseline.
+ """
+ for name in (
+ "LDR_DISABLE_RATE_LIMITING",
+ "DISABLE_RATE_LIMITING",
+ "RATE_LIMIT_STORAGE_URI",
+ "TRUST_PROXY_HEADERS",
+ "LDR_SERVER_TRUSTED_PROXY_COUNT",
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ return monkeypatch
+
+
+class TestProxyTrustComboGuard:
+ def test_combo_with_default_wildcard_allow_ips_hard_fails(
+ self, clean_proxy_trust_env
+ ):
+ """TRUST_PROXY_HEADERS=true + LDR_SERVER_TRUSTED_PROXY_COUNT>0, with
+ LDR_SERVER_FORWARDED_ALLOW_IPS left unset (defaults to "*"): the
+ genuinely poisoned configuration -- uvicorn trusts forwarded headers
+ from literally any direct peer, so hop-count mode's
+ fallback-to-direct-peer safety net is defeated for every request.
+ Must still hard-fail at import time.
+ """
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+ clean_proxy_trust_env.setenv("LDR_SERVER_TRUSTED_PROXY_COUNT", "1")
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ message = str(exc_info.value)
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" in message
+ assert "UNSAFE" in message
+
+ def test_combo_with_explicit_wildcard_allow_ips_hard_fails(
+ self, clean_proxy_trust_env
+ ):
+ """Same as above but with LDR_SERVER_FORWARDED_ALLOW_IPS explicitly
+ set to "*" rather than left unset -- an operator who copies the
+ wildcard value in by hand must get the identical hard-fail, not a
+ pass-through because the var happened to be present."""
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+ clean_proxy_trust_env.setenv("LDR_SERVER_TRUSTED_PROXY_COUNT", "2")
+ clean_proxy_trust_env.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "*")
+
+ with pytest.raises(RuntimeError):
+ _reload_rate_limit()
+
+ def test_explicit_wildcard_allow_ips_alone_hard_fails(
+ self, clean_proxy_trust_env
+ ):
+ """Explicitly setting LDR_SERVER_FORWARDED_ALLOW_IPS="*" is itself
+ an opt-in to this PR's new settings, even with
+ LDR_SERVER_TRUSTED_PROXY_COUNT left unset/0 -- an operator who
+ writes the wildcard in by hand has made a deliberate, unsafe
+ choice and must not be let through only because the count-based
+ opt-in wasn't used. Distinguished from the default/unset case
+ (which only warns) by whether the value the operator wrote has any
+ non-empty entry, not by the resolved value -- both resolve to the
+ same string "*". An empty value ("" or ",") does not count as
+ explicit."""
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+ clean_proxy_trust_env.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "*")
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ message = str(exc_info.value)
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" in message
+ assert "UNSAFE" in message
+
+ def test_restricted_allow_ips_alone_boots_cleanly(
+ self, clean_proxy_trust_env
+ ):
+ """A restricted LDR_SERVER_FORWARDED_ALLOW_IPS with
+ LDR_SERVER_TRUSTED_PROXY_COUNT left unset/0 -- the plain
+ TRUST_PROXY_HEADERS=true + HTTPS-detection deployment, no
+ multi-hop hop-counting involved -- boots cleanly. Not exploitable:
+ uvicorn only rewrites request.client for a direct peer matching
+ the restricted allow-list."""
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+ clean_proxy_trust_env.setenv(
+ "LDR_SERVER_FORWARDED_ALLOW_IPS", "10.0.0.5"
+ )
+
+ mod = _reload_rate_limit()
+
+ assert mod._TRUSTED_PROXY_COUNT == 0
+ assert mod._TRUST_PROXY_HEADERS is True
+ assert mod._FORWARDED_ALLOW_IPS == "10.0.0.5"
+ assert mod._PROXY_TRUST_OPTED_IN is True
+
+ def test_combo_with_restricted_allow_ips_boots_cleanly(
+ self, clean_proxy_trust_env
+ ):
+ """The fix: the same combination boots without error once
+ LDR_SERVER_FORWARDED_ALLOW_IPS names the actual trusted proxy
+ IP(s). This is now the RECOMMENDED HTTPS + hop-count deployment
+ (docs/deployment/reverse-proxy.md)."""
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+ clean_proxy_trust_env.setenv("LDR_SERVER_TRUSTED_PROXY_COUNT", "1")
+ clean_proxy_trust_env.setenv(
+ "LDR_SERVER_FORWARDED_ALLOW_IPS", "10.0.0.5"
+ )
+
+ mod = _reload_rate_limit()
+
+ assert mod._TRUSTED_PROXY_COUNT == 1
+ assert mod._TRUST_PROXY_HEADERS is True
+ assert mod._FORWARDED_ALLOW_IPS == "10.0.0.5"
+
+ def test_hop_count_alone_without_trust_proxy_headers_boots_cleanly(
+ self, clean_proxy_trust_env
+ ):
+ """Negative control: LDR_SERVER_TRUSTED_PROXY_COUNT>0 by itself
+ (TRUST_PROXY_HEADERS unset) never touches this guard at all -- it
+ doesn't reach uvicorn's proxy-headers middleware, so there is
+ nothing to poison."""
+ clean_proxy_trust_env.setenv("LDR_SERVER_TRUSTED_PROXY_COUNT", "1")
+
+ mod = _reload_rate_limit()
+
+ assert mod._TRUSTED_PROXY_COUNT == 1
+ assert mod._TRUST_PROXY_HEADERS is False
+
+ def test_trust_proxy_headers_alone_without_hop_count_boots_cleanly(
+ self, clean_proxy_trust_env, loguru_caplog_full
+ ):
+ """The legacy config -- TRUST_PROXY_HEADERS=true set by itself, hop
+ count and LDR_SERVER_FORWARDED_ALLOW_IPS both left untouched --
+ predates this PR and MUST keep booting on a plain upgrade (this is
+ the defect round 7 introduced: it started raising RuntimeError
+ here). It boots with a startup warning instead of the RuntimeError,
+ since the operator has not opted into either of this PR's new
+ settings and is not, therefore, relying on this PR's guarantees.
+ """
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+
+ with loguru_caplog_full.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._TRUSTED_PROXY_COUNT == 0
+ assert mod._TRUST_PROXY_HEADERS is True
+ assert mod._FORWARDED_ALLOW_IPS == "*"
+ assert mod._PROXY_TRUST_OPTED_IN is False
+ assert "TRUST_PROXY_HEADERS=true" in loguru_caplog_full.text
+ assert "SPOOFABLE" in loguru_caplog_full.text
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" in loguru_caplog_full.text
+
+ def test_default_forwarded_allow_ips_is_wildcard(
+ self, clean_proxy_trust_env
+ ):
+ """Pin the backward-compatible default so a change to it is caught
+ here rather than only showing up as a startup failure in an
+ unrelated test."""
+ mod = _reload_rate_limit()
+
+ assert mod._FORWARDED_ALLOW_IPS == "*"
+
+
+_PROXY_STARTUP_ENV_VARS = (
+ "LDR_DISABLE_RATE_LIMITING",
+ "DISABLE_RATE_LIMITING",
+ "RATE_LIMIT_STORAGE_URI",
+ "RATELIMIT_STORAGE_URL",
+ "TRUST_PROXY_HEADERS",
+ "LDR_SERVER_TRUSTED_PROXY_COUNT",
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+)
+
+
+class TestProxyStartupLinesReachAnExternalAsgiServer:
+ """An external ASGI server must still show the forwarding-trust lines.
+
+ ``local_deep_research/__init__.py`` disables the package's loguru
+ namespace and only ``config_logger()`` (run by ``ldr-web``) enables
+ it again, so ``uvicorn local_deep_research.web.fastapi_app:app``
+ used to import this module with these warnings silently dropped,
+ including the one the changelog and docs promise for a bare
+ ``TRUST_PROXY_HEADERS=true``.
+ """
+
+ @pytest.mark.timeout(300)
+ @pytest.mark.parametrize(
+ ("env", "expected"),
+ [
+ ({"TRUST_PROXY_HEADERS": "true"}, "SPOOFABLE configuration"),
+ (
+ {"LDR_SERVER_FORWARDED_ALLOW_IPS": "10.0.0.0/8"},
+ "trusts every peer inside",
+ ),
+ ({"LDR_SERVER_FORWARDED_ALLOW_IPS": "nginx"}, "matches no peer"),
+ ],
+ ids=["legacy-trust-proxy-headers", "broad-entry", "opaque-literal"],
+ )
+ def test_warning_reaches_stderr_while_package_logging_is_off(
+ self, tmp_path, env, expected
+ ):
+ """A fresh interpreter, exactly as an ASGI server imports the app:
+ nothing has enabled the package's logging."""
+ child_env = {
+ name: value
+ for name, value in os.environ.items()
+ if name not in _PROXY_STARTUP_ENV_VARS
+ }
+ child_env.update(env)
+ child_env["LDR_DATA_DIR"] = str(tmp_path)
+
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ "import local_deep_research.web.dependencies.rate_limit",
+ ],
+ capture_output=True,
+ text=True,
+ env=child_env,
+ timeout=240,
+ )
+
+ assert result.returncode == 0, result.stderr
+ assert result.stderr.count(expected) == 1, result.stderr
+
+ def test_line_is_not_repeated_on_stderr_when_loguru_delivers_it(
+ self, clean_proxy_trust_env, loguru_caplog
+ ):
+ """With logging enabled (``ldr-web``) loguru alone emits the line."""
+ clean_proxy_trust_env.setenv("TRUST_PROXY_HEADERS", "true")
+ stderr = io.StringIO()
+ clean_proxy_trust_env.setattr(sys, "stderr", stderr)
+
+ with loguru_caplog.at_level("WARNING"):
+ _reload_rate_limit()
+
+ assert loguru_caplog.text.count("SPOOFABLE configuration") == 1
+ assert "SPOOFABLE" not in stderr.getvalue()
diff --git a/tests/web/dependencies/test_rate_limit_restricted_allow_list.py b/tests/web/dependencies/test_rate_limit_restricted_allow_list.py
new file mode 100644
index 0000000000..4d8f756b1e
--- /dev/null
+++ b/tests/web/dependencies/test_rate_limit_restricted_allow_list.py
@@ -0,0 +1,1390 @@
+"""Security regression tests for restricted-allow-list forwarding trust
+and port-bearing forwarded entries in ``web/dependencies/rate_limit.py``.
+
+Two defects found by the adversarial PR gate are pinned here:
+
+1. Every application-level forwarding-trust gate (the combo-mode
+ X-Real-IP fallback, hop-count mode's direct-peer check, and the default
+ left-most heuristic) consulted ``_is_trusted_peer`` -- a PRIVATE-NESS
+ heuristic. With ``TRUST_PROXY_HEADERS=true`` and a RESTRICTED, explicitly
+ configured ``LDR_SERVER_FORWARDED_ALLOW_IPS`` (the documented, recommended
+ combination), a merely-PRIVATE direct peer outside that allow-list (another
+ container/pod on the same network, a LAN host) could rotate a spoofed
+ forwarding header and mint a fresh rate-limit bucket per request -- exactly
+ what docs/deployment/reverse-proxy.md promises cannot happen in restricted
+ mode ("an attacker connecting directly to LDR keeps their real raw socket
+ peer"). In restricted mode the allow-list alone decides.
+
+2. Hop-count mode returned the selected X-Forwarded-For token verbatim. A
+ proxy that appends the observed address WITH its TCP source port (a form
+ uvicorn's own forwarded parser accepts and normalises) therefore handed the
+ same client a different bucket per connection -- connection churn alone
+ replenished per-IP quotas.
+
+Same pure-unit style as test_rate_limit_keys.py: minimal Starlette ``Request``
+objects built from raw ASGI scopes; module globals monkeypatched per test
+(and restored) instead of reloading the module.
+
+The two classes at the END of this file are the exception: they pin
+IMPORT-time constants (the allow-list restriction predicate and the startup
+guard), which no monkeypatched global can reach, so they reload the module
+under a snapshot/restore context manager instead.
+"""
+
+import re
+import sys
+from contextlib import contextmanager
+from pathlib import Path
+
+import pytest
+from starlette.requests import Request
+
+RESTRICTED_ENTRIES = ("10.0.0.5",)
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+
+
+def rl():
+ """The rate_limit module as currently loaded (see test_rate_limit_keys.py
+ for why this is resolved per-test, not at import time)."""
+ from local_deep_research.web.dependencies import rate_limit
+
+ return rate_limit
+
+
+def make_request(peer="8.8.8.8", headers=None):
+ """Build a minimal Starlette Request from a raw ASGI scope dict."""
+ scope = {
+ "type": "http",
+ "method": "GET",
+ "path": "/",
+ "query_string": b"",
+ "client": (peer, 51234),
+ "headers": [
+ (k.lower().encode(), v.encode()) for k, v in (headers or {}).items()
+ ],
+ }
+ return Request(scope)
+
+
+def restricted(rl, monkeypatch):
+ """Put the module into restricted-allow-list mode for one proxy IP."""
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", True)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", RESTRICTED_ENTRIES)
+
+
+class TestRestrictedAllowListComboMode:
+ """TRUST_PROXY_HEADERS=true + restricted allow-list: the allow-list is
+ the ONLY source of application-level forwarding trust."""
+
+ def test_private_non_allowlisted_peer_varying_real_ip_mints_no_new_keys(
+ self, rl, monkeypatch, restricted
+ ):
+ """The gate repro: a PRIVATE direct peer outside the allow-list,
+ connecting directly (no X-Forwarded-For at all), rotating a spoofed
+ X-Real-IP. Its own address must be the rate-limit key on every
+ request -- a private peer that bypassed the proxy is a direct
+ client, not a trusted proxy."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer="10.0.0.23",
+ headers={"X-Real-IP": f"203.0.113.{i}"},
+ )
+ )
+ for i in range(5)
+ }
+ assert keys == {"10.0.0.23"}
+
+ def test_real_ip_honored_from_allowlisted_peer(
+ self, rl, monkeypatch, restricted
+ ):
+ """Positive control: the allow-listed proxy keeps its X-Real-IP
+ fallback (no X-Forwarded-For -- the common nginx pattern)."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="10.0.0.5", headers={"X-Real-IP": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+ def test_private_non_allowlisted_peer_xff_present_keeps_raw_peer(
+ self, rl, monkeypatch, restricted
+ ):
+ """With X-Forwarded-For present the combo branch trusts uvicorn's
+ already-computed request.client either way; this pins that the
+ restricted-mode change did not reopen header parsing here."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="10.0.0.23", headers={"X-Forwarded-For": "203.0.113.7"}
+ )
+ assert rl._get_client_ip(request) == "10.0.0.23"
+
+ @pytest.mark.parametrize(
+ "forwarded", ["user:alice", "unknown", "evil user_agent=x"]
+ )
+ def test_non_address_client_from_uvicorn_shares_one_bucket(
+ self, rl, monkeypatch, restricted, forwarded
+ ):
+ """uvicorn's restricted walk returns the first unlisted entry from
+ the right WITHOUT checking that it is an address, so a listed
+ proxy relaying junk hands LDR free text as ``request.client``.
+ That value must key on the fixed unparseable-peer bucket, not
+ verbatim: ``user:alice`` would collide with ``_user_key``'s
+ namespace, and any free text is an unbounded key that is also
+ written to the 429 audit log. The client address is computed by
+ uvicorn's REAL middleware, so the premise is uvicorn's behaviour,
+ not a guess at it."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ headers = [("X-Forwarded-For", forwarded)]
+ computed = _client_after_uvicorn(
+ peer="10.0.0.5",
+ headers=headers,
+ trusted_hosts=",".join(RESTRICTED_ENTRIES),
+ )
+ assert computed == forwarded, (
+ "premise: uvicorn copies the unlisted entry verbatim"
+ )
+ request = make_request(peer=computed, headers=dict(headers))
+ assert rl._get_client_ip(request) == rl._UNPARSEABLE_PEER_KEY
+
+ def test_rotating_non_address_clients_mint_no_new_keys(
+ self, rl, monkeypatch, restricted
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer=f"token-{i}",
+ headers={"X-Forwarded-For": f"token-{i}"},
+ )
+ )
+ for i in range(16)
+ }
+ assert keys == {rl._UNPARSEABLE_PEER_KEY}
+
+
+class TestRestrictedAllowListHopCountMode:
+ """TRUST_PROXY_HEADERS=false + LDR_SERVER_TRUSTED_PROXY_COUNT>0 with an
+ explicitly configured allow-list: the declared count is not permission
+ for a merely-private peer outside the list to feed us X-Forwarded-For."""
+
+ def test_private_non_allowlisted_peer_crafted_xff_ignored(
+ self, rl, monkeypatch, restricted
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 2)
+ request = make_request(
+ peer="192.168.1.9",
+ headers={"X-Forwarded-For": "6.6.6.6, 9.9.9.9"},
+ )
+ assert rl._get_client_ip(request) == "192.168.1.9"
+
+ def test_allowlisted_peer_still_hop_counts(
+ self, rl, monkeypatch, restricted
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ request = make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": "93.184.216.34, 10.0.0.9"},
+ )
+ assert rl._get_client_ip(request) == "10.0.0.9"
+
+
+class TestRestrictedAllowListDefaultHeuristic:
+ """Default mode (TRUST_PROXY_HEADERS off, count 0): an explicitly
+ configured restricted allow-list revokes private-ness trust here too."""
+
+ def test_private_non_allowlisted_peer_leftmost_xff_ignored(
+ self, rl, monkeypatch, restricted
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ request = make_request(
+ peer="192.168.1.9",
+ headers={"X-Forwarded-For": "93.184.216.34, 10.0.0.9"},
+ )
+ assert rl._get_client_ip(request) == "192.168.1.9"
+
+ def test_private_non_allowlisted_peer_real_ip_ignored(
+ self, rl, monkeypatch, restricted
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ request = make_request(
+ peer="192.168.1.9", headers={"X-Real-IP": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "192.168.1.9"
+
+
+class TestRestrictedAllowListUnrestrictedModesPreserved:
+ """The documented behavior for UNRESTRICTED configurations (allow-list
+ unset, or explicitly "*") must not change: private/loopback peers keep
+ their heuristic trust."""
+
+ def test_explicit_wildcard_is_not_restricted(self, rl, monkeypatch):
+ """An allow-list explicitly set to "*" only reaches request handling
+ when TRUST_PROXY_HEADERS is false (the startup guard refuses the
+ true+explicit-"*" combination); the private/loopback heuristic keeps
+ applying."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ())
+ request = make_request(
+ peer="192.168.1.9", headers={"X-Real-IP": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+ def test_unset_allow_list_keeps_private_heuristic(self, rl, monkeypatch):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ())
+ request = make_request(
+ peer="10.0.0.5", headers={"X-Forwarded-For": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+
+class TestPeerInForwardedAllowList:
+ """Membership must mirror uvicorn's --forwarded-allow-ips semantics:
+ exact IP compare (by parsed address, not string), CIDR networks, and
+ verbatim comparison for non-IP literals."""
+
+ def test_exact_ip_match(self, rl, monkeypatch, restricted):
+ assert rl._peer_in_forwarded_allow_list("10.0.0.5") is True
+
+ def test_same_range_different_ip_does_not_match(
+ self, rl, monkeypatch, restricted
+ ):
+ assert rl._peer_in_forwarded_allow_list("10.0.0.6") is False
+
+ def test_cidr_network_entry_matches_member(self, rl, monkeypatch):
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ("10.0.1.0/24",))
+ assert rl._peer_in_forwarded_allow_list("10.0.1.77") is True
+ assert rl._peer_in_forwarded_allow_list("10.0.2.77") is False
+
+ def test_ipv6_compares_by_parsed_address(self, rl, monkeypatch):
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ("::1",))
+ assert rl._peer_in_forwarded_allow_list("::1") is True
+ assert rl._peer_in_forwarded_allow_list("2001:db8::9") is False
+
+ def test_non_ip_literal_matches_verbatim(self, rl, monkeypatch):
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ("unix-proxy",))
+ assert rl._peer_in_forwarded_allow_list("unix-proxy") is True
+ assert rl._peer_in_forwarded_allow_list("other-proxy") is False
+
+ def test_malformed_entry_never_crashes_the_lookup(self, rl, monkeypatch):
+ """An unparseable allow-list entry degrades to a literal (uvicorn's
+ own conservative behaviour), not an exception on the request path."""
+ monkeypatch.setattr(
+ rl, "_FORWARDED_ALLOW_ENTRIES", ("not-an-ip/24", "10.0.0.5")
+ )
+ assert rl._peer_in_forwarded_allow_list("10.0.0.5") is True
+ assert rl._peer_in_forwarded_allow_list("8.8.8.8") is False
+
+
+class TestRestrictedModeTestclientSentinel:
+ def test_sentinel_stays_trusted_in_restricted_mode(
+ self, rl, monkeypatch, restricted
+ ):
+ """The test-suite sentinel never appears as a real network peer;
+ keeping it trusted in restricted mode lets the suites hand out
+ unique IPs (no shared buckets across test modules)."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ request = make_request(
+ peer="testclient", headers={"X-Real-IP": "93.184.216.34"}
+ )
+ assert rl._get_client_ip(request) == "93.184.216.34"
+
+
+class TestSelectTrustedHopStripsPort:
+ """The hop-count-selected X-Forwarded-For entry must be normalised the
+ way uvicorn's own forwarded parser normalises it: an observed source
+ port (bare IPv4 ``host:port``, bracketed ``[v6]:port``) is stripped, so
+ a per-connection TCP source port cannot mint a fresh rate-limit bucket.
+
+ Malformed values are passed through unchanged -- uvicorn's conservative
+ rule, so trust checks never silently normalise arbitrary input.
+ """
+
+ def test_bare_ipv4_with_port_is_stripped(self, rl):
+ assert rl._select_trusted_hop("198.51.100.20:41000", 1) == (
+ "198.51.100.20"
+ )
+
+ def test_bracketed_ipv6_with_port_is_stripped(self, rl):
+ assert rl._select_trusted_hop("[2001:db8::1]:443", 1) == "2001:db8::1"
+
+ def test_bracketed_ipv6_without_port_loses_only_brackets(self, rl):
+ """uvicorn's parser drops the brackets even without a port; mirror
+ it so both spellings key identically."""
+ assert rl._select_trusted_hop("[2001:db8::1]", 1) == "2001:db8::1"
+
+ def test_bare_ipv6_is_untouched(self, rl):
+ assert rl._select_trusted_hop("2001:db8::1", 1) == "2001:db8::1"
+
+ def test_address_without_port_is_untouched(self, rl):
+ assert rl._select_trusted_hop("198.51.100.20", 1) == "198.51.100.20"
+
+ def test_malformed_ipv4_port_is_untouched(self, rl):
+ assert rl._select_trusted_hop("198.51.100.20:notaport", 1) == (
+ "198.51.100.20:notaport"
+ )
+
+ def test_malformed_bracketed_ipv6_port_loses_only_brackets(self, rl):
+ """Unlike the bare-IPv4 case above, uvicorn's parser keeps the
+ bracketed host when the port does not parse."""
+ assert rl._select_trusted_hop("[2001:db8::1]:notaport", 1) == (
+ "2001:db8::1"
+ )
+
+ def test_six_digit_port_makes_the_entry_unusable(self, rl, monkeypatch):
+ """A port has at most five digits, so ``5.6.7.8:123456`` is not an
+ address: the default heuristic keys the private proxy itself."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 0)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ keys = [
+ rl._get_client_ip(
+ make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": f"5.6.7.8:{port}"},
+ )
+ )
+ for port in ("65535", "123456")
+ ]
+ assert keys == ["5.6.7.8", "10.0.0.5"]
+
+ def test_port_bearing_entries_yield_one_key_per_client(
+ self, rl, monkeypatch
+ ):
+ """The actual bypass shape: same client address, two different
+ observed source ports. One rate-limit bucket, not two."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", False)
+ monkeypatch.setattr(rl, "_TRUSTED_PROXY_COUNT", 1)
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer="10.0.0.5",
+ headers={"X-Forwarded-For": f"198.51.100.20:{port}"},
+ )
+ )
+ for port in (41000, 41001)
+ }
+ assert keys == {"198.51.100.20"}
+
+ def test_selected_entry_in_longer_chain_is_normalised(self, rl):
+ assert rl._select_trusted_hop(
+ "forged, 203.0.113.7:51000, 10.0.0.9", 2
+ ) == ("203.0.113.7")
+
+
+# ---------------------------------------------------------------------------
+# Round-2 gate findings: the "uvicorn trusts every peer" check was textual
+# (``_FORWARDED_ALLOW_IPS == "*"``), and the X-Real-IP fallback's new gate is
+# a deliberate behaviour break for one shape of deployment. Both are pinned
+# below. These need the module's IMPORT-time constants, so unlike everything
+# above they reload the module instead of monkeypatching globals.
+# ---------------------------------------------------------------------------
+
+#: Allow-lists that leave uvicorn trusting an entire address family. Every
+#: one of them is exactly as exploitable as the literal ``"*"`` and none of
+#: them looks like it: once every hop in a chain is trusted, uvicorn's
+#: ``_TrustedHosts.get_trusted_client_address`` returns an entry the client
+#: supplied rather than the raw socket peer.
+UNRESTRICTED_SPELLINGS = (
+ "*",
+ "0.0.0.0/0",
+ "::/0",
+ "0.0.0.0/0,::/0",
+ "0.0.0.0/1,128.0.0.0/1",
+ # Every IPv4 peer reaching a listener that accepts IPv6 arrives
+ # IPv4-mapped, so this trusts all of IPv4 while contributing 2**32 of
+ # the 2**128 addresses a whole-IPv6-family sum would need.
+ "::ffff:0.0.0.0/96",
+ # Same mapped range, split into two entries that neither alone
+ # contains it -- only collapsing them first reveals they merge back
+ # into ``::ffff:0.0.0.0/96``. Checking each entry against
+ # ``subnet_of`` in isolation missed this (round-3 gate finding N2):
+ # real uvicorn honours a forged X-Forwarded-For from any mapped
+ # peer under this list.
+ "::ffff:0.0.0.0/97,::ffff:128.0.0.0/97",
+ # A whole-IPv6-family-minus-nothing-that-matters entry that CONTAINS
+ # the mapped range without being equal to it: a ``subnet_of`` call
+ # with its two arguments swapped would misclassify this as
+ # restricted (round-3 gate finding N3) even though it still trusts
+ # every mapped IPv4 peer.
+ "::/1",
+ # A trailing comma must not turn the wildcard into an allow-list of
+ # ("*",) that matches no real peer -- which booted, logged "a safe
+ # combination", and keyed every client into one bucket.
+ "*,",
+ # Zone/scope id (``%eth0``) on the mapped range: ``ipaddress``
+ # compares a scoped IPv6Network by scope id too, so
+ # ``_IPV4_MAPPED_RANGE.subnet_of(scoped)`` used to come back False
+ # even though the scope id changes nothing about which addresses
+ # match -- uvicorn's own comparison is purely by integer address and
+ # honours a forged X-Forwarded-For from every mapped peer the same
+ # as the unscoped ``::ffff:0.0.0.0/96`` spelling.
+ "::ffff:0:0%eth0/96",
+ "::ffff:0.0.0.0%1/96",
+)
+
+#: Controls: lists that really do restrict which peers uvicorn trusts.
+#: ``0.0.0.0/1`` is the boundary case -- half of IPv4 is enormous, but it is
+#: not a whole family, so the predicate must NOT over-reject it.
+RESTRICTED_SPELLINGS = (
+ "10.0.0.5",
+ "10.0.0.0/8",
+ "0.0.0.0/1",
+ "2001:db8::/64",
+ "10.0.0.5,",
+ # Three overlapping entries whose NAIVE (uncollapsed) address sum is
+ # exactly 2**31 + 2**30 + 2**30 == 2**32 -- a false "whole family"
+ # positive for a configuration that in fact only restricts to
+ # ``0.0.0.0/1`` (round-3 gate finding N6: the two-entry example this
+ # comment used to cite can never overflow, so it never exercised the
+ # collapse_addresses call it was meant to justify).
+ "0.0.0.0/1,0.0.0.0/2,64.0.0.0/2",
+ # A scoped network duplicated verbatim except for its zone id:
+ # scope-blind ``collapse_addresses`` used to treat the two as
+ # adjacent and merge them into ``fe80::/63`` (double the true
+ # coverage) instead of recognising them as the same ``fe80::/64``
+ # range -- real uvicorn's ``_TrustedHosts`` never trusts a peer
+ # under either entry (link-local addresses match no probed peer),
+ # so this stays a restricted, non-covering control.
+ "fe80::/64,fe80::%eth1/64",
+)
+
+_PROXY_TRUST_ENV_VARS = (
+ "LDR_DISABLE_RATE_LIMITING",
+ "DISABLE_RATE_LIMITING",
+ "RATE_LIMIT_STORAGE_URI",
+ "TRUST_PROXY_HEADERS",
+ "LDR_SERVER_TRUSTED_PROXY_COUNT",
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+)
+
+
+def _reload_rate_limit():
+ import importlib
+
+ from local_deep_research.web.dependencies import rate_limit
+
+ importlib.reload(rate_limit)
+ return rate_limit
+
+
+@contextmanager
+def _rate_limit_module_restored():
+ """Snapshot the module namespace and put the ORIGINAL objects back.
+
+ Same idiom, and the same reason, as
+ ``tests/web/dependencies/test_rate_limit_config.py``: ``reload``
+ rebinds ``limiter`` to a brand-new ``Limiter`` with empty registries
+ while every router keeps the object it was decorated against, so the
+ namespace has to be restored wholesale rather than reloaded again.
+ """
+ from local_deep_research.web.dependencies import rate_limit
+
+ snapshot = dict(rate_limit.__dict__)
+ try:
+ yield rate_limit
+ finally:
+ rate_limit.__dict__.clear()
+ rate_limit.__dict__.update(snapshot)
+
+
+def _client_after_uvicorn(peer, headers, trusted_hosts):
+ """The client address uvicorn's REAL middleware computes, verbatim."""
+ import asyncio
+
+ from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
+
+ captured = {}
+
+ async def inner_app(scope, receive, send):
+ captured["scope"] = scope
+
+ middleware = ProxyHeadersMiddleware(inner_app, trusted_hosts=trusted_hosts)
+ scope = {
+ "type": "http",
+ "method": "GET",
+ "path": "/",
+ "query_string": b"",
+ "client": (peer, 51234),
+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers],
+ }
+
+ async def receive():
+ return {"type": "http.disconnect"}
+
+ async def send(message):
+ pass
+
+ asyncio.run(middleware(scope, receive, send))
+ return captured["scope"]["client"][0]
+
+
+class TestUnrestrictedAllowListDetectionIsSemantic:
+ """``0.0.0.0/0`` is ``"*"`` with extra steps.
+
+ The startup guard and ``_ALLOW_LIST_IS_RESTRICTED`` used to compare the
+ configured string to the literal ``"*"``, so an operator who had opted
+ into this release's settings and wrote a whole-family CIDR booted,
+ logged "This is a safe combination", and handed every direct-connecting
+ attacker a rate-limit bucket of their choosing. Both now route through
+ one predicate (``_ALLOW_LIST_IS_UNRESTRICTED``) built from uvicorn's own
+ ``_TrustedHosts``, so they cannot disagree about one configuration.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _isolated_reloadable_module(self, monkeypatch):
+ for name in _PROXY_TRUST_ENV_VARS:
+ monkeypatch.delenv(name, raising=False)
+ with _rate_limit_module_restored():
+ yield
+
+ @pytest.mark.parametrize("allow_ips", UNRESTRICTED_SPELLINGS)
+ def test_whole_family_lists_are_not_restricted(
+ self, monkeypatch, allow_ips
+ ):
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is True, (
+ f"{allow_ips!r} was classified as a restricting allow-list"
+ )
+ # ... and therefore does NOT put the module into restricted mode,
+ # where allow-list membership would replace the private-peer
+ # heuristic with a list that trusts everyone anyway.
+ assert mod._ALLOW_LIST_IS_RESTRICTED is False
+ assert mod._FORWARDED_ALLOW_ENTRIES == ()
+
+ @pytest.mark.parametrize("allow_ips", UNRESTRICTED_SPELLINGS)
+ def test_whole_family_lists_hard_fail_the_opted_in_combination(
+ self, monkeypatch, allow_ips
+ ):
+ """Explicitly setting the variable IS the opt-in, so every spelling
+ above must refuse to start with ``TRUST_PROXY_HEADERS=true`` --
+ exactly as the literal ``"*"`` already did."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ message = str(exc_info.value)
+ assert "UNSAFE" in message
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" in message
+ # The remediation text must name the CIDR spellings, or an operator
+ # who wrote 0.0.0.0/0 reads a message about "*" and concludes the
+ # check misfired.
+ assert "0.0.0.0/0" in message
+ assert "::/0" in message
+ assert "0.0.0.0/1,128.0.0.0/1" in message
+
+ @pytest.mark.parametrize("allow_ips", RESTRICTED_SPELLINGS)
+ def test_genuinely_restricted_lists_are_not_over_rejected(
+ self, monkeypatch, allow_ips
+ ):
+ """Negative control. ``0.0.0.0/1`` is half the IPv4 internet and
+ still restricts something: uvicorn does not take its always-trust
+ shortcut, and for a peer OUTSIDE the range (``200.0.0.1``) it
+ leaves the raw socket peer alone. For a peer inside it the
+ reverse walk stops at the first entry that is not itself trusted
+ -- which, for a chain the attacker wrote, is an address the
+ attacker chose; that is uvicorn's semantics for any allow-listed
+ peer, and it is what the startup warning about networks broader
+ than /24 exists to say out loud. A predicate that rejected
+ ``0.0.0.0/1`` here would be pinning "looks big", not "trusts
+ everyone"."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is False
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+
+ def test_trailing_comma_does_not_mint_an_empty_allow_list(
+ self, monkeypatch
+ ):
+ """``"*,"`` parses to the entries ``("*",)``, which matches no real
+ IP: the module used to call that "restricted", log a safe-combination
+ line, and key every client by the proxy. Empty entries are stripped
+ before anything looks at the value, so it is the wildcard again."""
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "*,")
+
+ mod = _reload_rate_limit()
+
+ assert mod._FORWARDED_ALLOW_IPS == "*"
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is True
+ assert mod._ALLOW_LIST_IS_RESTRICTED is False
+
+ def test_empty_allow_list_is_not_an_explicit_opt_in(self, monkeypatch):
+ """``LDR_SERVER_FORWARDED_ALLOW_IPS=""`` is what an orchestrator
+ emits for an unconfigured variable (the repo-wide ``LDR_X=""``
+ means unset contract). It must NOT count as the operator adopting
+ this release's settings, which would turn a plain upgrade of a
+ legacy ``TRUST_PROXY_HEADERS=true`` deployment into a boot
+ failure."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "")
+
+ mod = _reload_rate_limit()
+
+ assert mod._FORWARDED_ALLOW_IPS == "*"
+ assert mod._FORWARDED_ALLOW_IPS_EXPLICIT is False
+ assert mod._PROXY_TRUST_OPTED_IN is False
+
+ def test_empty_hop_count_is_not_an_explicit_opt_in(self, monkeypatch):
+ """Same contract for the hop count: an empty value is unset, not a
+ malformed integer that aborts startup."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_TRUSTED_PROXY_COUNT", "")
+
+ mod = _reload_rate_limit()
+
+ assert mod._TRUSTED_PROXY_COUNT == 0
+ assert mod._PROXY_TRUST_OPTED_IN is False
+
+ def test_ipv6_default_route_alone_is_treated_as_unrestricted(
+ self, monkeypatch
+ ):
+ """Documented choice for ``::/0`` on its own.
+
+ uvicorn compares parsed addresses, and an ``IPv4Address`` is never
+ ``in`` an IPv6 network, so an IPv4 peer arriving at a listener
+ configured with ``::/0`` keeps its raw address (asserted here
+ against the real middleware). LDR still classifies the list as
+ unrestricted. Not because the default listener is dual-stack --
+ it is not: ``web/server_config.py``'s ``_DEFAULTS`` is
+ ``"host": "127.0.0.1"`` and binding wider is the explicit
+ ``LDR_WEB_HOST=0.0.0.0`` opt-in the Dockerfile sets, both IPv4
+ only. Because wherever the listener DOES accept IPv6
+ (``LDR_WEB_HOST=::``, an external ASGI server, a v6-capable
+ ingress) ``::/0`` trusts every peer arriving over it, and an
+ operator who wrote ``::/0`` meant "everything". Failing closed is
+ the conservative reading; the alternative makes the trust
+ boundary depend on the bind address.
+ """
+ assert (
+ _client_after_uvicorn(
+ peer="8.8.8.8",
+ headers=[("X-Forwarded-For", "1.2.3.4, 203.0.113.7")],
+ trusted_hosts="::/0",
+ )
+ == "8.8.8.8"
+ )
+ assert (
+ _client_after_uvicorn(
+ peer="2001:db8::99",
+ headers=[("X-Forwarded-For", "1.2.3.4, 203.0.113.7")],
+ trusted_hosts="::/0",
+ )
+ != "2001:db8::99"
+ )
+
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "::/0")
+ mod = _reload_rate_limit()
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is True
+
+ def test_ipv4_mapped_range_covers_the_ipv4_family(self, monkeypatch):
+ """``::ffff:0.0.0.0/96`` is ``0.0.0.0/0`` spelled in IPv6.
+
+ It holds 2**32 of IPv6's 2**128 addresses, so the whole-family
+ sum never reaches it -- but every IPv4 peer that reaches a
+ listener accepting IPv6 arrives inside it, and uvicorn then
+ honours whatever chain that peer wrote. Asserted against the
+ real middleware first: an attacker at ``::ffff:8.8.8.8``
+ supplies the address the application ends up keying on.
+ """
+ computed = _client_after_uvicorn(
+ peer="::ffff:8.8.8.8",
+ headers=[("X-Forwarded-For", "1.2.3.4, 203.0.113.7")],
+ trusted_hosts="::ffff:0.0.0.0/96",
+ )
+ assert computed == "203.0.113.7", computed
+ assert computed != "::ffff:8.8.8.8"
+
+ monkeypatch.setenv(
+ "LDR_SERVER_FORWARDED_ALLOW_IPS", "::ffff:0.0.0.0/96"
+ )
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is True
+ assert "::ffff:0.0.0.0/96" in mod._ALLOW_LIST_UNRESTRICTED_REASON
+ assert mod._ALLOW_LIST_IS_RESTRICTED is False
+
+ def test_ipv4_mapped_range_split_across_two_entries_still_covers_the_family(
+ self, monkeypatch
+ ):
+ """Round-3 gate finding N2: the mapped range in two pieces.
+
+ ``::ffff:0.0.0.0/97`` and ``::ffff:128.0.0.0/97`` are each only
+ half of ``::ffff:0.0.0.0/96``, so a ``subnet_of`` check against
+ each entry ALONE never sees the mapped range contained in
+ either one -- the predicate used to call this list restricted
+ while the real middleware honoured a forged X-Forwarded-For
+ from any mapped IPv4 peer anyway. Collapsing the entries first
+ (``ipaddress.collapse_addresses``) merges the pair back into
+ ``::ffff:0.0.0.0/96`` before the containment check runs.
+ """
+ computed = _client_after_uvicorn(
+ peer="::ffff:8.8.8.8",
+ headers=[("X-Forwarded-For", "1.2.3.4, 203.0.113.7")],
+ trusted_hosts="::ffff:0.0.0.0/97,::ffff:128.0.0.0/97",
+ )
+ assert computed == "203.0.113.7", computed
+ assert computed != "::ffff:8.8.8.8"
+
+ monkeypatch.setenv(
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+ "::ffff:0.0.0.0/97,::ffff:128.0.0.0/97",
+ )
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is True
+ assert "::ffff:0.0.0.0/96" in mod._ALLOW_LIST_UNRESTRICTED_REASON
+ assert mod._ALLOW_LIST_IS_RESTRICTED is False
+
+ @pytest.mark.parametrize(
+ ("allow_ips", "peer"),
+ [
+ ("*", "8.8.8.8"),
+ ("0.0.0.0/0", "8.8.8.8"),
+ ("0.0.0.0/0,::/0", "8.8.8.8"),
+ ("0.0.0.0/1,128.0.0.0/1", "8.8.8.8"),
+ ("::ffff:0.0.0.0/97,::ffff:128.0.0.0/97", "::ffff:8.8.8.8"),
+ ("::/1", "::ffff:8.8.8.8"),
+ ("::/0", "2001:db8::99"),
+ ("::ffff:0.0.0.0/96", "::ffff:8.8.8.8"),
+ ("10.0.0.5", "8.8.8.8"),
+ # Scoped spellings of the mapped range (round-4 gate finding
+ # R1): a zone id must not hide the mapped-range containment
+ # from the predicate.
+ ("::ffff:0:0%eth0/96", "::ffff:8.8.8.8"),
+ ("::ffff:0.0.0.0%1/96", "::ffff:8.8.8.8"),
+ ],
+ )
+ def test_predicate_agrees_with_the_real_middleware(
+ self, monkeypatch, allow_ips, peer
+ ):
+ """The predicate is checked against uvicorn's observable behaviour,
+ not against a re-implementation of it.
+
+ An attacker connects straight to LDR and sends a forged chain. The
+ configuration is exploitable exactly when uvicorn hands the
+ application an address the ATTACKER supplied instead of the raw
+ socket peer -- whether that is the left-most entry (the
+ always-trust / whole-chain-trusted shortcut) or the right-most one
+ (``::/0``, where the v4 entries are not trusted but the header is
+ still entirely the attacker's). ``_ALLOW_LIST_IS_UNRESTRICTED``
+ must agree with uvicorn for these representative cases -- the
+ parametrisation is a sample, not an enumeration of every
+ allow-list spelling, and the predicate is deliberately
+ CONSERVATIVE where they can differ (it may call a list
+ unrestricted that uvicorn would still narrow; it must never call
+ one restricted that uvicorn trusts wholesale).
+ """
+ computed = _client_after_uvicorn(
+ peer=peer,
+ headers=[("X-Forwarded-For", "1.2.3.4, 203.0.113.7")],
+ trusted_hosts=allow_ips,
+ )
+ attacker_header_was_honoured = computed != peer
+
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+ mod = _reload_rate_limit()
+
+ assert (
+ mod._ALLOW_LIST_IS_UNRESTRICTED is attacker_header_was_honoured
+ ), (
+ f"allow-list {allow_ips!r}: uvicorn computed {computed!r} for a "
+ f"direct connection from {peer!r}, but LDR classified the list "
+ f"as {'unrestricted' if mod._ALLOW_LIST_IS_UNRESTRICTED else 'restricted'}"
+ )
+
+
+class TestNonPrivateProxyXRealIpFallbackIsABreakingChange:
+ """The X-Real-IP fallback under ``TRUST_PROXY_HEADERS=true`` is now
+ gated by ``_peer_may_supply_forwarding_headers``; before this release it
+ was honoured unconditionally in that mode.
+
+ This is a DELIBERATE behaviour break, pinned here rather than left to be
+ rediscovered: a proxy that reaches LDR from a NON-private address (a
+ cloud load balancer such as GCP's 35.191.0.0/16, a CGNAT/Tailscale peer
+ in 100.64.0.0/10, a public nginx host) and forwards only ``X-Real-IP``
+ -- no ``X-Forwarded-For``, the common nginx pattern -- now has its
+ header ignored, so every client behind it shares the proxy's single
+ bucket and the login/registration lockouts become deployment-global.
+ Naming that proxy in ``LDR_SERVER_FORWARDED_ALLOW_IPS`` restores
+ per-client keying; the changelog, the docs and the startup warning all
+ say so (``TestXRealIpBreakIsNamedWhereOperatorsLook`` pins that).
+ """
+
+ # Peers the notes call "private, loopback or link-local": X-Real-IP counts.
+ COUNTED_PEERS = (
+ "10.0.0.5",
+ "127.0.0.1",
+ "169.254.1.1",
+ "::1",
+ "fe80::1",
+ "::ffff:10.0.0.5",
+ )
+ # Peers they call "public or carrier-grade-NAT": X-Real-IP is ignored.
+ # 6to4 and an IPv4-mapped public address are public on every Python.
+ IGNORED_PEERS = (
+ "35.191.10.5",
+ "100.64.0.9",
+ "2002:808:808::1",
+ "::ffff:35.191.10.5",
+ )
+
+ @pytest.mark.parametrize("peer", COUNTED_PEERS)
+ def test_x_real_ip_counts_from_private_loopback_and_link_local_peers(
+ self, rl, monkeypatch, peer
+ ):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ())
+
+ key = rl._get_client_ip(
+ make_request(peer=peer, headers={"X-Real-IP": "198.51.100.7"})
+ )
+
+ assert key == "198.51.100.7"
+
+ @pytest.mark.parametrize("peer", IGNORED_PEERS)
+ def test_only_the_x_real_ip_of_a_public_peer_is_ignored(
+ self, rl, monkeypatch, peer
+ ):
+ """The notes say a public proxy's ``X-Forwarded-For`` still counts
+ with no allow-list and only its ``X-Real-IP`` is ignored."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ())
+
+ real_ip_only = rl._get_client_ip(
+ make_request(peer=peer, headers={"X-Real-IP": "198.51.100.7"})
+ )
+ forwarded_for = rl._get_client_ip(
+ make_request(peer=peer, headers={"X-Forwarded-For": "198.51.100.7"})
+ )
+
+ assert real_ip_only == peer
+ assert forwarded_for == "198.51.100.7"
+
+ @pytest.mark.parametrize("peer", IGNORED_PEERS)
+ def test_setting_the_allow_list_to_the_peer_restores_its_x_real_ip(
+ self, rl, monkeypatch, peer
+ ):
+ """The remedy every note gives, for each kind of peer they name."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", True)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", (peer,))
+
+ key = rl._get_client_ip(
+ make_request(peer=peer, headers={"X-Real-IP": "198.51.100.7"})
+ )
+
+ assert key == "198.51.100.7"
+
+ def test_non_private_proxy_x_real_ip_is_ignored(self, rl, monkeypatch):
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", False)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ())
+
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer="35.191.10.5",
+ headers={"X-Real-IP": f"198.51.100.{i}"},
+ )
+ )
+ for i in range(5)
+ }
+
+ assert keys == {"35.191.10.5"}, (
+ "pre-release behaviour returned the X-Real-IP value here; if "
+ "this test starts failing the fallback was un-gated again"
+ )
+
+ def test_listing_the_proxy_restores_per_client_keys(self, rl, monkeypatch):
+ """The documented migration: put the proxy's address in
+ ``LDR_SERVER_FORWARDED_ALLOW_IPS`` and the same requests key by the
+ real client again."""
+ monkeypatch.setattr(rl, "_TRUST_PROXY_HEADERS", True)
+ monkeypatch.setattr(rl, "_ALLOW_LIST_IS_RESTRICTED", True)
+ monkeypatch.setattr(rl, "_FORWARDED_ALLOW_ENTRIES", ("35.191.10.5",))
+
+ keys = {
+ rl._get_client_ip(
+ make_request(
+ peer="35.191.10.5",
+ headers={"X-Real-IP": f"198.51.100.{i}"},
+ )
+ )
+ for i in range(5)
+ }
+
+ assert keys == {f"198.51.100.{i}" for i in range(5)}
+
+
+# What the startup warning and each operator-facing note must say about the
+# break pinned above, as fragments of its whitespace-normalised text. Both
+# halves are required: WHO is hit (a proxy on a public or carrier-grade-NAT
+# address that sends X-Real-IP without X-Forwarded-For) and the REMEDY (set
+# LDR_SERVER_FORWARDED_ALLOW_IPS to that proxy's address). A note that names
+# only one half sends the operator to the wrong fix.
+_X_REAL_IP_BREAK_WARNING = (
+ "X-Real-IP is now honoured only from a private, loopback or link-local "
+ "direct peer (before this release, from any peer)",
+ "reaches LDR from a public or carrier-grade-NAT address",
+ "and sends X-Real-IP without X-Forwarded-For, its X-Real-IP is now "
+ "IGNORED and every client behind it shares ONE rate-limit bucket",
+ "set LDR_SERVER_FORWARDED_ALLOW_IPS to that proxy's IP address as LDR "
+ "sees it",
+)
+
+_X_REAL_IP_BREAK_NOTES = {
+ "changelog.d/3299.breaking.md": (
+ "connects from a public or carrier-grade-NAT address and sends "
+ "`X-Real-IP` without `X-Forwarded-For`",
+ "set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that proxy's IP address",
+ ),
+ "changelog.d/4870.security.md": (
+ "on a public or carrier-grade-NAT address that sends `X-Real-IP` "
+ "and no `X-Forwarded-For` of its own",
+ "until you set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that proxy's IP "
+ "address as LDR sees it",
+ ),
+ "docs/deployment/upgrading.md": (
+ "connects to LDR from a public or carrier-grade-NAT address",
+ "set `LDR_SERVER_FORWARDED_ALLOW_IPS` to its IP address as LDR sees it",
+ "reads `X-Real-IP` only from a private, loopback or link-local peer",
+ "sends `X-Real-IP` without `X-Forwarded-For`",
+ ),
+ "docs/deployment/reverse-proxy.md": (
+ "a proxy on a public or carrier-grade-NAT address that sends "
+ "`X-Real-IP` without `X-Forwarded-For` is no longer trusted for it, "
+ "so list that proxy's IP address in `LDR_SERVER_FORWARDED_ALLOW_IPS`",
+ "and sends `X-Real-IP` without `X-Forwarded-For`, that header is now "
+ "ignored",
+ "`LDR_SERVER_FORWARDED_ALLOW_IPS=<your proxy's address(es)>` (its IP "
+ "address as LDR sees it) to restore per-client keying",
+ ),
+ "docs/MIGRATION_GUIDE_v1.md": (
+ "connects from a public or carrier-grade-NAT address and sends "
+ "`X-Real-IP` without `X-Forwarded-For`",
+ "Set `LDR_SERVER_FORWARDED_ALLOW_IPS` to that proxy's IP address as "
+ "LDR sees it",
+ ),
+ "README.md": (
+ "from a public or carrier-grade-NAT address",
+ "with `TRUST_PROXY_HEADERS=true` and no allow-list its `X-Real-IP` is "
+ "ignored, while its `X-Forwarded-For` still counts",
+ "Set `LDR_SERVER_FORWARDED_ALLOW_IPS` to the proxy's IP address(es)",
+ ),
+}
+
+
+def _prose(path):
+ """The text of ``path`` with blockquote markers and line breaks removed,
+ so a fragment can span a wrapped line or a ``>`` quote."""
+ text = path.read_text(encoding="utf-8")
+ text = re.sub(r"(?m)^[ \t]*(?:>[ \t]*)+", "", text)
+ return " ".join(text.split())
+
+
+class TestXRealIpBreakIsNamedWhereOperatorsLook:
+ """The break pinned above has to be stated, exactly, wherever an
+ operator upgrading a ``TRUST_PROXY_HEADERS=true`` deployment will read:
+ the startup warning, the changelog fragments, the upgrade guide and the
+ reverse-proxy, migration and README notes.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _isolated_reloadable_module(self, monkeypatch):
+ for name in _PROXY_TRUST_ENV_VARS:
+ monkeypatch.delenv(name, raising=False)
+ with _rate_limit_module_restored():
+ yield
+
+ def test_startup_warning_names_the_case_and_the_remedy(
+ self, monkeypatch, loguru_caplog
+ ):
+ """The legacy configuration (``TRUST_PROXY_HEADERS=true`` and
+ nothing else) is the one the break hits, and its warning is the one
+ line every such operator sees."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+
+ with loguru_caplog.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is True
+ assert mod._PROXY_TRUST_OPTED_IN is False
+ text = " ".join(loguru_caplog.text.split())
+ for fragment in _X_REAL_IP_BREAK_WARNING:
+ assert fragment in text, f"the startup warning lost {fragment!r}"
+
+ @pytest.mark.parametrize("note", sorted(_X_REAL_IP_BREAK_NOTES))
+ def test_note_names_the_case_and_the_remedy(self, note):
+ path = REPO_ROOT / note
+ if note.startswith("changelog.d/") and not path.exists():
+ pytest.skip("fragment consumed by towncrier at release prep")
+ text = _prose(path)
+ for fragment in _X_REAL_IP_BREAK_NOTES[note]:
+ assert fragment in text, f"{note} lost {fragment!r}"
+
+
+class TestUvicornParserFallback:
+ """What happens when uvicorn's private ``_TrustedHosts`` is not there.
+
+ ``rate_limit.py`` imports a leading-underscore class out of
+ ``uvicorn.middleware.proxy_headers``. ``pyproject.toml`` pins
+ ``uvicorn[standard]~=0.34``, which admits any 0.x, so a rename is a
+ routine upgrade away -- and a rename surfaces as AttributeError or
+ TypeError at construction, not as ImportError at import.
+
+ The fallback must not be "declare every allow-list unrestricted":
+ that is FAIL-OPEN in the two ``TRUST_PROXY_HEADERS=false`` modes
+ (``_ALLOW_LIST_IS_RESTRICTED`` silently goes False, so a private peer
+ outside the allow-list regains forwarding trust) and it makes the
+ PR's own recommended configuration refuse to boot. LDR classifies
+ the list with its own parser instead, failing closed.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _isolated_reloadable_module(self, monkeypatch):
+ for name in _PROXY_TRUST_ENV_VARS:
+ monkeypatch.delenv(name, raising=False)
+ with _rate_limit_module_restored():
+ yield
+
+ @pytest.fixture()
+ def _uvicorn_parser_missing(self, monkeypatch):
+ """Break the import the way a rename or a removal would.
+
+ ``None`` in ``sys.modules`` is the documented way to make a
+ ``from ... import`` raise; the entry is restored by monkeypatch.
+ """
+ monkeypatch.setitem(
+ sys.modules, "uvicorn.middleware.proxy_headers", None
+ )
+
+ def test_import_failure_is_not_only_importerror(self):
+ """The guard catches ``Exception``, not ``ImportError``.
+
+ An attribute rename raises AttributeError/TypeError, which an
+ ``except ImportError`` would let escape as a raw traceback at
+ import time.
+ """
+ import ast
+ import inspect
+
+ from local_deep_research.web.dependencies import rate_limit
+
+ source = inspect.getsource(rate_limit)
+ tree = ast.parse(source)
+ handlers = [
+ handler
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Try)
+ for handler in node.handlers
+ if any(
+ isinstance(sub, ast.ImportFrom)
+ and sub.module == "uvicorn.middleware.proxy_headers"
+ for sub in ast.walk(node)
+ )
+ ]
+ assert handlers, "the guarded uvicorn import is gone"
+ assert all(
+ isinstance(handler.type, ast.Name)
+ and handler.type.id == "Exception"
+ for handler in handlers
+ ), "the uvicorn import guard narrowed back to ImportError"
+
+ def test_construction_failure_falls_back_not_raises(
+ self, rl, monkeypatch, loguru_caplog
+ ):
+ """A renamed attribute must not escape ``_describe_...``."""
+
+ class _Renamed:
+ def __init__(self, allow_ips):
+ raise AttributeError("_TrustedHosts.always_trust")
+
+ monkeypatch.setattr(rl, "_UvicornTrustedHosts", _Renamed)
+
+ with loguru_caplog.at_level("WARNING"):
+ assert rl._describe_unrestricted_allow_list("10.0.0.5") is None
+ assert rl._describe_unrestricted_allow_list("*") is not None
+ assert rl._describe_unrestricted_allow_list("0.0.0.0/0") is not None
+
+ assert "_TrustedHosts" in loguru_caplog.text
+ assert "fails CLOSED" in loguru_caplog.text
+
+ def test_fallback_keeps_the_recommended_config_bootable(
+ self, monkeypatch, _uvicorn_parser_missing, loguru_caplog
+ ):
+ """TRUST_PROXY_HEADERS=true + an exact proxy IP still starts."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "10.0.0.5")
+
+ with loguru_caplog.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._UvicornTrustedHosts is None
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is False
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+ assert mod._FORWARDED_ALLOW_ENTRIES == ("10.0.0.5",)
+ assert "_TrustedHosts" in loguru_caplog.text
+ assert "fails CLOSED" in loguru_caplog.text
+
+ @pytest.mark.parametrize(
+ "env",
+ [
+ {},
+ {"LDR_SERVER_TRUSTED_PROXY_COUNT": "2"},
+ ],
+ ids=["default-heuristic-mode", "hop-count-mode"],
+ )
+ def test_fallback_keeps_restricted_mode_in_trust_false_modes(
+ self, monkeypatch, _uvicorn_parser_missing, env
+ ):
+ """The fail-open regression, pinned in both untrusting modes.
+
+ Declaring the list unrestricted here would put the module back on
+ ``_is_trusted_peer``, so a merely-private peer outside the
+ allow-list could rotate a spoofed ``X-Real-IP`` again.
+ """
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "10.0.0.5")
+
+ mod = _reload_rate_limit()
+
+ assert mod._TRUST_PROXY_HEADERS is False
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+ assert mod._peer_may_supply_forwarding_headers("10.0.0.23") is False
+ assert mod._peer_may_supply_forwarding_headers("10.0.0.5") is True
+
+ @pytest.mark.parametrize("allow_ips", UNRESTRICTED_SPELLINGS)
+ def test_fallback_still_hard_fails_the_opted_in_combination(
+ self, monkeypatch, _uvicorn_parser_missing, allow_ips
+ ):
+ """Every spelling the uvicorn-backed predicate refuses is still
+ refused by LDR's own parser."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ with pytest.raises(RuntimeError) as exc_info:
+ _reload_rate_limit()
+
+ assert "UNSAFE" in str(exc_info.value)
+
+ def test_fallback_agrees_with_uvicorn_about_a_stray_wildcard(
+ self, monkeypatch, _uvicorn_parser_missing
+ ):
+ """``"*,*"`` is two literals, to uvicorn AND to the fallback.
+
+ ``always_trust`` is the WHOLE (normalised) value being exactly
+ ``"*"`` in both parsers -- round-3 gate finding N4 caught the
+ fallback treating ANY entry spelled ``"*"`` as the wildcard,
+ which fails OPEN for a mix like ``"10.0.0.5,*"`` (uvicorn: two
+ literals, restricted; fallback: unrestricted). Both spellings
+ below are restricted under uvicorn's own parser and under the
+ fallback -- there is no divergence left to document.
+ """
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "*,*")
+
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is False
+
+ def test_fallback_agrees_with_uvicorn_about_a_partial_wildcard(
+ self, monkeypatch, _uvicorn_parser_missing
+ ):
+ """``"10.0.0.5,*"`` must stay restricted, not fail open.
+
+ Before the N4 fix, ``any(entry == "*")`` made the fallback treat
+ this as the unrestricted wildcard, silently discarding the
+ operator's real ``10.0.0.5`` restriction and letting a peer
+ outside it supply forwarding headers.
+ """
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "false")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "10.0.0.5,*")
+
+ mod = _reload_rate_limit()
+
+ assert mod._UvicornTrustedHosts is None
+ assert mod._ALLOW_LIST_IS_UNRESTRICTED is False
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+ assert mod._peer_may_supply_forwarding_headers("10.0.0.99") is False
+ assert mod._peer_may_supply_forwarding_headers("10.0.0.5") is True
+
+
+class TestImpreciseAllowListEntriesAreWarnedAbout:
+ """A restricted allow-list is not automatically a precise one.
+
+ Two shapes boot happily and are silently not what the operator
+ meant, so each gets its own startup WARNING (never a hard failure):
+ a network entry trusts every peer inside it, and an entry uvicorn
+ keeps as an opaque literal matches no peer at all.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _isolated_reloadable_module(self, monkeypatch):
+ for name in _PROXY_TRUST_ENV_VARS:
+ monkeypatch.delenv(name, raising=False)
+ with _rate_limit_module_restored():
+ yield
+
+ @pytest.mark.parametrize(
+ "allow_ips",
+ [
+ "10.0.0.0/8",
+ "10.1.0.0/23",
+ "2001:db8::/48",
+ # IPv4-mapped entries: an IPv6 network that is ITSELF a
+ # subnet of ::ffff:0.0.0.0/96 is a disguised IPv4 network,
+ # so it is held to the /24 IPv4 limit against its prefix
+ # length within the mapped /96, not the /64 IPv6 one
+ # (round-3 gate finding N5: these two used to be silent).
+ "::ffff:10.0.0.0/104", # == 10.0.0.0/8 (/8 < 24)
+ "::ffff:0.0.0.0/97", # == 0.0.0.0/1 (/1 < 24)
+ # Scoped mapped entry (round-4 gate finding R2): the zone id
+ # must not hide the mapped range from the containment check
+ # that picks the IPv4 limit over the raw IPv6 one.
+ "::ffff:0.0.0.0%eth0/104",
+ # NAT64 well-known prefix (RFC 6052): IPv4 peers arrive through
+ # a translator as 64:ff9b::<ipv4>, so the /96 trusts every
+ # IPv4 host on that path and is judged by the IPv4 limit too.
+ "64:ff9b::/96",
+ "64:ff9b::a00:0/104", # == 10.0.0.0/8 via NAT64
+ # Entries CONTAINING the NAT64 /96 trust every translated IPv4
+ # host -- as broad as 0.0.0.0/0 on that path -- but their raw
+ # prefix length is not below the /64 IPv6 limit, and a
+ # subnet-only check judged them as ordinary IPv6 and stayed
+ # silent.
+ "64:ff9b::/64",
+ "64:ff9b::/80",
+ "64:ff9b::/95",
+ "64:ff9b::%eth0/80",
+ # RFC 8215 local-use NAT64 prefix: an operator's translator
+ # prefix carved from it embeds IPv4 the same way.
+ "64:ff9b:1::/96",
+ "64:ff9b:1:abcd::/64",
+ "64:ff9b:1::a00:0/104", # == 10.0.0.0/8 via local-use NAT64
+ # Teredo (RFC 4380): the low 32 bits are each client's
+ # obfuscated IPv4, so a /64 is one relay server with every
+ # client behind it, not one host.
+ "2001:0:4136:e378::/64",
+ "2001:0:4136:e378:8000:63bf::/96",
+ ],
+ )
+ def test_broad_network_entry_warns(
+ self, monkeypatch, loguru_caplog, allow_ips
+ ):
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ with loguru_caplog.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+ assert "trusts every peer inside" in loguru_caplog.text
+ assert "name the proxy's exact addresses" in loguru_caplog.text
+
+ @pytest.mark.parametrize(
+ "allow_ips", ["nginx", "10.0.0.5/8", "*,*", "proxy.internal"]
+ )
+ def test_unmatchable_literal_entry_warns(
+ self, monkeypatch, loguru_caplog, allow_ips
+ ):
+ """``nginx`` is a hostname, ``10.0.0.5/8`` has host bits set, and
+ a second ``*`` is not uvicorn's wildcard. uvicorn compares each
+ verbatim against the peer string, which is always an IP for a TCP
+ connection, so none of them ever matches."""
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ with loguru_caplog.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+ assert "matches no peer" in loguru_caplog.text
+ assert "share one bucket" in loguru_caplog.text
+
+ @pytest.mark.parametrize(
+ "allow_ips",
+ [
+ "10.0.0.5",
+ "10.0.0.5,10.0.0.6",
+ "10.0.1.0/24",
+ "2001:db8::/64",
+ # Mapped equivalent of a /24 (120 - 96 == 24): the boundary
+ # case for the mapped-entry limit too.
+ "::ffff:10.0.1.0/120",
+ # Same boundary, scoped: the zone id must not push a legitimately
+ # tight mapped entry over the limit either.
+ "::ffff:10.0.1.0%eth0/120",
+ # NAT64 equivalent of a /24, and a single translated address.
+ "64:ff9b::a00:100/120",
+ "64:ff9b::a00:105",
+ # Same boundary under the local-use prefix.
+ "64:ff9b:1::a00:100/120",
+ "64:ff9b:1::a00:105",
+ # One Teredo client address, and the /24 boundary under Teredo.
+ "2001:0:4136:e378:8000:63bf:3fff:fdd2",
+ "2001:0:4136:e378:8000:63bf:3fff:fd00/120",
+ ],
+ )
+ def test_exact_addresses_and_tight_networks_do_not_warn(
+ self, monkeypatch, loguru_caplog, allow_ips
+ ):
+ """Negative control: the recommended shapes stay quiet, or the
+ warning is noise every correct deployment would learn to ignore.
+ /24 and /64 are the boundary -- broader warns, equal does not."""
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", allow_ips)
+
+ with loguru_caplog.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_RESTRICTED is True
+ assert "trusts every peer inside" not in loguru_caplog.text
+ assert "matches no peer" not in loguru_caplog.text
+
+ def test_no_warning_when_the_list_is_not_restricted(
+ self, monkeypatch, loguru_caplog
+ ):
+ """An unrestricted list already has its own, louder line; these
+ warnings are scoped to the entries the module will actually use
+ as its trust boundary."""
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "0.0.0.0/0")
+
+ with loguru_caplog.at_level("WARNING"):
+ mod = _reload_rate_limit()
+
+ assert mod._ALLOW_LIST_IS_RESTRICTED is False
+ assert "trusts every peer inside" not in loguru_caplog.text
+ assert "matches no peer" not in loguru_caplog.text
+
+ def test_the_restricted_startup_line_no_longer_claims_safety_flatly(
+ self, monkeypatch, loguru_caplog
+ ):
+ """The info line used to say "This is a safe combination" for any
+ restricted list, including a pod CIDR every co-tenant sits in."""
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ monkeypatch.setenv("LDR_SERVER_FORWARDED_ALLOW_IPS", "10.0.0.0/8")
+
+ with loguru_caplog.at_level("INFO"):
+ _reload_rate_limit()
+
+ assert "This is a safe combination" not in loguru_caplog.text
+ assert "one proxy's exact address" in loguru_caplog.text
diff --git a/tests/web/test_forwarded_proto_warning.py b/tests/web/test_forwarded_proto_warning.py
index e77eb35c32..f90d969176 100644
--- a/tests/web/test_forwarded_proto_warning.py
+++ b/tests/web/test_forwarded_proto_warning.py
@@ -14,6 +14,7 @@ HTTPS.
import pytest
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient
+from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
from local_deep_research.web.fastapi_app import SecureCookieMiddleware
@@ -51,6 +52,12 @@ def test_warns_when_forwarded_proto_https_is_not_honoured(loguru_caplog_full):
assert "TRUST_PROXY_HEADERS" in msgs[0], (
"the warning must name the env var that fixes it"
)
+ # With TRUST_PROXY_HEADERS already on, the same symptom means a
+ # restricted allow-list that misses this proxy; telling that operator
+ # only to set the flag they already set would leave them stuck.
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" in msgs[0], (
+ "the warning must also name the allow-list that can exclude the proxy"
+ )
def test_warns_at_most_once_per_process(loguru_caplog_full):
@@ -95,6 +102,26 @@ def test_public_request_cannot_suppress_later_private_proxy_warning(
assert len(_warnings(loguru_caplog_full)) == 1
+def test_noncanonical_public_header_cannot_suppress_private_proxy_warning(
+ loguru_caplog_full,
+):
+ """A spoofed malformed header must not consume the other warning type."""
+ middleware = SecureCookieMiddleware(_ok_app, testing=False)
+ public = TestClient(middleware, client=("8.8.8.8", 40000))
+ private = TestClient(middleware, client=("127.0.0.1", 40001))
+
+ with loguru_caplog_full.at_level("WARNING"):
+ public.get("/", headers={"X-Forwarded-Proto": "HTTPS"})
+ public.get("/", headers={"X-Forwarded-Proto": "HTTPS"})
+ private.get("/", headers={"X-Forwarded-Proto": "https"})
+ private.get("/", headers={"X-Forwarded-Proto": "https"})
+
+ messages = _warnings(loguru_caplog_full)
+ assert len(messages) == 2
+ assert "exactly 'https'" in messages[0]
+ assert "TRUST_PROXY_HEADERS" in messages[1]
+
+
def test_silent_when_no_forwarded_proto_header(loguru_caplog_full):
"""Negative control. Without it, a middleware that warned on EVERY plain
HTTP request would satisfy the first test for the wrong reason — and would
@@ -142,3 +169,217 @@ def test_silent_for_a_public_peer(loguru_caplog_full):
"a public peer was told to enable TRUST_PROXY_HEADERS; that advice is "
"attacker-plantable and would let them control the cookie Secure flag"
)
+
+
+ "peer",
+ [
+ "2002:808:808::1", # 6to4 wrapping 8.8.8.8
+ "2001:0:4136:e378:8000:63bf:3fff:fdd2", # Teredo
+ "64:ff9b:1::808:808", # RFC 8215 NAT64 local-use
+ ],
+)
+def test_tunnelled_remote_peer_cannot_plant_the_advice(
+ loguru_caplog_full, peer
+):
+ """CPython's ``ipaddress`` may report 6to4, Teredo and NAT64 local-use
+ addresses as private (which ones depends on the version), so these
+ remote clients could pass the private-peer gate. The warning stays armed until a real local proxy
+ request arrives (a health check must not consume it), so without the
+ classifier fix any such client could send the header and plant
+ "set TRUST_PROXY_HEADERS=true" in the operator's log at will."""
+ middleware = SecureCookieMiddleware(_ok_app, testing=False)
+ remote = TestClient(middleware, client=(peer, 40000))
+ local = TestClient(middleware, client=("127.0.0.1", 40001))
+
+ with loguru_caplog_full.at_level("WARNING"):
+ remote.get("/", headers={"X-Forwarded-Proto": "https"})
+ assert not _warnings(loguru_caplog_full)
+ # The remote attempt did not consume the warning either.
+ local.get("/", headers={"X-Forwarded-Proto": "https"})
+
+ messages = _warnings(loguru_caplog_full)
+ assert len(messages) == 1
+ assert "TRUST_PROXY_HEADERS" in messages[0]
+ assert peer not in messages[0]
+
+
+def test_tunnelled_remote_peer_gets_the_public_client_warning(
+ loguru_caplog_full,
+):
+ """The other consumer of the same classifier: a 6to4 client served over
+ plain HTTP is a public client and must trip that warning."""
+ client = TestClient(
+ SecureCookieMiddleware(_ok_app, testing=False),
+ client=("2002:808:808::1", 40000),
+ )
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get("/")
+
+ assert "Serving HTTP to a public client" in loguru_caplog_full.text
+
+
+# ---------------------------------------------------------------------------
+# Through uvicorn's real ProxyHeadersMiddleware.
+#
+# In production SecureCookieMiddleware never sees the raw socket peer when
+# TRUST_PROXY_HEADERS=true: uvicorn's ProxyHeadersMiddleware runs first and may
+# already have replaced scope["client"] with an X-Forwarded-For entry (under
+# "*", the client-forgeable left-most one, unvalidated), and it honours
+# X-Forwarded-Proto only for an exact lower-case value. The tests above use a
+# bare TestClient, so none of that happens there.
+# ---------------------------------------------------------------------------
+
+# Text an attacker could try to plant in the operator's log through the
+# client address uvicorn copies out of X-Forwarded-For.
+_PLANTED = "please set LDR_DISABLE_RATE_LIMITING=true"
+
+
+def _proxied_client(trusted_hosts, peer):
+ return TestClient(
+ ProxyHeadersMiddleware(
+ SecureCookieMiddleware(_ok_app, testing=False),
+ trusted_hosts=trusted_hosts,
+ ),
+ client=(peer, 40000),
+ )
+
+
[email protected]("forwarded_for", ["8.8.8.8/32", _PLANTED, "10.1.2.3"])
[email protected]("proto", ["https", "HTTPS", "https, https"])
+def test_attacker_forwarded_for_never_reaches_the_advice(
+ loguru_caplog_full, forwarded_for, proto
+):
+ """A public peer under the legacy "*" allow-list chooses scope["client"]
+ through X-Forwarded-For. Whatever it sends -- a CIDR, free text, a
+ private-looking address that passes the private-peer gate -- none of it
+ may appear in the warning, and the advice must never tell the operator
+ to allow-list an address taken from the request."""
+ client = _proxied_client("*", "8.8.8.8")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get(
+ "/",
+ headers={
+ "X-Forwarded-Proto": proto,
+ "X-Forwarded-For": forwarded_for,
+ },
+ )
+
+ assert forwarded_for not in loguru_caplog_full.text
+ for line in _warnings(loguru_caplog_full):
+ assert "8.8.8.8" not in line
+
+
+def test_unlisted_private_co_tenant_is_not_named(loguru_caplog_full):
+ """Restricted allow-list, request from an unlisted private peer. uvicorn
+ leaves it the raw socket peer, so the "proxy is not trusted" advice fires
+ -- but that peer is exactly who the restricted list excludes, so its
+ address must not be offered as the one to add."""
+ client = _proxied_client("10.0.0.5", "10.0.0.9")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get(
+ "/",
+ headers={
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-For": "10.0.0.9",
+ },
+ )
+
+ msgs = _warnings(loguru_caplog_full)
+ assert msgs, "an untrusted private proxy must still be diagnosed"
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" in msgs[0]
+ assert "10.0.0.9" not in loguru_caplog_full.text
+
+
[email protected]("proto", ["HTTPS", "https, https", "https,http"])
+def test_trusted_proxy_with_non_canonical_proto_gets_proxy_advice(
+ loguru_caplog_full, proto
+):
+ """The proxy IS listed, and uvicorn rewrote the client from
+ X-Forwarded-For, but it ignored the non-canonical proto value. Telling
+ the operator the proxy is untrusted (and naming the rewritten client as
+ the proxy) would be wrong and would widen trust to a client; the fix is
+ on the proxy's header."""
+ client = _proxied_client("10.0.0.5", "10.0.0.5")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get(
+ "/",
+ headers={
+ "X-Forwarded-Proto": proto,
+ "X-Forwarded-For": "192.168.1.50",
+ },
+ )
+
+ msgs = _warnings(loguru_caplog_full)
+ assert msgs, "the ignored X-Forwarded-Proto produced no warning"
+ assert "exactly 'https'" in msgs[0]
+ assert "LDR_SERVER_FORWARDED_ALLOW_IPS" not in msgs[0]
+ assert "TRUST_PROXY_HEADERS" not in msgs[0]
+ assert "192.168.1.50" not in loguru_caplog_full.text
+
+
+def test_non_canonical_proto_is_diagnosed_for_a_public_client(
+ loguru_caplog_full,
+):
+ """Under "*" uvicorn rewrites the client to the (public) end user, so a
+ peer-based gate would silence the most common real deployment. The
+ reconfigure-your-proxy advice widens no trust, so it is not gated."""
+ client = _proxied_client("*", "10.0.0.5")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get(
+ "/",
+ headers={
+ "X-Forwarded-Proto": "HTTPS",
+ "X-Forwarded-For": "8.8.4.4",
+ },
+ )
+
+ msgs = _warnings(loguru_caplog_full)
+ assert msgs and "exactly 'https'" in msgs[0]
+
+
+def test_trusted_proxy_with_canonical_proto_is_silent(loguru_caplog_full):
+ """Positive control: a correctly configured proxy is honoured by uvicorn,
+ the scheme is https, and nothing is logged."""
+ client = _proxied_client("10.0.0.5", "10.0.0.5")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get(
+ "/",
+ headers={
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-For": "192.168.1.50",
+ },
+ )
+
+ assert not _warnings(loguru_caplog_full)
+
+
+def test_the_last_forwarded_proto_line_decides_like_uvicorn(loguru_caplog_full):
+ """uvicorn reads the LAST X-Forwarded-Proto line. A trusted proxy whose
+ final line says "http" is honoured as plain HTTP; an earlier "https" line
+ must not trigger a misconfiguration warning."""
+ client = _proxied_client("10.0.0.5", "10.0.0.5")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get(
+ "/",
+ headers=[
+ ("X-Forwarded-Proto", "https"),
+ ("X-Forwarded-Proto", "http"),
+ ],
+ )
+
+ assert not _warnings(loguru_caplog_full)
+
+
+def test_public_warning_drops_an_ipv6_zone_id(loguru_caplog_full):
+ """ipaddress accepts an IPv6 zone id of arbitrary text, and under "*"
+ uvicorn copies such an X-Forwarded-For entry into scope["client"]
+ unchecked. The public-client warning logs the address alone."""
+ client = _proxied_client("*", "8.8.8.8")
+ with loguru_caplog_full.at_level("WARNING"):
+ client.get("/", headers={"X-Forwarded-For": f"2001:4860::1%{_PLANTED}"})
+
+ assert "Serving HTTP to a public client (2001:4860::1)" in (
+ loguru_caplog_full.text
+ )
+ assert _PLANTED not in loguru_caplog_full.text
diff --git a/tests/web/test_rate_limit_coverage.py b/tests/web/test_rate_limit_coverage.py
index 34c741d0f7..a93453da3e 100644
--- a/tests/web/test_rate_limit_coverage.py
+++ b/tests/web/test_rate_limit_coverage.py
@@ -115,6 +115,9 @@ class TestUserKey:
request = Mock()
request.scope = {}
request.client = Mock(host="203.0.113.7")
+ # A real Headers object, not a plain dict: _get_forwarded_for()
+ # calls .getlist() (Starlette's per-line header API), which a
+ # dict does not have.
request.headers = Headers({})
assert _user_key(request) == "203.0.113.7"
@@ -178,6 +181,9 @@ class TestRateLimitExceededHandler:
request = Mock()
request.url.path = "/auth/login"
request.client = Mock(host="203.0.113.7")
+ # A real Headers object, not a plain dict: _get_forwarded_for()
+ # calls .getlist() (Starlette's per-line header API), which a
+ # dict does not have.
request.headers = Headers({"User-Agent": "test-agent"})
with patch("local_deep_research.web.fastapi_app.logger") as mock_logger:
diff --git a/tests/web/test_startup_ordering_contracts.py b/tests/web/test_startup_ordering_contracts.py
index 8a7d5b4e4b..15e142ed22 100644
--- a/tests/web/test_startup_ordering_contracts.py
+++ b/tests/web/test_startup_ordering_contracts.py
@@ -365,7 +365,24 @@ _IMPORT_TIME_CONFIG = {
# The master on/off switch for brute-force protection.
"is_rate_limiting_enabled()",
"RATE_LIMIT_STORAGE_URI",
+ # Read at module scope, then resolved (with slowapi's ./.env
+ # fallback) by ``_resolve_legacy_storage_uri()`` -- also at import.
"RATELIMIT_STORAGE_URL",
+ # Which direct peers uvicorn's ProxyHeadersMiddleware trusts
+ # forwarded headers from when TRUST_PROXY_HEADERS=true; decides
+ # whether the startup guard raises or only warns, and gates
+ # whether _get_client_ip trusts request.client outright.
+ "LDR_SERVER_FORWARDED_ALLOW_IPS",
+ # How many trusted proxy hops append to X-Forwarded-For. Frozen
+ # for the same reason as the two above: it is the other half of
+ # the import-time startup guard's input, and _get_client_ip's
+ # hop-count branch reads the module global rather than the
+ # environment. The module reads it through ``os.environ.get`` as
+ # well as through the typed ``TRUSTED_PROXY_COUNT`` setting
+ # precisely so this scanner (which matches ``environ.get`` /
+ # ``getenv`` call sites, not a settings object's
+ # ``.get_value()``) can see it.
+ "LDR_SERVER_TRUSTED_PROXY_COUNT",
# Supplies DEFAULT_RATE_LIMIT and the per-route login/registration
# limits, which are then baked into the Limiter and into every
# @limiter.limit decorator at router-import time.
diff --git a/tests/web/test_uvicorn_integration.py b/tests/web/test_uvicorn_integration.py
index 25cd1c8743..f111315f37 100644
--- a/tests/web/test_uvicorn_integration.py
+++ b/tests/web/test_uvicorn_integration.py
@@ -149,8 +149,24 @@ def _run_server(workdir: Path, *, trust_proxy_headers: bool):
env.pop("PYTEST_CURRENT_TEST", None)
if trust_proxy_headers:
env["TRUST_PROXY_HEADERS"] = "true"
+ # As of the fix for the round-7 regression, the startup guard in
+ # web/dependencies/rate_limit.py only hard-fails
+ # TRUST_PROXY_HEADERS=true + a wildcard LDR_SERVER_FORWARDED_
+ # ALLOW_IPS when the operator has ALSO opted into
+ # LDR_SERVER_TRUSTED_PROXY_COUNT or set LDR_SERVER_FORWARDED_
+ # ALLOW_IPS explicitly -- neither of which this fixture does, so
+ # omitting the line below would no longer abort startup (it would
+ # log a warning and boot). It is kept anyway, restricted to
+ # 127.0.0.1, so uvicorn's ProxyHeadersMiddleware only trusts
+ # X-Forwarded-For from the test process's own direct peer --
+ # mirroring the single-hop reverse-proxy-on-loopback deployment
+ # this combination is meant for, and keeping these tests exercising
+ # the "safe, restricted" code path rather than the merely-warned
+ # legacy one.
+ env["LDR_SERVER_FORWARDED_ALLOW_IPS"] = "127.0.0.1"
else:
env.pop("TRUST_PROXY_HEADERS", None)
+ env.pop("LDR_SERVER_FORWARDED_ALLOW_IPS", None)
server = LiveServer(
base_url=f"http://127.0.0.1:{port}",