"""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 ``. 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 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)] # --- 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 `` 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)]