Module

_proxy

Proxy header validation — extract real client info from trusted reverse proxies.

Whentrusted_hostsis configured, X-Forwarded-For/Proto/Host headers are honoured only if the direct peer IP is in the trusted set. When no trusted hosts are configured, forwarded headers are stripped to prevent spoofing.

RFC 7239 defines a formalForwarded header, but the X-Forwarded-* family remains the de-facto standard used by nginx, Caddy, AWS ALB, Cloudflare, and virtually every reverse proxy in production.

Functions

apply_proxy_headers 2 dict[str, Any]
Rewrite ASGI scope fields using proxy headers from a trusted peer. **When the …
def apply_proxy_headers(scope: dict[str, Any], *, trusted_hosts: tuple[str, ...]) -> dict[str, Any]

Rewrite ASGI scope fields using proxy headers from a trusted peer.

When the direct peer is trusted:

  • client is overwritten with the leftmost IP from X-Forwarded-For
  • scheme is overwritten from X-Forwarded-Proto
  • server host is overwritten from X-Forwarded-Host(port preserved)

When the direct peer is not trusted (ortrusted_hostsis empty), allX-Forwarded-*headers are stripped from the scope to prevent downstream apps from trusting spoofed values.

Parameters
Name Type Description
scope dict[str, Any]

Mutable ASGI scope dict (modified in place and returned).

trusted_hosts tuple[str, ...]

Tuple of trusted peer IPs/hostnames. The wildcard"*"trusts all peers (use only behind a known proxy layer).

Returns
dict[str, Any]
_strip_forwarded_headers 1 None
Remove all X-Forwarded-* headers from an ASGI scope. Prevents untrusted client…
def _strip_forwarded_headers(scope: dict[str, Any]) -> None

Remove all X-Forwarded-* headers from an ASGI scope.

Prevents untrusted clients from injecting proxy headers that downstream ASGI apps might naively trust.

Parameters
Name Type Description
scope dict[str, Any]