"""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 `` 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. | module | | |---|---| | `config.py` | `AuthConfig`: the `auth:` block of the app's `config.yaml` | | `store.py` | `AuthStore`: scrypt, the lockout, sessions, passkeys, four `auth_*` tables in whatever SQLite file it is given | | `models.py` | `Account`, `SessionInfo`, `Passkey` — what the account screen is told, which carries no credential | | `middleware.py` | `RequireLogin`, `locked()`, the open list, the cookie | | `passkeys.py` | the two WebAuthn ceremonies; `webauthn` is an optional extra, imported lazily | | `schemas.py` | the five request bodies | | `router.py` | `/login`, `/logout`, `/api/account/*`, the passkey routes, `/_auth/*.js` | | `templates/login.html` | the one page served without a session | | `static/` | `passkey.js` (the browser half of WebAuthn) and `account.js` (``) | The reasoning is `docs/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 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 OPEN, RequireLogin, client_address, locked, token_from from auth.models import Account, Passkey, SessionInfo from auth.router import router from auth.store import AuthStore log = logging.getLogger(__name__) __all__ = [ "OPEN", "Account", "AuthConfig", "AuthStore", "Passkey", "RequireLogin", "SessionInfo", "bootstrap", "client_address", "connect", "locked", "passkeys", "router", "token_from", ] def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *, open: 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. | | `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. 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 "" app.include_router(router) app.add_middleware(RequireLogin, store=store, config=config, open=tuple(open), host=host) 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) async with inner(this) as state: yield state 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. """ pinned = os.environ.get(config.password_env, "") if pinned: if not store.check_password(pinned): store.set_password(pinned) log.info("password set from %s", config.password_env) 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, )