fix: resolve real visitor IP via CF-Connecting-IP for per-IP limiting
websocket.client.host is always the Cloudflare Tunnel machine's LAN IP for every internet-facing connection (the tunnel runs on a separate machine and terminates TLS there), which collapsed per-IP rate limiting into a single shared bucket for all remote visitors — the exact gap flagged in review. Cloudflare's edge sets CF-Connecting-IP itself, overwriting any client-supplied value, so it's safe to trust when present. Falls back to the raw socket peer for direct LAN/local access.
This commit is contained in:
@@ -1,5 +1,24 @@
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from typing import Mapping
|
||||
|
||||
|
||||
def resolve_client_ip(headers: Mapping[str, str], direct_host: str | None) -> str:
|
||||
"""Resolves the real visitor IP for per-IP rate limiting.
|
||||
|
||||
The App CT sits behind a Cloudflare Tunnel that runs on a separate
|
||||
machine (see README Architecture) — every internet-facing connection's
|
||||
raw TCP peer is that tunnel machine, not the visitor, which would
|
||||
collapse per-IP limiting to a single shared bucket for all remote
|
||||
traffic. Cloudflare's edge sets `CF-Connecting-IP` itself, stripping any
|
||||
client-supplied value first, so it's safe to trust here. Direct
|
||||
LAN/local access (no Cloudflare in front, e.g. local dev) has no such
|
||||
header and falls back to the raw socket peer.
|
||||
"""
|
||||
forwarded = headers.get("cf-connecting-ip")
|
||||
if forwarded:
|
||||
return forwarded
|
||||
return direct_host or "unknown"
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
|
||||
@@ -36,7 +36,7 @@ from app.models.contact_session import ContactSession
|
||||
from app.models.entity import Entity
|
||||
from app.models.entity_sighting import EntitySighting
|
||||
from app.models.event import Event
|
||||
from app.rate_limit import RateLimiter
|
||||
from app.rate_limit import RateLimiter, resolve_client_ip
|
||||
from app.telemetry import detect_wire_spike, sample_network
|
||||
from app.tts.piper import synthesize_spirit_voice
|
||||
from app.tts.voices import pick_voice
|
||||
@@ -103,7 +103,8 @@ def serialize_entity(entity: Entity) -> dict:
|
||||
|
||||
|
||||
def _client_ip(websocket: WebSocket) -> str:
|
||||
return websocket.client.host if websocket.client else "unknown"
|
||||
host = websocket.client.host if websocket.client else None
|
||||
return resolve_client_ip(websocket.headers, host)
|
||||
|
||||
|
||||
async def _authenticate(websocket: WebSocket) -> uuid.UUID | None:
|
||||
|
||||
Reference in New Issue
Block a user