- Add Go, npm, Python, and Java validation to CI - Run Go tests against PostgreSQL - Record performance fixes in the report
77 lines
3.0 KiB
Python
77 lines
3.0 KiB
Python
"""Trusted-proxy-aware client address, the Python counterpart of backend/auth/clientip.go.
|
|
|
|
The address used for attempt limits and forwarded to AuthGuard is the TCP peer. X-Forwarded-For is
|
|
read only when that peer is inside a configured trusted-proxy list (the TRUSTED_PROXIES setting),
|
|
and is then walked from the right to the first hop that is not itself a trusted proxy. The list is
|
|
empty by default, so a client can never choose its own address.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import os
|
|
from collections.abc import Iterable, Mapping, Sequence
|
|
|
|
__all__ = ["client_address", "parse_trusted_proxies", "trusted_proxies_from_env"]
|
|
|
|
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
|
|
IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
|
|
|
|
|
|
def parse_trusted_proxies(value: str | None) -> list[IPNetwork]:
|
|
"""Parses a comma-separated list of CIDR ranges or bare IP addresses. An empty value trusts no
|
|
proxy. Raises ValueError for an entry that is neither."""
|
|
networks: list[IPNetwork] = []
|
|
for entry in (value or "").split(","):
|
|
entry = entry.strip()
|
|
if not entry:
|
|
continue
|
|
try:
|
|
networks.append(ipaddress.ip_network(entry, strict=False))
|
|
except ValueError as exc:
|
|
raise ValueError(
|
|
f"trusted proxy {entry!r} is neither an IP address nor a CIDR range"
|
|
) from exc
|
|
return networks
|
|
|
|
|
|
def trusted_proxies_from_env(env: Mapping[str, str] | None = None) -> list[IPNetwork]:
|
|
"""Reads the TRUSTED_PROXIES setting."""
|
|
source = os.environ if env is None else env
|
|
return parse_trusted_proxies(source.get("TRUSTED_PROXIES", ""))
|
|
|
|
|
|
def _parse_ip(value: str) -> IPAddress | None:
|
|
try:
|
|
ip = ipaddress.ip_address(value)
|
|
except ValueError:
|
|
return None
|
|
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
|
|
return ip.ipv4_mapped
|
|
return ip
|
|
|
|
|
|
def _is_trusted(ip: IPAddress, trusted: Sequence[IPNetwork]) -> bool:
|
|
return any(ip.version == network.version and ip in network for network in trusted)
|
|
|
|
|
|
def client_address(peer: str, forwarded_for: Iterable[str], trusted: Sequence[IPNetwork]) -> str:
|
|
"""Returns the address a request is counted against. peer is the TCP peer's host and
|
|
forwarded_for the values of every X-Forwarded-For header line. A malformed entry makes the peer
|
|
the answer, so a bad header can never choose the key."""
|
|
peer_ip = _parse_ip(peer)
|
|
if peer_ip is None or not _is_trusted(peer_ip, trusted):
|
|
return peer
|
|
hops = [part.strip() for line in forwarded_for for part in line.split(",") if part.strip()]
|
|
if not hops:
|
|
return peer
|
|
for hop in reversed(hops):
|
|
ip = _parse_ip(hop)
|
|
if ip is None:
|
|
return peer
|
|
if not _is_trusted(ip, trusted):
|
|
return str(ip)
|
|
# Every hop is a trusted proxy, so the left-most one is closest to the client.
|
|
first = _parse_ip(hops[0])
|
|
return str(first) if first is not None else peer
|