Files
poorBird/server/src/poorbird/api/routes/enroll.py
T
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

128 lines
4.8 KiB
Python

"""POST /api/v1/enroll -- device enrollment and re-enrollment.
The only device endpoint not guarded by a bearer token, because it is where
the token comes from. It is guarded by ``X-Enroll-Secret`` instead: either the
shared bootstrap secret, or the device's own re-enrollment secret once it has
one (firmware/API.md, Authentication).
Re-enrollment is a normal, expected operation, not an error path. The firmware
re-enrolls on any 401, which is how a token rotated in the admin UI heals
itself without anyone climbing to the camera. API.md is explicit that a known
``device_uid`` must return the existing row with a fresh token rather than a
duplicate -- expect it on every rotation and after any database restore.
"""
from __future__ import annotations
import logging
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,
enroll_secret_accepted,
hash_credential,
new_credential,
require_enroll_secret_configured,
server_time_ms,
)
from ..schemas import EnrollRequest, EnrollResponse
log = logging.getLogger(__name__)
router = APIRouter()
@router.post(
"/enroll",
status_code=status.HTTP_201_CREATED,
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,
db: DbDep,
settings: SettingsDep,
x_enroll_secret: str | None = Header(default=None),
) -> EnrollResponse:
# 503 before anything else: a server with no bootstrap secret is
# misconfigured, not rejecting this particular device. A 4xx here would
# make the firmware discard a token that is probably still good.
require_enroll_secret_configured(settings)
device = db.scalar(select(Device).where(Device.device_uid == body.device_uid))
# The lookup has to come first, because a returning device presents its own
# per-device secret rather than the shared one.
if not enroll_secret_accepted(x_enroll_secret, settings, device):
log.warning("enrollment refused", extra={"device_uid": body.device_uid})
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid enrollment secret",
)
# A disabled device must not be able to re-enroll its way back in, or
# disabling it in the admin UI would mean nothing: it would simply collect
# a fresh token on its next 401.
if device is not None and not device.enabled:
log.warning("enrollment refused for disabled device", extra={"device_uid": body.device_uid})
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="device is disabled")
token = new_credential()
reenroll_secret = new_credential()
returning = device is not None
if device is None:
device = Device(device_uid=body.device_uid, name=body.device_name)
db.add(device)
# Hardware facts always follow the device: it is the authority on what it
# is running. The name deliberately does not -- it is set once at first
# enrollment and is an operator-facing label after that, so a re-enrollment
# must not silently undo a rename made in the admin UI.
device.mac = body.mac
device.hw_revision = body.hw_revision
device.fw_version = body.fw_version
device.token_hash = hash_credential(token)
device.reenroll_secret_hash = hash_credential(reenroll_secret)
try:
db.commit()
except IntegrityError:
# Two enrollments of the same device_uid racing each other. 503 rather
# than 409: it is transient and the firmware already retries, whereas a
# 4xx reads as "this device is not welcome".
db.rollback()
log.warning("enrollment raced", extra={"device_uid": body.device_uid})
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="enrollment is busy, retry",
) from None
db.refresh(device)
log.info(
"device re-enrolled" if returning else "device enrolled",
extra={"device_uid": device.device_uid, "device_id": device.id},
)
# The plaintext token and secret exist here and nowhere else. Only their
# hashes were stored, so this response is the single opportunity to hand
# them to the device.
return EnrollResponse(
token=token,
device_id=device.id,
reenroll_secret=reenroll_secret,
server_time=server_time_ms(),
config_version=device.config_version,
)