Commit Graph
11 Commits
Author SHA1 Message Date
Thomas KarnerandClaude Opus 5 e326dd8226 Add rate limiting to the device endpoints (REVIEW SEC-004)
In-process token buckets, no Redis and no slowapi - for the same reason the
job queue has no Redis (SPEC C8). This is one uvicorn process serving a
handful of cameras on a LAN, and slowapi's default storage is in-process
anyway, so a dependency would buy convenience rather than capability.

That assumption is named in the module: poorbird serve runs a single process,
and if the deployment ever gains workers each gets its own buckets and the
effective limit multiplies. Move the state to PostgreSQL at that point rather
than widening the numbers.

Buckets rather than fixed windows, because a camera uploads three to five
frames back to back when the radar fires and then goes quiet. A window would
reject the tail of a legitimate burst that straddled a boundary.

Authenticated endpoints key on the device, so one wedged camera cannot spend
another's allowance. /enroll keys on the caller address, since there is no
device yet and it is the one place a shared secret could be ground at.

This required a Caddyfile change, not a cosmetic one: the :8080 camera block
proxied without X-Real-IP, so every camera reached the app as 127.0.0.1 and
they would all have shared one enrollment bucket - one noisy device locking
the rest out. The header is trusted only because uvicorn binds loopback.

Limits are deliberately loose, each derived from what the firmware actually
does and noted in the code so the number can be re-derived rather than
guessed at. A throttled camera stops delivering photographs, which on a
private LAN is worse than the flooding the limit prevents.

Throttling answers 429, never 401: the firmware clears its token on a 401,
and being busy is not a credential problem. Retry-After gives it something
better than a guess.

The key table is LRU-bounded. It is keyed partly on caller address, and an
unbounded map keyed by something a caller influences is itself a way to
exhaust memory.

Off by default in tests, which fire far more requests than any camera would.
tests/test_ratelimit.py turns it back on and proves the buckets are wired to
the routes.

Also fixes the same teardown-in-test-body flaw in the new file, found by
re-running a deliberate mutation and noticing a leaked device row. Teardown
is in fixtures; the mutation now fails its one test and leaves nothing
behind.

Tests: 158 -> 175.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:29:53 +02:00
Thomas KarnerandClaude Opus 5 269a6eadcb 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>
2026-09-21 13:19:26 +02:00
Thomas KarnerandClaude Opus 5 6223d960c4 Add POST /api/v1/ingest (Phase 2)
Raw JPEG body with metadata in headers, which is API.md's deliberate
deviation from SPEC 4.1: multipart would make the device assemble a second
buffer purely to add a wrapper the server strips immediately. REVIEW.AI.md's
reference code implemented the multipart version and would not have matched
the firmware at all. Returns the same envelope as /heartbeat, so a capture
that was going to happen anyway also drains the command queue.

api/images.py holds the storage helpers, with no imaging library. Reading
nine bytes of JPEG header for the dimensions beats decoding a frame on a
path that runs once per capture, and the same parse doubles as content
validation: the magic bytes decide whether this is a JPEG, not the
Content-Type header. Pillow belongs in the thumbnail worker, off the request
path, where the image has to be decoded anyway.

Ordering and failure:

  - The file is written first, through a temp file in the same directory and
    an atomic rename, so a half-written JPEG is never visible at its final
    path. The row is inserted second, and the file is removed if the commit
    fails. The reverse order would be worse: a row pointing at a missing
    image is a broken gallery entry, while a stray file is invisible and
    sweepable.
  - A body that is not a JPEG is 400, never 401, so the device does not read
    it as a credential problem and clear a good token. Unwritable storage is
    503, because from the device's side it is transient.
  - 12MB cap mirrors the Caddyfile, since a limit that only exists in the
    proxy is not a limit in development.

Identical bytes from the same device are treated as a retry and return the
original capture, with the command queue still attached. The device cannot
tell a lost response from a real failure, and two genuine frames never
collide - sensor noise alone makes every capture unique. Checked in the
application rather than with a unique constraint, so a freak collision loses
a frame instead of raising.

X-Captured-At: 0 means the clock is unsynced and is stored as NULL. An epoch
date would bury the frame at the bottom of every chronological view forever.
received_at stays authoritative either way (SPEC C7), and is what dates the
YYYY/MM/DD path.

NOT included, and deliberately: the thumbnail job. An unknown job kind is
failed immediately by the worker (worker/main.py:35), so enqueuing one now
would produce a failed job per capture. thumb_path stays NULL, which the
gallery has to handle regardless - a capture is visible when it lands, not
once it is processed. Thumbnails are the next unit of work and need Pillow.

Tests: 122 -> 148. Verified by disabling dedup and by removing the
captured-at-zero guard: the two corresponding tests fail, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 13:08:05 +02:00
Thomas KarnerandClaude Opus 5 46f54dbe81 Add POST /commands/{id}/ack, closing the command lifecycle (Phase 2)
/heartbeat hands commands out and marks them delivered; this is where the
device reports what became of one. The two halves stay separate because the
ack may never arrive: reboot and sleep_now are acked and then the device is
gone, and a device that dies mid-command never acks at all. delivered_at
means "handed over", acked_at means "it ran", and the gap between them is
the operational signal worth having.

