Files
poorBird/server/tests/test_device_auth.py
Thomas KarnerandClaude Opus 5 8038060578 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>
2026-09-21 12:23:56 +02:00

193 lines
6.1 KiB
Python

"""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"