17 Commits
Author SHA1 Message Date
Thomas KarnerandClaude Opus 5 51750e1644 Add poorbird seed so the gallery has volume to be built against
The recorded TODO 3.0 decision: generated, not downloaded. No image licensing
question, no binary blobs in git, and it can produce the volume a virtualised
grid actually has to be tested against, which no set of real photos on hand
would.

Frames are written to disk for real, and thumbnails with them. A gallery whose
rows point at files that do not exist tests nothing about the delivery path,
which is the half most likely to be wrong. --no-thumbnails leaves thumb_path
NULL instead, which is how to exercise the queue at volume.

The data imitates what the firmware sends rather than being uniformly random:
bursts of frames around one radar trigger, the first one or two out of the
PSRAM pre-trigger ring, timestamps weighted toward daylight because birds are
diurnal and a gallery grouped by day looks wrong otherwise. Frames within a
burst land milliseconds apart on purpose - that is the received_at collision
the gallery cursor has to survive, and a seed that spread a burst over minutes
would never reproduce the paging bug it causes.

--clear is scoped by device_uid prefix, and that is the whole reason the prefix
exists. This command holds a DELETE over the same tables a real camera writes
to, so the property worth having is not that it removes seeded rows but that it
removes nothing else. The test for that is the one to keep: it puts a non-seed
device with a capture alongside the seeded ones and asserts both survive.

That test was mutation-checked against a scratch database rather than the dev
one, deliberately - a widened clear() would have taken the six real captures
with it, and verifying a safety property is not worth risking the thing it
protects. Against the scratch database, removing the scoping failed exactly
that test and nothing else.

The seed device is issued no token. It is a row for the gallery to point at,
not a camera, and giving it a working credential would be creating a real way
in for the sake of test data.

One flaky test found and fixed rather than re-run. test_every_burst_has_
pre_trigger_frames failed about one run in fifteen, because a count that is
not a multiple of the burst size left a truncated final burst - sometimes of
one frame, which is necessarily all pre-trigger, so "not all frames are
pre-trigger" did not hold. Both sides were wrong: a one-frame burst with
burst_count=1 is not something a camera sends, so the generator now absorbs a
short tail into the previous burst (bursts are 3-7 rather than 3-5), and the
test states its precondition instead of assuming it. Verified by running the
randomised tests fifteen times with the fix (0 failures) and fifteen times
without it (1 failure), rather than by one green run.

Tests: 293 -> 308.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 19:27:27 +02:00
Thomas KarnerandClaude Opus 5 735cbcc5a0 Add the captures API and auth-checked image serving (SPEC 3.3)
The server half of the gallery. Listing and delivery land together because
neither is useful alone: a listing with no way to fetch bytes renders empty
tiles, and image serving with nothing to enumerate has no entry point.

Delivery follows the design deploy/Caddyfile already committed to. The app
authorises, then answers empty with X-Accel-Redirect and Caddy reads the file,
so a 3 MB JPEG never occupies a Python worker thread. There is no Caddy in
development, though, and that header reaching a browser is an empty 200 - every
image in the gallery blank, with nothing to explain it. So
POORBIRD_SERVE_IMAGES_DIRECTLY makes the app send the bytes instead.

The important part is what that flag does NOT do: the authorisation is the same
code either way, and the flag only changes how an already-authorised response
is finished. A separate unauthenticated file route "only reachable in dev" is
exactly the kind of thing that survives into production because it works, and
this deliberately is not one.

Both delivery paths refuse a path that escapes its root. captures.path is
written by our own ingest code so it should never happen, but "should never" is
not a security control and the cost of being wrong is serving an arbitrary file
off the server. The handoff path needs it just as much as the direct one - a
traversal in the header makes *Caddy* read the file, where the app never opens
it at all.

Keyset paging, not OFFSET. At 5000 captures a day OFFSET gets slower the
further back you scroll, which is the direction a gallery scrolls. The cursor
carries (received_at, id), and the id is in there for a specific reason: a
burst arrives inside the same fraction of a second, so ties are normal rather
than exotic, and a timestamp-only cursor would either repeat rows or skip them.
A gallery that loses a frame while you scroll is one you cannot trust.

Page size is fetched as limit + 1 rather than counted. It answers "is there
another page" without a COUNT over the whole filtered set, and the test for a
full final page covers the off-by-one that trick invites.

