develop
7
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
6907d9a014 |
Add a front door, a user guide in two languages, and an honest list of what is broken
Four documents and two fixes to the deploy directory that the documents exposed while being written. The repo had no root README. Cloning it landed you on a 40 KB spec and a 24 KB plan with nothing to orient you, which mattered more once main stopped being an empty branch. The new one links rather than duplicates, and its status table says plainly what has never run on hardware and that there are no backups. docs/README.USER.md and its German twin are written for someone who will use this, not build it: what radar buys over a PIR sensor, why there is no sign-up page, what "pre-trigger" means, what to do when the six-digit code is refused. Every POORBIRD_* setting is described in plain language, including the two that cost an hour each the first time they bite. The German version is a translation, not a mechanical flip of the English. docs/OPEN-TOPICS.AI.md is the list nobody writes: unfixed security issues, traps, and test debt, each labelled ACCEPTED, OPEN or TRAP, because the difference between "known trade-off" and "not done yet" is the only thing that makes such a list usable. It ends with a section of things that are NOT problems -- the SHA-256/Argon2id split, the frozen 0001 migration, the finite pool_timeout -- so they stop being rediscovered and "fixed". Two real defects surfaced while documenting the install: Nothing served the WebUI in production. The Caddyfile's human-facing block only reverse-proxied to FastAPI, and FastAPI mounts no static files, so a by-the-book install produced a working API and no gallery. It now has a file_server with a try_files fallback, because the router does client-side routing and without it only the entry page survives a reload. INSTALL.md never created an account. With no sign-up endpoint, following it end to end left you at a login form with no credentials that work -- the exact wall hit on the dev machine today, and worse on a headless host. It also never built or copied the UI, so a git pull on the server silently kept the old bundle; that is now its own step, with --delete spelled out because Vite emits content-hashed filenames. Verified: caddy validate via the official caddy:2 image reports "Valid configuration" (with the cloudflare-DNS block stripped, since that plugin is not in the stock image and the block is unchanged); npm run build is clean at 192 modules; all 31 relative links across every .md resolve; the committed line endings are LF, so caddy fmt's complaint was my working tree only. Not verified: none of the install has run on a real host. The doc says so. One claim was wrong before it shipped: both guides said signing out ends every session everywhere. logout calls revoke_session for the current token only -- revoke_all_for_user exists but is not called there -- so it ends that browser's session alone, and `user passwd` is what clears them all. Corrected in both languages. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
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> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
8a51e3d95e | Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090) |