79ac1d463275697b5a23f8c7c0b2b955c997b94c
5
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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) |