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
+11
View File
@@ -25,6 +25,7 @@ from __future__ import annotations
import hashlib
import secrets
import time
from collections.abc import Iterator
from typing import Annotated
@@ -47,6 +48,16 @@ DbDep = Annotated[Session, Depends(get_db)]
SettingsDep = Annotated[Settings, Depends(get_settings)]
def server_time_ms() -> int:
"""Epoch milliseconds, UTC.
Authoritative (SPEC C7). The device adopts this whenever it is unsynced or
more than 2 s out, so the endpoint is the clock even where SNTP is not
reachable -- which is why every device response carries it.
"""
return int(time.time() * 1000)
# --- credentials ------------------------------------------------------------
+123
View File
@@ -0,0 +1,123 @@
"""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, Header, HTTPException, status
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from ...models.devices import Device
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"],
)
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,
)