Take auth/ whole from boilerplate 09e144d: the lockout claimed before the scrypt, APP_PASSWORD recovery closing every session, Starlette's cookie parser, the rightmost forwarded hop in the log, revoke_all on a password change, a 421 for a non-loopback Host on an open app, API tokens in auth_tokens behind Authorization: Bearer, and sockets closed with their credential
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
1 parent
83e965dfeb
commit
244e57ac29
19 files changed
+2288
-214
No files matched your search
+58
-19
@@ -9,27 +9,30 @@ 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.
|
||||
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, 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 |
|
||||
| `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 five request bodies |
|
||||
| `router.py` | `/login`, `/logout`, `/api/account/*`, the passkey routes, `/_auth/*.js` |
|
||||
| `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 `docs/password-protection.md`, and this package is that
|
||||
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
|
||||
@@ -41,23 +44,29 @@ 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.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__ = [
|
||||
"OPEN", "Account", "AuthConfig", "AuthStore", "Passkey", "RequireLogin",
|
||||
"SessionInfo", "bootstrap", "client_address", "connect", "locked",
|
||||
"passkeys", "router", "token_from",
|
||||
"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] = (), stylesheet: str | None = None,
|
||||
host: str = "") -> AuthStore:
|
||||
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
|
||||
@@ -72,13 +81,17 @@ def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *,
|
||||
| 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.
|
||||
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.
|
||||
"""
|
||||
@@ -88,10 +101,12 @@ def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *,
|
||||
#: 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)
|
||||
open=tuple(open), host=host, session_only=tuple(session_only))
|
||||
|
||||
inner = app.router.lifespan_context
|
||||
|
||||
@@ -104,8 +119,18 @@ def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *,
|
||||
# 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
|
||||
# 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
|
||||
@@ -124,12 +149,26 @@ def bootstrap(store: AuthStore, config: AuthConfig) -> None:
|
||||
|
||||
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)
|
||||
log.info("password set from %s", config.password_env)
|
||||
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():
|
||||
|
||||
Reference in new issue
Block a user