From bde67e9a415ab3b45c53c4944031c57d8c00ac52 Mon Sep 17 00:00:00 2001 From: Thomas Karner Date: Mon, 21 Sep 2026 12:37:31 +0200 Subject: [PATCH] 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) --- server/src/poorbird/api/app.py | 11 +- server/src/poorbird/api/deps.py | 11 + server/src/poorbird/api/routes/enroll.py | 123 +++++++++++ server/tests/test_enroll.py | 264 +++++++++++++++++++++++ 4 files changed, 405 insertions(+), 4 deletions(-) create mode 100644 server/src/poorbird/api/routes/enroll.py create mode 100644 server/tests/test_enroll.py diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 53c86a5..0f84bd9 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -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 diff --git a/server/src/poorbird/api/deps.py b/server/src/poorbird/api/deps.py index 9533162..7e237ad 100644 --- a/server/src/poorbird/api/deps.py +++ b/server/src/poorbird/api/deps.py @@ -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 ------------------------------------------------------------ diff --git a/server/src/poorbird/api/routes/enroll.py b/server/src/poorbird/api/routes/enroll.py new file mode 100644 index 0000000..74e6c38 --- /dev/null +++ b/server/src/poorbird/api/routes/enroll.py @@ -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, + ) diff --git a/server/tests/test_enroll.py b/server/tests/test_enroll.py new file mode 100644 index 0000000..2050799 --- /dev/null +++ b/server/tests/test_enroll.py @@ -0,0 +1,264 @@ +"""POST /api/v1/enroll (firmware/API.md, Authentication). + +The server has no enroll secret configured by default, so every test that +expects to get past the door overrides it. +""" + +from __future__ import annotations + +import secrets + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, verify_device_token +from poorbird.config import Settings, get_settings +from poorbird.models.devices import Device + +SHARED = "test-bootstrap-secret" + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def uid(): + """A device_uid no other test will collide with.""" + return secrets.token_hex(6) + + +@pytest.fixture +def api(client, db): + """`client`, with an enroll secret configured and created rows cleaned up.""" + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, enroll_secret=SHARED + ) + created: list[str] = [] + + class Api: + def enroll(self, uid, secret=SHARED, **over): + created.append(uid) + body = { + "device_uid": uid, + "device_name": "poorbird-cam-1", + "hw_revision": "xiao-esp32s3-sense-ld2410", + "fw_version": "0.1.0", + "mac": "A0:B7:65:1F:2C:3D", + } + body.update(over) + headers = {"X-Enroll-Secret": secret} if secret is not None else {} + return client.post("/api/v1/enroll", json=body, headers=headers) + + def unconfigured(self): + client.app.dependency_overrides[get_settings] = lambda: Settings( + _env_file=None, enroll_secret="" + ) + + yield Api() + + client.app.dependency_overrides.clear() + for u in created: + for d in db.scalars(select(Device).where(Device.device_uid == u)): + db.delete(d) + db.commit() + + +# --- first enrollment ------------------------------------------------------- + + +@needs_db +def test_first_enrollment_returns_201_and_the_documented_shape(api, uid): + r = api.enroll(uid) + assert r.status_code == 201 + + body = r.json() + assert set(body) == { + "token", + "device_id", + "reenroll_secret", + "server_time", + "config_version", + } + assert len(body["token"]) == 64 + assert len(body["reenroll_secret"]) == 64 + assert body["token"] != body["reenroll_secret"] + assert isinstance(body["device_id"], int) + assert body["server_time"] > 1_700_000_000_000 # epoch ms, not seconds + assert body["config_version"] >= 1 + + +@needs_db +def test_the_issued_token_actually_authenticates(api, uid, db): + """The regression that REVIEW.AI.md's reference code would have shipped. + + Its /enroll hands back devices.token_hash. The device would present that, + the server would hash it again, and every request after enrollment would + 401. This is the round trip that proves it does not. + """ + token = api.enroll(uid).json()["token"] + + device = verify_device_token(db=db, authorization=f"Bearer {token}") + assert device.device_uid == uid + + +@needs_db +def test_only_hashes_are_persisted(api, uid, db): + body = api.enroll(uid).json() + device = db.scalar(select(Device).where(Device.device_uid == uid)) + + assert device.token_hash == hash_credential(body["token"]) + assert device.reenroll_secret_hash == hash_credential(body["reenroll_secret"]) + # The plaintext must appear nowhere on the row. + stored = " ".join(str(v) for v in device.__dict__.values()) + assert body["token"] not in stored + assert body["reenroll_secret"] not in stored + + +# --- re-enrollment ---------------------------------------------------------- + + +@needs_db +def test_re_enrollment_reuses_the_row_and_rotates_the_token(api, uid, db): + """API.md: a known device_uid returns the existing device, not a duplicate. + + Expected on every token rotation and after any database restore. + """ + first = api.enroll(uid).json() + second = api.enroll(uid).json() + + assert second["device_id"] == first["device_id"] + assert second["token"] != first["token"] + assert db.scalars(select(Device).where(Device.device_uid == uid)).all().__len__() == 1 + + +@needs_db +def test_the_old_token_stops_working_after_rotation(api, uid, db): + from fastapi import HTTPException + + old = api.enroll(uid).json()["token"] + new = api.enroll(uid).json()["token"] + + assert verify_device_token(db=db, authorization=f"Bearer {new}") is not None + with pytest.raises(HTTPException) as exc: + verify_device_token(db=db, authorization=f"Bearer {old}") + assert exc.value.status_code == 401 + + +@needs_db +def test_a_device_can_re_enroll_with_its_own_secret(api, uid): + """The firmware swaps the shared secret for this one after first enrollment, + so from then on it is the only credential it has.""" + per_device = api.enroll(uid).json()["reenroll_secret"] + + again = api.enroll(uid, secret=per_device) + assert again.status_code == 201 + # and it is rotated in turn, so a captured secret is good for one use + assert again.json()["reenroll_secret"] != per_device + + +@needs_db +def test_one_devices_secret_cannot_enroll_a_different_uid(api, uid): + mine = api.enroll(uid).json()["reenroll_secret"] + assert api.enroll(secrets.token_hex(6), secret=mine).status_code == 401 + + +@needs_db +def test_hardware_facts_follow_the_device(api, uid, db): + api.enroll(uid) + api.enroll(uid, fw_version="0.2.0", hw_revision="rev-b") + + device = db.scalar(select(Device).where(Device.device_uid == uid)) + db.refresh(device) + assert device.fw_version == "0.2.0" + assert device.hw_revision == "rev-b" + + +@needs_db +def test_re_enrollment_does_not_undo_an_operator_rename(api, uid, db): + """The name is an operator-facing label after first enrollment. + + A camera that re-enrolls on every token rotation must not keep reverting a + rename made in the admin UI. + """ + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.name = "Feeder by the shed" + db.commit() + + api.enroll(uid, device_name="poorbird-cam-1") + + db.refresh(device) + assert device.name == "Feeder by the shed" + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +@pytest.mark.parametrize("secret", ["wrong", "", None]) +def test_bad_or_missing_secret_is_401(api, uid, secret): + assert api.enroll(uid, secret=secret).status_code == 401 + + +@needs_db +def test_unconfigured_server_is_503_not_401(api, uid): + """A 4xx would tell the camera it is unwelcome and make it clear its token. + The server being misconfigured is not the device's fault.""" + api.unconfigured() + assert api.enroll(uid).status_code == 503 + + +@needs_db +def test_a_disabled_device_cannot_re_enroll_its_way_back_in(api, uid, db): + """Otherwise disabling a device in the admin UI would mean nothing.""" + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.enabled = False + db.commit() + + assert api.enroll(uid).status_code == 403 + + +@needs_db +def test_a_disabled_devices_token_is_not_rotated_by_the_refusal(api, uid, db): + api.enroll(uid) + device = db.scalar(select(Device).where(Device.device_uid == uid)) + device.enabled = False + db.commit() + before = device.token_hash + + api.enroll(uid) + + db.refresh(device) + assert device.token_hash == before + + +@needs_db +@pytest.mark.parametrize( + "bad", + [ + {"device_uid": "not-hex!"}, + {"device_uid": ""}, + {"device_name": ""}, + {"device_name": "x" * 65}, + ], +) +def test_malformed_bodies_are_422(api, uid, bad): + assert api.enroll(uid, **bad).status_code == 422 + + +@needs_db +def test_the_legacy_name_field_is_not_accepted(api, uid, client): + """REVIEW.AI.md's model calls it `name`; the firmware sends `device_name`.""" + r = client.post( + "/api/v1/enroll", + json={"device_uid": uid, "name": "cam-1"}, + headers={"X-Enroll-Secret": SHARED}, + ) + assert r.status_code == 422