Files
Hello/server/src/poorbird/config.py
T
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

144 lines
6.2 KiB
Python

"""Configuration.
Every value comes from the environment (TODO.md Phase 1.2). Nothing is read
from a committed config file, and no path, host or secret is baked into code.
systemd supplies these via ``EnvironmentFile=/etc/poorbird/poorbird.env``; for
local development a ``.env`` in the working directory is picked up as well.
"""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from typing import Literal
from pydantic import SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
# Values that mean "nobody filled this in". The .example files ship with these,
# and a copied-but-unedited example must not boot as if it were configured.
_PLACEHOLDERS = frozenset({"change_me", "changeme", "todo", "xxx", "secret"})
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="POORBIRD_",
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
# --- database ---------------------------------------------------------
# Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket
# is the one genuinely container-hostile choice (TODO.md Phase 1.2).
#
# No default. A working URL in code means real credentials in code, and the
# module docstring above already promises none (REVIEW SEC-006). Absence is
# reported by ``poorbird check`` and raised with a readable message by db.py,
# rather than silently connecting to whatever happens to be on localhost.
database_url: str = ""
# FastAPI runs this app's ``def`` handlers in anyio's threadpool (40 threads
# by default), and each one holds a session for the whole request. A pool of
# 5 meant the 6th concurrent request waited on ``pool_timeout`` before it
# even reached the database (REVIEW §7). The real ceiling is
# pool_size + db_max_overflow, so both are named here rather than left to
# SQLAlchemy's invisible default of 10.
db_pool_size: int = 15
db_max_overflow: int = 10
db_echo: bool = False
# --- http -------------------------------------------------------------
api_host: str = "127.0.0.1"
api_port: int = 8080
# --- storage ----------------------------------------------------------
# A small number of explicit top-level directories, never scattered under
# the app dir: these are the future volume mounts.
#
# image_root is the single source of truth for the image path. Caddy reads
# the same value, because the auth-checked handoff (SPEC 3.3) needs the app
# and the proxy to agree on where the bytes live.
image_root: Path = Path("/srv/poorbird/images")
thumb_root: Path = Path("/srv/poorbird/thumbs")
state_dir: Path = Path("/var/lib/poorbird")
# --- devices ----------------------------------------------------------
# Shared bootstrap secret presented by a device in X-Enroll-Secret.
# See firmware/API.md: do NOT rotate this without shipping new firmware,
# or you remove the last-resort recovery path for a mounted camera.
#
# Environment only, never a literal here (REVIEW SEC-001). Empty is allowed
# so the Phase 1 commands still run on a fresh clone; the device endpoints
# 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
# bucket and start asserting against 429s.
rate_limit_enabled: bool = True
# --- worker -----------------------------------------------------------
# Idle polling only: the loop drains a non-empty queue back to back without
# sleeping, so this is the delay before a *newly* enqueued job is noticed,
# not a per-job cost. 5s trades latency nobody can perceive on a bird camera
# for 12 idle queries a minute instead of 30.
worker_poll_interval_s: float = 5.0
job_max_attempts: int = 3
# --- logging ----------------------------------------------------------
# Always to stdout/stderr. journald catches it now; a log driver would
# catch it later. Never app-managed log files.
log_level: str = "INFO"
log_format: Literal["text", "json"] = "text"
@field_validator("database_url")
@classmethod
def _reject_unedited_example(cls, v: str) -> str:
if any(p in v.lower() for p in _PLACEHOLDERS):
raise ValueError(
"POORBIRD_DATABASE_URL still contains a placeholder from the "
"example file. Put the real password in, or leave the variable "
"unset."
)
return v
@field_validator("enroll_secret")
@classmethod
def _reject_placeholder_secret(cls, v: SecretStr) -> SecretStr:
if v.get_secret_value().strip().lower() in _PLACEHOLDERS:
raise ValueError(
"POORBIRD_ENROLL_SECRET is a placeholder. Generate one with "
"'openssl rand -hex 32', or leave it unset until Phase 2."
)
return v
@property
def database_url_is_set(self) -> bool:
return bool(self.database_url.strip())
@property
def enroll_secret_is_set(self) -> bool:
return bool(self.enroll_secret.get_secret_value())
def storage_paths(self) -> list[Path]:
return [self.image_root, self.thumb_root, self.state_dir]
@lru_cache
def get_settings() -> Settings:
return Settings()