The last device endpoint. With it, the whole firmware/API.md contract is implemented apart from /stream, which is Phase 6. The device checks three things before it erases a partition (ota_mgr.cpp:110-128): status exactly 200, a Content-Length header at all - it refuses chunked, because it wants to size-check first - and that length equal to the size the envelope advertised. FileResponse gives an exact length from the file, and the camera's :8080 Caddy block has no encode directive, so nothing recompresses it on the way out. A row whose file is missing, or whose file does not match its recorded size, is 503 with a loud log rather than a quiet 404. The device would abort on the Content-Length check anyway; failing here turns a confusing remote abort into one clear server line. A test walks the whole OTA handshake: heartbeat names a target, and the relative URL it advertises is fetched the way ota_mgr builds it, base plus url, and the bytes hash to the advertised sha256. The admin-facing POST /firmware is not included. It needs user auth and an admin role, neither of which exists yet (SEC-007). Also fixes a real defect in the tests. Several put their cleanup at the end of the test body, so a failing assertion skipped it. A deliberate mutation made two tests fail, which left two is_target firmware rows behind, and those rows then picked themselves as the OTA target for unrelated tests - one broken thing looked like three. Teardown now lives in fixtures and runs whatever happens. Re-running the same mutation now fails exactly the two tests it should and leaves the database clean. Tests: 148 -> 158. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
225 lines
6.7 KiB
Python
225 lines
6.7 KiB
Python
"""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
|