Files
poorBird/server/src/poorbird/api/deps.py
T
Thomas KarnerandClaude Opus 5 bde67e9a41 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>
2026-09-21 12:37:31 +02:00

172 lines
6.1 KiB
Python

"""Shared dependencies: database sessions and device authentication.
Device auth is two-step (firmware/API.md). ``POST /enroll`` is guarded by a
shared bootstrap secret in ``X-Enroll-Secret``; everything else carries
``Authorization: Bearer <token>``. Only hashes are stored.
Two details here are easy to get wrong, and the reference code in
``docs/reviews/server-basic-implementation/REVIEW.AI.md`` got both wrong, so
they are spelled out:
1. The plaintext token is returned to the device exactly once, at enrollment,
and only its hash is persisted. Returning the stored hash would give the
device a credential the server cannot recognise and 401 every request after.
2. Re-enrollment must accept the device's *per-device* ``reenroll_secret`` as
well as the shared bootstrap secret. The firmware swaps the shared secret
for the per-device one the first time the server offers it, so from then on
that is what it presents. Checking only the shared secret would lock out
every device that had successfully enrolled, which is the exact failure the
re-enrollment path exists to prevent -- and the camera cannot be reached
over USB once mounted.
"""
from __future__ import annotations
import hashlib
import secrets
import time
from collections.abc import Iterator
from typing import Annotated
from fastapi import Depends, Header, HTTPException, status
from sqlalchemy import select
from sqlalchemy.orm import Session
from ..config import Settings, get_settings
from ..db import SessionLocal
from ..models.devices import Device
from .schemas import TOKEN_CHARS
def get_db() -> Iterator[Session]:
with SessionLocal() as session:
yield session
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 ------------------------------------------------------------
def new_credential() -> str:
"""A fresh token or re-enrollment secret: exactly 64 hex characters.
The firmware stores these in ``char[65]`` (app_config.h), so 64 characters
plus a NUL fits exactly and cannot be silently truncated. API.md documents
"64 hex chars" for both. ``secrets.token_urlsafe(32)``, which REVIEW.AI.md
suggests, yields 43 non-hex characters -- it would fit the buffer but would
not match the documented contract.
"""
return secrets.token_hex(TOKEN_CHARS // 2)
def hash_credential(value: str) -> str:
"""SHA-256 hex.
A fast hash, deliberately. API.md: "the token is high-entropy, so a fast
hash is defensible here". These are 256 bits of CSPRNG output, not
passwords -- there is no dictionary to attack, and a per-request Argon2
would cost every heartbeat. Argon2id belongs on ``users.password_hash``
(SEC-008), which is a different problem.
"""
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def _matches(presented: str | None, stored_hash: str | None) -> bool:
"""Constant-time compare of a presented credential against a stored hash."""
if not presented or not stored_hash:
return False
return secrets.compare_digest(hash_credential(presented), stored_hash)
# --- enrollment -------------------------------------------------------------
def enroll_secret_accepted(
presented: str | None,
settings: Settings,
device: Device | None,
) -> bool:
"""True if ``presented`` may enroll (or re-enroll) ``device``.
Accepts the shared bootstrap secret, or -- for a device that has enrolled
before -- that device's own re-enrollment secret. Both comparisons are
constant-time, and both run even when the first has already succeeded, so
the answer takes the same time either way.
"""
if not presented:
return False
shared = settings.enroll_secret.get_secret_value()
by_shared = bool(shared) and secrets.compare_digest(presented, shared)
by_device = device is not None and _matches(presented, device.reenroll_secret_hash)
return by_shared or by_device
def require_enroll_secret_configured(settings: Settings) -> None:
"""503 rather than 500 when the server has no bootstrap secret (SEC-001).
A camera that gets this should retry later, not treat itself as rejected:
a 4xx would make the firmware clear a perfectly good token.
"""
if not settings.enroll_secret_is_set:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="enrollment is not configured on this server",
)
# --- bearer token -----------------------------------------------------------
def verify_device_token(
db: DbDep,
authorization: Annotated[str | None, Header()] = None,
) -> Device:
"""Resolve ``Authorization: Bearer <token>`` to a Device, or 401.
401 is load-bearing: the firmware treats it as "clear the stored token and
re-enroll", which is how a rotated token heals itself without a ladder. A
disabled device gets 403 instead, precisely so that it does *not* re-enroll
in a loop (API.md, Behaviour the Pi should expect).
"""
unauthorized = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid or missing device token",
headers={"WWW-Authenticate": "Bearer"},
)
if not authorization:
raise unauthorized
scheme, _, token = authorization.partition(" ")
if scheme.lower() != "bearer" or not token.strip():
raise unauthorized
# Look the device up by hash. The hash is deterministic, so this is an
# indexed equality match, not a scan over every device.
device = db.scalar(select(Device).where(Device.token_hash == hash_credential(token.strip())))
if device is None:
raise unauthorized
if not device.enabled:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="device is disabled",
)
return device
DeviceDep = Annotated[Device, Depends(verify_device_token)]