diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 4136fcb..16b7b3f 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -8,7 +8,7 @@ from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging -from .routes import commands, conditions, device_config, enroll, health, ingest +from .routes import commands, conditions, device_config, enroll, firmware, health, ingest log = logging.getLogger(__name__) @@ -50,8 +50,11 @@ def create_app() -> FastAPI: app.include_router(device_config.router, prefix=API_PREFIX) app.include_router(commands.router, prefix=API_PREFIX) app.include_router(ingest.router, prefix=API_PREFIX) + app.include_router(firmware.router, prefix=API_PREFIX) - # Still to come: /firmware/{version}.bin. + # The device contract (firmware/API.md) is complete apart from /stream, + # which is Phase 6. Still to come: the admin-facing POST /firmware, which + # needs user auth, and the Phase 3 UI endpoints. # Phase 3 mounts the UI endpoints. return app diff --git a/server/src/poorbird/api/routes/firmware.py b/server/src/poorbird/api/routes/firmware.py new file mode 100644 index 0000000..7bc3da1 --- /dev/null +++ b/server/src/poorbird/api/routes/firmware.py @@ -0,0 +1,110 @@ +"""GET /api/v1/firmware/{version}.bin -- the OTA image. + +Bearer auth, like every other device endpoint. Three things the device +requires of this response, all checked before it erases a partition +(firmware/src/ota_mgr.cpp:110-128): + +1. status exactly 200, +2. a ``Content-Length`` header -- it refuses a chunked response, because it + wants to size-check before committing to an erase, +3. that length equal to the ``size`` the envelope advertised. + +So this must not be compressed or chunked on the way out. The camera talks to +the :8080 Caddy block, which has no ``encode`` directive, and FileResponse +sets an exact Content-Length from the file itself. + +The admin-facing ``POST /api/v1/firmware`` from API.md is not here: it needs +user authentication and an admin role, neither of which exists yet +(REVIEW SEC-007). Rows are expected to arrive by other means until then. +""" + +from __future__ import annotations + +import logging +from pathlib import Path + +from fastapi import APIRouter, HTTPException, status +from fastapi.responses import FileResponse +from sqlalchemy import select + +from ...config import Settings +from ...models.devices import Firmware +from ..deps import DbDep, DeviceDep, SettingsDep + +log = logging.getLogger(__name__) + +router = APIRouter() + + +def _resolve(file_path: str, settings: Settings) -> Path: + """Where the image actually lives. + + An absolute path is used as given; a relative one resolves under the + state directory. The value comes from the firmware row, which only an + administrator can write -- it is never built from anything in the + request, so there is no traversal to defend against here. The upload + endpoint that eventually writes it is where that check belongs. + """ + candidate = Path(file_path) + return candidate if candidate.is_absolute() else settings.state_dir / "firmware" / candidate + + +@router.get( + "/firmware/{version}.bin", + response_class=FileResponse, + summary="Download an OTA image", + tags=["firmware"], +) +def download_firmware( + version: str, + db: DbDep, + device: DeviceDep, + settings: SettingsDep, +) -> FileResponse: + row = db.scalar(select(Firmware).where(Firmware.version == version)) + if row is None: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no such firmware") + + path = _resolve(row.file_path, settings) + + if not path.is_file(): + # The row promises an image that is not there. 503 rather than 404: + # the firmware genuinely exists as far as the operator is concerned, + # and this is a server fault worth shouting about rather than a + # missing resource. + log.error( + "firmware row points at a missing file", + extra={"version": row.version, "path": str(path)}, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="firmware image unavailable", + ) + + # The device compares Content-Length against the size the envelope gave + # it and aborts on a mismatch. Catching that here turns a confusing + # device-side abort into one clear line in the server log. + actual = path.stat().st_size + if actual != row.size_bytes: + log.error( + "firmware size does not match its row", + extra={"version": row.version, "recorded": row.size_bytes, "on_disk": actual}, + ) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="firmware image does not match its manifest", + ) + + log.info( + "serving firmware", + extra={"version": row.version, "device_id": device.id, "bytes": actual}, + ) + + return FileResponse( + path, + media_type="application/octet-stream", + filename=f"{row.version}.bin", + # The image is immutable for a given version, and the device verifies + # SHA-256 over the whole thing before activating the slot anyway. + headers={"Cache-Control": "public, max-age=31536000, immutable"}, + ) diff --git a/server/tests/test_conditions.py b/server/tests/test_conditions.py index 4ae5e63..bdb0281 100644 --- a/server/tests/test_conditions.py +++ b/server/tests/test_conditions.py @@ -49,6 +49,39 @@ def device(db): db.commit() +@pytest.fixture +def firmware(db): + """Create firmware rows that are removed even when the test fails. + + Teardown has to live in a fixture, not at the end of the test body: a + failing assertion skips the rest of the function, and a leftover + is_target row then picks itself as the OTA target for every later test. + """ + created: list[Firmware] = [] + + def make(version: str, *, is_target: bool = True) -> Firmware: + row = Firmware( + version=version, + file_path=f"/srv/poorbird/fw/{version}.bin", + sha256="a" * 64, + size_bytes=1148320, + is_target=is_target, + ) + db.add(row) + db.commit() + db.refresh(row) + created.append(row) + return row + + yield make + + for row in created: + existing = db.get(Firmware, row.id) + if existing is not None: + db.delete(existing) + db.commit() + + def body(reason: str = "periodic", **over) -> dict: b = { "reason": reason, @@ -186,40 +219,21 @@ def test_one_devices_commands_do_not_leak_to_another(client, device, db): @needs_db -def test_firmware_key_is_absent_when_the_device_is_on_target(client, device, db): +def test_firmware_key_is_absent_when_the_device_is_on_target(client, device, firmware): """Absent, not null: present-and-different is itself the flash instruction.""" d, auth = device - fw = Firmware( - version="0.1.0", # same as the device - file_path="/srv/poorbird/fw/0.1.0.bin", - sha256="a" * 64, - size_bytes=1148320, - is_target=True, - ) - db.add(fw) - db.commit() + firmware("0.1.0") # same version the device reports e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() assert "firmware" not in e - db.delete(db.get(Firmware, fw.id)) - db.commit() - @needs_db -def test_a_different_target_is_offered_with_a_relative_url(client, device, db): +def test_a_different_target_is_offered_with_a_relative_url(client, device, firmware): """ota_mgr.cpp appends a non-http url to the API base, which already ends in /api/v1 -- so this must not carry the prefix itself.""" d, auth = device - fw = Firmware( - version="0.2.0", - file_path="/srv/poorbird/fw/0.2.0.bin", - sha256="b" * 64, - size_bytes=1148320, - is_target=True, - ) - db.add(fw) - db.commit() + firmware("0.2.0") e = client.post("/api/v1/heartbeat", json=body(), headers=auth).json() assert e["firmware"]["version"] == "0.2.0" @@ -227,9 +241,6 @@ def test_a_different_target_is_offered_with_a_relative_url(client, device, db): assert not e["firmware"]["url"].startswith("/api/v1") assert e["firmware"]["size"] == 1148320 - db.delete(db.get(Firmware, fw.id)) - db.commit() - # --- telemetry recording ---------------------------------------------------- diff --git a/server/tests/test_firmware.py b/server/tests/test_firmware.py new file mode 100644 index 0000000..9a1cdd3 --- /dev/null +++ b/server/tests/test_firmware.py @@ -0,0 +1,224 @@ +"""GET /api/v1/firmware/{version}.bin. + +The device checks the response before it erases a partition, so the tests +here are mostly about the headers being exactly right rather than about the +bytes. +""" + +from __future__ import annotations + +import hashlib +import secrets +from pathlib import Path + +import pytest +from conftest import needs_db + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.config import get_settings +from poorbird.models.devices import Device, Firmware + +IMAGE = b"\xe9" + secrets.token_bytes(4095) # stands in for an .bin, 4096 bytes + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + db.delete(db.get(Device, d.id)) + db.commit() + + +@pytest.fixture +def make_image(db): + """Build firmware rows with real files, and clean both up unconditionally. + + Teardown belongs here rather than at the end of a test body: a failing + assertion skips the rest of the function, and a leftover is_target row + then picks itself as the OTA target for every later test. That is exactly + how a deliberate mutation once poisoned two unrelated suites. + """ + created: list[tuple[Firmware, Path]] = [] + folder = get_settings().state_dir / "firmware" + folder.mkdir(parents=True, exist_ok=True) + + def make(version: str | None = None, *, is_target: bool = False): + version = version or f"9.{secrets.randbelow(100000)}.0" + path = folder / f"{version}.bin" + path.write_bytes(IMAGE) + row = Firmware( + version=version, + file_path=str(path), + sha256=hashlib.sha256(IMAGE).hexdigest(), + size_bytes=len(IMAGE), + is_target=is_target, + ) + db.add(row) + db.commit() + db.refresh(row) + created.append((row, path)) + return row, path + + yield make + + for row, path in created: + path.unlink(missing_ok=True) + existing = db.get(Firmware, row.id) + if existing is not None: + db.delete(existing) + db.commit() + + +@pytest.fixture +def image(make_image): + """One firmware row with a real file behind it.""" + return make_image() + + +# --- what the device needs -------------------------------------------------- + + +@needs_db +def test_the_image_comes_back_intact(client, device, image): + _, auth = device + row, _ = image + + r = client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth) + + assert r.status_code == 200 + assert r.content == IMAGE + assert hashlib.sha256(r.content).hexdigest() == row.sha256 + + +@needs_db +def test_content_length_is_present_and_exact(client, device, image): + """The device refuses a chunked response: it size-checks against the + manifest before erasing a partition (ota_mgr.cpp:111-120).""" + _, auth = device + row, _ = image + + r = client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth) + + assert "content-length" in r.headers + assert int(r.headers["content-length"]) == len(IMAGE) + assert int(r.headers["content-length"]) == row.size_bytes + assert "transfer-encoding" not in r.headers + + +@needs_db +def test_the_response_is_not_compressed(client, device, image): + """Compression would change Content-Length and the device would refuse.""" + _, auth = device + row, _ = image + + r = client.get( + f"/api/v1/firmware/{row.version}.bin", + headers={**auth, "Accept-Encoding": "gzip, deflate, br"}, + ) + + assert r.headers.get("content-encoding") in (None, "identity") + assert int(r.headers["content-length"]) == len(IMAGE) + + +@needs_db +def test_a_dotted_version_is_parsed_out_of_the_path(client, device, make_image): + """Versions are semver-ish, so the path has several dots before .bin.""" + _, auth = device + make_image("1.2.3-rc.1") + + r = client.get("/api/v1/firmware/1.2.3-rc.1.bin", headers=auth) + assert r.status_code == 200 + assert r.content == IMAGE + + +# --- the envelope names it, this serves it ---------------------------------- + + +@needs_db +def test_the_url_the_envelope_advertises_actually_resolves(client, device, db, image): + """End to end: heartbeat names a target, that URL downloads it. + + The envelope sends a relative URL because ota_mgr.cpp appends it to the + API base, which already ends in /api/v1. This proves the two halves agree. + """ + d, auth = device + row, _ = image + row.is_target = True + d.fw_version = "0.0.1" # not the target, so the key is present + db.commit() + + envelope = client.post("/api/v1/heartbeat", json={"reason": "heartbeat"}, headers=auth).json() + advertised = envelope["firmware"]["url"] + assert advertised == f"/firmware/{row.version}.bin" + + # What the device builds: apiBaseUrl() + url, where the base ends /api/v1. + r = client.get(f"/api/v1{advertised}", headers=auth) + assert r.status_code == 200 + assert int(r.headers["content-length"]) == envelope["firmware"]["size"] + assert hashlib.sha256(r.content).hexdigest() == envelope["firmware"]["sha256"] + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +def test_an_unknown_version_is_404(client, device): + _, auth = device + assert client.get("/api/v1/firmware/0.0.0-nope.bin", headers=auth).status_code == 404 + + +@needs_db +def test_a_row_whose_file_is_missing_is_503_not_404(client, device, image): + """The firmware exists as far as the operator is concerned; this is a + server fault worth shouting about, not a missing resource.""" + _, auth = device + row, path = image + path.unlink() + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 503 + + +@needs_db +def test_a_size_mismatch_is_caught_here_rather_than_on_the_device(client, device, db, image): + """The device would abort on the Content-Length check anyway. Failing + here turns a confusing remote abort into one clear server log line.""" + _, auth = device + row, path = image + path.write_bytes(IMAGE + b"extra") + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 503 + + +@needs_db +def test_firmware_requires_a_bearer_token(client, image): + row, _ = image + assert client.get(f"/api/v1/firmware/{row.version}.bin").status_code == 401 + + +@needs_db +def test_a_disabled_device_cannot_download(client, device, db, image): + d, auth = device + row, _ = image + d.enabled = False + db.commit() + + assert client.get(f"/api/v1/firmware/{row.version}.bin", headers=auth).status_code == 403