Add POST /api/v1/enroll (Phase 2)

The first device endpoint, and the one every other endpoint depends on:
nothing else can authenticate until a device has a token.

Guarded by X-Enroll-Secret rather than a bearer token, accepting either the
shared bootstrap secret or the device's own re-enrollment secret. Issues a
token and a per-device re-enrollment secret, stores only their hashes, and
returns the plaintext exactly once.

Re-enrollment of a known device_uid returns the existing row with a fresh
token, never a duplicate (API.md). The firmware re-enrolls on any 401, so
this is the normal path by which a rotated token heals itself without
physical access to a mounted camera.

Two judgement calls, both marked in the code:

- A disabled device is refused 403 and its token is left alone. Otherwise
  disabling a device in the admin UI would achieve nothing, since it would
  collect a fresh token on its next 401.
- Hardware facts (mac, hw_revision, fw_version) follow the device on every
  enrollment, because it is the authority on what it is running. The name
  does not: it is set at first enrollment and is an operator label after
  that, so a re-enrollment must not silently undo a rename.

Status codes are chosen for how the firmware reacts, not just for
correctness: 401 makes it clear its token and retry, so a misconfigured
server returns 503 and a contended write returns 503, never 4xx.

Tests: 57 -> 77. Verified by reintroducing the REVIEW.AI.md bug of returning
token_hash instead of the token: three tests fail, including the round trip
that feeds the issued token back through verify_device_token.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 12:37:31 +02:00
1 parent 8cf2329762
commit bde67e9a41
4 files changed
+405 -4

No files matched your search

+7 -4
View File
@@ -8,7 +8,7 @@ from fastapi import FastAPI
from .. import __version__
from ..config import get_settings
from ..logging_setup import configure_logging
from .routes import health
from .routes import enroll, health
log = logging.getLogger(__name__)
@@ -44,9 +44,12 @@ def create_app() -> FastAPI:
app.include_router(health.router, prefix=API_PREFIX, tags=["health"])
app.include_router(health.root_router)
# Phase 2 mounts the device endpoints here: /enroll, /ingest, /heartbeat,
# /status, /config, /commands/{id}/ack, /firmware/{version}.bin.
# Phase 3 mounts the UI endpoints. See firmware/API.md for the contract.
# Phase 2 device endpoints. See firmware/API.md for the contract.
app.include_router(enroll.router, prefix=API_PREFIX)
# Still to come: /ingest, /heartbeat, /status, /config,
# /commands/{id}/ack, /firmware/{version}.bin.
# Phase 3 mounts the UI endpoints.
return app