Device auth and request validation (REVIEW SEC-002, SEC-003)
The plumbing every Phase 2 endpoint needs, before any endpoint exists. api/schemas.py: Pydantic models for the whole device contract - enrollment, the shared /ingest + /heartbeat envelope, the conditions body and command acks. Enums are imported from the models, so a schema cannot drift from the CHECK constraint that backs it. api/deps.py: credential generation, hashing and bearer resolution. Written against firmware/API.md and, where prose and code disagree, against firmware/src/api_client.cpp. Four places where REVIEW.AI.md's reference code would not have worked: - Its /enroll returns devices.token_hash to the device. The device would then present the hash, the server would hash it again, and every request after enrollment would 401. Plaintext goes back once, only the hash is stored. - It checks only the shared bootstrap secret on re-enrollment. The firmware swaps that for a per-device reenroll_secret after first enrollment, so that check would lock out every device that had ever succeeded - the exact failure the re-enrollment path exists to prevent. - Its /ingest is multipart. API.md deviates from SPEC 4.1 deliberately: the body is the raw JPEG and metadata rides in headers, so the device does not assemble a second buffer. Modelled as IngestMeta. - It uses secrets.token_urlsafe(32) - 43 non-hex chars. API.md says 64 hex, and the firmware's char[65] buffers make that exact. token_hex(32) it is. capture_id is documented as an int but captures.id is a UUID. parseEnvelope never reads the field, so it is sent as a UUID string. The conditions models accept unknown keys on purpose: firmware grows fields before the server learns them, device_status.raw keeps the whole body, and a 422 would take a camera offline for reporting something new. devices.token_hash is now indexed and unique - it is resolved on every authenticated request, and two devices must never share a token. No migration: the live database already had exactly this index, so the model had drifted from it. 'alembic check' is clean. Tests: 17 -> 57. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
3344a9e9b1
commit
8038060578
5 files changed
+905
-7
No files matched your search
@@ -1,12 +1,159 @@
|
||||
"""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 REVIEW.AI.md's reference code 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 <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)]
|
||||
Reference in new issue
Block a user