Files
rengine/api/app/core/client_ip.py
T
Yogesh OjhaandClaude Opus 5 5784a75ff7 fix(api): the global rate limit could be lifted with one forged header
GlobalRateLimitMiddleware keyed its per-client bucket on the first
entry of X-Forwarded-For whenever the header was present. Nothing in
the shipped stack writes that header — the Vite proxy does not set
xfwd — so in practice the value was always supplied by the caller, and
rotating it per request gave every request a fresh bucket. Measured:
40 requests with a rotating header all returned 200 while 20 from the
same client without one were refused.

Reading the leftmost entry is also wrong behind a real reverse proxy,
which appends the peer address rather than replacing the header, so a
caller who prepends a value of their own is keyed on that value even in
a correct deployment.

client_id() now walks the chain right to left and returns the first hop
that is not itself a trusted proxy, and only consults the header at all
when the immediate peer is trusted. TRUSTED_PROXIES (empty by default)
names those hops as IPs or CIDRs; with no value set the peer address is
the only identity considered. The 429 now carries Retry-After.

Login is keyed by username and was never affected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K6LcH8uUddjJbKrahf34ys
2026-09-07 06:47:41 +05:30

46 lines
1.2 KiB
Python

import ipaddress
from functools import lru_cache
from starlette.requests import Request
from app.config import settings
UNKNOWN = "unknown"
@lru_cache(maxsize=1)
def _trusted() -> tuple[ipaddress.IPv4Network | ipaddress.IPv6Network, ...]:
nets = []
for raw in settings.TRUSTED_PROXIES.split(","):
entry = raw.strip()
if not entry:
continue
try:
nets.append(ipaddress.ip_network(entry, strict=False))
except ValueError:
continue
return tuple(nets)
def _is_trusted(host: str) -> bool:
nets = _trusted()
if not nets:
return False
try:
addr = ipaddress.ip_address(host)
except ValueError:
return False
return any(addr in net for net in nets)
def client_id(request: Request) -> str:
"""The furthest-out address we are willing to believe, walking X-Forwarded-For right to left."""
peer = request.client.host if request.client else UNKNOWN
if not _is_trusted(peer):
return peer
hops = [h.strip() for h in request.headers.get("x-forwarded-for", "").split(",")]
for hop in reversed([h for h in hops if h]):
if not _is_trusted(hop):
return hop
return peer