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:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 12:23:56 +02:00
1 parent 3344a9e9b1
commit 8038060578
5 files changed
+905 -7

No files matched your search

+277
View File
@@ -0,0 +1,277 @@
"""Device API request/response shapes (REVIEW SEC-003).
These assert against firmware/API.md and, where the two disagree, against what
firmware/src/api_client.cpp actually sends.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from pydantic import ValidationError
from poorbird.api.schemas import (
Command,
DeviceConditions,
EnrollRequest,
Envelope,
IngestMeta,
)
# --- enrollment -------------------------------------------------------------
def test_enroll_accepts_what_the_firmware_sends():
"""Exactly the body built in api_client.cpp::enrollWith."""
r = EnrollRequest.model_validate(
{
"device_uid": "a0b7651f2c3d",
"device_name": "poorbird-cam-1",
"hw_revision": "xiao-esp32s3-sense-ld2410",
"fw_version": "0.1.0",
"mac": "A0:B7:65:1F:2C:3D",
}
)
assert r.device_uid == "a0b7651f2c3d"
assert r.device_name == "poorbird-cam-1"
def test_the_field_is_device_name_not_name():
"""REVIEW.AI.md calls it 'name'. The firmware sends 'device_name'."""
with pytest.raises(ValidationError):
EnrollRequest.model_validate({"device_uid": "a0b7651f2c3d", "name": "cam-1"})
def test_device_uid_must_be_hex():
"""It is the eFuse MAC in hex; anything else is not a device identity."""
for bad in ["not-hex!", "zzzz", "", "ab"]:
with pytest.raises(ValidationError):
EnrollRequest.model_validate({"device_uid": bad, "device_name": "cam"})
def test_oversized_fields_are_rejected_before_the_database_sees_them():
"""devices.name is String(64); a 422 beats a DataError from psycopg."""
with pytest.raises(ValidationError):
EnrollRequest.model_validate({"device_uid": "a0b765", "device_name": "x" * 65})
# --- ingest -----------------------------------------------------------------
def test_ingest_trigger_enum_matches_the_database_constraint():
for t in ("radar", "manual", "timer", "stream_grab"):
assert IngestMeta(trigger=t).trigger == t
with pytest.raises(ValidationError):
IngestMeta(trigger="motion")
def test_radar_fields_are_range_checked():
IngestMeta(trigger="radar", radar_state=3, radar_energy=100)
with pytest.raises(ValidationError):
IngestMeta(trigger="radar", radar_state=4)
with pytest.raises(ValidationError):
IngestMeta(trigger="radar", radar_energy=101)
def test_captured_at_defaults_to_none():
"""X-Captured-At: 0 means the clock is unsynced -- NULL, not 1970."""
assert IngestMeta(trigger="radar").captured_at is None
# --- conditions -------------------------------------------------------------
def _example_body() -> dict:
"""The status payload from firmware/API.md, verbatim."""
return {
"reason": "periodic",
"fw_version": "0.1.0",
"hw_revision": "xiao-esp32s3-sense-ld2410",
"config_version": 8,
"power": {
"uptime_ms": 91204,
"awake_ms": 91204,
"boot_count": 37,
"wake_cause": "radar",
"last_sleep_s": 300,
"total_sleep_s": 10800,
"sleep_enabled": False,
"sleep_allowed": False,
"inhibits": "stream,upload",
},
"battery": {
"valid": True,
"mv": 3912,
"pct": 74,
"raw_mv": 1956,
"chemistry": 1,
"low": False,
},
"counters": {
"captured_today": 412,
"delivered_today": 407,
"failed_today": 5,
"events_today": 41,
"day_index": 20716,
"captured_boot": 88,
"delivered_boot": 88,
},
"camera": {"frame_size": 8, "jpeg_quality": 12, "profile": "day", "ready": True},
"night": {
"is_night": False,
"nightlight_on": False,
"behaviour": 2,
"capture_allowed": True,
},
"stream": {"enabled": False, "active": False, "frames_sent": 0, "seconds_left": 0},
"radar": {
"baud": 256000,
"uart_ok": True,
"out_pin": False,
"state": 0,
"moving_cm": 0,
"moving_energy": 0,
"stationary_cm": 0,
"stationary_energy": 0,
},
"system": {
"rssi": -61,
"ip": "192.168.1.88",
"free_heap": 184320,
"free_psram": 6815744,
"ring_depth": 24,
"ring_bytes": 1179648,
},
"time_synced": True,
"device_time": "2026-09-20T14:31:07Z",
}
def test_the_documented_status_payload_validates():
c = DeviceConditions.model_validate(_example_body())
assert c.reason == "periodic"
assert c.battery.mv == 3912
assert c.counters.day_index == 20716
assert c.system.free_psram == 6815744
def test_reason_enum_matches_the_database_constraint():
for r in (
"heartbeat",
"periodic",
"after_event",
"before_sleep",
"before_night_sleep",
"on_request",
):
assert DeviceConditions(reason=r).reason == r
with pytest.raises(ValidationError):
DeviceConditions(reason="whenever")
def test_unknown_firmware_fields_are_kept_not_rejected():
"""The firmware grows fields before the server learns about them.
device_status.raw exists to keep the whole body; a 422 would take a camera
offline for reporting something new.
"""
body = _example_body()
body["quantum_flux"] = 42
body["battery"]["future_field"] = "x"
c = DeviceConditions.model_validate(body)
assert c.reason == "periodic"
assert c.model_dump()["quantum_flux"] == 42
def test_missing_blocks_default_rather_than_failing():
"""Only `reason` is genuinely required; a minimal report still lands."""
c = DeviceConditions(reason="before_sleep")
assert c.battery.valid is None # None = not reported, distinct from False
assert c.counters.captured_today is None
def test_battery_valid_false_is_preserved_as_false():
"""false means NOT MEASURED. It must not collapse into None anywhere."""
c = DeviceConditions.model_validate({"reason": "periodic", "battery": {"valid": False}})
assert c.battery.valid is False
def test_frame_size_accepts_a_name_as_well_as_an_index():
"""Names are authoritative: framesize_t indices have shifted between
driver releases, so a stored index can mean a different resolution."""
assert (
DeviceConditions.model_validate(
{"reason": "periodic", "camera": {"frame_size": "SVGA"}}
).camera.frame_size
== "SVGA"
)
assert (
DeviceConditions.model_validate(
{"reason": "periodic", "camera": {"frame_size": 8}}
).camera.frame_size
== 8
)
# --- envelope ---------------------------------------------------------------
def test_envelope_omits_firmware_when_the_device_is_on_target():
"""Present-and-different is itself the signal to flash, so absent must
mean absent -- not null."""
e = Envelope(server_time=1758376267000, config_version=7)
assert "firmware" not in e.model_dump(exclude_none=True)
def test_envelope_matches_the_documented_example():
e = Envelope(
capture_id="3f786850-e387-550f-dab8-36ed7e6dc881",
server_time=1758376267000,
config_version=7,
firmware={
"version": "0.2.0",
"url": "/firmware/0.2.0.bin",
"sha256": "3f786850e387550fdab836ed7e6dc881de23001b" + "0" * 24,
"size": 1148320,
},
commands=[
Command(
id=12,
type="stream_start",
payload={"session_id": "s-88f1", "duration_s": 45, "mode": 0},
expires_at=1758376400000,
)
],
)
dumped = json.loads(e.model_dump_json(exclude_none=True))
# Exactly the keys parseEnvelope reads, plus capture_id.
assert dumped["server_time"] == 1758376267000
assert dumped["config_version"] == 7
assert dumped["firmware"]["version"] == "0.2.0"
assert dumped["commands"][0]["id"] == 12
assert dumped["commands"][0]["type"] == "stream_start"
def test_command_type_enum_matches_the_database_constraint():
with pytest.raises(ValidationError):
Command(id=1, type="self_destruct")
def test_empty_command_list_is_the_default():
assert Envelope(server_time=0, config_version=1).commands == []
# --- contract drift ---------------------------------------------------------
def test_api_md_is_where_we_think_it_is():
"""If this moves, the comments above stop pointing anywhere."""
api_md = Path(__file__).resolve().parents[2] / "firmware" / "API.md"
assert api_md.is_file(), f"contract not found at {api_md}"
text = api_md.read_text(encoding="utf-8")
# The two deviations from SPEC.md that these schemas encode.
assert "device_name" in text
assert "raw JPEG as the body" in text