Files
Hello/server/tests/test_ratelimit.py
Thomas KarnerandClaude Opus 5 e326dd8226 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>
2026-09-21 13:29:53 +02:00

271 lines
8.2 KiB
Python

"""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}