"""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, )