Files
rengine/api/app/core/client_ip.py
T
Yogesh OjhaandClaude Fable 5.1 0a69f3201c copy: state the fact, delete the explanation
Repo-wide sweep of every user-facing string: frontend components, routes,
config and stores; API details and route docs; shared definitions and
models; stage config help; report prose; MCP, toolbox, interest and
connector text; notification and worker messages.

Descriptions that explained, reassured, justified or restated their title
are deleted. Confirm dialogs name what is removed and stop. Failed actions
read "<Noun> not <verbed>", successes "<Noun> <verbed>". No reader address,
no product-as-subject, no em-dashes or parentheticals in prose.

Mirrors updated on both sides: EPSS band help, compare refusal reasons,
interest labels. Four tests asserting on old wording follow the new text.
The rules are condensed into CLAUDE.md under Writing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SK5o8xR96cbSnAfjYSTPSe
2026-09-12 11:35:07 +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:
"""Outermost untrusted hop of X-Forwarded-For, or the peer."""
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