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)]
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Request and response shapes for the device API (REVIEW SEC-003).
|
||||
|
||||
The contract is ``firmware/API.md``, and where it disagrees with SPEC.md the
|
||||
firmware wins, because the firmware is what is actually on the camera. Two
|
||||
places where that matters are called out inline: ``/ingest`` carries a raw JPEG
|
||||
body with metadata in headers, not multipart, and the enrollment body field is
|
||||
``device_name``, not ``name``.
|
||||
|
||||
Nothing here talks to the database. These models exist so that a malformed or
|
||||
hostile request is rejected at the edge with a 422, before any handler reaches
|
||||
for a session.
|
||||
|
||||
One deliberate looseness: the conditions models accept unknown keys. The
|
||||
firmware grows fields faster than the server learns about them, and
|
||||
``device_status.raw`` exists precisely to keep the whole posted body. Rejecting
|
||||
a camera because it reports something new would be the wrong failure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from ..models.captures import TRIGGERS
|
||||
from ..models.devices import COMMAND_TYPES, STATUS_REASONS
|
||||
|
||||
Trigger = Literal[TRIGGERS] # type: ignore[valid-type]
|
||||
StatusReason = Literal[STATUS_REASONS] # type: ignore[valid-type]
|
||||
CommandType = Literal[COMMAND_TYPES] # type: ignore[valid-type]
|
||||
|
||||
# The firmware holds these in char[65], so 64 characters plus a NUL. Issue
|
||||
# exactly 64 hex characters and a token can never be silently truncated on the
|
||||
# device (firmware/include/app_config.h).
|
||||
TOKEN_CHARS = 64
|
||||
|
||||
|
||||
class _Loose(BaseModel):
|
||||
"""Base for anything the firmware posts: keep unknown keys, do not 422."""
|
||||
|
||||
model_config = ConfigDict(extra="allow")
|
||||
|
||||
|
||||
# --- enrollment -------------------------------------------------------------
|
||||
|
||||
|
||||
class EnrollRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
# eFuse MAC in hex. Survives reflashing, which is what makes it an identity
|
||||
# rather than a name (API.md, Enrollment).
|
||||
device_uid: Annotated[str, Field(min_length=6, max_length=32, pattern=r"^[0-9a-fA-F]+$")]
|
||||
# API.md calls this device_name. REVIEW.AI.md calls it name; the firmware
|
||||
# sends device_name, so that is what this is.
|
||||
device_name: Annotated[str, Field(min_length=1, max_length=64)]
|
||||
hw_revision: Annotated[str | None, Field(max_length=64)] = None
|
||||
fw_version: Annotated[str | None, Field(max_length=32)] = None
|
||||
mac: Annotated[str | None, Field(max_length=32)] = None
|
||||
|
||||
|
||||
class EnrollResponse(BaseModel):
|
||||
"""201. The token is returned in the clear exactly once, here.
|
||||
|
||||
Only its hash is stored. Returning the stored hash instead would hand the
|
||||
device a credential the server cannot recognise, and every later request
|
||||
would 401.
|
||||
"""
|
||||
|
||||
token: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)]
|
||||
device_id: int
|
||||
reenroll_secret: Annotated[str, Field(min_length=TOKEN_CHARS, max_length=TOKEN_CHARS)]
|
||||
server_time: int # epoch ms, UTC, authoritative (SPEC C7)
|
||||
config_version: int
|
||||
|
||||
|
||||
# --- the shared response envelope -------------------------------------------
|
||||
|
||||
|
||||
class FirmwareTarget(BaseModel):
|
||||
version: str
|
||||
url: str
|
||||
sha256: Annotated[str, Field(min_length=64, max_length=64)]
|
||||
size: int
|
||||
|
||||
|
||||
class Command(BaseModel):
|
||||
id: int
|
||||
type: CommandType
|
||||
payload: dict[str, Any] | None = None
|
||||
expires_at: int | None = None # epoch ms; the firmware ignores it, the server prunes on it
|
||||
|
||||
|
||||
class Envelope(BaseModel):
|
||||
"""Returned by /ingest and /heartbeat, identically (API.md, SPEC 4.1).
|
||||
|
||||
``capture_id`` is documented as an integer in API.md's example, but
|
||||
``captures.id`` is a UUID and the firmware never reads the field back
|
||||
(verified in firmware/src/api_client.cpp::parseEnvelope, which pulls only
|
||||
server_time, config_version, firmware and commands). Sent as a UUID string.
|
||||
"""
|
||||
|
||||
capture_id: str | None = None
|
||||
server_time: int
|
||||
config_version: int
|
||||
# Omit the key entirely when the device is on target: present-and-different
|
||||
# is itself the signal to flash (API.md). Omission is a serialisation
|
||||
# concern, so the routes set response_model_exclude_none=True rather than
|
||||
# anything here.
|
||||
firmware: FirmwareTarget | None = None
|
||||
commands: list[Command] = Field(default_factory=list)
|
||||
|
||||
|
||||
# --- ingest -----------------------------------------------------------------
|
||||
|
||||
|
||||
class IngestMeta(BaseModel):
|
||||
"""Metadata for POST /ingest, which arrives in headers, not a body.
|
||||
|
||||
Deviation from SPEC 4.1, and a deliberate one: the raw JPEG is the body, so
|
||||
the device hands over its framebuffer pointer without assembling a second
|
||||
multipart buffer (API.md). REVIEW.AI.md's reference code used multipart and
|
||||
would not have matched the firmware.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
trigger: Trigger
|
||||
burst_id: Annotated[str | None, Field(max_length=64)] = None
|
||||
burst_index: int | None = None
|
||||
burst_count: int | None = None
|
||||
pre_trigger: bool = False
|
||||
# epoch ms UTC. 0 means the device clock is unsynced: that is NULL, not
|
||||
# 1970 (API.md). received_at stays authoritative either way (SPEC C7).
|
||||
captured_at: datetime | None = None
|
||||
frame_seq: int | None = None
|
||||
radar_state: Annotated[int | None, Field(ge=0, le=3)] = None
|
||||
radar_distance_cm: int | None = None
|
||||
radar_energy: Annotated[int | None, Field(ge=0, le=100)] = None
|
||||
|
||||
|
||||
# --- device conditions: one body, two endpoints -----------------------------
|
||||
#
|
||||
# POST /heartbeat -> 200 + Envelope, POST /status -> 204 and nothing.
|
||||
# The split is not cosmetic: the device posts status immediately before deep
|
||||
# sleep, and handing it commands at that moment would mark them delivered to a
|
||||
# device that is about to be unable to run them (API.md).
|
||||
|
||||
|
||||
class PowerBlock(_Loose):
|
||||
uptime_ms: int | None = None
|
||||
# Resets on every wake, unlike uptime_ms which resets only on reboot.
|
||||
awake_ms: int | None = None
|
||||
boot_count: int | None = None
|
||||
wake_cause: Annotated[str | None, Field(max_length=16)] = None
|
||||
last_sleep_s: int | None = None
|
||||
total_sleep_s: int | None = None
|
||||
sleep_enabled: bool | None = None
|
||||
sleep_allowed: bool | None = None
|
||||
inhibits: str | None = None
|
||||
|
||||
|
||||
class BatteryBlock(_Loose):
|
||||
# false means NOT MEASURED, not empty: no divider is wired by default.
|
||||
# Render as an em dash, never as a low-battery alarm (API.md).
|
||||
valid: bool | None = None
|
||||
mv: int | None = None
|
||||
pct: Annotated[int | None, Field(ge=0, le=100)] = None
|
||||
raw_mv: int | None = None
|
||||
# 0 means pct is meaningless; show the voltage only.
|
||||
chemistry: int | None = None
|
||||
low: bool | None = None
|
||||
|
||||
|
||||
class CountersBlock(_Loose):
|
||||
"""The device's opinion, not the truth: RTC memory, reset on power loss.
|
||||
|
||||
``captures`` is authoritative. What these are genuinely good for is the gap
|
||||
between captured_today and delivered_today, which is an upload-health
|
||||
signal you would otherwise only notice as a quiet camera.
|
||||
"""
|
||||
|
||||
captured_today: int | None = None
|
||||
delivered_today: int | None = None
|
||||
failed_today: int | None = None
|
||||
events_today: int | None = None
|
||||
# Days since epoch in local time. Stays 0 until the clock syncs, so the
|
||||
# pre-sync bucket is a phantom day that rolls over once. Do not chart it.
|
||||
day_index: int | None = None
|
||||
captured_boot: int | None = None
|
||||
delivered_boot: int | None = None
|
||||
|
||||
|
||||
class CameraBlock(_Loose):
|
||||
# Send names, not indices: entries have been inserted into the middle of
|
||||
# framesize_t between driver releases, so a stored index silently means a
|
||||
# different resolution after a firmware update (API.md).
|
||||
frame_size: str | int | None = None
|
||||
frame_size_id: int | None = None
|
||||
width: int | None = None
|
||||
height: int | None = None
|
||||
# 0x2640 OV2640, 0x3660 OV3660, 0x5640 OV5640. Newer XIAO Sense units have
|
||||
# shipped with OV3660, so do not assume from the product listing.
|
||||
sensor_pid: int | None = None
|
||||
jpeg_quality: int | None = None
|
||||
profile: Annotated[str | None, Field(max_length=16)] = None
|
||||
ready: bool | None = None
|
||||
|
||||
|
||||
class NightBlock(_Loose):
|
||||
is_night: bool | None = None
|
||||
nightlight_on: bool | None = None
|
||||
behaviour: int | None = None
|
||||
capture_allowed: bool | None = None
|
||||
|
||||
|
||||
class StreamBlock(_Loose):
|
||||
enabled: bool | None = None
|
||||
active: bool | None = None
|
||||
frames_sent: int | None = None
|
||||
seconds_left: int | None = None
|
||||
|
||||
|
||||
class RadarBlock(_Loose):
|
||||
# 0 here means no valid frame decoded at any rate: wiring or a dead module,
|
||||
# and worth an alert (API.md).
|
||||
baud: int | None = None
|
||||
uart_ok: bool | None = None
|
||||
out_pin: bool | None = None
|
||||
state: Annotated[int | None, Field(ge=0, le=3)] = None
|
||||
moving_cm: int | None = None
|
||||
moving_energy: int | None = None
|
||||
stationary_cm: int | None = None
|
||||
stationary_energy: int | None = None
|
||||
|
||||
|
||||
class SystemBlock(_Loose):
|
||||
rssi: int | None = None
|
||||
ip: Annotated[str | None, Field(max_length=45)] = None
|
||||
free_heap: int | None = None
|
||||
free_psram: int | None = None
|
||||
ring_depth: int | None = None
|
||||
ring_bytes: int | None = None
|
||||
|
||||
|
||||
class DeviceConditions(_Loose):
|
||||
"""The body of both POST /heartbeat and POST /status."""
|
||||
|
||||
reason: StatusReason
|
||||
fw_version: Annotated[str | None, Field(max_length=32)] = None
|
||||
hw_revision: Annotated[str | None, Field(max_length=64)] = None
|
||||
config_version: int | None = None
|
||||
|
||||
power: PowerBlock = Field(default_factory=PowerBlock)
|
||||
battery: BatteryBlock = Field(default_factory=BatteryBlock)
|
||||
counters: CountersBlock = Field(default_factory=CountersBlock)
|
||||
camera: CameraBlock = Field(default_factory=CameraBlock)
|
||||
night: NightBlock = Field(default_factory=NightBlock)
|
||||
stream: StreamBlock = Field(default_factory=StreamBlock)
|
||||
radar: RadarBlock = Field(default_factory=RadarBlock)
|
||||
system: SystemBlock = Field(default_factory=SystemBlock)
|
||||
|
||||
time_synced: bool | None = None
|
||||
device_time: datetime | None = None
|
||||
|
||||
@field_validator("device_time", mode="before")
|
||||
@classmethod
|
||||
def _empty_is_none(cls, v: Any) -> Any:
|
||||
return None if v in ("", 0) else v
|
||||
|
||||
|
||||
# --- commands ---------------------------------------------------------------
|
||||
|
||||
|
||||
class CommandAck(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
status: Literal["done", "failed", "rejected"]
|
||||
detail: Annotated[str | None, Field(max_length=1000)] = None
|
||||
Reference in new issue
Block a user