Add GET /firmware/{version}.bin, and fix test teardown (Phase 2)
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>
This commit is contained in:
1 parent
6223d960c4
commit
269a6eadcb
4 files changed
+376
-28
No files matched your search
@@ -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
|
||||
|
||||
@@ -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"},
|
||||
)
|
||||
Reference in new issue
Block a user