Files
jobboard/auth/__init__.py
T

200 lines
9.9 KiB
Python

"""One password on a public hostname, in one call.
app = FastAPI()
store = connect(app, AuthStore("data/app.db"), config.auth,
host=config.server.host, open=("/static/",),
stylesheet="/static/app.css")
That is the middleware in front of everything (the WebSocket included), the
login page, the account API, the `<auth-account>` element, and the startup
bootstrap that makes sure there is a password at all. 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: the password, a passkey, or an
API token carried by a script as `Authorization: Bearer`.
| module | |
|---|---|
| `config.py` | `AuthConfig`: the `auth:` block of the app's `config.yaml` |
| `store.py` | `AuthStore`: scrypt, the lockout, sessions, passkeys, API tokens, five `auth_*` tables in whatever SQLite file it is given |
| `models.py` | `Account`, `SessionInfo`, `Passkey`, `ApiToken` — what the account screen is told, which carries no credential |
| `middleware.py` | `RequireLogin`, `locked()`, the open list, the cookie, the bearer header, the same-site rule, `confirm_password`, `confirm_current` and `warn`, and `close_ended_sockets` with its sweep |
| `passkeys.py` | the two WebAuthn ceremonies; `webauthn` is an optional extra, imported lazily |
| `schemas.py` | the seven request bodies |
| `router.py` | `/login`, `/logout`, `/api/account/*`, the passkey and token routes, `/_auth/*.js` |
| `templates/login.html` | the one page served without a session |
| `static/` | `passkey.js` (the browser half of WebAuthn) and `account.js` (`<auth-account>`) |
The reasoning is the boilerplate's `documentation/Password Protection.md`, and this package is that
document in code. `auth/README.md` is how to copy the folder into a project
that has never heard of this one.
"""
from __future__ import annotations
import asyncio
import contextlib
import logging
import os
import secrets
from collections.abc import AsyncIterator, Iterable
from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI
from auth import passkeys
from auth.config import AuthConfig
from auth.middleware import (
ACCOUNT, CURRENT_HEADER, OPEN, RequireLogin, bearer_from, client_address,
close_ended_sockets, confirm_current, confirm_password, credential_live, locked,
sweep_ended_sockets, token_from, warn,
)
from auth.models import Account, ApiToken, Passkey, SessionInfo
from auth.router import router
from auth.store import AuthStore
log = logging.getLogger(__name__)
__all__ = [
"ACCOUNT", "CURRENT_HEADER", "OPEN", "Account", "ApiToken", "AuthConfig", "AuthStore",
"Passkey", "RequireLogin", "SessionInfo", "bearer_from", "bootstrap", "client_address",
"close_ended_sockets", "confirm_current", "confirm_password", "connect",
"credential_live", "locked", "passkeys", "router", "sweep_ended_sockets", "token_from",
"warn",
]
def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *,
open: Iterable[str] = (), session_only: Iterable[str] = (),
stylesheet: str | None = None, host: str = "") -> AuthStore:
"""Put `app` behind a password: middleware, routes, element, bootstrap.
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.
`store` is 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.
| keyword | |
|---|---|
| `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. |
| `session_only` | extra paths an API token may not reach, added to `middleware.ACCOUNT`, matched the same way. Anything that reads or replaces the database as a file belongs here: it holds the password hash and the tokens, so a token that could fetch or swap it would hold the account. A route listed here should also take the current password; a route that hands out or replaces the database as a file takes it in an `X-Current-Password` header, through `auth.confirm_current`, and any other through `auth.confirm_password`. |
| `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. |
| `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. |
The lifespan is wrapped rather than replaced, the same way
`pipeline.web.connect` does it, so an app's own lifespan still runs inside
this one: the password exists before the app's startup code, which may want
to say something about it. On a locked app it also runs
`sweep_ended_sockets` for as long as the app is up, as the task on
`app.state.auth_sweep` (None on an unlocked app), so a socket whose session
or token expires is closed within `middleware.SWEEP` seconds.
Returns the store, for the app to keep if it wants one.
"""
app.state.auth = store
app.state.auth_config = config
#: Whether a session is required. Decided once, here, because it depends on
#: the bind address, which only the caller knows.
app.state.auth_locked = locked(config, host)
app.state.auth_stylesheet = stylesheet or ""
#: The `sweep_ended_sockets` task while a locked app is up; see below.
app.state.auth_sweep = None
app.include_router(router)
app.add_middleware(RequireLogin, store=store, config=config,
open=tuple(open), host=host, session_only=tuple(session_only))
inner = app.router.lifespan_context
@asynccontextmanager
async def lifespan(this: FastAPI) -> AsyncIterator[Any]:
if app.state.auth_locked:
bootstrap(store, config)
store.purge()
# Outside the `locked` check on purpose: a passkey can be registered on
# a loopback app before it is ever deployed, which is the order this
# encourages, so an unlocked one can still have keys it cannot use.
passkeys.warn_if_missing(store)
# Expiry ends no request, so no route closes the socket it ended.
sweep = (asyncio.create_task(sweep_ended_sockets(app))
if app.state.auth_locked else None)
app.state.auth_sweep = sweep
try:
async with inner(this) as state:
yield state
finally:
if sweep is not None:
sweep.cancel()
with contextlib.suppress(asyncio.CancelledError):
await sweep
app.router.lifespan_context = lifespan
return store
def bootstrap(store: AuthStore, config: AuthConfig) -> None:
"""Make sure there is a password, and say so once if we invented one.
The variable named by `config.password_env` — `APP_PASSWORD` by default —
is authoritative while it is set: if it is in the environment, it *is* the
password, and the account screen says so and declines to change it. That is
a deliberate choice over seeding from it once — a variable that silently
stopped applying the moment you changed the password in the browser would
be worse than either rule, and this way round the environment doubles as
the way back in when you are locked out of your own server.
Re-derived only when the stored hash does not already match, so a restart is
not a write and "password last changed" keeps meaning something.
When the variable replaces a password that was there, every session is
closed: that is the recovery, and whoever had the old password may be
signed in. API tokens and passkeys stay, since the environment cannot say
which of them are the owner's, and their counts are logged at WARNING so
the owner knows to review them under Account.
"""
pinned = os.environ.get(config.password_env, "")
if pinned:
if not store.check_password(pinned):
replaced = store.has_password()
store.set_password(pinned)
if not replaced:
log.info("password set from %s", config.password_env)
return
closed = store.close_all()
tokens, keys = store.counts()
log.warning("password reset from %s: closed %d sessions; %d API tokens and "
"%d passkeys remain, review them under Account",
config.password_env, closed, tokens, keys)
return
if store.has_password():
return
password = secrets.token_urlsafe(12)
store.set_password(password)
# At WARNING so it survives the default log level, and banner-shaped because
# it is printed exactly once in the life of a database and being scrolled
# past is the same as not being printed at all.
#
# ASCII, deliberately. This is the one log line whose *contents* someone has
# to read back character by character, and it is read wherever the server
# happens to be running -- a Windows console under cp1252, a `docker logs`
# pipe with no locale set. Box-drawing characters come out as `?` in both,
# which turns the frame around the password into noise around the password.
log.warning(
"\n"
" ------------------------------------------------------------\n"
" This app is locked and had no password, so here is one:\n"
"\n"
" %s\n"
"\n"
" This is the only time it is shown. Change it under Account,\n"
" or set %s to pin one.\n"
" ------------------------------------------------------------",
password, config.password_env,
)