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>
This commit is contained in:
Thomas KarnerandClaude Opus 5 committed 2026-09-21 18:17:29 +02:00
1 parent 9c44ab6b2a
commit 0c3fb2d837
16 files changed
+1796 -21

No files matched your search

+15
View File
@@ -45,6 +45,21 @@ POORBIRD_STATE_DIR=/var/lib/poorbird
# Rotating it here WITHOUT shipping new firmware removes that escape hatch.
POORBIRD_ENROLL_SECRET=
# --- user sessions ----------------------------------------------------------
# How long a signed-in browser stays signed in. SPEC 3.4 makes this a
# UI-editable server setting eventually; for now it is here.
POORBIRD_SESSION_LIFETIME_H=336
# Leave this TRUE in production. Caddy always terminates HTTPS, so the cookie
# can and must be Secure.
#
# Set it false ONLY for local development against the Vite dev server, which is
# plain http on localhost. A Secure cookie is silently discarded by the browser
# over http, and the symptom is "login returns 200 but I am never signed in",
# with nothing in any log to explain it. That is the only reason this is a
# setting rather than a constant.
POORBIRD_SESSION_COOKIE_SECURE=true
# --- rate limiting ------------------------------------------------------------
# In-process token buckets. Sized for ONE uvicorn process: if you ever run the
# API with workers, each gets its own buckets and the effective limit
+506 -19
View File
@@ -1,32 +1,34 @@
"""Baseline schema: SPEC 3 plus the SPEC 0 additions.
Explicit DDL, and frozen.
This revision used to call ``Base.metadata.create_all()``. That could not drift
from the models, which was the point, but it also meant a fresh database got
the *current* models here and then had every later migration applied on top of
what it had already created -- so the first revision added after it failed with
"column token_hash of relation sessions already exists".
``tests/test_schema_matches_models.py`` caught that the moment one was added,
which is the only reason it did not reach a deployment.
So the baseline is now what Alembic expects a baseline to be: the schema as it
stood at the end of Phase 1, and nothing after it. Later revisions change it.
**Do not edit this file to reflect a model change -- add a revision.** Editing
it would reintroduce exactly the failure above, for anyone whose database is
already past this point.
Revision ID: 0001
Revises:
Create Date: 2026-09-20
This baseline builds the schema from ``Base.metadata`` rather than from
hand-written DDL. That is a deliberate, bounded exception, and it applies to
this revision only:
* it cannot drift from the models, which hand-written DDL silently can;
* ``tests/test_schema_matches_models.py`` asserts that a freshly migrated
database produces an empty autogenerate diff, so the guarantee is checked
rather than assumed;
* every subsequent revision is a normal autogenerated one with real
``op.*`` operations.
If you would rather have explicit DDL here, run
``alembic revision --autogenerate`` against an empty database once Postgres is
up and replace this file with the result. The drift test passes either way.
"""
from __future__ import annotations
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
from poorbird.models import Base
from sqlalchemy.dialects import postgresql
revision: str = "0001"
down_revision: str | None = None
@@ -35,8 +37,493 @@ depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
Base.metadata.create_all(bind=op.get_bind())
op.create_table(
"backup_runs",
sa.Column("id", sa.BigInteger(), nullable=False),
sa.Column(
"started_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("status", sa.String(length=16), nullable=False),
sa.Column("bytes", sa.BigInteger(), nullable=True),
sa.Column("snapshot_id", sa.String(length=64), nullable=True),
sa.Column("restore_tested_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
sa.PrimaryKeyConstraint("id", name=op.f("pk_backup_runs")),
)
op.create_table(
"devices",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("device_uid", sa.String(length=32), nullable=False),
sa.Column("name", sa.String(length=64), nullable=False),
sa.Column("mac", sa.String(length=32), nullable=True),
sa.Column("hw_revision", sa.String(length=64), nullable=True),
sa.Column("fw_version", sa.String(length=32), nullable=True),
sa.Column("token_hash", sa.String(length=128), nullable=True),
sa.Column("reenroll_secret_hash", sa.String(length=128), nullable=True),
sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("battery_mv", sa.Integer(), nullable=True),
sa.Column("battery_pct", sa.Integer(), nullable=True),
sa.Column("battery_valid", sa.Boolean(), nullable=False),
sa.Column("rssi", sa.Integer(), nullable=True),
sa.Column("temp_c", sa.Float(), nullable=True),
sa.Column("awake", sa.Boolean(), nullable=False),
sa.Column(
"config", postgresql.JSONB(astext_type=sa.Text()), server_default="{}", nullable=False
),
sa.Column("config_version", sa.Integer(), server_default="1", nullable=False),
sa.Column("heartbeat_interval_s", sa.Integer(), server_default="300", nullable=False),
sa.Column("status_interval_s", sa.Integer(), server_default="900", nullable=False),
sa.Column("responsive_mode", sa.Boolean(), server_default="false", nullable=False),
sa.Column("enabled", sa.Boolean(), server_default="true", nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_devices")),
)
op.create_index(op.f("ix_devices_device_uid"), "devices", ["device_uid"], unique=True)
op.create_index(op.f("ix_devices_token_hash"), "devices", ["token_hash"], unique=True)
op.create_table(
"jobs",
sa.Column("id", sa.BigInteger(), nullable=False),
sa.Column("kind", sa.String(length=64), nullable=False),
sa.Column(
"payload", postgresql.JSONB(astext_type=sa.Text()), server_default="{}", nullable=False
),
sa.Column("status", sa.String(length=16), server_default="queued", nullable=False),
sa.Column("priority", sa.Integer(), server_default="0", nullable=False),
sa.Column(
"run_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False
),
sa.Column("attempts", sa.Integer(), server_default="0", nullable=False),
sa.Column("max_attempts", sa.Integer(), server_default="3", nullable=False),
sa.Column("locked_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("locked_by", sa.String(length=128), nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint(
"status IN ('queued', 'running', 'done', 'failed')", name=op.f("ck_jobs_status_valid")
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_jobs")),
)
op.create_index("ix_jobs_claimable", "jobs", ["status", "run_at", "priority"], unique=False)
op.create_table(
"tags",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("label", sa.String(length=64), nullable=False),
sa.Column("colour", sa.String(length=16), nullable=True),
sa.PrimaryKeyConstraint("id", name=op.f("pk_tags")),
sa.UniqueConstraint("label", name=op.f("uq_tags_label")),
)
op.create_table(
"taxa",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("gbif_key", sa.BigInteger(), nullable=True),
sa.Column("scientific_name", sa.String(length=128), nullable=False),
sa.Column("name_de", sa.String(length=128), nullable=True),
sa.Column("name_en", sa.String(length=128), nullable=True),
sa.Column("family", sa.String(length=64), nullable=True),
sa.Column("order", sa.String(length=64), nullable=True),
sa.Column("iucn_status", sa.String(length=8), nullable=True),
sa.Column("is_local_common", sa.Boolean(), server_default="false", nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_taxa")),
sa.UniqueConstraint("gbif_key", name=op.f("uq_taxa_gbif_key")),
sa.UniqueConstraint("scientific_name", name=op.f("uq_taxa_scientific_name")),
)
op.create_index(op.f("ix_taxa_name_de"), "taxa", ["name_de"], unique=False)
op.create_index(op.f("ix_taxa_name_en"), "taxa", ["name_en"], unique=False)
op.create_table(
"users",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("username", sa.String(length=64), nullable=False),
sa.Column("email", sa.String(length=255), nullable=True),
sa.Column("password_hash", sa.String(length=255), nullable=True),
sa.Column("role", sa.String(length=16), server_default="viewer", nullable=False),
sa.Column("totp_secret", sa.String(length=64), nullable=True),
sa.Column("is_active", sa.Boolean(), server_default="true", nullable=False),
sa.Column("theme", sa.String(length=16), server_default="light", nullable=False),
sa.Column("locale", sa.String(length=8), server_default="de", nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("last_login_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint(
"role IN ('admin', 'editor', 'viewer')", name=op.f("ck_users_role_valid")
),
sa.CheckConstraint("theme IN ('light', 'dark', 'blue')", name=op.f("ck_users_theme_valid")),
sa.PrimaryKeyConstraint("id", name=op.f("pk_users")),
sa.UniqueConstraint("username", name=op.f("uq_users_username")),
)
op.create_table(
"audit_log",
sa.Column("id", sa.BigInteger(), nullable=False),
sa.Column(
"at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False
),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("action", sa.String(length=64), nullable=False),
sa.Column("entity", sa.String(length=64), nullable=False),
sa.Column("entity_id", sa.String(length=64), nullable=True),
sa.Column("before", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column("after", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column("ip", sa.String(length=45), nullable=True),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name=op.f("fk_audit_log_user_id_users"), ondelete="SET NULL"
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_audit_log")),
)
op.create_index("ix_audit_log_entity", "audit_log", ["entity", "entity_id", "at"], unique=False)
op.create_table(
"captures",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("device_id", sa.Integer(), nullable=False),
sa.Column("path", sa.Text(), nullable=False),
sa.Column("thumb_path", sa.Text(), nullable=True),
sa.Column("sha256", sa.String(length=64), nullable=False),
sa.Column("width", sa.Integer(), nullable=True),
sa.Column("height", sa.Integer(), nullable=True),
sa.Column("bytes", sa.BigInteger(), nullable=False),
sa.Column("captured_at_device", sa.DateTime(timezone=True), nullable=True),
sa.Column(
"received_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("trigger", sa.String(length=16), nullable=False),
sa.Column("burst_id", sa.String(length=64), nullable=True),
sa.Column("burst_index", sa.Integer(), nullable=True),
sa.Column("burst_count", sa.Integer(), nullable=True),
sa.Column("pre_trigger", sa.Boolean(), server_default="false", nullable=False),
sa.Column("frame_seq", sa.Integer(), nullable=True),
sa.Column("radar_state", sa.Integer(), nullable=True),
sa.Column("radar_distance_cm", sa.Integer(), nullable=True),
sa.Column("radar_energy", sa.Integer(), nullable=True),
sa.Column("battery_mv", sa.Integer(), nullable=True),
sa.Column("rssi", sa.Integer(), nullable=True),
sa.Column("temp_c", sa.Float(), nullable=True),
sa.Column("reviewed", sa.Boolean(), server_default="false", nullable=False),
sa.Column("kept", sa.Boolean(), server_default="true", nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"trigger IN ('radar', 'manual', 'timer', 'stream_grab')",
name=op.f("ck_captures_trigger_valid"),
),
sa.ForeignKeyConstraint(
["device_id"],
["devices.id"],
name=op.f("fk_captures_device_id_devices"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_captures")),
)
op.create_index("ix_captures_burst", "captures", ["burst_id", "burst_index"], unique=False)
op.create_index(
"ix_captures_device_received", "captures", ["device_id", "received_at"], unique=False
)
op.create_index(op.f("ix_captures_sha256"), "captures", ["sha256"], unique=False)
op.create_index(
"ix_captures_triage", "captures", ["kept", "reviewed", "received_at"], unique=False
)
op.create_table(
"device_commands",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("device_id", sa.Integer(), nullable=False),
sa.Column("type", sa.String(length=32), nullable=False),
sa.Column("payload", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("acked_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("ack_status", sa.String(length=16), nullable=True),
sa.Column("result", sa.Text(), nullable=True),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint(
"ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')",
name=op.f("ck_device_commands_ack_status_valid"),
),
sa.CheckConstraint(
"type IN ('apply_config', 'capture_now', 'report_status', 'wake_and_hold', 'sleep_now', 'stream_start', 'stream_stop', 'ota_update', 'reboot')",
name=op.f("ck_device_commands_type_valid"),
),
sa.ForeignKeyConstraint(
["created_by"],
["users.id"],
name=op.f("fk_device_commands_created_by_users"),
ondelete="SET NULL",
),
sa.ForeignKeyConstraint(
["device_id"],
["devices.id"],
name=op.f("fk_device_commands_device_id_devices"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_device_commands")),
)
op.create_index(
"ix_device_commands_pending", "device_commands", ["device_id", "created_at"], unique=False
)
op.create_table(
"device_status",
sa.Column("id", sa.BigInteger(), nullable=False),
sa.Column("device_id", sa.Integer(), nullable=False),
sa.Column(
"at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False
),
sa.Column("reason", sa.String(length=32), nullable=False),
sa.Column("battery_mv", sa.Integer(), nullable=True),
sa.Column("battery_pct", sa.Integer(), nullable=True),
sa.Column("battery_valid", sa.Boolean(), nullable=True),
sa.Column("awake_ms", sa.BigInteger(), nullable=True),
sa.Column("boot_count", sa.Integer(), nullable=True),
sa.Column("wake_cause", sa.String(length=16), nullable=True),
sa.Column("last_sleep_s", sa.Integer(), nullable=True),
sa.Column("total_sleep_s", sa.BigInteger(), nullable=True),
sa.Column("captured_today", sa.Integer(), nullable=True),
sa.Column("delivered_today", sa.Integer(), nullable=True),
sa.Column("failed_today", sa.Integer(), nullable=True),
sa.Column("events_today", sa.Integer(), nullable=True),
sa.Column("day_index", sa.Integer(), nullable=True),
sa.Column("is_night", sa.Boolean(), nullable=True),
sa.Column("nightlight_on", sa.Boolean(), nullable=True),
sa.Column("cam_profile", sa.String(length=16), nullable=True),
sa.Column("radar_baud", sa.Integer(), nullable=True),
sa.Column("radar_uart_ok", sa.Boolean(), nullable=True),
sa.Column("stream_active", sa.Boolean(), nullable=True),
sa.Column("rssi", sa.Integer(), nullable=True),
sa.Column("ip", sa.String(length=45), nullable=True),
sa.Column("free_heap", sa.BigInteger(), nullable=True),
sa.Column("free_psram", sa.BigInteger(), nullable=True),
sa.Column("ring_depth", sa.Integer(), nullable=True),
sa.Column("time_synced", sa.Boolean(), nullable=True),
sa.Column("device_time", sa.DateTime(timezone=True), nullable=True),
sa.Column("fw_version", sa.String(length=32), nullable=True),
sa.Column("config_version", sa.Integer(), nullable=True),
sa.Column("raw", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.CheckConstraint(
"reason IN ('heartbeat', 'periodic', 'after_event', 'before_sleep', 'before_night_sleep', 'on_request')",
name=op.f("ck_device_status_reason_valid"),
),
sa.ForeignKeyConstraint(
["device_id"],
["devices.id"],
name=op.f("fk_device_status_device_id_devices"),
ondelete="CASCADE",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_device_status")),
)
op.create_index(
"ix_device_status_device_at", "device_status", ["device_id", "at"], unique=False
)
op.create_table(
"firmware",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("version", sa.String(length=32), nullable=False),
sa.Column("semver", sa.String(length=32), nullable=True),
sa.Column("file_path", sa.Text(), nullable=False),
sa.Column("sha256", sa.String(length=64), nullable=False),
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
sa.Column("release_notes", sa.Text(), nullable=True),
sa.Column("min_battery_pct", sa.Integer(), server_default="50", nullable=False),
sa.Column("uploaded_by", sa.Integer(), nullable=True),
sa.Column(
"uploaded_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("is_target", sa.Boolean(), server_default="false", nullable=False),
sa.ForeignKeyConstraint(
["uploaded_by"],
["users.id"],
name=op.f("fk_firmware_uploaded_by_users"),
ondelete="SET NULL",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_firmware")),
sa.UniqueConstraint("version", name=op.f("uq_firmware_version")),
)
op.create_table(
"sessions",
sa.Column("id", sa.Uuid(), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("ip", sa.String(length=45), nullable=True),
sa.Column("user_agent", sa.String(length=255), nullable=True),
sa.ForeignKeyConstraint(
["user_id"], ["users.id"], name=op.f("fk_sessions_user_id_users"), ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_sessions")),
)
op.create_index(op.f("ix_sessions_expires_at"), "sessions", ["expires_at"], unique=False)
op.create_index(op.f("ix_sessions_user_id"), "sessions", ["user_id"], unique=False)
op.create_table(
"settings",
sa.Column("key", sa.String(length=64), nullable=False),
sa.Column("value", sa.Text(), nullable=True),
sa.Column("value_type", sa.String(length=16), server_default="str", nullable=False),
sa.Column("scope", sa.String(length=16), server_default="server", nullable=False),
sa.Column("updated_by", sa.Integer(), nullable=True),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint("scope IN ('server', 'device')", name=op.f("ck_settings_scope_valid")),
sa.ForeignKeyConstraint(
["updated_by"],
["users.id"],
name=op.f("fk_settings_updated_by_users"),
ondelete="SET NULL",
),
sa.PrimaryKeyConstraint("key", name=op.f("pk_settings")),
)
op.create_table(
"capture_tags",
sa.Column("capture_id", sa.Uuid(), nullable=False),
sa.Column("tag_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["capture_id"],
["captures.id"],
name=op.f("fk_capture_tags_capture_id_captures"),
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["tag_id"], ["tags.id"], name=op.f("fk_capture_tags_tag_id_tags"), ondelete="CASCADE"
),
sa.PrimaryKeyConstraint("capture_id", "tag_id", name=op.f("pk_capture_tags")),
)
op.create_table(
"observations",
sa.Column("id", sa.BigInteger(), nullable=False),
sa.Column("capture_id", sa.Uuid(), nullable=False),
sa.Column("taxon_id", sa.Integer(), nullable=True),
sa.Column("individuals", sa.Integer(), server_default="1", nullable=False),
sa.Column("age", sa.String(length=16), server_default="unknown", nullable=False),
sa.Column("sex", sa.String(length=16), server_default="unknown", nullable=False),
sa.Column("behaviour", sa.String(length=16), nullable=True),
sa.Column("certainty", sa.String(length=16), server_default="certain", nullable=False),
sa.Column("notes", sa.Text(), nullable=True),
sa.Column("source", sa.String(length=8), server_default="human", nullable=False),
sa.Column("model_version", sa.String(length=64), nullable=True),
sa.Column("confidence", sa.Float(), nullable=True),
sa.Column("bbox", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(timezone=True),
server_default=sa.text("now()"),
nullable=False,
),
sa.CheckConstraint(
"age IN ('adult', 'juvenile', 'unknown')", name=op.f("ck_observations_age_valid")
),
sa.CheckConstraint(
"behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')",
name=op.f("ck_observations_behaviour_valid"),
),
sa.CheckConstraint(
"certainty IN ('certain', 'probable', 'uncertain')",
name=op.f("ck_observations_certainty_valid"),
),
sa.CheckConstraint(
"sex IN ('male', 'female', 'unknown')", name=op.f("ck_observations_sex_valid")
),
sa.CheckConstraint(
"source IN ('human', 'model')", name=op.f("ck_observations_source_valid")
),
sa.ForeignKeyConstraint(
["capture_id"],
["captures.id"],
name=op.f("fk_observations_capture_id_captures"),
ondelete="CASCADE",
),
sa.ForeignKeyConstraint(
["created_by"],
["users.id"],
name=op.f("fk_observations_created_by_users"),
ondelete="SET NULL",
),
sa.ForeignKeyConstraint(
["taxon_id"],
["taxa.id"],
name=op.f("fk_observations_taxon_id_taxa"),
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_observations")),
)
op.create_index(
op.f("ix_observations_capture_id"), "observations", ["capture_id"], unique=False
)
# ### end Alembic commands ###
def downgrade() -> None:
Base.metadata.drop_all(bind=op.get_bind())
op.drop_index(op.f("ix_observations_capture_id"), table_name="observations")
op.drop_table("observations")
op.drop_table("capture_tags")
op.drop_table("settings")
op.drop_index(op.f("ix_sessions_user_id"), table_name="sessions")
op.drop_index(op.f("ix_sessions_expires_at"), table_name="sessions")
op.drop_table("sessions")
op.drop_table("firmware")
op.drop_index("ix_device_status_device_at", table_name="device_status")
op.drop_table("device_status")
op.drop_index("ix_device_commands_pending", table_name="device_commands")
op.drop_table("device_commands")
op.drop_index("ix_captures_triage", table_name="captures")
op.drop_index(op.f("ix_captures_sha256"), table_name="captures")
op.drop_index("ix_captures_device_received", table_name="captures")
op.drop_index("ix_captures_burst", table_name="captures")
op.drop_table("captures")
op.drop_index("ix_audit_log_entity", table_name="audit_log")
op.drop_table("audit_log")
op.drop_table("users")
op.drop_index(op.f("ix_taxa_name_en"), table_name="taxa")
op.drop_index(op.f("ix_taxa_name_de"), table_name="taxa")
op.drop_table("taxa")
op.drop_table("tags")
op.drop_index("ix_jobs_claimable", table_name="jobs")
op.drop_table("jobs")
op.drop_index(op.f("ix_devices_token_hash"), table_name="devices")
op.drop_index(op.f("ix_devices_device_uid"), table_name="devices")
op.drop_table("devices")
op.drop_table("backup_runs")
# ### end Alembic commands ###
@@ -0,0 +1,53 @@
"""session token hash and csrf token
The cookie stops being the primary key. ``sessions.id`` becomes internal and the
browser carries a separate token of which only the SHA-256 is stored, so a
database dump no longer hands over every live session. ``csrf_token`` is per
session, which is what stops the double-submit check being satisfiable by
someone who can merely set a cookie on the domain.
Both columns are NOT NULL with no default, and that is deliberate: there is no
value that could be back-filled. A session row without a token hash cannot be
looked up by any request, so it is not a session -- it is a row that would sit
there until it expired. Existing rows are therefore deleted rather than given a
placeholder hash, which would be a credential nobody holds and the unique index
would reject on the second row anyway.
In practice this table is empty: nothing before Phase 3 ever wrote a session.
The DELETE is here so the migration is also correct on a database where that
turns out not to be true.
Revision ID: c00181d246b9
Revises: 0001
Create Date: 2026-09-21 17:57:33.783616
"""
from __future__ import annotations
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
revision: str = "c00181d246b9"
down_revision: str | None = "0001"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
# Any pre-existing row is unusable under the new scheme; signing those
# browsers out is the correct outcome, not a loss.
op.execute("DELETE FROM sessions")
op.add_column("sessions", sa.Column("token_hash", sa.String(length=64), nullable=False))
op.add_column("sessions", sa.Column("csrf_token", sa.String(length=64), nullable=False))
op.create_index(op.f("ix_sessions_token_hash"), "sessions", ["token_hash"], unique=True)
def downgrade() -> None:
# Going back makes every session unauthenticatable for the same reason, so
# clear them here too rather than leaving rows that resolve to nothing.
op.drop_index(op.f("ix_sessions_token_hash"), table_name="sessions")
op.drop_column("sessions", "csrf_token")
op.drop_column("sessions", "token_hash")
op.execute("DELETE FROM sessions")
+7
View File
@@ -53,3 +53,10 @@ src = ["src"]
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.ruff.lint.per-file-ignores]
# Migrations are generated, then linted like everything else -- except for line
# length. The over-long lines are CHECK constraint bodies, which are SQL string
# literals: wrapping one means editing the constraint, and a migration that has
# already run is not a file to edit for tidiness.
"migrations/versions/*.py" = ["E501"]
+12 -1
View File
@@ -8,7 +8,8 @@ from fastapi import FastAPI
from .. import __version__
from ..config import get_settings
from ..logging_setup import configure_logging
from .routes import commands, conditions, device_config, enroll, firmware, health, ingest
from .routes import auth, commands, conditions, device_config, enroll, firmware, health, ingest
from .userauth import csrf_middleware
log = logging.getLogger(__name__)
@@ -41,9 +42,19 @@ def create_app() -> FastAPI:
lifespan=lifespan,
)
# CSRF for cookie-authenticated mutations. Middleware rather than a
# per-route dependency so a new endpoint cannot forget it; it applies only
# to unsafe methods on requests that carry the session cookie, which is why
# the device endpoints -- bearer tokens, no cookies -- are unaffected. See
# userauth.csrf_middleware.
app.middleware("http")(csrf_middleware)
app.include_router(health.router, prefix=API_PREFIX, tags=["health"])
app.include_router(health.root_router)
# Phase 3 WebUI endpoints.
app.include_router(auth.router, prefix=API_PREFIX)
# Phase 2 device endpoints. See firmware/API.md for the contract.
app.include_router(enroll.router, prefix=API_PREFIX)
app.include_router(conditions.router, prefix=API_PREFIX)
+10
View File
@@ -189,3 +189,13 @@ ACK = Limit.per_minute(30, burst=15)
# Whole firmware images. Expensive to serve, and a device needs one rarely;
# a loop here would be a device failing verification over and over.
FIRMWARE = Limit.per_hour(12, burst=3)
# --- people -----------------------------------------------------------------
# Login is the one endpoint where the secret is human-chosen and therefore
# guessable, so this is a real control rather than abuse protection. A person
# mistyping a password needs a handful of tries in quick succession; nobody
# needs sixty an hour. Argon2 already makes each attempt cost tens of
# milliseconds of CPU, which is itself a reason to cap the rate: without this,
# the login endpoint is also the cheapest way to spend the server's CPU.
LOGIN = Limit.per_hour(30, burst=8)
+216
View File
@@ -0,0 +1,216 @@
"""Sign in, sign out, and "who am I" (SPEC 3.1, REVIEW SEC-007).
The three endpoints ``web/src/auth/AuthProvider.tsx`` was written against, and
the ones it distinguishes carefully: a 404 there means "the server has no auth
yet" and shows a banner, whereas a 401 means "not signed in". Now that these
exist, 404 stops happening and the banner goes away.
There is no registration endpoint, on purpose. Accounts come from
``poorbird user add`` -- see the note in cli.py.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from sqlalchemy import select
from sqlalchemy.orm import Session as DbSession
from ...models import AuditLog, User
from ...passwords import hash_password, needs_rehash, verify_password
from ...totp import verify as verify_totp
from .. import ratelimit
from ..deps import DbDep, SettingsDep
from ..ratelimit import client_address
from ..sessions import (
SESSION_COOKIE,
clear_session_cookies,
create_session,
resolve_session,
revoke_session,
set_session_cookies,
)
from ..ui_schemas import LoginRequest, SessionUser
from ..userauth import SessionDep
log = logging.getLogger(__name__)
router = APIRouter(prefix="/auth", tags=["auth"])
def _as_session_user(user: User) -> SessionUser:
return SessionUser(
id=user.id,
username=user.username,
role=user.role,
locale=user.locale,
theme=user.theme,
)
def _audit(
db: DbSession,
*,
action: str,
user_id: int | None,
ip: str | None,
detail: dict | None = None,
) -> None:
"""Record an auth event (SPEC 3.1: audit_log on every mutation).
Failed attempts are recorded as well as successful ones. A log of only the
successes cannot answer the one question worth asking afterwards, which is
how many times someone tried before getting in.
"""
db.add(
AuditLog(
user_id=user_id,
action=action,
entity="session",
entity_id=str(user_id) if user_id is not None else None,
after=detail,
ip=ip[:45] if ip else None,
)
)
@router.post(
"/login",
response_model=SessionUser,
summary="Sign in and open a session",
# By address, not by username: keying on the username would let an attacker
# lock a known account out by failing at it deliberately, turning a rate
# limit into a denial of service against exactly the person it protects.
dependencies=[Depends(ratelimit.by_address("login", ratelimit.LOGIN))],
)
def login(
body: LoginRequest,
request: Request,
response: Response,
db: DbDep,
settings: SettingsDep,
) -> SessionUser:
"""Verify a password and optional TOTP code, then set the session cookies.
Every failure answers with the same 401 and the same message. Saying "no
such user" would confirm which usernames exist, and saying "wrong code"
would confirm that the password was right -- which is most of what an
attacker wanted to know.
"""
ip = client_address(request)
rejected = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials",
)
user = db.scalar(select(User).where(User.username == body.username))
# Verify against a hash even when there is no such user, by hashing the
# submitted password and throwing it away. Returning early would make a
# missing username measurably faster than a wrong password, which is a
# username oracle built out of timing.
stored = user.password_hash if user is not None else hash_password(body.password)
password_ok = verify_password(body.password, stored)
if user is None or not password_ok:
_audit(
db,
action="login_failed",
user_id=user.id if user is not None else None,
ip=ip,
detail={"username": body.username, "reason": "credentials"},
)
db.commit()
log.warning("login failed", extra={"username": body.username, "ip": ip})
raise rejected
if not user.is_active:
_audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "inactive"})
db.commit()
log.warning("login refused, account inactive", extra={"username": user.username, "ip": ip})
raise rejected
# TOTP is required exactly when the account has a secret. The policy that
# admins must have one is enforced at account creation (cli.py), not here:
# enforcing it at login would let the only admin be locked out by their own
# account, with no way back in through the UI.
if user.totp_secret and not verify_totp(user.totp_secret, body.totp):
_audit(db, action="login_failed", user_id=user.id, ip=ip, detail={"reason": "totp"})
db.commit()
log.warning("login failed on second factor", extra={"username": user.username, "ip": ip})
raise rejected
# Login is the only moment the plaintext password exists, so it is the only
# moment the hash can be upgraded to current parameters.
if needs_rehash(user.password_hash or ""):
user.password_hash = hash_password(body.password)
log.info("password hash upgraded", extra={"username": user.username})
token, csrf = create_session(
db,
user,
settings=settings,
ip=ip,
user_agent=request.headers.get("user-agent"),
)
user.last_login_at = datetime.now(UTC)
_audit(db, action="login", user_id=user.id, ip=ip, detail={"totp": bool(user.totp_secret)})
db.commit()
set_session_cookies(response, token, csrf, settings=settings)
log.info("login", extra={"username": user.username, "role": user.role, "ip": ip})
return _as_session_user(user)
@router.post(
"/logout",
status_code=status.HTTP_204_NO_CONTENT,
summary="End the current session",
)
def logout(
request: Request,
response: Response,
db: DbDep,
settings: SettingsDep,
) -> None:
"""Delete the session row and clear both cookies.
Deliberately succeeds whether or not there was a session. Signing out is
something a client should always be able to do, and a 401 here would leave a
browser holding a cookie it cannot get rid of.
The row is deleted rather than flagged, which is what makes this immediate:
the next request cannot resolve a session that is gone. That is the whole
reason sessions are server-side rather than a self-contained token.
"""
token = request.cookies.get(SESSION_COOKIE)
resolved = resolve_session(db, token) if token else None
revoke_session(db, token)
if resolved is not None:
_audit(db, action="logout", user_id=resolved[1].id, ip=client_address(request))
log.info("logout", extra={"username": resolved[1].username})
db.commit()
# Cookies are set on the injected Response, whose headers FastAPI merges
# into the 204 it sends. Returning a fresh Response here instead would
# discard them, and the logout would appear to work without clearing
# anything.
clear_session_cookies(response, settings=settings)
@router.get(
"/session",
response_model=SessionUser,
summary="The signed-in user, or 401",
)
def whoami(resolved: SessionDep) -> SessionUser:
"""401 when not signed in, which the UI treats as "anonymous".
Not 200-with-null: the client already distinguishes 401 (signed out) from
404 (no auth on this server), and a 200 carrying null would collapse a
working server into the same shape as one that has no auth at all.
"""
return _as_session_user(resolved[1])
+181
View File
@@ -0,0 +1,181 @@
"""Server-side sessions for the WebUI (SPEC 3.1, REVIEW SEC-007).
Cookies, not JWTs, and the session state lives in Postgres. The reason is
revocation: signing a user out, or ending every session when their password
changes, has to take effect immediately. A self-contained token cannot be
withdrawn before it expires without keeping a deny-list, which is the database
lookup it was supposed to avoid.
The cookie value is a 64-hex token; only its SHA-256 is stored. It reuses
``deps.new_credential``/``hash_credential`` rather than growing a second
implementation of the same idea -- device tokens and session tokens have the
same shape and the same reasoning behind a fast hash: both are CSPRNG output,
not passwords.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
from fastapi import Response
from sqlalchemy import delete, select
from sqlalchemy.orm import Session as DbSession
from ..config import Settings
from ..models import Session as UserSession
from ..models import User
from .deps import hash_credential, new_credential
log = logging.getLogger(__name__)
SESSION_COOKIE = "poorbird_session"
CSRF_COOKIE = "poorbird_csrf"
CSRF_HEADER = "x-csrf-token"
# Lax, not Strict. Strict would also suppress the cookie when someone follows
# an ordinary link into the app from anywhere else, so they arrive apparently
# signed out and sign in again for no reason. Lax still withholds the cookie
# from cross-site POST, which is the CSRF case that matters, and the per-session
# token below covers the rest.
SAMESITE = "lax"
def create_session(
db: DbSession,
user: User,
*,
settings: Settings,
ip: str | None = None,
user_agent: str | None = None,
) -> tuple[str, str]:
"""Open a session for ``user``. Returns ``(session_token, csrf_token)``.
Both are returned in plaintext exactly once, here, and only hashes or
per-session values are persisted. The caller is responsible for putting
them in cookies and for committing.
"""
token = new_credential()
csrf = new_credential()
db.add(
UserSession(
user_id=user.id,
token_hash=hash_credential(token),
csrf_token=csrf,
expires_at=datetime.now(UTC) + timedelta(hours=settings.session_lifetime_h),
# Truncated to the column width rather than allowed to raise: a
# long or hostile User-Agent must not be able to fail a login.
ip=ip[:45] if ip else None,
user_agent=user_agent[:255] if user_agent else None,
)
)
db.flush()
return token, csrf
def resolve_session(db: DbSession, token: str | None) -> tuple[UserSession, User] | None:
"""Look up a live session and its user, or None.
None covers every failure the caller should treat identically: no cookie, an
unknown token, an expired session, a deleted or deactivated user. They are
deliberately not distinguished in the return value -- the endpoint answers
401 for all of them, because telling a caller *which* one it was is telling
them whether a token was ever real.
"""
if not token:
return None
row = db.execute(
select(UserSession, User)
.join(User, User.id == UserSession.user_id)
.where(UserSession.token_hash == hash_credential(token))
).first()
if row is None:
return None
session, user = row
if session.expires_at <= datetime.now(UTC):
# Clear it out on the way past. Nothing else would, between the
# scheduled purge below and the row's own irrelevance.
db.delete(session)
db.commit()
return None
if not user.is_active:
return None
return session, user
def revoke_session(db: DbSession, token: str | None) -> None:
"""End one session. Idempotent: signing out twice is not an error."""
if not token:
return
db.execute(delete(UserSession).where(UserSession.token_hash == hash_credential(token)))
def revoke_all_for_user(db: DbSession, user_id: int) -> int:
"""End every session for one user, and return how many.
Used when a password changes: otherwise the old credential keeps working
through any browser that is already signed in, which is usually the reason
it was changed.
"""
result = db.execute(delete(UserSession).where(UserSession.user_id == user_id))
return result.rowcount or 0
# Deleting expired rows is deliberately *not* here. Expiry is enforced on read
# above, so a leftover row is inert, and the sweep is a scheduled job -- it
# lives with the worker's other housekeeping in worker/handlers.py. Putting it
# here would mean the worker importing from api/, which is the wrong way round
# for the same reason images.py sits at the package root.
# --- cookies ----------------------------------------------------------------
def set_session_cookies(response: Response, token: str, csrf: str, *, settings: Settings) -> None:
"""Attach both cookies to a login response.
The session cookie is HttpOnly so script cannot read it. The CSRF cookie
deliberately is **not**: the whole mechanism depends on the app's own
JavaScript reading it and echoing it in a header, which an attacker on
another origin cannot do.
"""
max_age = settings.session_lifetime_h * 3600
response.set_cookie(
SESSION_COOKIE,
token,
max_age=max_age,
httponly=True,
secure=settings.session_cookie_secure,
samesite=SAMESITE,
path="/",
)
response.set_cookie(
CSRF_COOKIE,
csrf,
max_age=max_age,
httponly=False,
secure=settings.session_cookie_secure,
samesite=SAMESITE,
path="/",
)
def clear_session_cookies(response: Response, *, settings: Settings) -> None:
"""Remove both cookies.
The attributes have to match the ones they were set with or the browser
treats it as a different cookie and leaves the original in place -- a logout
that appears to work and does not.
"""
for name, httponly in ((SESSION_COOKIE, True), (CSRF_COOKIE, False)):
response.delete_cookie(
name,
httponly=httponly,
secure=settings.session_cookie_secure,
samesite=SAMESITE,
path="/",
)
+53
View File
@@ -0,0 +1,53 @@
"""Request and response shapes for the WebUI (Phase 3).
Separate from ``schemas.py``, which is the device contract in
``firmware/API.md`` and is not free to change. These are ours on both sides: the
server and ``web/`` are versioned together and ship together, so a field can be
renamed here in one commit.
The shapes are pinned to what ``web/src/auth/AuthProvider.tsx`` already expects,
because the scaffold was written first and there is no reason to make it move.
"""
from __future__ import annotations
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field
from ..models.users import ROLES, THEMES
Role = Literal[ROLES] # type: ignore[valid-type]
Theme = Literal[THEMES] # type: ignore[valid-type]
class LoginRequest(BaseModel):
model_config = ConfigDict(extra="ignore")
# Bounded, but not validated against a character set. Usernames are matched
# exactly against the database, so there is nothing to sanitise; a length cap
# is here only so an enormous body cannot reach Argon2.
username: Annotated[str, Field(min_length=1, max_length=64)]
# The password floor lives in passwords.validate_password_strength and is
# applied when a password is *set*. Applying it here too would refuse to
# even check a password that predates the rule, which is a lockout rather
# than a policy. Only an upper bound, matching MAX_PASSWORD_LENGTH.
password: Annotated[str, Field(min_length=1, max_length=1024)]
# Six digits when the account has TOTP. Absent, not empty, when it does not.
totp: Annotated[str | None, Field(max_length=16)] = None
class SessionUser(BaseModel):
"""What ``GET /auth/session`` and ``POST /auth/login`` both return.
Deliberately small. It is what the UI needs to render a shell and make role
decisions, and nothing else -- no email, no TOTP state, no password
metadata. A response shape is a place things accumulate, and the browser is
where they end up.
"""
id: int
username: str
role: Role
locale: str
theme: Theme
+153
View File
@@ -0,0 +1,153 @@
"""User authentication and authorization for the WebUI.
Separate from ``deps.py`` on purpose. That file is device auth: bearer tokens,
no cookies, no CSRF, and a 401 there means "clear your token and re-enroll".
This file is people: session cookies, CSRF, and roles. Mixing them is how a
device ends up able to read the gallery, which SPEC 3.1 forbids outright.
"""
from __future__ import annotations
import logging
import secrets
from typing import Annotated
from fastapi import Depends, HTTPException, Request, status
from ..models import Session as UserSession
from ..models import User
from .deps import DbDep
from .ratelimit import client_address
from .sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE, resolve_session
log = logging.getLogger(__name__)
# Methods that can change state. A GET must never need CSRF, and must never
# change anything -- if one did, no CSRF scheme would protect it.
UNSAFE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_UNAUTHENTICATED = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="not signed in",
)
def current_session(request: Request, db: DbDep) -> tuple[UserSession, User]:
"""Resolve the session cookie to a live session and user, or 401."""
resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE))
if resolved is None:
raise _UNAUTHENTICATED
return resolved
def current_user(
resolved: Annotated[tuple[UserSession, User], Depends(current_session)],
) -> User:
return resolved[1]
SessionDep = Annotated[tuple[UserSession, User], Depends(current_session)]
CurrentUser = Annotated[User, Depends(current_user)]
def require_role(*roles: str):
"""Dependency factory: allow only these roles (SPEC 3.1).
``admin`` is not implicitly granted everything -- each route names the roles
it accepts, so widening one route cannot silently widen another. Where admin
should be included, it is listed.
403, not 404: the caller is authenticated, and pretending the route does not
exist would only make a permission problem look like a bug.
"""
def guard(user: CurrentUser) -> User:
if user.role not in roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"requires one of: {', '.join(sorted(roles))}",
)
return user
return guard
# --- CSRF -------------------------------------------------------------------
async def csrf_middleware(request: Request, call_next):
"""Reject mutating cookie-authenticated requests without a valid CSRF token.
Applied as middleware rather than per-route so a new endpoint cannot forget
it. The condition is what keeps it correct:
* Only unsafe methods. A GET needing this would mean a GET that mutates.
* Only requests that **carry the session cookie**. Device endpoints
authenticate with a bearer token and never send cookies, so they are
untouched -- which matters, because a camera has no way to obtain a CSRF
token and blocking /ingest would take the whole system down.
* Logging in is therefore exempt without a special case: there is no session
cookie yet. Logging out is not exempt, and should not be -- an attacker
signing someone out is a nuisance worth preventing.
The header is compared against the token stored on the session row, not
merely against the cookie. Plain double-submit would let an attacker who can
write a cookie on the domain set both sides to a value they chose; the
victim's session token, which they cannot read, is what they would also
need.
"""
if request.method not in UNSAFE_METHODS or SESSION_COOKIE not in request.cookies:
return await call_next(request)
presented = request.headers.get(CSRF_HEADER)
if not presented:
return _csrf_failure(request, "missing")
# Middleware runs outside the dependency system, so it opens its own
# session. This is one indexed lookup, on mutating requests only.
from ..db import SessionLocal
with SessionLocal() as db:
resolved = resolve_session(db, request.cookies.get(SESSION_COOKIE))
if resolved is None:
# Not signed in after all. Let the route's own dependency produce
# the 401, so the answer stays consistent with every other route.
return await call_next(request)
session, _user = resolved
if not secrets.compare_digest(presented, session.csrf_token):
return _csrf_failure(request, "mismatch")
return await call_next(request)
def _csrf_failure(request: Request, why: str):
from fastapi.responses import JSONResponse
log.warning(
"csrf check failed",
extra={
"reason": why,
"path": request.url.path,
"method": request.method,
"ip": client_address(request),
},
)
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content={
"detail": (
f"CSRF token {why}. Send the value of the {CSRF_COOKIE} cookie "
f"in the {CSRF_HEADER} header."
)
},
)
__all__ = [
"CurrentUser",
"SessionDep",
"csrf_middleware",
"current_session",
"current_user",
"require_role",
]
+13
View File
@@ -72,6 +72,19 @@ class Settings(BaseSettings):
# refuse to serve without it.
enroll_secret: SecretStr = SecretStr("")
# --- user sessions (Phase 3) ------------------------------------------
# SPEC 3.4 lists session lifetime as a UI-editable server setting. It lives
# here until the settings UI exists; promoting it to the settings table then
# is a read, not a redesign.
session_lifetime_h: int = 24 * 14
# Secure cookies require HTTPS, which Caddy always terminates in production.
# It must be false for local development, because the Vite dev server is
# plain http on localhost and a Secure cookie is silently dropped there --
# which presents as "login succeeds but I am never signed in", with nothing
# in any log. Hence a setting rather than a hardcoded True.
session_cookie_secure: bool = True
# --- rate limiting ----------------------------------------------------
# In-process token buckets (api/ratelimit.py), sized for one uvicorn
# process. Off by default in tests, which would otherwise exhaust a
+18
View File
@@ -51,10 +51,28 @@ class User(Base):
class Session(Base):
"""A signed-in browser.
``id`` is internal and never leaves the server. The cookie carries a
separate high-entropy token of which only the SHA-256 is stored, exactly as
device tokens work (api/deps.py). Using ``id`` as the cookie value would be
simpler and would mean a database dump handed over every live session.
``csrf_token`` is per session rather than global, so the double-submit check
cannot be satisfied by an attacker who can merely set a cookie on the
domain -- they would also need this session's token, which is what they do
not have.
"""
__tablename__ = "sessions"
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
# SHA-256 hex of the cookie value. Unique so a collision is a constraint
# error rather than two users sharing a session, and indexed because this
# is the lookup on every authenticated request.
token_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
csrf_token: Mapped[str] = mapped_column(String(64))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
ip: Mapped[str | None] = mapped_column(String(45))
+18 -1
View File
@@ -12,15 +12,17 @@ from __future__ import annotations
import logging
import uuid
from collections.abc import Callable
from datetime import UTC, datetime
from typing import Any
from pydantic import BaseModel, ValidationError
from sqlalchemy import text
from sqlalchemy import delete, text
from sqlalchemy.orm import Session
from ..config import get_settings
from ..images import UndecodableImage, make_thumbnail, relative_thumb_path, write_atomically
from ..models import Capture
from ..models import Session as UserSession
log = logging.getLogger(__name__)
@@ -114,6 +116,21 @@ def _thumbnail(session: Session, payload: dict[str, Any]) -> None:
)
@handler("purge_expired_sessions")
def _purge_expired_sessions(session: Session, payload: dict[str, Any]) -> None:
"""Delete expired WebUI sessions.
Housekeeping, not security: expiry is already enforced on every read
(api/sessions.resolve_session), so a row left here is inert and cannot
authenticate anything. This only stops the table growing for as long as the
server runs.
"""
result = session.execute(delete(UserSession).where(UserSession.expires_at <= datetime.now(UTC)))
session.commit()
if result.rowcount:
log.info("purged expired sessions", extra={"count": result.rowcount})
@handler("prune_expired_commands")
def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None:
"""Expire commands the device never came back for.
+11
View File
@@ -69,6 +69,17 @@ def _build_scheduler() -> BackgroundScheduler:
coalesce=True,
)
# Hourly is plenty: expired sessions are already refused on read, so this
# is only stopping the table from growing.
scheduler.add_job(
lambda: _enqueue("purge_expired_sessions"),
"interval",
hours=1,
id="purge_expired_sessions",
max_instances=1,
coalesce=True,
)
def _reclaim() -> None:
with SessionLocal() as session:
queue.requeue_stale(session)
+6
View File
@@ -13,6 +13,12 @@ os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state")
# camera would, and would otherwise spend its own budget and start asserting
# against 429s. tests/test_ratelimit.py turns it back on deliberately.
os.environ.setdefault("POORBIRD_RATE_LIMIT_ENABLED", "false")
# The test client speaks http://testserver, and a Secure cookie is not stored
# for an http origin -- so with this left at its production default every
# session test would fail with "not signed in" and nothing to show why. The
# same trap catches local development against the Vite dev server, which is
# why this is a setting at all. See config.session_cookie_secure.
os.environ.setdefault("POORBIRD_SESSION_COOKIE_SECURE", "false")
def database_is_reachable() -> bool:
+524
View File
@@ -0,0 +1,524 @@
"""Sessions, login, logout and CSRF (SPEC 3.1, REVIEW SEC-007).
Needs a real PostgreSQL: sessions are rows, and the point of server-side
sessions is that deleting the row takes effect immediately. Mocking that away
would test the mock.
The ``client`` fixture is session-scoped and its cookie jar therefore outlives
a single test, so every fixture here clears it. A signed-in cookie leaking into
the next test would make that test pass for the wrong reason, which is worse
than failing.
"""
from __future__ import annotations
import secrets
import uuid
from datetime import UTC, datetime, timedelta
import pyotp
import pytest
from conftest import needs_db
from sqlalchemy import delete, func, select, text
from poorbird.api.sessions import CSRF_COOKIE, CSRF_HEADER, SESSION_COOKIE
from poorbird.models import AuditLog, User
from poorbird.models import Session as UserSession
from poorbird.passwords import hash_password
from poorbird.totp import new_secret
pytestmark = [pytest.mark.db, needs_db]
PASSWORD = "a-perfectly-usable-passphrase"
@pytest.fixture
def db():
from poorbird.db import SessionLocal
with SessionLocal() as session:
yield session
@pytest.fixture(autouse=True)
def clean_cookies(client):
"""No test starts signed in, and none leaves a cookie behind."""
client.cookies.clear()
yield
client.cookies.clear()
@pytest.fixture(autouse=True)
def no_audit_leaks(db):
"""Sweep audit rows by id, not by user.
audit_log.user_id is ON DELETE SET NULL on purpose -- a trail that vanished
with the account would be useless -- so deleting a test's user does not
delete its audit rows. Worse, a failed login for a username that never
existed writes user_id NULL from the start, which no user-scoped cleanup
can ever match. Seven suite runs had quietly left eight such rows behind
before this fixture existed.
A high-water mark catches every row any test in this file creates,
whichever user it is attributed to, including none.
"""
high_water = db.scalar(select(func.coalesce(func.max(AuditLog.id), 0)))
yield
db.execute(delete(AuditLog).where(AuditLog.id > high_water))
db.commit()
@pytest.fixture
def make_user(db):
"""Users that are removed even when the test fails.
Teardown belongs in a fixture: a failing assertion skips the rest of the
test body, so cleanup written at the end of it silently never runs. This
has bitten this suite three times already.
Sessions cascade from the user, but audit_log rows are ON DELETE SET NULL
by design -- an audit trail that vanished when the account did would be
useless -- so they are removed explicitly here.
"""
created: list[int] = []
def make(
*,
role: str = "viewer",
password: str | None = PASSWORD,
totp: bool = False,
is_active: bool = True,
) -> User:
user = User(
username=f"t_{secrets.token_hex(6)}",
password_hash=hash_password(password) if password is not None else None,
role=role,
totp_secret=new_secret() if totp else None,
is_active=is_active,
)
db.add(user)
db.commit()
db.refresh(user)
created.append(user.id)
return user
yield make
for user_id in created:
db.execute(text("DELETE FROM audit_log WHERE user_id = :i"), {"i": user_id})
db.execute(text("DELETE FROM sessions WHERE user_id = :i"), {"i": user_id})
db.execute(text("DELETE FROM users WHERE id = :i"), {"i": user_id})
db.commit()
def login(client, user: User, *, password: str = PASSWORD, totp: str | None = None):
body: dict[str, object] = {"username": user.username, "password": password}
if totp is not None:
body["totp"] = totp
return client.post("/api/v1/auth/login", json=body)
def csrf_headers(client) -> dict[str, str]:
"""What the browser does: read the readable cookie, echo it in the header."""
return {CSRF_HEADER: client.cookies.get(CSRF_COOKIE, "")}
# --- signing in -------------------------------------------------------------
def test_a_correct_password_signs_you_in(client, make_user):
user = make_user(role="editor")
response = login(client, user)
assert response.status_code == 200
body = response.json()
assert body == {
"id": user.id,
"username": user.username,
"role": "editor",
"locale": "de",
"theme": "light",
}
def test_the_response_carries_no_password_or_secret_material(client, make_user):
"""A response shape is where things accumulate, and this one goes to a
browser. Assert the absence, not just the presence."""
user = make_user(totp=True)
body = login(client, user, totp=pyotp.TOTP(user.totp_secret).now()).json()
assert set(body) == {"id", "username", "role", "locale", "theme"}
serialised = str(body)
assert PASSWORD not in serialised
assert user.totp_secret not in serialised
def test_both_cookies_are_set_with_the_right_visibility(client, make_user):
response = login(client, make_user())
cookies = response.headers.get_list("set-cookie")
session_cookie = next(c for c in cookies if c.startswith(SESSION_COOKIE))
csrf_cookie = next(c for c in cookies if c.startswith(CSRF_COOKIE))
# The session cookie must be unreadable by script; the CSRF cookie must be
# readable, because the whole mechanism is the app's own JS echoing it.
assert "HttpOnly" in session_cookie
assert "HttpOnly" not in csrf_cookie
# Lax, not Strict: Strict would also drop the cookie when someone follows an
# ordinary link into the app and they would arrive apparently signed out.
assert "SameSite=lax" in session_cookie.lower() or "samesite=lax" in session_cookie.lower()
def test_a_wrong_password_is_refused(client, make_user):
assert login(client, make_user(), password="not the password").status_code == 401
def test_an_unknown_username_is_refused_identically(client, make_user):
"""Same status and same message as a wrong password.
A distinguishable answer is a username oracle: it tells an attacker which
accounts exist, which is the first half of the work.
"""
user = make_user()
wrong_password = login(client, user, password="not the password")
no_such_user = client.post(
"/api/v1/auth/login", json={"username": "nobody-here", "password": PASSWORD}
)
assert wrong_password.status_code == no_such_user.status_code == 401
assert wrong_password.json() == no_such_user.json()
def test_a_user_with_no_password_set_cannot_sign_in(client, make_user):
"""Every row seeded before Phase 3 has password_hash IS NULL. None of them
may be loggable-in, and the route must not 500 trying."""
assert login(client, make_user(password=None)).status_code == 401
def test_an_inactive_account_is_refused(client, make_user):
assert login(client, make_user(is_active=False)).status_code == 401
def test_a_deactivated_user_loses_an_existing_session(client, make_user, db):
"""Deactivating an account has to take effect now, not at expiry."""
user = make_user()
assert login(client, user).status_code == 200
assert client.get("/api/v1/auth/session").status_code == 200
user.is_active = False
db.commit()
assert client.get("/api/v1/auth/session").status_code == 401
# --- second factor ----------------------------------------------------------
def test_totp_is_required_when_the_account_has_a_secret(client, make_user):
user = make_user(totp=True)
assert login(client, user).status_code == 401
def test_a_wrong_totp_code_is_refused(client, make_user):
user = make_user(totp=True)
assert login(client, user, totp="000000").status_code == 401
def test_a_correct_totp_code_signs_you_in(client, make_user):
user = make_user(totp=True)
assert login(client, user, totp=pyotp.TOTP(user.totp_secret).now()).status_code == 200
def test_a_totp_code_alone_is_not_enough(client, make_user):
"""The second factor is second, not alternative."""
user = make_user(totp=True)
response = login(client, user, password="wrong", totp=pyotp.TOTP(user.totp_secret).now())
assert response.status_code == 401
def test_an_account_without_totp_ignores_a_supplied_code(client, make_user):
"""Sending a code to an account that has no secret must not fail closed in
the other direction -- it is simply irrelevant."""
assert login(client, make_user(), totp="123456").status_code == 200
# --- the session itself -----------------------------------------------------
def test_session_returns_401_when_not_signed_in(client):
"""401, not 404. The UI reads 404 as "this server has no auth at all" and
shows a banner; now that the endpoint exists, that must stop."""
assert client.get("/api/v1/auth/session").status_code == 401
def test_session_returns_the_user_when_signed_in(client, make_user):
user = make_user(role="admin", totp=True)
login(client, user, totp=pyotp.TOTP(user.totp_secret).now())
response = client.get("/api/v1/auth/session")
assert response.status_code == 200
assert response.json()["username"] == user.username
assert response.json()["role"] == "admin"
def test_only_the_hash_of_the_session_token_is_stored(client, make_user, db):
"""The cookie value must not be findable in the database.
This is the whole reason sessions.id is internal and the cookie is a
separate token: a database dump should not hand over every live session.
"""
user = make_user()
login(client, user)
cookie = client.cookies.get(SESSION_COOKIE)
rows = db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()
assert len(rows) == 1
assert rows[0].token_hash != cookie
assert cookie not in rows[0].token_hash
# And the token must actually resolve, or the hash is of the wrong thing.
assert client.get("/api/v1/auth/session").status_code == 200
def test_an_unknown_session_cookie_is_refused(client, make_user):
make_user()
client.cookies.set(SESSION_COOKIE, secrets.token_hex(32))
assert client.get("/api/v1/auth/session").status_code == 401
def test_an_expired_session_is_refused_and_cleaned_up(client, make_user, db):
user = make_user()
login(client, user)
db.execute(
text("UPDATE sessions SET expires_at = :t WHERE user_id = :i"),
{"t": datetime.now(UTC) - timedelta(minutes=1), "i": user.id},
)
db.commit()
assert client.get("/api/v1/auth/session").status_code == 401
# Enforced on read, and swept on the way past.
assert db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() == []
def test_each_login_opens_a_separate_session(client, make_user, db):
"""Two browsers, two rows. Signing out of one must not sign out the other,
which is only possible if they are distinct."""
user = make_user()
login(client, user)
first = client.cookies.get(SESSION_COOKIE)
client.cookies.clear()
login(client, user)
second = client.cookies.get(SESSION_COOKIE)
assert first != second
assert len(db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()) == 2
# --- signing out ------------------------------------------------------------
def test_logout_ends_the_session(client, make_user, db):
user = make_user()
login(client, user)
assert client.post("/api/v1/auth/logout", headers=csrf_headers(client)).status_code == 204
assert db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all() == []
def test_the_old_cookie_stops_working_after_logout(client, make_user):
"""The row is deleted, not flagged, so this is immediate. It is the reason
sessions are server-side rather than a self-contained token."""
user = make_user()
login(client, user)
cookie = client.cookies.get(SESSION_COOKIE)
csrf = csrf_headers(client)
client.post("/api/v1/auth/logout", headers=csrf)
client.cookies.set(SESSION_COOKIE, cookie)
assert client.get("/api/v1/auth/session").status_code == 401
def test_logout_without_a_session_is_not_an_error(client):
"""A client must always be able to sign out. A 401 here would leave a
browser holding a cookie it cannot get rid of."""
assert client.post("/api/v1/auth/logout").status_code == 204
def test_logging_out_one_session_leaves_the_other_alone(client, make_user, db):
user = make_user()
login(client, user)
first_cookie = client.cookies.get(SESSION_COOKIE)
client.cookies.clear()
login(client, user)
client.post("/api/v1/auth/logout", headers=csrf_headers(client))
client.cookies.clear()
client.cookies.set(SESSION_COOKIE, first_cookie)
assert client.get("/api/v1/auth/session").status_code == 200
def test_changing_a_password_ends_every_session(client, make_user, db):
"""Otherwise the old password keeps working through any browser already
signed in, which is usually why it was changed."""
from poorbird.api.sessions import revoke_all_for_user
user = make_user()
login(client, user)
assert client.get("/api/v1/auth/session").status_code == 200
assert revoke_all_for_user(db, user.id) == 1
db.commit()
assert client.get("/api/v1/auth/session").status_code == 401
# --- CSRF -------------------------------------------------------------------
def test_a_mutating_request_without_a_csrf_header_is_refused(client, make_user):
user = make_user()
login(client, user)
response = client.post("/api/v1/auth/logout")
assert response.status_code == 403
assert "csrf" in response.json()["detail"].lower()
def test_a_mutating_request_with_a_wrong_csrf_token_is_refused(client, make_user):
user = make_user()
login(client, user)
response = client.post("/api/v1/auth/logout", headers={CSRF_HEADER: secrets.token_hex(32)})
assert response.status_code == 403
def test_a_csrf_token_from_a_different_session_is_refused(client, make_user):
"""The check is against the token on *this* session's row, not merely
against the cookie. Plain double-submit would accept any self-consistent
pair, so someone able to write a cookie on the domain could satisfy it.
"""
user = make_user()
login(client, user)
victim_session_cookie = client.cookies.get(SESSION_COOKIE)
client.cookies.clear()
login(client, user)
other_csrf = client.cookies.get(CSRF_COOKIE)
# The victim's session, with an attacker-chosen (but real) CSRF value in
# both the cookie and the header -- which is exactly what a cookie-writing
# attacker could arrange.
client.cookies.clear()
client.cookies.set(SESSION_COOKIE, victim_session_cookie)
client.cookies.set(CSRF_COOKIE, other_csrf)
response = client.post("/api/v1/auth/logout", headers={CSRF_HEADER: other_csrf})
assert response.status_code == 403
def test_a_matching_csrf_token_is_accepted(client, make_user):
user = make_user()
login(client, user)
assert client.post("/api/v1/auth/logout", headers=csrf_headers(client)).status_code == 204
def test_reading_never_needs_a_csrf_token(client, make_user):
"""A GET that needed one would be a GET that mutates."""
login(client, make_user())
assert client.get("/api/v1/auth/session").status_code == 200
def test_logging_in_needs_no_csrf_token(client, make_user):
"""There is no session cookie yet, so it is exempt without a special case
-- which is why the middleware keys on the cookie rather than the path."""
assert login(client, make_user()).status_code == 200
def test_device_endpoints_are_not_subject_to_csrf(client):
"""A camera has no way to obtain a CSRF token, and blocking /ingest would
take the whole system down. Device requests carry a bearer token and no
cookies, which is what the middleware keys on.
"""
response = client.post(
"/api/v1/ingest",
content=b"\xff\xd8\xff not really a jpeg",
headers={"Authorization": "Bearer nonsense", "Content-Type": "image/jpeg"},
)
# 401 for the bad token -- the point is that it is not 403-for-CSRF.
assert response.status_code == 401
# --- audit trail ------------------------------------------------------------
def test_a_successful_login_is_audited(client, make_user, db):
user = make_user()
login(client, user)
actions = db.scalars(
select(AuditLog.action).where(AuditLog.user_id == user.id).order_by(AuditLog.id)
).all()
assert "login" in actions
def test_a_failed_login_is_audited_too(client, make_user, db):
"""A log of only the successes cannot answer the question worth asking
afterwards, which is how many times someone tried first."""
user = make_user()
login(client, user, password="wrong")
login(client, user, password="wrong again")
actions = db.scalars(select(AuditLog.action).where(AuditLog.user_id == user.id)).all()
assert actions.count("login_failed") == 2
def test_the_audit_record_never_contains_the_password(client, make_user, db):
user = make_user()
login(client, user, password="hunter2-and-then-some")
rows = db.scalars(select(AuditLog).where(AuditLog.user_id == user.id)).all()
assert rows
for row in rows:
assert "hunter2" not in str(row.after)
def test_logout_is_audited(client, make_user, db):
user = make_user()
login(client, user)
client.post("/api/v1/auth/logout", headers=csrf_headers(client))
actions = db.scalars(select(AuditLog.action).where(AuditLog.user_id == user.id)).all()
assert "logout" in actions
# --- housekeeping -----------------------------------------------------------
def test_purge_expired_removes_only_expired_sessions(client, make_user, db):
"""The sweep lives with the worker's other scheduled housekeeping, not in
api/, so that the worker never imports from the HTTP layer."""
from poorbird.worker.handlers import HANDLERS
user = make_user()
live = UserSession(
user_id=user.id,
token_hash=uuid.uuid4().hex + uuid.uuid4().hex,
csrf_token=secrets.token_hex(16),
expires_at=datetime.now(UTC) + timedelta(days=1),
)
dead = UserSession(
user_id=user.id,
token_hash=uuid.uuid4().hex + uuid.uuid4().hex,
csrf_token=secrets.token_hex(16),
expires_at=datetime.now(UTC) - timedelta(days=1),
)
db.add_all([live, dead])
db.commit()
live_id = live.id
HANDLERS["purge_expired_sessions"](db, {})
remaining = db.scalars(select(UserSession).where(UserSession.user_id == user.id)).all()
assert [r.id for r in remaining] == [live_id]