Commit Graph
5 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 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 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 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