"""POST /api/v1/commands/{id}/ack, and the full command lifecycle with it.""" from __future__ import annotations import secrets import pytest from conftest import needs_db from poorbird.api.deps import hash_credential, new_credential from poorbird.models.devices import Device, DeviceCommand, DeviceStatus @pytest.fixture def db(): from poorbird.db import SessionLocal with SessionLocal() as session: yield session def _make_device(db, name="cam"): token = new_credential() d = Device( device_uid=secrets.token_hex(6), name=name, token_hash=hash_credential(token), enabled=True, ) db.add(d) db.commit() db.refresh(d) return d, {"Authorization": f"Bearer {token}"} def _cleanup(db, *devices): for d in devices: db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) db.delete(db.get(Device, d.id)) db.commit() @pytest.fixture def device(db): d, auth = _make_device(db) yield d, auth _cleanup(db, d) @pytest.fixture def queued(db, device): d, auth = device cmd = DeviceCommand(device_id=d.id, type="capture_now") db.add(cmd) db.commit() db.refresh(cmd) return d, auth, cmd CONDITIONS = {"reason": "heartbeat"} # --- the lifecycle ---------------------------------------------------------- @needs_db def test_delivered_then_acked(client, queued, db): """The whole round trip: queued -> delivered by heartbeat -> acked.""" d, auth, cmd = queued assert cmd.delivered_at is None and cmd.acked_at is None envelope = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() assert [c["id"] for c in envelope["commands"]] == [cmd.id] db.refresh(cmd) assert cmd.delivered_at is not None assert cmd.acked_at is None # delivered is not the same as done r = client.post( f"/api/v1/commands/{cmd.id}/ack", json={"status": "done", "detail": "captured 3 frames"}, headers=auth, ) assert r.status_code == 204 assert r.content == b"" db.refresh(cmd) assert cmd.acked_at is not None assert cmd.ack_status == "done" assert cmd.result == "captured 3 frames" @needs_db @pytest.mark.parametrize("outcome", ["done", "failed", "rejected"]) def test_every_documented_outcome_is_accepted(client, queued, db, outcome): d, auth, cmd = queued r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": outcome}, headers=auth) assert r.status_code == 204 db.refresh(cmd) assert cmd.ack_status == outcome @needs_db def test_an_unknown_outcome_is_422(client, queued): d, auth, cmd = queued r = client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "maybe"}, headers=auth) assert r.status_code == 422 @needs_db def test_an_empty_detail_is_stored_as_null(client, queued, db): """The firmware always sends the key, empty when it has nothing to say.""" d, auth, cmd = queued client.post( f"/api/v1/commands/{cmd.id}/ack", json={"status": "done", "detail": ""}, headers=auth ) db.refresh(cmd) assert cmd.result is None @needs_db def test_a_command_can_be_acked_without_having_been_delivered(client, queued, db): """Odd but harmless, and refusing it would strand a real ack if delivery bookkeeping ever went wrong.""" d, auth, cmd = queued assert cmd.delivered_at is None assert ( client.post( f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth ).status_code == 204 ) # --- retries ---------------------------------------------------------------- @needs_db def test_re_acking_is_allowed_and_the_last_word_wins(client, queued, db): """The device cannot tell a lost response from a lost request, so it retries. Refusing the second attempt would strand a command that ran.""" d, auth, cmd = queued client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "failed"}, headers=auth) db.refresh(cmd) first = cmd.acked_at r = client.post( f"/api/v1/commands/{cmd.id}/ack", json={"status": "done", "detail": "worked on retry"}, headers=auth, ) assert r.status_code == 204 db.refresh(cmd) assert cmd.ack_status == "done" assert cmd.result == "worked on retry" assert cmd.acked_at >= first @needs_db def test_acking_does_not_put_the_command_back_in_the_queue(client, queued, db): d, auth, cmd = queued client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth) client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth) again = client.post("/api/v1/heartbeat", json=CONDITIONS, headers=auth).json() assert again["commands"] == [] # --- scoping ---------------------------------------------------------------- @needs_db def test_another_devices_command_is_404_not_403(client, queued, db): """Command ids are sequential. A distinct status code would confirm that an id exists, which is the thing worth not saying.""" d, auth, cmd = queued intruder, intruder_auth = _make_device(db, name="intruder") r = client.post( f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=intruder_auth ) assert r.status_code == 404 db.refresh(cmd) assert cmd.acked_at is None, "an intruder must not be able to close a command" _cleanup(db, intruder) @needs_db def test_an_unknown_command_id_is_404(client, device): _, auth = device assert ( client.post( "/api/v1/commands/999999999/ack", json={"status": "done"}, headers=auth ).status_code == 404 ) @needs_db def test_ack_requires_a_bearer_token(client, queued): d, auth, cmd = queued assert client.post(f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}).status_code == 401 @needs_db def test_a_disabled_device_cannot_ack(client, queued, db): d, auth, cmd = queued d.enabled = False db.commit() assert ( client.post( f"/api/v1/commands/{cmd.id}/ack", json={"status": "done"}, headers=auth ).status_code == 403 )