Filters cover the columns that have data: device, received-date range, kept,
reviewed, pre_trigger, trigger. Taxon and tag filters are in TODO Phase 3 and
deliberately absent - both need a join, and neither has anything to join to
until the observation editor and a seeded taxa table exist. A filter that can
only ever return nothing is worse than an absent one, because the UI offers it.

Dates filter on received_at and never captured_at_device, which is NULL
whenever the camera's clock was unsynced (API.md, X-Captured-At: 0). Filtering
on it would silently drop exactly those frames.

A missing thumbnail is 404 rather than a fallback to the full JPEG. The grid
needs to tell "queued" from "never decoded" and show a placeholder; a silent
fallback would make 200 tiles fetch a hundred times the bytes and still look
like it worked.

`poorbird check` now verifies the layout the handoff depends on: Caddy serves
the PARENT of both roots, so they have to be siblings named images/ and
thumbs/. Getting it wrong produces 404s from Caddy with nothing in the app's
log, which is the kind of thing worth failing a preflight check over rather
than discovering in a browser.

One test-quality fix worth naming: two delivery tests were inheriting their
mode from whatever server/.env happened to say, and broke the moment
SERVE_IMAGES_DIRECTLY=true was added there for the dev server's benefit. Both
modes are now named explicitly by a fixture, and conftest pins the production
default - a test that changes its answer because of an untracked file is not
testing the code.

Verified against the real server and the six real captures already in the dev
database: 401 before signing in, two pages of three with no overlap and correct
termination, device_name garden-feeder on the detail, a 1572-byte WebP with
RIFF magic and a 3469-byte JPEG with FFD8FF magic, and 401 on the image again
immediately after logout.

Mutation-tested the two claims that matter: removing the traversal guard and
reducing the cursor to a timestamp each failed exactly the tests written for
them. The traversal test escapes to a canary file that really exists just
outside the root rather than to /etc/passwd, which does not exist on this
machine and would have let the test pass for the wrong reason.

Tests: 257 -> 293.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 19:06:59 +02:00
Thomas KarnerandClaude Opus 5 0c3fb2d837 Add sessions, login, logout and CSRF (REVIEW SEC-007)
The three endpoints web/src/auth/AuthProvider.tsx was written against. It
already distinguishes 404 ("this server has no auth at all", show a banner)
from 401 ("not signed in"), so these landing is what makes the banner go away.

Cookies with server-side state, not JWTs, and the reason is revocation. Signing
someone out, or ending every session when a password changes, has to take
effect on the next request. A self-contained token cannot be withdrawn before
it expires without a deny-list, which is the database lookup it was meant to
avoid. So logout DELETEs the row and the old cookie is dead immediately.

The cookie is not the primary key. sessions.id stays internal and the browser
carries a separate 64-hex token of which only the SHA-256 is stored, exactly as
device tokens work. Using the id would have been simpler and would mean a
database dump handed over every live session.

CSRF is a per-session token, checked in middleware rather than per route so a
new endpoint cannot forget it. Two decisions worth keeping:

  - It triggers only on unsafe methods for requests that CARRY THE SESSION
    COOKIE. Device endpoints authenticate with a bearer token and send no
    cookies, so /ingest is untouched - a camera has no way to obtain a CSRF
    token and blocking it would take the whole system down. Login is exempt by
    the same rule, with no special case: there is no session cookie yet.
  - The header is compared against the token on the session row, not against
    the CSRF cookie. Plain double-submit accepts any self-consistent pair, so
    anyone able to write a cookie on the domain can satisfy it while the
    victim's session cookie rides along. Binding it to the session means they
    would also need a value they cannot read.

Login answers every failure identically - same status, same body - because
"no such user" confirms which accounts exist and "wrong code" confirms the
password was right. It also hashes the submitted password when the username
does not exist, so a missing user is not measurably faster than a wrong
password; that timing difference is a username oracle.

Failed logins are audited, not just successful ones. A log of only the
successes cannot answer the question worth asking afterwards.

Rate limited by address rather than by username. Keying on the username would
let someone lock a known account out by failing at it deliberately, turning the
protection into a denial of service against the person it protects.

session_cookie_secure is a setting rather than a constant for one reason worth
writing down: a Secure cookie is silently discarded over http, so with it
hardcoded true every local login would return 200 and never sign anyone in,
with nothing in any log. The tests hit the same trap through http://testserver.

--- and the migration baseline had to be frozen to do any of this ---

