Files
WolfandClaude Opus 5.5 9d666d0937 Bring in pipeline, auth, deploy and docs from the boilerplate
roledesk is built on the boilerplate from here on: pipeline 2.0 (queue and
scheduler), auth (one password, sessions, passkeys), the deploy kit and its
docs, plus the coupling and packaging tests. Downstream copies, unedited.

Refreshed from boilerplate/d56949f7d0f6c0bfe5745478e09007bfad67ae87

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:29:16 +02:00
..

auth

One password on a public hostname. scrypt, a lockout counted in the database, sessions you can revoke, passkeys, and one middleware in front of everything — the WebSocket included. No user management: there is one user, they are the person who deployed it, and the only questions are whether the door is locked and what opens it.

Needs Python 3.12+, fastapi and pydantic. webauthn is optional and only for passkeys; every import of it is inside a function, and the passkey routes answer 501 with a sentence saying what to install when it is missing.

The source of truth is boilerplate/auth/. Copies elsewhere are copies: take the whole folder, and run its tests where it lands.

cp -r boilerplate/auth yourproject/auth
python -m pytest yourproject/auth/tests

Then add auth* to that project's pyproject.toml packages, "auth" = ["templates/*.html", "static/*"] to its package data, and auth/tests to its testpaths. docs/password-protection.md in this repository is the reasoning behind every decision below, at length.

Five lines

from fastapi import FastAPI
import auth

app = FastAPI()
auth.connect(app, auth.AuthStore(config.database), config.auth,
             host=config.server.host, open=("/static/",),
             stylesheet="/static/app.css")

Call it first, before the app's own routers. Starlette wraps the whole router in its middleware whenever the routes were added, so the socket and every page are covered either way — but written first it is also read first, and nobody reviewing the file has to work out whether the socket is behind the password.

That gives you /login (the page and the POST), /logout, /api/account, /api/account/password, /api/account/sessions/{id} and /api/account/sessions/close, the four passkey routes, /_auth/passkey.js and /_auth/account.js — and a startup bootstrap that makes sure there is a password at all.

connect(app, store, config, ...)
store an AuthStore on whatever database the app keeps. Handing it in rather than building it here is what lets the app decide there is one file.
config an AuthConfig. The app's own config model carries it as a field; see below.
host= the address the server binds — config.server.host. What enabled: auto decides from, and deliberately not taken from a request, since a Host header is written by whoever is talking.
open= extra paths reachable without a session, added to middleware.OPEN. A name ending in / is a prefix; any other is matched whole. ("/static/",) is what an app with a stylesheet passes.
stylesheet= a URL the login page links, so it looks like the rest of the app. Optional: the page carries enough inline CSS to be presentable on its own.

The account screen is two lines in a template, the same deal <desk-jobs> makes:

<script type="module" src="/_auth/account.js"></script>
<auth-account></auth-account>

It draws the lot — locked or not, change the password, the sessions with revoke and close-others, the passkeys with register, rename and revoke, and sign out — and it is themed from outside by the same --desk-jobs-* custom properties the queue's elements read, so desk-jobs, desk-schedules, auth-account { ... } in one stylesheet is all three.

The config block

AuthConfig is pydantic and imports nothing from the app, so an app's own config model carries it as a field:

from auth import AuthConfig

class Config(Section):
    auth: AuthConfig = Field(default_factory=AuthConfig)
auth:
  enabled: auto           # auto | always | never
  session_days: 30
  secure_cookie: auto     # `always` behind a proxy that terminates TLS
  rp_id: ""               # app.example.com -- passkeys are bound to a domain
  rp_name: app            # what the authenticator shows you
  origin: ""              # https://app.example.com
  password_env: APP_PASSWORD
  cookie: app_session

enabled: auto is the setting that matters: locked unless the server binds a loopback address. Deciding from the bind address rather than defaulting to off prevents the failure that actually happens — you deploy, it works, and nothing anywhere tells you the door is open. Production says always anyway, because behind a TLS-terminating proxy every request looks local to the app and is not.

password_env and cookie are settings because this folder is copied into projects that are not called app, and two of those on one hostname would otherwise share a cookie and sign each other out.

Getting in the first time

The password is never in the config file — only ever an scrypt hash in the database. The first locked start takes $APP_PASSWORD if it is set, and otherwise invents one and prints it to the log once, in a plain ASCII banner you can read back off docker compose logs.

APP_PASSWORD is authoritative while it is set: the Account screen says so and declines to change it. That is the way back in when a login is lost — set it, get in, empty it, recreate the container, then change the password in the app. A variable that silently stopped applying the moment you changed the password in the browser would be worse than either rule.

What the app has to provide

Almost nothing, and that is the point.

  • A SQLite path. AuthStore creates four auth_* tables in whatever file it is given, so it can share the app's own.
  • The bind host, for enabled: auto.
  • Nothing for the open list, as a rule. /login, /login/, /_auth/ and /health are opened by this package; the app adds /static/ if it serves one, or the login page arrives unstyled. Everything else stays shut — a module's own scripts and sockets included, so in this repository /_jobs/jobs.js and /ws/jobs need a session like the pages that load them.
  • An error handler that keeps {"detail": "..."} for /api, /ws and /_auth, if it has one. Every refusal here is already that shape.

What it must not do is protect its own routes. Everything is shut except the open list, which is four entries long and asserted in a test — so a router added next month is safe because it exists, not because somebody remembered.

The decisions, in one paragraph each

scrypt, not SHA-256. Memory-hard rather than merely slow: one guess costs 16 MB, which is what takes a stolen database file out of range of a GPU. A wrong answer costs a full derivation too, so the delay an attacker meets is the one the honest user meets.

A session is 32 random bytes, and the table holds only its SHA-256. No signing key to generate, store, keep out of backups and rotate; signing out everywhere is one DELETE, which no self-contained token can offer without keeping exactly this state.

The lockout is counted in the file and read before the check. A counter on the process is a free reset for whoever is guessing, on a server that reloads. Read after instead of before, and hammering the button extends your own lockout — which punishes the owner far harder than the attacker who is not watching. Five wrong answers are free, then 30 s doubling to a quarter of an hour, with the exponent capped so a bot cannot turn arithmetic into a 500.

One counter, not one per address. Behind a proxy the only address the app sees is one the caller wrote. Keyed on that, an attacker gets a fresh counter per request while the owner still gets locked out by their own typos. So the address is logged — one WARNING per refusal, auth.router: wrong password from <addr>, stripped to the characters an address is made of — and decided from at the layer that knows who connected. docs/password-protection.md has the nginx and fail2ban half.

No CSRF token. SameSite=Lax refuses to send this cookie on any cross-site request that is not a top-level navigation, and no GET here changes anything, so the attack a token would stop cannot be mounted. A second secret to rotate, and a second way for a request to fail, buys nothing.

Passkeys need a real hostname. A passkey is bound to an origin, and that binding is what makes it unphishable — so it needs HTTPS, with localhost the one exception, which is what lets it be tried before deploying. Behind a proxy, set rp_id and origin explicitly or every ceremony fails as an origin mismatch. Changing rp_id later invalidates every key registered against the old one. The password never goes away, which is why revoking a key can never lock you out.

Tests

uv run pytest auth/tests

The passkey ceremonies are tested against auth/tests/softkey.py, a real WebAuthn authenticator that happens to be in software: it produces the same CBOR, the same authenticator data and the same ECDSA signatures a hardware key does, so a wrong origin fails because the origin is signed over and a clone is caught because the counter went backwards. Those tests skip without the extra; what the app does without it is test_without_passkeys.py, which always runs.