Three decisions:

- Scoped to the calling device, and a command belonging to someone else is
  404 rather than 403. Command ids are sequential, so a distinct status code
  would confirm that an id exists - and without the scope filter a device
  could close every other device's queue. Pinned by a test that also asserts
  the intruder did not manage to set acked_at.
- Re-acking is allowed and the last word wins. The device cannot tell a lost
  response from a lost request, so it retries; refusing the second attempt
  would strand a command that actually ran.
- An empty detail is stored as NULL. The firmware always sends the key,
  empty when it has nothing to say.

Liveness deliberately stays with /heartbeat, so the device list keeps one
source of truth for when a device was last heard from.

Tests: 109 -> 122, including the full queued -> delivered -> acked round
trip. Verified by removing the device scope from the lookup: the intruder
test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:57:18 +02:00
Thomas KarnerandClaude Opus 5 e83fc757d0 Add GET /api/v1/config (Phase 2)
Returns the device's settings document: the stored JSONB, plus the settings
that live in real columns, plus config_version last - mirroring
configApplyJson, which applies the version only after the rest of the payload
has been processed.

No response model, deliberately. devices.config is one JSONB document rather
than forty columns because the firmware grows tunables faster than a schema
should change, and the device merges and clamps whatever arrives: unknown
keys ignored, absent keys left alone, dangerous values clamped on the device
itself. Partial documents are the normal case, not a degraded one. Validating
this shape belongs on the write path, when the admin UI saves a config.

Unknown keys are passed through rather than filtered, so the admin UI can
push a new firmware tunable without waiting for the server to learn it.

Column-backed keys win over any stale copy of themselves in the JSONB. The
columns are the modelled source of truth, and a leftover key shadowing one
would mean a change to the column never reached the camera.

This also closes a loop left open at enrollment. Enrollment refuses to let a
device overwrite a rename made in the admin UI, which raised the fair
question of how the rename ever reaches the device. It reaches it here:
configApplyJson merges device_name like any other key (app_config.cpp:307).
The operator owns the name, the server pushes it down, and the device adopts
it - so the two decisions are consistent rather than merely defensible.

Named device_config.py so it does not read as poorbird.config. The route is
/config as specified.

Tests: 99 -> 109. Verified by letting the JSONB win over the columns: the
precedence test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:52:50 +02:00
Thomas KarnerandClaude Opus 5 5fd3c094a4 Add POST /heartbeat and POST /status, and the shared envelope (Phase 2)
One body, two endpoints. The firmware builds the conditions payload once, in
buildConditions, and posts it to both; they differ only in the response.

  /heartbeat -> 200 and the envelope: commands, config version, firmware
  /status    -> 204 and nothing

The split is not cosmetic and is now pinned by a test. The device posts
status immediately before deep sleep, so delivering commands there would mark
them delivered to a device about to be unable to run them.

api/envelope.py holds the shared builder, because /ingest returns the same
shape and parseEnvelope handles both with one function - they must not drift.

  - Commands are marked delivered when handed over, not on ack: the ack may
    never come, since the device runs reboot and sleep_now and is gone.
    acked_at stays the separate, later signal that it actually ran.
  - Expired commands are skipped but left in place, so the admin UI can show
    that a command timed out rather than silently losing it. The worker's
    prune job is what removes them.
  - The firmware URL is deliberately relative. ota_mgr.cpp:86 appends any
    non-http url to the API base, which already ends in /api/v1, so
    /firmware/0.2.0.bin resolves to /api/v1/firmware/0.2.0.bin.
  - Being on target means the firmware key is absent, not null: naming a
    different version is itself the instruction to flash (main.cpp:104).

Recording conditions appends a device_status row and refreshes the
denormalised columns on devices. Three details worth stating:

  - A field the device omits does not erase the last good value. None means
    not sent, not zero.
  - battery.valid false means NOT MEASURED and is stored as false, so the UI
    renders an em dash instead of inventing a low-battery alarm.
  - The device's reported config_version never overwrites the server's. The
    difference between them is exactly what tells the device to GET /config.

Tests: 77 -> 99. Verified by making /status build the envelope: the contract
test fails, as intended.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:46:59 +02:00
Thomas KarnerandClaude Opus 5 bde67e9a41 Add POST /api/v1/enroll (Phase 2)
The first device endpoint, and the one every other endpoint depends on:
nothing else can authenticate until a device has a token.

Guarded by X-Enroll-Secret rather than a bearer token, accepting either the
shared bootstrap secret or the device's own re-enrollment secret. Issues a
token and a per-device re-enrollment secret, stores only their hashes, and
returns the plaintext exactly once.

Re-enrollment of a known device_uid returns the existing row with a fresh
token, never a duplicate (API.md). The firmware re-enrolls on any 401, so
this is the normal path by which a rotated token heals itself without
physical access to a mounted camera.