0001 called Base.metadata.create_all(). That could not drift from the models,
which was its purpose, but it also meant a fresh database got the *current*
models from 0001 and then had every later migration applied on top of what it
had just created. The first migration added after it therefore failed with
"column token_hash of relation sessions already exists" - not on this machine,
where the columns were added incrementally, but on any clean one.

tests/test_schema_matches_models.py caught it immediately, which is the only
reason it did not reach a deployment. It is also the reason this is fixed now
rather than at the next schema change: the problem gets worse with every
revision added on top of it.

So 0001 is now explicit DDL for the schema as it stood at the end of Phase 1,
generated against an empty database with the new columns temporarily removed
from the model, and it says at the top not to edit it for a model change.
Verified on a fresh database: upgrade to head, downgrade to base, upgrade
again, alembic check clean at each end.

Also: the suite was leaking audit rows. audit_log.user_id is ON DELETE SET NULL
on purpose, and a failed login for a username that never existed writes NULL
from the start, so no user-scoped cleanup could ever match it - seven runs had
quietly left eight rows behind. Swept by id high-water mark now. Two
consecutive suite runs leave zero users, zero sessions, zero audit rows and
zero jobs.

Verified against a real uvicorn as well as the test client: 401 before login,
200 with both cookies and the right HttpOnly flags, 403 on logout without the
CSRF header with the session still alive afterwards, 204 with it, 401 after.

Mutation-tested the three properties this commit claims: comparing CSRF against
the cookie instead of the session, dropping the expiry check, and dropping the
TOTP requirement each failed exactly the tests written for them.

Tests: 221 -> 257.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 18:17:29 +02:00
Thomas KarnerandClaude Opus 5 9c44ab6b2a Add Argon2id passwords, TOTP and account creation (REVIEW SEC-009)
The foundation the rest of Phase 3 auth stands on, and the part that has to be
right before anything can be logged into.

passwords.py and totp.py sit at the package root, not under api/, because the
CLI creates the first account before any HTTP request exists and a CLI importing
from api would be the wrong way round - the same reason images.py lives there.

Argon2id, with argon2-cffi's own defaults rather than numbers pinned here, so
the cost tracks the library's guidance instead of this commit's. Note the
deliberate contrast with api/deps.py: device tokens are 256 bits of CSPRNG
output and stay on SHA-256, because there is no dictionary to attack and a
per-request Argon2 would cost every heartbeat. A password is human-chosen from
a tiny space, so its hash has to be slow. Same word, opposite requirements, and
the docstrings on both sides now say so.

verify_password never raises. A NULL password_hash is the Phase 1 state of every
seeded row, and a corrupt one means something wrote that column by hand; both
have to mean "no" rather than a 500 on the login route. needs_rehash is there so
raising the cost later is possible at all - login is the only moment the
plaintext exists, so it is the only moment a hash can be upgraded.

2FA is enforced at *creation*, not at login. "Enforced for admin" implemented as
a login-time check means the only admin can be locked out by their own account,
so instead `user add --role admin` enables TOTP by default and prints the
provisioning URI once. --no-totp still works and says loudly that it is against
the TODO 3.0 policy.

TOTP uses pyotp rather than 30 hand-rolled lines, because the two parts that
matter - the constant-time compare and the clock-skew window - are the two
easiest to get quietly wrong. The replay window is documented rather than
pretended away: a code stays valid about 90 seconds, and closing that needs a
last-accepted-counter column this schema does not have.

Accounts are created by CLI, never over HTTP. Public registration and a
"first run" web form are both bootstrap paths that stay reachable forever and
have to be defended forever; shell access on the server is already the trust
boundary. `user passwd` also deletes that user's sessions, since otherwise the
old password keeps working through any browser already signed in, which is the
main reason people change it.

One real bug found while exercising it: reading the password with
rstrip("\n") left the carriage return from a CRLF pipe inside the password, and
Windows PowerShell additionally prepends a UTF-8 BOM when piping to a native
exe. Either one silently creates an account whose password nobody can type,
discoverable only by failing to log in. Both are stripped, with a comment
saying why, because the next person will pipe a password on Windows too.

Mutation-tested the two fail-closed guards: making a missing password hash
verify, and letting a user with no TOTP secret pass the check, each failed
exactly the tests written for them.

Tests: 194 -> 221.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:56:43 +02:00
Thomas KarnerandClaude Opus 5 05f144ed98 Size the connection pool, slow the idle poll, drop a dead setting (REVIEW 7)
The three performance settings the review flagged, one of which turned out
not to exist in any meaningful sense.

