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