"""Rate limiting (REVIEW SEC-004). A token bucket per key, held in memory. No Redis and no slowapi, for the same reason the job queue has no Redis (SPEC C8): this deployment is one uvicorn process serving a handful of cameras on a LAN, and slowapi's default storage is in-process anyway, so a dependency would buy convenience rather than capability. **That is an assumption with a name.** ``poorbird serve`` runs a single uvicorn process (cli.py passes no ``workers``). If the deployment ever gains workers, every worker gets its own buckets and the effective limit multiplies by the worker count. Move the state to PostgreSQL or Redis at that point -- do not just widen the numbers. Buckets allow a burst and then refill steadily, which is the right shape here: a camera uploads three to five frames back to back when the radar fires, then goes quiet. A fixed window would reject the tail of a legitimate burst that happened to straddle a boundary. The limits are deliberately loose. A throttled camera stops delivering photographs, which on a private LAN is a worse outcome than the flooding the limit is meant to prevent. These are here to stop something pathological -- a wedged device in a retry loop, or someone grinding at the enrollment secret -- not to police normal use. """ from __future__ import annotations import threading import time from collections import OrderedDict from dataclasses import dataclass from fastapi import HTTPException, Request, status from ..config import Settings from .deps import DeviceDep, SettingsDep # Enough for a LAN's worth of cameras and then some. Bounded because the # enrollment limiter keys on client address, and an unbounded dictionary # keyed by something a caller influences is itself a way to exhaust memory. MAX_TRACKED_KEYS = 4096 @dataclass(frozen=True) class Limit: """``capacity`` requests available at once, refilled at ``per_second``.""" capacity: int per_second: float @classmethod def per_minute(cls, rate: int, *, burst: int | None = None) -> Limit: return cls(capacity=burst or rate, per_second=rate / 60.0) @classmethod def per_hour(cls, rate: int, *, burst: int | None = None) -> Limit: return cls(capacity=burst or rate, per_second=rate / 3600.0) class TokenBuckets: """Thread-safe token buckets with an LRU bound. Handlers are sync ``def``, so FastAPI runs them in a threadpool and two requests really can land here at once. """ def __init__(self, max_keys: int = MAX_TRACKED_KEYS) -> None: self._lock = threading.Lock() self._state: OrderedDict[str, tuple[float, float]] = OrderedDict() self._max_keys = max_keys def take(self, key: str, limit: Limit, *, now: float | None = None) -> float | None: """Spend one token. Returns None if allowed, else seconds to wait.""" now = time.monotonic() if now is None else now with self._lock: tokens, last = self._state.get(key, (float(limit.capacity), now)) tokens = min(limit.capacity, tokens + (now - last) * limit.per_second) if tokens >= 1.0: self._state[key] = (tokens - 1.0, now) allowed: float | None = None else: self._state[key] = (tokens, now) allowed = (1.0 - tokens) / limit.per_second self._state.move_to_end(key) while len(self._state) > self._max_keys: self._state.popitem(last=False) return allowed def reset(self) -> None: with self._lock: self._state.clear() BUCKETS = TokenBuckets() def client_address(request: Request) -> str: """The camera's address, not Caddy's. Caddy sets X-Real-IP (deploy/Caddyfile, both blocks). Without it every camera would share one bucket, since they all arrive from 127.0.0.1 via the proxy. Trusting the header is safe only because uvicorn binds loopback and nothing but Caddy can reach it. """ forwarded = request.headers.get("x-real-ip") if forwarded: return forwarded.strip() chain = request.headers.get("x-forwarded-for") if chain: return chain.split(",")[0].strip() return request.client.host if request.client else "unknown" def _enforce(key: str, limit: Limit, settings: Settings) -> None: if not settings.rate_limit_enabled: return retry_after = BUCKETS.take(key, limit) if retry_after is None: return # 429 and not 401: the firmware clears its token on a 401, and being busy # is not a credential problem. Retry-After gives it something better than # a guess to back off by. raise HTTPException( status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="too many requests", headers={"Retry-After": str(max(1, int(retry_after + 0.5)))}, ) def by_address(name: str, limit: Limit): """Limit by caller address. For endpoints with no device yet.""" def dependency(request: Request, settings: SettingsDep) -> None: _enforce(f"{name}:{client_address(request)}", limit, settings) return dependency def by_device(name: str, limit: Limit): """Limit per device. Keyed on the authenticated device rather than the address so that one misbehaving camera cannot spend another's allowance. Depends on DeviceDep, which FastAPI resolves once per request, so this adds no second token lookup. """ def dependency(device: DeviceDep, settings: SettingsDep) -> None: _enforce(f"{name}:{device.id}", limit, settings) return dependency # --- the limits ------------------------------------------------------------- # # Each is set well above what the firmware does when healthy, with the # relevant firmware behaviour noted so the number can be re-derived rather # than guessed at next time. # The device tries its stored secret and then the compiled-in bootstrap one, # so a single enrollment attempt is up to two requests. Enrollment is rare -- # first boot, and a token rotation - so this is the one place worth being # strict: it is where a shared secret could be ground at. ENROLL = Limit.per_hour(20, burst=6) # 5000 captures/day is ~3.5/min, arriving in bursts of three to five frames # when the radar fires. 120/min with a burst of 40 leaves enormous headroom. INGEST = Limit.per_minute(120, burst=40) # heartbeat_interval_s defaults to 300 and the firmware clamps it to 30, so # the fastest legitimate cadence is 2/min. Ten times that. CONDITIONS = Limit.per_minute(20, burst=10) # Pulled only when config_version changes, which is operator-driven. CONFIG = Limit.per_minute(10, burst=5) # Acks follow commands, which an operator queues by hand. ACK = Limit.per_minute(30, burst=15) # Whole firmware images. Expensive to serve, and a device needs one rarely; # a loop here would be a device failing verification over and over. FIRMWARE = Limit.per_hour(12, burst=3)