e142afd24366793f62c6b59fd0fdc8f8503860d8
4
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>
|
||
|
|
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>
|
||
|
|
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
|
||
|
|
8a51e3d95e | Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090) |