Add rate limiting to the device endpoints (REVIEW SEC-004)
In-process token buckets, no Redis and no slowapi - for the same reason the job queue has no Redis (SPEC C8). This 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 assumption is named in the module: poorbird serve runs a single process, and if the deployment ever gains workers each gets its own buckets and the effective limit multiplies. Move the state to PostgreSQL at that point rather than widening the numbers. Buckets rather than fixed windows, because a camera uploads three to five frames back to back when the radar fires and then goes quiet. A window would reject the tail of a legitimate burst that straddled a boundary. Authenticated endpoints key on the device, so one wedged camera cannot spend another's allowance. /enroll keys on the caller address, since there is no device yet and it is the one place a shared secret could be ground at. This required a Caddyfile change, not a cosmetic one: the :8080 camera block proxied without X-Real-IP, so every camera reached the app as 127.0.0.1 and they would all have shared one enrollment bucket - one noisy device locking the rest out. The header is trusted only because uvicorn binds loopback. Limits are deliberately loose, each derived from what the firmware actually does and noted in the code so the number can be re-derived rather than guessed at. A throttled camera stops delivering photographs, which on a private LAN is worse than the flooding the limit prevents. Throttling answers 429, never 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. The key table is LRU-bounded. It is keyed partly on caller address, and an unbounded map keyed by something a caller influences is itself a way to exhaust memory. Off by default in tests, which fire far more requests than any camera would. tests/test_ratelimit.py turns it back on and proves the buckets are wired to the routes. Also fixes the same teardown-in-test-body flaw in the new file, found by re-running a deliberate mutation and noticing a leaked device row. Teardown is in fixtures; the mutation now fails its one test and leaves nothing behind. Tests: 158 -> 175. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
269a6eadcb
commit
e326dd8226
12 files changed
+505
-6
No files matched your search
@@ -0,0 +1,191 @@
|
||||
"""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)
|
||||
@@ -14,10 +14,11 @@ from __future__ import annotations
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Response, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...models.devices import DeviceCommand
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep
|
||||
from ..schemas import CommandAck
|
||||
|
||||
@@ -32,6 +33,7 @@ router = APIRouter()
|
||||
response_class=Response,
|
||||
summary="Report the outcome of a command",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("ack", ratelimit.ACK))],
|
||||
)
|
||||
def ack_command(
|
||||
command_id: int,
|
||||
|
||||
@@ -23,9 +23,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from fastapi import APIRouter, Response, status
|
||||
from fastapi import APIRouter, Depends, Response, status
|
||||
|
||||
from ...models.devices import DeviceStatus
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep
|
||||
from ..envelope import build_envelope
|
||||
from ..schemas import DeviceConditions, Envelope
|
||||
@@ -116,6 +117,7 @@ def _record(db: DbDep, device, body: DeviceConditions) -> None:
|
||||
response_model_exclude_none=True,
|
||||
summary="Device conditions; returns the command envelope",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("heartbeat", ratelimit.CONDITIONS))],
|
||||
)
|
||||
def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope:
|
||||
_record(db, device, body)
|
||||
@@ -130,6 +132,7 @@ def heartbeat(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Envelope:
|
||||
response_class=Response,
|
||||
summary="Device conditions; returns nothing actionable",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("status", ratelimit.CONDITIONS))],
|
||||
)
|
||||
def device_status(body: DeviceConditions, db: DbDep, device: DeviceDep) -> Response:
|
||||
_record(db, device, body)
|
||||
|
||||
@@ -24,8 +24,9 @@ from __future__ import annotations
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from .. import ratelimit
|
||||
from ..deps import DeviceDep
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -52,6 +53,7 @@ _COLUMN_BACKED = (
|
||||
"/config",
|
||||
summary="The device's full settings document",
|
||||
tags=["devices"],
|
||||
dependencies=[Depends(ratelimit.by_device("config", ratelimit.CONFIG))],
|
||||
)
|
||||
def get_config(device: DeviceDep) -> dict[str, Any]:
|
||||
# Start from the stored document, then let the column-backed keys win.
|
||||
|
||||
@@ -16,11 +16,12 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from ...models.devices import Device
|
||||
from .. import ratelimit
|
||||
from ..deps import (
|
||||
DbDep,
|
||||
SettingsDep,
|
||||
@@ -43,6 +44,9 @@ router = APIRouter()
|
||||
response_model=EnrollResponse,
|
||||
summary="Enroll a device, or re-issue its token",
|
||||
tags=["devices"],
|
||||
# Keyed by caller address: there is no device to key on yet, and this is
|
||||
# the one endpoint where a shared secret could be ground at (SEC-004).
|
||||
dependencies=[Depends(ratelimit.by_address("enroll", ratelimit.ENROLL))],
|
||||
)
|
||||
def enroll(
|
||||
body: EnrollRequest,
|
||||
|
||||
@@ -23,12 +23,13 @@ from __future__ import annotations
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...config import Settings
|
||||
from ...models.devices import Firmware
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep, SettingsDep
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -54,6 +55,7 @@ def _resolve(file_path: str, settings: Settings) -> Path:
|
||||
response_class=FileResponse,
|
||||
summary="Download an OTA image",
|
||||
tags=["firmware"],
|
||||
dependencies=[Depends(ratelimit.by_device("firmware", ratelimit.FIRMWARE))],
|
||||
)
|
||||
def download_firmware(
|
||||
version: str,
|
||||
|
||||
@@ -26,6 +26,7 @@ from pydantic import ValidationError
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...models.captures import Capture
|
||||
from .. import ratelimit
|
||||
from ..deps import DbDep, DeviceDep, SettingsDep
|
||||
from ..envelope import build_envelope
|
||||
from ..images import (
|
||||
@@ -91,6 +92,7 @@ def ingest_meta(
|
||||
response_model_exclude_none=True,
|
||||
summary="Accept a captured frame; returns the command envelope",
|
||||
tags=["captures"],
|
||||
dependencies=[Depends(ratelimit.by_device("ingest", ratelimit.INGEST))],
|
||||
)
|
||||
def ingest(
|
||||
db: DbDep,
|
||||
|
||||
@@ -65,6 +65,12 @@ class Settings(BaseSettings):
|
||||
# refuse to serve without it.
|
||||
enroll_secret: SecretStr = SecretStr("")
|
||||
|
||||
# --- rate limiting ----------------------------------------------------
|
||||
# In-process token buckets (api/ratelimit.py), sized for one uvicorn
|
||||
# process. Off by default in tests, which would otherwise exhaust a
|
||||
# bucket and start asserting against 429s.
|
||||
rate_limit_enabled: bool = True
|
||||
|
||||
# --- worker -----------------------------------------------------------
|
||||
worker_poll_interval_s: float = 2.0
|
||||
worker_batch_size: int = 1
|
||||
|
||||
Reference in new issue
Block a user