Files
Hello/server
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
..

poorBird server

Phases 1 and 2: configuration, schema, health, job queue, scheduler, and every endpoint the camera calls.

POST /api/v1/enroll                     X-Enroll-Secret, returns a bearer token
POST /api/v1/ingest                     raw JPEG body, metadata in headers
POST /api/v1/heartbeat                  conditions in, envelope + commands out
POST /api/v1/status                     conditions in, 204 out
GET  /api/v1/config                     ~40 optional keys the device merges
POST /api/v1/commands/{id}/ack          204
GET  /api/v1/firmware/{version}.bin     OTA image, exact Content-Length
GET  /api/v1/health

../firmware/API.md is the contract, and it wins over anything here: it is what the firmware already does, and the camera is the side that cannot be patched from a laptop once it is mounted outdoors. The operator half — firmware upload, device management, the gallery — needs user auth and arrives with Phase 3.

Stack per SPEC §6, deployed natively per ../TODO.md Phase 1.2: FastAPI + PostgreSQL 17 + SQLAlchemy 2.0 + Alembic, run as systemd units behind Caddy. No containers — but nothing here blocks them either.


Developing on Windows (uv + Podman)

This is the verified setup on the dev machine. Python is managed by uv, so nothing touches the system PATH or the registry, and PostgreSQL runs in a throwaway Podman container. Neither changes how the project deploys — the app still talks loopback TCP exactly as it will on the server.

winget install astral-sh.uv
uv python install 3.14.7

podman machine start
podman run -d --name poorbird-db -p 127.0.0.1:5432:5432 `
  -e POSTGRES_USER=poorbird -e POSTGRES_PASSWORD=poorbird -e POSTGRES_DB=poorbird `
  docker.io/library/postgres:17

cd server
uv venv --python 3.14.7
uv pip install -e ".[dev]"
# write .env (see the Linux section below; use Windows paths for the roots)

.venv\Scripts\poorbird check
.venv\Scripts\poorbird migrate
.venv\Scripts\python -m pytest

Later sessions only need podman machine start and podman start poorbird-db.

Try it on any Linux machine

Needs Python ≥ 3.11 and a PostgreSQL you can reach. Production targets 3.13; the floor is lower so this runs on a stock Debian 12 or Ubuntu 24.04 box.

sudo apt install -y python3-venv postgresql

sudo -u postgres psql <<'SQL'
CREATE ROLE poorbird LOGIN PASSWORD 'poorbird';
CREATE DATABASE poorbird OWNER poorbird;
SQL

cd server
python3 -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'

cat > .env <<'ENV'
POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird
POORBIRD_IMAGE_ROOT=/tmp/poorbird/images
POORBIRD_THUMB_ROOT=/tmp/poorbird/thumbs
POORBIRD_STATE_DIR=/tmp/poorbird/state
POORBIRD_API_PORT=8090
ENV
mkdir -p /tmp/poorbird/{images,thumbs,state}

poorbird check          # config, paths, database — before starting anything
poorbird migrate        # alembic upgrade head
poorbird serve          # http://127.0.0.1:8090/api/v1/health

In a second shell:

cd server && . .venv/bin/activate
poorbird worker &
poorbird enqueue noop '{"hello": "world"}'   # the worker logs it within ~2s

poorbird check is the fast answer to "is this machine set up correctly" — it validates config, storage paths and database connectivity and prints what it found, without starting a service.

Tests

pytest                  # everything reachable
pytest -m 'not db'      # no PostgreSQL needed

Queue and schema tests need a real PostgreSQL — FOR UPDATE SKIP LOCKED has no equivalent elsewhere, and mocking it would test nothing. They skip automatically when the database is unreachable, so a green run with no Postgres proves less than it looks. Check for skipped in the summary; a complete run is 12 passed, 0 skipped.

test_schema_matches_models.py creates and drops a poorbird_schema_check database on the same server. It needs a role that may CREATE DATABASE.


Layout

src/poorbird/
  config.py          every value from the environment, nothing baked in
  logging_setup.py   stdout only; journald or a log driver catches it
  db.py              engine + session factory (sync, deliberately)
  models/            SPEC §3 schema + the SPEC §0 additions
  images.py          JPEG sniffing, atomic writes, thumbnails
  api/               FastAPI app, device routes, auth, rate limiting
  worker/            queue (SKIP LOCKED), handlers, scheduler
  cli.py             serve | worker | migrate | check | enqueue
migrations/          Alembic
deploy/              systemd units, Caddyfile, env template, INSTALL.md
tests/

Decisions worth knowing before you read the code

Sync SQLAlchemy, not async. At one camera and a few thousand frames a day the async machinery buys nothing and costs clarity, and the worker's claim loop is far easier to reason about synchronously. FastAPI runs def handlers in a threadpool, so this does not block the event loop. The one thing that may argue otherwise later is the MJPEG relay in Phase 6.

Device config is one JSONB column, not forty. GET /config returns ~40 optional keys and the firmware merges and clamps partial documents, so a column per key would mean a migration every time the firmware gains a tunable. Validation belongs in a Pydantic model, not in the DDL. The trade: you cannot index or constrain an individual setting in SQL. If one ever needs querying across devices, promote just that key to a column.

Server defaults are compared through a normaliser. Postgres reflects a varchar default as 'viewer'::character varying while the model renders 'viewer'. Compared literally, every string default in the schema reads as drift forever — which trains you to ignore the one time it isn't. See schema_compare.py; autogenerate and the drift test share it, so the tool and the test can never disagree about what counts as a difference.

Migration 0001 builds from Base.metadata. A bounded exception, and tests/test_schema_matches_models.py migrates a scratch database and asserts an empty autogenerate diff, so the models and the migration cannot silently diverge. Every later revision is a normal autogenerated one. If you prefer explicit DDL in the baseline, autogenerate it against an empty database and replace the file — the drift test passes either way.

The scheduler only enqueues, never executes. Every unit of work goes through the queue, where it is visible, retried and auditable, rather than running inside a timer callback where a failure disappears.


Two things the code already guards, and the UI must too

  • battery_valid = false means not measured — no divider is wired by default. Render it as "—", never as a low-battery alarm.
  • The daily counters live in the device's RTC memory and reset on power loss. captures is authoritative. The counters' value is the gap between captured and delivered, which is an upload-health signal.

Deploying for real

See deploy/INSTALL.md.