db_pool_size 5 -> 15, and max_overflow named explicitly. FastAPI runs this
app's def handlers in anyio's threadpool - 40 threads by default - and each
holds a session for the whole request, so a pool of 5 put the sixth
concurrent request on pool_timeout before it reached the database. The real
ceiling was never 5 either: it was 15, because SQLAlchemy quietly adds
max_overflow=10. Leaving that invisible is the actual hazard, since an
operator raising pool_size has no way to see what they are raising it from,
so both halves are settings now and the arithmetic is written down next to
PostgreSQL's max_connections in the env example. pool_timeout is pinned at
30s rather than inherited: it has to stay finite, or a pool leak presents as
requests hanging forever instead of an error that names the pool.

worker_poll_interval_s 2.0 -> 5.0. This only ever delays noticing a job
enqueued into an empty queue - the loop drains a queue that has work back to
back without sleeping - so it costs latency nobody can perceive on a bird
camera and halves the idle queries, 30 a minute down to 12.

worker_batch_size is removed rather than raised to 5. Nothing read it. It
has sat in Settings since Phase 1 looking like it tuned something while the
worker claimed one job at a time regardless, which is worse than no setting
at all. Implementing it would also be a mistake here: claiming five jobs
marks all five 'running', so dying after the first leaves four locked by a
process that no longer exists and invisible until requeue_stale reaches them
up to fifteen minutes later. Single claims keep exactly one job at risk, and
batching would only have saved claim round-trips on a loopback connection
that no thumbnail decode would notice. The reasoning is at the claim loop,
where the next person will ask.

The test asserts against a pool an engine really built, because comparing
Settings to itself would pass no matter what db.py does. It has to use
values that differ from SQLAlchemy's own defaults - hence 17 and 7 - which
is the point mutation testing earned: with max_overflow unwired the first
version of this test still passed, because the default it fell back to was
10 and the setting also said 10.

Tests: 193 -> 194.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 17:31:43 +02:00
Thomas KarnerandClaude Opus 5 ec9ef9b3a6 Add the thumbnail worker, and stop tests leaking jobs (Phase 2)
Captures now get a WebP thumbnail: 400px on the long edge, written to
thumbs/<uuid>_400.webp (SPEC 3.3). /ingest enqueues the job in the same
transaction as the capture row, so the worker never sees a job for a capture
that was rolled back, and decoding stays off the request path - it is the one
genuinely expensive part of a capture, and the device is waiting with a burst
still to upload.

api/images.py moves up to poorbird/images.py. Both sides use it now, and a
worker importing from api would be the wrong way round. The split by cost
stays: everything the ingest path touches still reads nine bytes of JPEG
header, and Pillow appears only in the thumbnail half.

Handler behaviour is about which failures are worth retrying:

  - An undecodable frame returns rather than raises. The handler contract
    makes a raise mean "retry", and a frame that will never decode should not
    spend three attempts proving it. Logged, thumb_path left NULL.
  - A missing source file raises, because it should be there and a mount that
    has not come back yet is worth retrying for.
  - A capture deleted between enqueue and run is not an error. Retention will
    do that routinely in Phase 5.
  - A malformed payload is validated with a Pydantic model and recorded, not
    retried (SEC-003 applied to a job payload).
  - Never upscales: blowing a 100px frame up to 400px produces a blurry lie.
  - Fills in width/height when the ingest header parse could not. This is the
    first full decode, so it is the chance to fix that.

Verified end to end against a real device row, a real HTTP ingest and the
real worker dispatch path - claim, _run_one, complete - not just the handler
called directly: 1600x1200 JPEG in, WEBP 400x300 on disk, job marked done.
That run is what caught the rest of this commit.

Tests were leaking jobs into the shared queue, which broke test_queue.py once
/ingest started enqueuing. Three separate causes, all the same shape as the
teardown bug fixed in 269a6ea:

  - test_ingest cleaned captures but not their thumbnail jobs, and one test
    hand-rolled teardown for a second device and forgot half of it. Devices
    now come from a fixture that cleans frames, captures and jobs for every
    device a test makes.
  - test_queue claimed jobs without checking they were its own, so a leftover
    thumbnail job could be failed on its behalf, and one test claimed a
    second job to prove the first did not recur and then stranded it in
    'running' forever. It now enqueues at a priority that wins, asserts every
    claim is its own, and releases anything else it touches.

The suite now runs twice in a row leaving zero jobs behind, which is the
assertion that actually matters here.

Tests: 175 -> 193.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 14:49:15 +02:00
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