From 803806057872be37a216b381aa4aa0ef57f11bba Mon Sep 17 00:00:00 2001 From: Thomas Karner Date: Mon, 21 Sep 2026 12:23:56 +0200 Subject: [PATCH] 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) --- server/src/poorbird/api/deps.py | 147 ++++++++++++++ server/src/poorbird/api/schemas.py | 279 ++++++++++++++++++++++++++ server/src/poorbird/models/devices.py | 17 +- server/tests/test_device_auth.py | 192 ++++++++++++++++++ server/tests/test_schemas.py | 277 +++++++++++++++++++++++++ 5 files changed, 905 insertions(+), 7 deletions(-) create mode 100644 server/src/poorbird/api/schemas.py create mode 100644 server/tests/test_device_auth.py create mode 100644 server/tests/test_schemas.py diff --git a/server/src/poorbird/api/deps.py b/server/src/poorbird/api/deps.py index 149f7ec..bcb69d4 100644 --- a/server/src/poorbird/api/deps.py +++ b/server/src/poorbird/api/deps.py @@ -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 ``. 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 `` 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)] diff --git a/server/src/poorbird/api/schemas.py b/server/src/poorbird/api/schemas.py new file mode 100644 index 0000000..5def750 --- /dev/null +++ b/server/src/poorbird/api/schemas.py @@ -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 diff --git a/server/src/poorbird/models/devices.py b/server/src/poorbird/models/devices.py index c1be8a9..14882e5 100644 --- a/server/src/poorbird/models/devices.py +++ b/server/src/poorbird/models/devices.py @@ -64,7 +64,14 @@ class Device(Base): # Only the hash is stored. The token is high-entropy, so a fast hash is # defensible here (API.md). - token_hash: Mapped[str | None] = mapped_column(String(128)) + # + # Indexed because every authenticated device request resolves a bearer + # token by this column: it is the hottest lookup in the device API. + # + # Unique so that two devices can never end up sharing a token. NULLs stay + # distinct in Postgres, so any number of devices may sit here un-enrolled + # or revoked. + token_hash: Mapped[str | None] = mapped_column(String(128), unique=True, index=True) # Per-device re-enrollment credential, so a rotated token cannot strand a # camera that has no USB access once mounted (SPEC 0). reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128)) @@ -96,9 +103,7 @@ class Device(Base): responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false") enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true") - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) commands: Mapped[list[DeviceCommand]] = relationship( back_populates="device", cascade="all, delete-orphan" @@ -132,9 +137,7 @@ class DeviceCommand(Base): payload: Mapped[dict | None] = mapped_column(JSONB) created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL")) - created_at: Mapped[datetime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) ack_status: Mapped[str | None] = mapped_column(String(16)) diff --git a/server/tests/test_device_auth.py b/server/tests/test_device_auth.py new file mode 100644 index 0000000..c211473 --- /dev/null +++ b/server/tests/test_device_auth.py @@ -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" diff --git a/server/tests/test_schemas.py b/server/tests/test_schemas.py new file mode 100644 index 0000000..77538c2 --- /dev/null +++ b/server/tests/test_schemas.py @@ -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