"""POST /api/v1/enroll (firmware/API.md, Authentication). The server has no enroll secret configured by default, so every test that expects to get past the door overrides it. """ from __future__ import annotations import secrets import pytest from conftest import needs_db from sqlalchemy import select from poorbird.api.deps import hash_credential, verify_device_token from poorbird.config import Settings, get_settings from poorbird.models.devices import Device SHARED = "test-bootstrap-secret" @pytest.fixture def db(): from poorbird.db import SessionLocal with SessionLocal() as session: yield session @pytest.fixture def uid(): """A device_uid no other test will collide with.""" return secrets.token_hex(6) @pytest.fixture def api(client, db): """`client`, with an enroll secret configured and created rows cleaned up.""" client.app.dependency_overrides[get_settings] = lambda: Settings( _env_file=None, enroll_secret=SHARED ) created: list[str] = [] class Api: def enroll(self, uid, secret=SHARED, **over): created.append(uid) body = { "device_uid": uid, "device_name": "poorbird-cam-1", "hw_revision": "xiao-esp32s3-sense-ld2410", "fw_version": "0.1.0", "mac": "A0:B7:65:1F:2C:3D", } body.update(over) headers = {"X-Enroll-Secret": secret} if secret is not None else {} return client.post("/api/v1/enroll", json=body, headers=headers) def unconfigured(self): client.app.dependency_overrides[get_settings] = lambda: Settings( _env_file=None, enroll_secret="" ) yield Api() client.app.dependency_overrides.clear() for u in created: for d in db.scalars(select(Device).where(Device.device_uid == u)): db.delete(d) db.commit() # --- first enrollment ------------------------------------------------------- @needs_db def test_first_enrollment_returns_201_and_the_documented_shape(api, uid): r = api.enroll(uid) assert r.status_code == 201 body = r.json() assert set(body) == { "token", "device_id", "reenroll_secret", "server_time", "config_version", } assert len(body["token"]) == 64 assert len(body["reenroll_secret"]) == 64 assert body["token"] != body["reenroll_secret"] assert isinstance(body["device_id"], int) assert body["server_time"] > 1_700_000_000_000 # epoch ms, not seconds assert body["config_version"] >= 1 @needs_db def test_the_issued_token_actually_authenticates(api, uid, db): """The regression that REVIEW.AI.md's reference code would have shipped. Its /enroll hands back devices.token_hash. The device would present that, the server would hash it again, and every request after enrollment would 401. This is the round trip that proves it does not. """ token = api.enroll(uid).json()["token"] device = verify_device_token(db=db, authorization=f"Bearer {token}") assert device.device_uid == uid @needs_db def test_only_hashes_are_persisted(api, uid, db): body = api.enroll(uid).json() device = db.scalar(select(Device).where(Device.device_uid == uid)) assert device.token_hash == hash_credential(body["token"]) assert device.reenroll_secret_hash == hash_credential(body["reenroll_secret"]) # The plaintext must appear nowhere on the row. stored = " ".join(str(v) for v in device.__dict__.values()) assert body["token"] not in stored assert body["reenroll_secret"] not in stored # --- re-enrollment ---------------------------------------------------------- @needs_db def test_re_enrollment_reuses_the_row_and_rotates_the_token(api, uid, db): """API.md: a known device_uid returns the existing device, not a duplicate. Expected on every token rotation and after any database restore. """ first = api.enroll(uid).json() second = api.enroll(uid).json() assert second["device_id"] == first["device_id"] assert second["token"] != first["token"] assert db.scalars(select(Device).where(Device.device_uid == uid)).all().__len__() == 1 @needs_db def test_the_old_token_stops_working_after_rotation(api, uid, db): from fastapi import HTTPException old = api.enroll(uid).json()["token"] new = api.enroll(uid).json()["token"] assert verify_device_token(db=db, authorization=f"Bearer {new}") is not None with pytest.raises(HTTPException) as exc: verify_device_token(db=db, authorization=f"Bearer {old}") assert exc.value.status_code == 401 @needs_db def test_a_device_can_re_enroll_with_its_own_secret(api, uid): """The firmware swaps the shared secret for this one after first enrollment, so from then on it is the only credential it has.""" per_device = api.enroll(uid).json()["reenroll_secret"] again = api.enroll(uid, secret=per_device) assert again.status_code == 201 # and it is rotated in turn, so a captured secret is good for one use assert again.json()["reenroll_secret"] != per_device @needs_db def test_one_devices_secret_cannot_enroll_a_different_uid(api, uid): mine = api.enroll(uid).json()["reenroll_secret"] assert api.enroll(secrets.token_hex(6), secret=mine).status_code == 401 @needs_db def test_hardware_facts_follow_the_device(api, uid, db): api.enroll(uid) api.enroll(uid, fw_version="0.2.0", hw_revision="rev-b") device = db.scalar(select(Device).where(Device.device_uid == uid)) db.refresh(device) assert device.fw_version == "0.2.0" assert device.hw_revision == "rev-b" @needs_db def test_re_enrollment_does_not_undo_an_operator_rename(api, uid, db): """The name is an operator-facing label after first enrollment. A camera that re-enrolls on every token rotation must not keep reverting a rename made in the admin UI. """ api.enroll(uid) device = db.scalar(select(Device).where(Device.device_uid == uid)) device.name = "Feeder by the shed" db.commit() api.enroll(uid, device_name="poorbird-cam-1") db.refresh(device) assert device.name == "Feeder by the shed" # --- refusals --------------------------------------------------------------- @needs_db @pytest.mark.parametrize("secret", ["wrong", "", None]) def test_bad_or_missing_secret_is_401(api, uid, secret): assert api.enroll(uid, secret=secret).status_code == 401 @needs_db def test_unconfigured_server_is_503_not_401(api, uid): """A 4xx would tell the camera it is unwelcome and make it clear its token. The server being misconfigured is not the device's fault.""" api.unconfigured() assert api.enroll(uid).status_code == 503 @needs_db def test_a_disabled_device_cannot_re_enroll_its_way_back_in(api, uid, db): """Otherwise disabling a device in the admin UI would mean nothing.""" api.enroll(uid) device = db.scalar(select(Device).where(Device.device_uid == uid)) device.enabled = False db.commit() assert api.enroll(uid).status_code == 403 @needs_db def test_a_disabled_devices_token_is_not_rotated_by_the_refusal(api, uid, db): api.enroll(uid) device = db.scalar(select(Device).where(Device.device_uid == uid)) device.enabled = False db.commit() before = device.token_hash api.enroll(uid) db.refresh(device) assert device.token_hash == before @needs_db @pytest.mark.parametrize( "bad", [ {"device_uid": "not-hex!"}, {"device_uid": ""}, {"device_name": ""}, {"device_name": "x" * 65}, ], ) def test_malformed_bodies_are_422(api, uid, bad): assert api.enroll(uid, **bad).status_code == 422 @needs_db def test_the_legacy_name_field_is_not_accepted(api, uid, client): """REVIEW.AI.md's model calls it `name`; the firmware sends `device_name`.""" r = client.post( "/api/v1/enroll", json={"device_uid": uid, "name": "cam-1"}, headers={"X-Enroll-Secret": SHARED}, ) assert r.status_code == 422