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:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 13:29:53 +02:00
1 parent 269a6eadcb
commit e326dd8226
12 files changed
+505 -6

No files matched your search

+8 -1
View File
@@ -60,7 +60,14 @@ poorbird.example.internal {
# ~1-2 MB. The default limit is too small for both.
max_size 12MB
}
reverse_proxy 127.0.0.1:8090
reverse_proxy 127.0.0.1:8090 {
# Required, not cosmetic. Rate limiting keys enrollment on the
# caller's address, and without this every camera arrives as
# 127.0.0.1 and they all share one bucket - one noisy device
# would lock the rest out. The app trusts this header only
# because uvicorn binds loopback and nothing else can reach it.
header_up X-Real-IP {remote_host}
}
}
handle /healthz {
+6
View File
@@ -37,6 +37,12 @@ POORBIRD_STATE_DIR=/var/lib/poorbird
# Rotating it here WITHOUT shipping new firmware removes that escape hatch.
POORBIRD_ENROLL_SECRET=
# --- rate limiting ------------------------------------------------------------
# In-process token buckets. Sized for ONE uvicorn process: if you ever run the
# API with workers, each gets its own buckets and the effective limit
# multiplies. Set false only for local development.
POORBIRD_RATE_LIMIT_ENABLED=true
# --- worker -----------------------------------------------------------------
POORBIRD_WORKER_POLL_INTERVAL_S=2
POORBIRD_JOB_MAX_ATTEMPTS=3
+191
View File
@@ -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)
+3 -1
View File
@@ -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,
+4 -1
View File
@@ -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.
+5 -1
View File
@@ -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,
+3 -1
View File
@@ -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,
+2
View File
@@ -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,
+6
View File
@@ -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
+4
View File
@@ -9,6 +9,10 @@ os.environ.setdefault("POORBIRD_LOG_LEVEL", "WARNING")
os.environ.setdefault("POORBIRD_IMAGE_ROOT", "/tmp/poorbird-test/images")
os.environ.setdefault("POORBIRD_THUMB_ROOT", "/tmp/poorbird-test/thumbs")
os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state")
# Off by default: the suite fires far more requests at an endpoint than any
# camera would, and would otherwise spend its own budget and start asserting
# against 429s. tests/test_ratelimit.py turns it back on deliberately.
os.environ.setdefault("POORBIRD_RATE_LIMIT_ENABLED", "false")
def database_is_reachable() -> bool:
+270
View File
@@ -0,0 +1,270 @@
"""Rate limiting (REVIEW SEC-004).
The rest of the suite runs with limiting off, so this is the one place that
turns it on and proves the buckets are actually wired to the routes.
"""
from __future__ import annotations
import secrets
import pytest
from conftest import needs_db
from poorbird.api import ratelimit
from poorbird.api.deps import hash_credential, new_credential
from poorbird.api.ratelimit import BUCKETS, Limit, TokenBuckets
from poorbird.config import Settings, get_settings
from poorbird.models.devices import Device, DeviceStatus
# --- the bucket itself ------------------------------------------------------
def test_a_bucket_allows_its_burst_then_refuses():
b = TokenBuckets()
limit = Limit(capacity=3, per_second=1.0)
assert [b.take("k", limit, now=0.0) for _ in range(3)] == [None, None, None]
assert b.take("k", limit, now=0.0) is not None
def test_it_says_how_long_to_wait():
b = TokenBuckets()
limit = Limit(capacity=1, per_second=0.5) # one every two seconds
assert b.take("k", limit, now=0.0) is None
retry = b.take("k", limit, now=0.0)
assert retry == pytest.approx(2.0)
def test_tokens_come_back_over_time():
b = TokenBuckets()
limit = Limit(capacity=2, per_second=1.0)
b.take("k", limit, now=0.0)
b.take("k", limit, now=0.0)
assert b.take("k", limit, now=0.0) is not None
assert b.take("k", limit, now=1.0) is None # one second, one token
def test_a_bucket_never_fills_past_its_capacity():
"""An idle week must not buy a week's worth of burst."""
b = TokenBuckets()
limit = Limit(capacity=2, per_second=1.0)
b.take("k", limit, now=0.0)
for _ in range(2):
assert b.take("k", limit, now=100_000.0) is None
assert b.take("k", limit, now=100_000.0) is not None
def test_keys_do_not_share_an_allowance():
b = TokenBuckets()
limit = Limit(capacity=1, per_second=1.0)
assert b.take("a", limit, now=0.0) is None
assert b.take("b", limit, now=0.0) is None
assert b.take("a", limit, now=0.0) is not None
def test_the_key_table_is_bounded():
"""It is keyed partly on caller address; unbounded growth would itself be
a way to exhaust memory."""
b = TokenBuckets(max_keys=10)
limit = Limit(capacity=1, per_second=1.0)
for i in range(100):
b.take(f"key-{i}", limit, now=0.0)
assert len(b._state) == 10
def test_the_documented_limits_are_the_shape_they_claim():
assert ratelimit.ENROLL.capacity == 6
assert ratelimit.INGEST.per_second == pytest.approx(2.0) # 120/min
# Ingest must comfortably clear a radar burst of three to five frames.
assert ratelimit.INGEST.capacity >= 10
# --- the client address -----------------------------------------------------
class _Req:
def __init__(self, headers=None, host="127.0.0.1"):
self.headers = headers or {}
self.client = type("C", (), {"host": host})()
def test_the_proxy_header_wins_over_the_socket():
"""Every camera reaches the app from 127.0.0.1 via Caddy. Without this
they would all share one bucket."""
assert ratelimit.client_address(_Req({"x-real-ip": "192.168.1.88"})) == "192.168.1.88"
def test_forwarded_for_is_read_as_a_fallback():
req = _Req({"x-forwarded-for": "192.168.1.88, 10.0.0.1"})
assert ratelimit.client_address(req) == "192.168.1.88"
def test_the_socket_address_is_the_last_resort():
assert ratelimit.client_address(_Req(host="10.1.2.3")) == "10.1.2.3"
# --- wired to the routes ----------------------------------------------------
@pytest.fixture
def db():
from poorbird.db import SessionLocal
with SessionLocal() as session:
yield session
@pytest.fixture
def limited(client, db):
"""Turn limiting on for one test, and leave no buckets behind."""
BUCKETS.reset()
client.app.dependency_overrides[get_settings] = lambda: Settings(
_env_file=None,
enroll_secret="test-secret",
rate_limit_enabled=True,
)
yield
client.app.dependency_overrides.clear()
BUCKETS.reset()
@pytest.fixture
def make_device(db):
"""Devices that are removed even when the test fails.
Teardown belongs in a fixture: a failing assertion skips the rest of the
test body, and cleanup written down there silently never runs.
"""
created: list[Device] = []
def make(name: str = "cam"):
token = new_credential()
d = Device(
device_uid=secrets.token_hex(6),
name=name,
token_hash=hash_credential(token),
enabled=True,
)
db.add(d)
db.commit()
db.refresh(d)
created.append(d)
return d, {"Authorization": f"Bearer {token}"}
yield make
for d in created:
db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id))
existing = db.get(Device, d.id)
if existing is not None:
db.delete(existing)
db.commit()
@pytest.fixture
def device(make_device):
return make_device()
@needs_db
def test_enrollment_is_limited_by_address(client, limited):
"""The one endpoint where a shared secret could be ground at."""
codes = [
client.post(
"/api/v1/enroll",
json={"device_uid": secrets.token_hex(6), "device_name": "cam"},
headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.90"},
).status_code
for _ in range(ratelimit.ENROLL.capacity + 2)
]
assert 429 in codes, "grinding at the enroll secret must eventually be refused"
assert codes.count(401) == ratelimit.ENROLL.capacity
@needs_db
def test_a_429_carries_retry_after(client, limited):
for _ in range(ratelimit.ENROLL.capacity + 1):
r = client.post(
"/api/v1/enroll",
json={"device_uid": secrets.token_hex(6), "device_name": "cam"},
headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.91"},
)
assert r.status_code == 429
assert int(r.headers["Retry-After"]) >= 1
@needs_db
def test_one_address_cannot_spend_anothers_budget(client, limited):
for _ in range(ratelimit.ENROLL.capacity + 1):
client.post(
"/api/v1/enroll",
json={"device_uid": secrets.token_hex(6), "device_name": "cam"},
headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.92"},
)
other = client.post(
"/api/v1/enroll",
json={"device_uid": secrets.token_hex(6), "device_name": "cam"},
headers={"X-Enroll-Secret": "wrong", "X-Real-IP": "192.168.1.93"},
)
assert other.status_code == 401, "a second camera must not inherit the first's throttle"
@needs_db
def test_heartbeat_is_limited_per_device(client, limited, device):
_, auth = device
codes = [
client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).status_code
for _ in range(ratelimit.CONDITIONS.capacity + 2)
]
assert codes[0] == 200
assert 429 in codes
@needs_db
def test_one_device_cannot_spend_anothers_budget(client, limited, device, make_device):
_, auth = device
for _ in range(ratelimit.CONDITIONS.capacity + 2):
client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth)
_, other_auth = make_device("other")
r = client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=other_auth)
assert r.status_code == 200, "one wedged camera must not starve the others"
@needs_db
def test_a_throttled_request_is_429_and_never_401(client, limited, device):
"""401 makes the firmware clear its token. Being busy is not a credential
problem, and throwing away a good token over it would be a real fault."""
_, auth = device
seen = set()
for _ in range(ratelimit.CONDITIONS.capacity + 3):
seen.add(
client.post("/api/v1/status", json={"reason": "periodic"}, headers=auth).status_code
)
assert 429 in seen
assert 401 not in seen
@needs_db
def test_limiting_off_means_off(client, device):
"""The default for the rest of the suite, and for local development."""
_, auth = device
codes = [
client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).status_code
for _ in range(ratelimit.CONDITIONS.capacity + 5)
]
assert set(codes) == {200}