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
@@ -0,0 +1,192 @@
|
||||
"""Device authentication plumbing (REVIEW SEC-002).
|
||||
|
||||
The cases that matter most here are the two REVIEW.AI.md's reference code got
|
||||
wrong: the token handed to the device must be the one the server can verify,
|
||||
and re-enrollment must accept the per-device secret.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from conftest import needs_db
|
||||
from fastapi import HTTPException
|
||||
|
||||
from poorbird.api.deps import (
|
||||
enroll_secret_accepted,
|
||||
hash_credential,
|
||||
new_credential,
|
||||
require_enroll_secret_configured,
|
||||
verify_device_token,
|
||||
)
|
||||
from poorbird.config import Settings
|
||||
from poorbird.models.devices import Device
|
||||
|
||||
# --- credential shape -------------------------------------------------------
|
||||
|
||||
|
||||
def test_credential_is_64_hex_chars():
|
||||
"""The firmware stores these in char[65]; 64 + NUL fits exactly.
|
||||
|
||||
A longer credential would be silently truncated on the device and every
|
||||
request after enrollment would 401.
|
||||
"""
|
||||
c = new_credential()
|
||||
assert len(c) == 64
|
||||
assert all(ch in "0123456789abcdef" for ch in c)
|
||||
assert len(c) + 1 <= 65 # app_config.h: char device_token[65]
|
||||
|
||||
|
||||
def test_credentials_do_not_repeat():
|
||||
assert len({new_credential() for _ in range(100)}) == 100
|
||||
|
||||
|
||||
def test_hash_is_stable_and_not_the_input():
|
||||
c = new_credential()
|
||||
assert hash_credential(c) == hash_credential(c)
|
||||
assert hash_credential(c) != c
|
||||
assert len(hash_credential(c)) == 64
|
||||
|
||||
|
||||
# --- the bug in REVIEW.AI.md's reference code -------------------------------
|
||||
|
||||
|
||||
def test_token_given_to_the_device_verifies_against_what_is_stored():
|
||||
"""Store the hash, hand back the plaintext.
|
||||
|
||||
REVIEW.AI.md's /enroll example returns ``device.token_hash`` to the device.
|
||||
The device would then present the hash, the server would hash it again, and
|
||||
the comparison could never match. Guard against reintroducing that.
|
||||
"""
|
||||
token = new_credential()
|
||||
stored = hash_credential(token)
|
||||
|
||||
assert hash_credential(token) == stored # what the device presents resolves
|
||||
assert hash_credential(stored) != stored # handing back the hash would not
|
||||
|
||||
|
||||
# --- enrollment secret ------------------------------------------------------
|
||||
|
||||
|
||||
def _settings(secret: str = "") -> Settings:
|
||||
return Settings(_env_file=None, enroll_secret=secret)
|
||||
|
||||
|
||||
def test_shared_bootstrap_secret_is_accepted():
|
||||
assert enroll_secret_accepted("s3cret", _settings("s3cret"), None)
|
||||
|
||||
|
||||
def test_wrong_secret_is_rejected():
|
||||
assert not enroll_secret_accepted("nope", _settings("s3cret"), None)
|
||||
|
||||
|
||||
def test_missing_secret_is_rejected():
|
||||
assert not enroll_secret_accepted(None, _settings("s3cret"), None)
|
||||
assert not enroll_secret_accepted("", _settings("s3cret"), None)
|
||||
|
||||
|
||||
def test_unset_server_secret_never_accepts_anything():
|
||||
"""An unconfigured server must not treat an empty presented secret as a match."""
|
||||
assert not enroll_secret_accepted("", _settings(""), None)
|
||||
assert not enroll_secret_accepted("anything", _settings(""), None)
|
||||
|
||||
|
||||
def test_per_device_reenroll_secret_is_accepted():
|
||||
"""The firmware swaps the shared secret for this one after first enrollment.
|
||||
|
||||
Accepting only the shared secret would lock out every device that had
|
||||
already enrolled -- the exact failure re-enrollment exists to prevent.
|
||||
"""
|
||||
per_device = new_credential()
|
||||
device = Device(device_uid="a0b7651f2c3d", name="cam-1")
|
||||
device.reenroll_secret_hash = hash_credential(per_device)
|
||||
|
||||
assert enroll_secret_accepted(per_device, _settings("shared"), device)
|
||||
# and the shared one still works as the last-resort path
|
||||
assert enroll_secret_accepted("shared", _settings("shared"), device)
|
||||
assert not enroll_secret_accepted("neither", _settings("shared"), device)
|
||||
|
||||
|
||||
def test_one_devices_secret_cannot_enroll_another():
|
||||
mine = new_credential()
|
||||
other = Device(device_uid="ffffffffffff", name="cam-2")
|
||||
other.reenroll_secret_hash = hash_credential(new_credential())
|
||||
|
||||
assert not enroll_secret_accepted(mine, _settings("shared"), other)
|
||||
|
||||
|
||||
def test_unconfigured_server_returns_503_not_500():
|
||||
"""A 4xx would make the firmware clear a perfectly good token."""
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
require_enroll_secret_configured(_settings(""))
|
||||
assert exc.value.status_code == 503
|
||||
|
||||
require_enroll_secret_configured(_settings("set")) # does not raise
|
||||
|
||||
|
||||
# --- bearer token -----------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db():
|
||||
from poorbird.db import SessionLocal
|
||||
|
||||
with SessionLocal() as session:
|
||||
yield session
|
||||
session.rollback()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def enrolled(db):
|
||||
token = new_credential()
|
||||
device = Device(
|
||||
device_uid="dead" + new_credential()[:8],
|
||||
name="test-cam",
|
||||
token_hash=hash_credential(token),
|
||||
enabled=True,
|
||||
)
|
||||
db.add(device)
|
||||
db.flush() # rolled back by the db fixture; nothing is committed
|
||||
yield device, token
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_valid_bearer_token_resolves_to_its_device(db, enrolled):
|
||||
device, token = enrolled
|
||||
assert verify_device_token(db=db, authorization=f"Bearer {token}").id == device.id
|
||||
|
||||
|
||||
@needs_db
|
||||
@pytest.mark.parametrize(
|
||||
"header",
|
||||
[None, "", "Bearer", "Bearer ", "Basic abc", "abc", "Bearer wrong-token"],
|
||||
)
|
||||
def test_bad_authorization_headers_are_401(db, enrolled, header):
|
||||
"""401 specifically: the firmware reads it as 'clear token and re-enroll'."""
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
verify_device_token(db=db, authorization=header)
|
||||
assert exc.value.status_code == 401
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_bearer_scheme_is_case_insensitive(db, enrolled):
|
||||
_, token = enrolled
|
||||
assert verify_device_token(db=db, authorization=f"bearer {token}") is not None
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_disabled_device_is_403_not_401(db, enrolled):
|
||||
"""403 stops it re-enrolling in a loop; 401 would invite exactly that."""
|
||||
device, token = enrolled
|
||||
device.enabled = False
|
||||
db.flush()
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
verify_device_token(db=db, authorization=f"Bearer {token}")
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_401_carries_www_authenticate(db, enrolled):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
verify_device_token(db=db, authorization=None)
|
||||
assert exc.value.headers.get("WWW-Authenticate") == "Bearer"
|
||||
@@ -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
|
||||
Reference in new issue
Block a user