Two judgement calls, both marked in the code:

- A disabled device is refused 403 and its token is left alone. Otherwise
  disabling a device in the admin UI would achieve nothing, since it would
  collect a fresh token on its next 401.
- Hardware facts (mac, hw_revision, fw_version) follow the device on every
  enrollment, because it is the authority on what it is running. The name
  does not: it is set at first enrollment and is an operator label after
  that, so a re-enrollment must not silently undo a rename.

Status codes are chosen for how the firmware reacts, not just for
correctness: 401 makes it clear its token and retry, so a misconfigured
server returns 503 and a contended write returns 503, never 4xx.

Tests: 57 -> 77. Verified by reintroducing the REVIEW.AI.md bug of returning
token_hash instead of the token: three tests fail, including the round trip
that feeds the issued token back through verify_device_token.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:37:31 +02:00
Thomas KarnerandClaude Opus 5 8038060578 Device auth and request validation (REVIEW SEC-002, SEC-003)
The plumbing every Phase 2 endpoint needs, before any endpoint exists.

api/schemas.py: Pydantic models for the whole device contract - enrollment,
the shared /ingest + /heartbeat envelope, the conditions body and command
acks. Enums are imported from the models, so a schema cannot drift from the
CHECK constraint that backs it.

api/deps.py: credential generation, hashing and bearer resolution.

Written against firmware/API.md and, where prose and code disagree, against
firmware/src/api_client.cpp. Four places where REVIEW.AI.md's reference code
would not have worked:

- Its /enroll returns devices.token_hash to the device. The device would then
  present the hash, the server would hash it again, and every request after
  enrollment would 401. Plaintext goes back once, only the hash is stored.
- It checks only the shared bootstrap secret on re-enrollment. The firmware
  swaps that for a per-device reenroll_secret after first enrollment, so that
  check would lock out every device that had ever succeeded - the exact
  failure the re-enrollment path exists to prevent.
- Its /ingest is multipart. API.md deviates from SPEC 4.1 deliberately: the
  body is the raw JPEG and metadata rides in headers, so the device does not
  assemble a second buffer. Modelled as IngestMeta.
- It uses secrets.token_urlsafe(32) - 43 non-hex chars. API.md says 64 hex,
  and the firmware's char[65] buffers make that exact. token_hex(32) it is.

capture_id is documented as an int but captures.id is a UUID. parseEnvelope
never reads the field, so it is sent as a UUID string.

The conditions models accept unknown keys on purpose: firmware grows fields
before the server learns them, device_status.raw keeps the whole body, and a
422 would take a camera offline for reporting something new.

devices.token_hash is now indexed and unique - it is resolved on every
authenticated request, and two devices must never share a token. No migration:
the live database already had exactly this index, so the model had drifted
from it. 'alembic check' is clean.

Tests: 17 -> 57.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:23:56 +02:00
Thomas KarnerandClaude Opus 5 3344a9e9b1 Harden config: no credentials in code (REVIEW SEC-001, SEC-006)
SEC-006: database_url had a working default carrying a real username and
password. Removed. Absence is now reported by 'poorbird check' as a problem
(exit 1) and raised by db.py with a message that names the variable and the
example file, instead of SQLAlchemy's "Could not parse URL from string ''"
three frames down.

SEC-001: enroll_secret stays environment-only and keeps its empty default so
the Phase 1 commands still run on a fresh clone. The device endpoints will
refuse to serve without it when they land.

Both fields now reject unedited placeholders (CHANGE_ME and friends), so a
copied .example cannot boot as though it were configured.

Tests: 12 -> 17. New cases cover the absent default, the readable failure,
and placeholder rejection for both fields.

Note: 6 files unrelated to this change are not clean under 'ruff format'
(the repo is wrapped at 88, pyproject sets line-length 100). Left alone to
keep this diff reviewable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 12:11:34 +02:00
Thomas KarnerandClaude Opus 5 5d16ded553 Server: verify Phase 1 end to end against PostgreSQL 17
Set up the dev environment (uv-managed CPython 3.14.7, postgres:17 in a
Podman container) and ran the skeleton for real: migrations apply, the
API serves /api/v1/health and /healthz, the worker claims a job and
drains it, 12/12 tests pass with nothing skipped.

The schema-drift test failed on its first real run and found a genuine
problem: Postgres reflects a varchar default as 'x'::character varying
while the model renders 'x', so all ten string defaults read as
permanent drift. Left alone that is the failure mode where you learn to
ignore the test and then miss the one real change. Add schema_compare.py,
a normaliser shared by migrations/env.py and the test so autogenerate and
the test can never disagree about what counts as a difference. A real
default change still fails it.

Also: ruff import-order fix in captures.py, and the README gains the
uv + Podman dev setup, the expected test count, and the CREATE DATABASE
privilege the drift test needs.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 00:30:52 +02:00
Thomas Karner 8a51e3d95e Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090) 2026-09-20 23:49:40 +02:00