From 244e57ac29a9d553d7636dc636a9385894b93c1e Mon Sep 17 00:00:00 2001 From: Wolf Date: Tue, 27 Oct 2026 11:51:21 +0100 Subject: [PATCH 1/2] 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 --- auth/README.md | 28 +- auth/__init__.py | 77 +++- auth/config.py | 16 +- auth/middleware.py | 539 ++++++++++++++++++++++++++-- auth/models.py | 27 +- auth/passkeys.py | 10 +- auth/router.py | 202 ++++++----- auth/schemas.py | 86 ++++- auth/static/account.js | 221 +++++++++++- auth/store.py | 233 ++++++++++-- auth/templates/login.html | 9 +- auth/tests/conftest.py | 7 +- auth/tests/harness.py | 49 ++- auth/tests/test_door.py | 225 +++++++++++- auth/tests/test_passkeys.py | 69 +++- auth/tests/test_sockets.py | 170 +++++++++ auth/tests/test_store.py | 67 +++- auth/tests/test_tokens.py | 465 ++++++++++++++++++++++++ auth/tests/test_without_passkeys.py | 2 +- 19 files changed, 2288 insertions(+), 214 deletions(-) create mode 100644 auth/tests/test_sockets.py create mode 100644 auth/tests/test_tokens.py diff --git a/auth/README.md b/auth/README.md index 520a207..5bef54d 100644 --- a/auth/README.md +++ b/auth/README.md @@ -1,6 +1,6 @@ # 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. +One password on a public hostname. scrypt, a lockout counted in the database, sessions you can revoke, passkeys, API tokens for scripts, 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: the password, a passkey, or a token. 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. @@ -11,7 +11,7 @@ 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. +Then add `auth*` to that project's `pyproject.toml` packages, `"auth" = ["templates/*.html", "static/*"]` to its package data, and `auth/tests` to its testpaths. The boilerplate's `documentation/Password Protection.md` is the reasoning behind every decision below, at length. ## Five lines @@ -27,7 +27,7 @@ auth.connect(app, auth.AuthStore(config.database), config.auth, 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. +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, the three token routes (`POST /api/account/tokens`, `POST /api/account/tokens/{id}/label`, `DELETE /api/account/tokens/{id}`), `/_auth/passkey.js` and `/_auth/account.js` — and a startup bootstrap that makes sure there is a password at all. | `connect(app, store, config, ...)` | | |---|---| @@ -35,6 +35,7 @@ That gives you `/login` (the page and the POST), `/logout`, `/api/account`, `/ap | `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. | +| `session_only=` | extra paths an API token may not reach, added to `middleware.ACCOUNT` and matched the same way. Anything that reads or replaces the database as a file belongs here, since the file holds the password hash and the token rows. | | `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 `` makes: @@ -44,7 +45,7 @@ The account screen is two lines in a template, the same deal `` makes ``` -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. +It draws the lot — locked or not, change the password, the sessions with revoke and close-others, the passkeys with register, rename and revoke, the API tokens with create, 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. Under `40rem` a row's buttons drop under its name when they do not fit beside it and a form's fields take the width; under a coarse pointer every button is a thumb's height and no field is under 16px. The login page does the same for itself, since it is served before any of the app's CSS. ## The config block @@ -69,7 +70,7 @@ auth: 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. +`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, so the lock does not depend on the bind address or on how the process was started. Under `auto` an app left open on loopback answers any request carrying `X-Forwarded-For`, `X-Forwarded-Proto`, `X-Forwarded-Host` or `Forwarded` with 421 and logs a warning once, since a proxy on the same machine would otherwise serve it to the network without a password. The Vite dev server's proxy sends none of these headers. `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. @@ -77,33 +78,42 @@ auth: 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. +`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. When it replaces a stored password, the start closes every session, since whoever had the old password may be signed in, and logs at WARNING how many API tokens and passkeys remain; review them under Account, or tick the revoke box on the next password change. ## 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. +- A SQLite path. `AuthStore` creates five `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. +- `app.state.bus`, if it holds sockets open: an object with a `sockets` tuple and an async `close(sockets, code, reason)`, which is what `pipeline.web.connect` puts there. Without one, a socket stays open after its credential ends until the tab reconnects. 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 +**One door, in front of everything.** The door is one middleware, installed once by `connect`, in front of every route and the socket. A route checks no credential itself, and the only exceptions are the open list. A route that needs the password again, such as a restore whose body is the database, calls `auth.confirm_password(request, current)`, which is counted and gated like the front door; when the body is a file, it calls `auth.confirm_current(request)` instead, which reads `current` from an `X-Current-Password` header before the body, and answers 403 without counting when the header is missing. A socket is checked at its handshake and closed with 1008 when its credential ends: on a revoke by `close_ended_sockets`, which `/logout`, the password change and the session and token revokes run after their answer, and on expiry by `sweep_ended_sockets`, which `connect` runs on a locked app every `SWEEP` (60) seconds. + **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. +**The lockout is counted in the file and claimed before the check.** A counter on the process is a free reset for whoever is guessing, on a server that reloads. Each guess is claimed before its derivation, in one `BEGIN IMMEDIATE` that reads `locked_until` and counts the attempt, and a right answer clears the count afterwards; read before the derivation and written after it, thirty concurrent guesses all found the door open. A claim refused while locked counts nothing, so hammering the button does not extend your own lockout, which would punish 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 `, 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. +**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.middleware: wrong password from `, stripped to the characters an address is made of — and decided from at the layer that knows who connected. The address is the rightmost hop of `X-Forwarded-For`, which the proxy appended, else `X-Real-IP`, else the peer; the hops left of it are the caller's own writing. `documentation/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. +**A passkey is added only with the password.** A session is not enough: a passkey stays valid after every session ends and after a password change, so a borrowed signed-in browser must not be able to add one. `POST /api/account/passkeys/options` takes `current`, checked behind the same lockout as the front door. An app with no password yet (loopback, never locked) registers without it. Changing the password leaves the passkeys registered; revoke any you do not recognise. + +**An API token is a session for a script.** `POST /api/account/tokens` takes the password like a passkey does, and answers with the token once; the table keeps its SHA-256, a label, the first eight characters so the owner can tell the rows apart, and an optional expiry. A script sends it as `Authorization: Bearer ` and it is looked up on every request, so revoking the row takes effect on the next call. It opens everything a session opens except `/api/account`, `/logout` and what the app names in `connect(session_only=...)`, which answer 403 to a token: a token that leaked cannot mint another, revoke the owner's sessions or read the list of ways in. A route that downloads or restores the database belongs on that list, because the file holds the password hash and the token rows, and a token that could fetch or swap it would hold the account after all. A token the store does not know is a 401 and a WARNING line like a wrong password, and is not counted against the lockout, since 256 random bits are not guessed and the counter would only hand a stranger a way to lock the owner out. A password change leaves tokens in place, as it does passkeys, unless `revoke_all` is sent with it, which deletes every token and passkey; the answer counts the sessions closed and the tokens and passkeys revoked and left. + +**Another site's page changes nothing.** `SameSite=Lax` covers a locked app, and an unlocked one on loopback has no cookie to withhold: a page open in the same browser could `POST` a `text/plain` body to any route that takes none, and open `/ws/jobs`, which CORS does not cover. So the middleware refuses a request that changes something when `Sec-Fetch-Site`, or `Origin` against `Host` or `auth.origin`, says it came from another site, refuses a body of a type a page can send without a preflight (the API is JSON), and refuses a socket handshake from another origin. A read is never refused, and a request with no `Origin` at all (`curl`, a script with a token) passes. The comparison is against the request's own `Host`, which a DNS rebinding page matches, so an app `auto` left open also answers 421 to any request whose `Host` is not a loopback name, a `.localhost` name or the host of `auth.origin`, whatever other headers it carries: a loopback app is reached as `localhost`, and nothing else should be naming it. A test client of an unlocked app therefore names one, e.g. `TestClient(app, base_url="http://127.0.0.1")`. + ## Tests ```bash diff --git a/auth/__init__.py b/auth/__init__.py index 9d6c934..cb6c4af 100644 --- a/auth/__init__.py +++ b/auth/__init__.py @@ -9,27 +9,30 @@ 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. +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` (``) | -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(): diff --git a/auth/config.py b/auth/config.py index 9fadaf7..63c5796 100644 --- a/auth/config.py +++ b/auth/config.py @@ -22,7 +22,7 @@ from pydantic import BaseModel, ConfigDict, Field class AuthConfig(BaseModel): - """The `auth:` block of `config.yaml`. See docs/password-protection.md.""" + """The `auth:` block of `config.yaml`. See documentation/Password Protection.md.""" #: Unknown keys are refused rather than ignored, the same rule the app's #: own sections keep: a setting you believe you have changed and have not @@ -38,9 +38,9 @@ class AuthConfig(BaseModel): #: Deciding from the bind address rather than defaulting to off is the #: whole point. The failure this prevents is the one that actually happens: #: you deploy, it works, and nothing anywhere tells you the door is open. - #: `always` locks it on localhost too and is what a deployment behind a - #: TLS-terminating proxy needs, since there every request looks local to - #: the app and is not. `never` is for putting some other authentication in + #: `always` locks it on localhost too and is what a deployment sets, so the + #: lock does not depend on the bind address or on how the process was + #: started. `never` is for putting some other authentication in #: front of this one, and means exactly what it says. enabled: Literal["auto", "always", "never"] = "auto" @@ -52,10 +52,10 @@ class AuthConfig(BaseModel): #: Whether the session cookie is marked `Secure`, so a browser will only #: ever send it back over HTTPS. `auto` sets it when the request itself - #: arrived over HTTPS, which is right when the app terminates TLS and wrong - #: behind a reverse proxy that terminates it for you -- there the app sees - #: plain HTTP and `auto` reads as "no". Set `always` when something else is - #: doing TLS. `never` exists for testing over http on a LAN and is the + #: arrived over HTTPS, which behind a reverse proxy that terminates TLS + #: holds only while the server trusts `X-Forwarded-Proto` from it; the app + #: alone cannot tell. Set `always` when something else is doing TLS. + #: `never` exists for testing over http on a LAN and is the #: setting to be uncomfortable with. secure_cookie: Literal["auto", "always", "never"] = "auto" diff --git a/auth/middleware.py b/auth/middleware.py index 5c707d4..eeab44e 100644 --- a/auth/middleware.py +++ b/auth/middleware.py @@ -1,8 +1,10 @@ """The lock on the door: is there a session, and what happens when there isn't. -Three things live here — when the door is locked at all, who gets past it, and -the cookie that says so. The password itself is `auth/store.py`; this module -never sees a hash. +Six things live here — when the door is locked at all, who gets past it, the +cookie and the bearer header that say so, the rule that another site's page +gets nothing changed, the password asked again from behind a session +(`confirm_password`, and `confirm_current` for a header), and the closing of a socket whose credential has ended. +The password itself is `auth/store.py`; this module never sees a hash. ## Why a middleware and not a dependency @@ -30,6 +32,66 @@ password is a second lock on it; bound to anything else, the app is on a network and needs its own. The alternative — default off, switch it on when you deploy — fails silently in the exact case it exists for, because an app serving the internet with no password looks and behaves precisely like one that is fine. +A reverse proxy on the same machine defeats the bind address, so an app `auto` +left open refuses any request a proxy forwarded; see +`RequireLogin._refuse_proxied`. + +## Three credentials, two carriers + +A session cookie is what the password and a passkey open, and it is what a +browser carries. An API token (`AuthStore.create_token`) is what a script +carries, as `Authorization: Bearer `, and it is looked up on every +request the way a session is, so revoking it takes effect on the next call. +The cookie is read first and wins; the header is read only when there is no +live session. A token opens every door the session does except the account: +a request carrying one for `/api/account` or `/logout` is answered 403 +(`ACCOUNT`), so a token that leaked cannot mint another, revoke the owner's +sessions or read the list of ways in. An app adds its own session-only routes +through `connect(session_only=...)`: anything that reads or replaces the +database as a file belongs there, since the file holds the password hash and +these rows, and a token that could fetch or swap it would hold the account +after all. A token that is not live is a 401 and a +WARNING line, like a wrong password; it is not counted against the lockout, +since 256 random bits are not guessed and the counter would only hand a +stranger a way to lock the owner out. + +## Another site's page + +`SameSite=Lax` keeps the session cookie off a cross-site `POST`, which covers +a locked app. An unlocked one on loopback has no cookie to withhold, so a page +open in the same browser could `POST` to `http://127.0.0.1:8787/api/...` with +a `text/plain` body, which needs no preflight, and every route that takes no +body acted on it; a WebSocket handshake is not subject to CORS at all, so the +same page could open `/ws/jobs` and read every job and notice. So a request +that changes something is refused when the browser says it came from another +site (`Sec-Fetch-Site`, else `Origin` against `Host` or `AuthConfig.origin`), +and a body of a type another site could send without a preflight is refused +whoever sent it: the API is JSON. Locked or not, because the rule costs two +header reads and a locked app with `secure_cookie: never` on a LAN is a real +deployment. See `cross_site`. + +That comparison is against the request's own `Host`, and a page served from +`rebind.example` whose name is pointed at 127.0.0.1 arrives with a `Host` and +an `Origin` that agree. So an app `auto` left open also refuses any request +whose `Host` is not a loopback name, a `.localhost` name or the host of +`AuthConfig.origin`, with the same 421 as a forwarded one, whatever else it +carries: a browser that sends no fetch metadata and no `Origin` on a read is +still a rebound page. A loopback app is reached as `localhost` or +`127.0.0.1`, and a request that names another host for it came through a +proxy or a rebinding, neither of which the bind address can see. A test +client names the host it is given (`base_url="http://127.0.0.1"`). + +## A socket outlives its handshake + +The door is checked when a socket opens, and the socket stays open for the +life of the tab. So a route that ends a credential (`/logout`, a password +change, a revoked session or token) runs `close_ended_sockets` after its +answer, which asks the store about every open socket's cookie or bearer header +and closes the ones it no longer knows with 1008. Expiry ends no request, so +`connect` also runs `sweep_ended_sockets`, which does the same every `SWEEP` +seconds. A tab's reconnect then meets the door. The sockets are the app's: +`app.state.bus`, which `pipeline.web.connect` sets, and an app without one has +nothing to close. """ from __future__ import annotations @@ -37,11 +99,11 @@ from __future__ import annotations import asyncio import ipaddress import logging -from http.cookies import SimpleCookie from typing import Any -from urllib.parse import quote +from urllib.parse import quote, urlsplit -from starlette.requests import HTTPConnection +from fastapi import HTTPException +from starlette.requests import HTTPConnection, cookie_parser from starlette.responses import JSONResponse, RedirectResponse, Response from starlette.types import ASGIApp, Receive, Scope, Send @@ -61,6 +123,22 @@ log = logging.getLogger(__name__) #: against the path only — a query string cannot widen this. OPEN: tuple[str, ...] = ("/login", "/login/", "/_auth/", "/health") +#: What a bearer token cannot reach: the account, which is managed from a +#: browser with a session, and the sign-out of a session a token has not got. +#: Matched as `OPEN` is. Everything else a session opens, a token opens. +ACCOUNT: tuple[str, ...] = ("/api/account", "/api/account/", "/logout") + +#: What a request carrying a token for the account is told. +TOKEN_NOT_HERE = ("An API token opens the API, not the account. Sign in with the " + "password or a passkey to manage it.") + + +def matches(path: str, names: tuple[str, ...]) -> bool: + """Whether `path` is one of `names`: a name ending in `/` is a prefix, any + other is matched whole. The one rule for `OPEN` and `ACCOUNT`.""" + return any(path == name.rstrip("/") or (name.endswith("/") and path.startswith(name)) + for name in names) + def locked(config: AuthConfig, host: str) -> bool: """Whether this app should ask for a password. See `AuthConfig.enabled`. @@ -126,47 +204,113 @@ def token_from(conn: HTTPConnection | Scope, config: AuthConfig) -> str: Both cookie names are looked for, so flipping `secure_cookie` or moving behind TLS does not strand a live session under the other name. + + Parsed per `;`-separated pair by Starlette's `cookie_parser`, as a browser + does, and not by `http.cookies.SimpleCookie`, whose `load` returns an + empty jar for the whole header when one cookie in it has a space or JSON + in its value: a sibling app on the parent domain setting `theme=dark mode` + signed the owner out on every request. A pair that is not a cookie is + skipped, so a garbage header is no cookie rather than a 500. """ scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn for key, value in scope.get("headers", ()): if key == b"cookie": - jar = SimpleCookie() - try: - jar.load(value.decode("latin-1")) - except Exception: # a cookie header that is not one - return "" + jar = cookie_parser(value.decode("latin-1")) for name in cookie_names(config): - if name in jar: - return jar[name].value + if jar.get(name): + return jar[name] return "" +def bearer_from(conn: HTTPConnection | Scope) -> str: + """The API token this request carries in `Authorization: Bearer`, or "". + + Only that header and only that scheme: a token in a query string would + land in every access log between the script and the app, and `Basic` is + a password, which has its own door. + """ + value = _header(conn, b"authorization") + scheme, _, token = value.strip().partition(" ") + if scheme.lower() != "bearer": + return "" + return token.strip() + + +def _header(conn: HTTPConnection | Scope, name: bytes) -> str: + scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn + for key, value in scope.get("headers", ()): + if key == name: + return value.decode("latin-1") + return "" + + +def credential_live(store: AuthStore, config: AuthConfig, + conn: HTTPConnection | Scope) -> bool: + """Whether what this request carries still opens the door: its cookie's + session, else its bearer token. What `RequireLogin` decides from, asked + again of an open socket by `close_ended_sockets`.""" + token = token_from(conn, config) + if token and store.touch(token) is not None: + return True + bearer = bearer_from(conn) + return bool(bearer) and store.touch_token(bearer) is not None + + def client_address(conn: HTTPConnection | Scope) -> str: """Who is asking, as well as it can be known, for the log to say so. Behind a reverse proxy the peer is a container on the same Docker network - and says nothing about who is at the other end; the address worth writing - down is the first hop of `X-Forwarded-For`, which the proxy sets. Both are - reported when they differ, because the header is only as trustworthy as - whoever sent it — which is why nothing is *decided* from this, only logged. - See `AuthStore.check_password` for that argument in full. + and says nothing about who is at the other end. The address worth writing + down is the rightmost hop of `X-Forwarded-For`, the one the proxy in front + of this app appended for the connection it accepted; every hop left of it + was in the request when it arrived and is whatever the caller wrote. nginx's + `$proxy_add_x_forwarded_for` appends rather than replaces, so the first hop + let an attacker name the address a fail2ban filter on this line bans. + Without that header, `X-Real-IP`, which such a proxy sets outright. The + claimed address and the peer are both reported when they differ, because a + header is only as trustworthy as the proxy that set it, which is why + nothing is *decided* from this, only logged. See + `AuthStore.check_password` for that argument in full. - That header is also the one piece of a stranger's own writing that ends up + The header is also the one piece of a stranger's writing that can end up in the log, so only the characters an address is made of survive the trip: a line in this log is something fail2ban reads and a person believes, and - neither should be forgeable by whoever is knocking. + neither should be forgeable by whoever is knocking. The address stays the + first word after `from`, so a filter is one regex. """ scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn peer = (scope.get("client") or ("", 0))[0] or "unknown" + forwarded = real = "" for key, value in scope.get("headers", ()): + # The last of each, should a header arrive twice: a proxy that adds + # one rather than appending writes it after the caller's. if key == b"x-forwarded-for": - first = value.decode("latin-1").split(",")[0] - claimed = "".join(c for c in first if c.isalnum() or c in ".:%-")[:45] - if claimed and claimed != peer: - return f"{claimed} via {peer}" + forwarded = value.decode("latin-1") + elif key == b"x-real-ip": + real = value.decode("latin-1") + hop = forwarded.split(",")[-1] if forwarded.strip() else real + claimed = "".join(c for c in hop if c.isalnum() or c in ".:%-")[:45] + if claimed and claimed != peer: + return f"{claimed} via {peer}" return peer +#: Headers a reverse proxy adds. Any one of them on a request to an app that +#: `auto` left open because it binds loopback means the bind address is not the +#: whole story: a proxy on this machine is passing on someone else. +FORWARDED = frozenset({b"forwarded", b"x-forwarded-for", b"x-forwarded-proto", + b"x-forwarded-host"}) + +#: What such a request is answered with, for whoever runs the proxy. +PROXIED = ("This app binds loopback and so asks for no password, but this request " + "came through a proxy. Set auth.enabled: always in config.yaml and restart.") + +#: What a browser script's request naming another host is answered with. +REBOUND = ("This app binds loopback and so asks for no password, but this request " + "names a host that is not localhost. Open the app as http://localhost, or " + "set auth.enabled: always in config.yaml and restart.") + + #: Prefixes whose refusal is JSON rather than a redirect. A caller that asked #: for data and is sent a login page reads it as a 200 full of HTML where its #: JSON should be; `{"detail": ...}` with a 401 is something it can act on. @@ -187,20 +331,35 @@ class RequireLogin: """ def __init__(self, app: ASGIApp, store: AuthStore, config: AuthConfig, - open: tuple[str, ...] = (), host: str = "") -> None: + open: tuple[str, ...] = (), host: str = "", + session_only: tuple[str, ...] = ()) -> None: self.app = app self.store = store self.config = config self.open = OPEN + tuple(open) + #: What a token may not reach: the account, and whatever the app adds. + self.session_only = (*ACCOUNT, *session_only) self.locked = locked(config, host) + #: Open only because `auto` saw loopback; see `_refuse_proxied`. + self.watch_proxy = config.enabled == "auto" and not self.locked + self.warned = False async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: - if scope["type"] not in ("http", "websocket") or not self.locked: + if scope["type"] not in ("http", "websocket"): + return await self.app(scope, receive, send) + # Another site's page, locked or not: see the module docstring. + refused = cross_site(scope, self.config.origin) + if refused is not None: + return await self._answer(scope, receive, send, *refused) + if not self.locked: + if self.watch_proxy and _forwarded(scope): + return await self._refuse_proxied(scope, receive, send, PROXIED) + if self.watch_proxy and _rebound(scope, self.config.origin): + return await self._refuse_proxied(scope, receive, send, REBOUND) return await self.app(scope, receive, send) path = scope.get("path", "") - if any(path == p.rstrip("/") or (p.endswith("/") and path.startswith(p)) - for p in self.open): + if matches(path, self.open): return await self.app(scope, receive, send) token = token_from(scope, self.config) @@ -214,8 +373,34 @@ class RequireLogin: scope["auth_token"] = token return await self.app(scope, receive, send) + bearer = bearer_from(scope) + if bearer: + held = await asyncio.to_thread(self.store.touch_token, bearer) + if held is not None: + if matches(path, self.session_only): + return await self._answer(scope, receive, send, 403, TOKEN_NOT_HERE) + # The row, for a route that wants to know it was a script. + scope["auth_bearer"] = held.id + return await self.app(scope, receive, send) + # The same line a wrong password writes, for the same reader. A + # script with a bad token gets JSON whatever it asked for: a + # redirect to the login page is for a browser, and a browser does + # not send this header. + log.warning("bad token from %s", client_address(scope)) + return await self._answer(scope, receive, send, 401, + "That token is not valid here.") + await self._refuse(scope, receive, send, path) + async def _answer(self, scope: Scope, receive: Receive, send: Send, + status: int, detail: str) -> None: + """A refusal in the shape the caller can act on: `{"detail"}` with the + status, or a 1008 close before the socket is accepted.""" + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 1008}) + return + await JSONResponse({"detail": detail}, status_code=status)(scope, receive, send) + async def _refuse(self, scope: Scope, receive: Receive, send: Send, path: str) -> None: """No session. Say so in whatever the caller can understand.""" @@ -244,3 +429,301 @@ class RequireLogin: else: response = JSONResponse({"detail": "Not signed in"}, status_code=401) await response(scope, receive, send) + + async def _refuse_proxied(self, scope: Scope, receive: Receive, send: Send, + detail: str) -> None: + """421 for a forwarded request to an app `auto` left open, and for a + request that names a host it is not reached under (`_rebound`). + + `auto` reads loopback as "this machine only", and a reverse proxy on + the same machine makes that false while every request still arrives + from 127.0.0.1. The peer cannot tell the proxy from a local browser, + only the headers the proxy adds can, so a request carrying one is + refused rather than served unlocked. A client can add the headers + itself, which only gets it refused. The Vite dev server's proxy adds + none (`xfwd` is off) and forwards `Host` unchanged, so `npm run dev` + is unaffected. Logged once at WARNING, since every request through + the proxy would repeat it. + """ + if not self.warned: + self.warned = True + log.warning("refused a proxied or rebound request to an unlocked app (%s): %s", + client_address(scope), detail) + if scope["type"] == "websocket": + await send({"type": "websocket.close", "code": 1008}) + return + await JSONResponse({"detail": detail}, status_code=421)(scope, receive, send) + + +def _forwarded(scope: Scope) -> bool: + return any(key in FORWARDED for key, _ in scope.get("headers", ())) + + +def _rebound(scope: Scope, configured_origin: str) -> bool: + """Whether a request reaches this loopback app under a name that is not + loopback: the shape of a DNS rebinding, where the page's own `Origin` and + the `Host` it sends agree and `_from_here` cannot tell. + + Every request is judged, whatever headers it carries. A browser that sends + neither `Sec-Fetch-Site` nor `Origin` on a read is still a page on the + rebound name reading the API, and the only names a loopback app is reached + under are a loopback address, `localhost` and its subdomains, and the host + of `AuthConfig.origin`. A missing or unparseable `Host` names none of + them and is refused too. + """ + try: + host = urlsplit("//" + _header(scope, b"host")).hostname or "" + except ValueError: # an unparseable authority, e.g. `[` + return True + if _loopback(host) or host.endswith(".localhost"): + return False + allowed = urlsplit(configured_origin).hostname if configured_origin else "" + return not host or host != (allowed or "").lower() + + +# ------------------------------------------------------ the password again + +def claim_attempt(conn: HTTPConnection) -> None: + """The lockout, in front of every place a password can be guessed: 429 + while it holds, else the guess is counted before it is derived. + + `AuthStore.claim_attempt` decides and counts in one write transaction, so + concurrent guesses each see the ones before them and a window admits five + of them, not a threadpool's worth. A refused claim counts nothing, so + hammering while locked out does not extend the lockout. The caller then + checks with `check_password(..., claimed=True)`, which clears the count + when the guess was right. Called from both doors rather than living inside + `check_password`, because the same comparison is a counted guess here and + a bootstrap comparison in `auth.bootstrap`, which must not be able to lock + anyone out of their own restart. + """ + wait = conn.app.state.auth.claim_attempt() + if wait: + warn(conn, "attempt while locked out") + raise HTTPException(429, f"Too many attempts. Try again in {_spell(wait)}.", + headers={"Retry-After": str(wait)}) + + +def confirm_password(conn: HTTPConnection, current: str) -> None: + """The password again, from someone already signed in: changing it, adding + a passkey, minting a token, and any app route that must not be one + borrowed browser away from the account (`connect(session_only=...)`). + Counted and gated like the front door, because `current` is a guess at the + password made from behind a session: 429 while locked out, 403 when wrong. + + It has nothing to confirm on an app with no password yet, which refuses + every guess, so a route that can run there asks `has_password()` first, as + the account routes do.""" + claim_attempt(conn) + if not conn.app.state.auth.check_password(current, claimed=True): + warn(conn, "wrong current password") + raise HTTPException(403, "That is not the current password.") + + +#: Where a route whose body is a file takes the current password. A header and +#: not a field, because the body is the file itself; read before the first byte +#: of that body, so a refusal costs no upload. +CURRENT_HEADER = "x-current-password" + + +def confirm_current(conn: HTTPConnection) -> None: + """The current password from the `X-Current-Password` header, for a route + that hands out or replaces the database as a file (`connect(session_only=...)`). + + A session is not enough for a route that replaces the credentials: the + restored file brings its own password hash, passkeys and tokens, so a + borrowed signed-in browser that could restore a doctored backup would own + the account. Call it before reading the body. A missing or empty header is + a WARNING line and a 403 that counts nothing against the lockout, since a + missing field is not a guess; a wrong one goes through `confirm_password`, + which counts it, warns and answers 403, or 429 while locked out. An app + that never had a password (loopback, never locked) has nothing to confirm. + + The check is a deliberately slow derivation, so a coroutine route runs it + in the threadpool. newsdesk's `/api/restore` is the caller. + """ + if not conn.app.state.auth.has_password(): + return + current = conn.headers.get(CURRENT_HEADER, "") + if not current: + warn(conn, f"no current password for {conn.scope.get('method', '')} " + f"{conn.scope.get('path', '')}") + raise HTTPException(403, "This takes the current password in X-Current-Password.") + confirm_password(conn, current) + + +def warn(conn: HTTPConnection, what: str) -> None: + """Write down that someone got it wrong, and who. + + The whole record of who is knocking. There is no access log worth the name — + uvicorn is run quietly — and no table of attempts, because the log is the + record and a second copy of it would only ever disagree. WARNING so it + survives that level, one line per refusal, and the address first after + `from` so a fail2ban filter is one regex; see documentation/Password Protection.md. + + The message does not name the package, because the logger already does: + with the usual `%(name)s: %(message)s` this module is `auth.middleware`, + and a line reading `auth.middleware: auth: wrong password` says it twice + and reads like a bug in the logging. + + Nothing is *decided* from the address — `AuthStore.check_password` says why + it cannot be — so this is where it earns its keep: at the layer that can + drop the connection instead of answering it. + """ + log.warning("%s from %s", what, client_address(conn)) + + +def _spell(seconds: int) -> str: + if seconds < 60: + return f"{seconds} seconds" + return f"{round(seconds / 60)} minutes" + + +# --------------------------------------------- sockets whose credential ended + +#: How often, in seconds, `sweep_ended_sockets` asks about every open socket: +#: the longest an expired session or token keeps the socket it opened. +SWEEP = 60.0 + + +async def close_ended_sockets(app: Any) -> int: + """Close every open socket whose session or token has ended. Returns how + many it closed. + + The door is checked at the handshake, and a socket stays open for the + life of the tab. So signing out, changing the password or revoking a + session or a token left the socket it had opened streaming to whoever + held it. Run after each of those, as a background task of the route, and + on a clock by `sweep_ended_sockets`, this asks the store about every + socket's cookie or bearer header (`credential_live`) and closes the ones + it no longer knows with 1008; a tab's reconnect then meets the door. + + The sockets are `app.state.bus`: what `pipeline.web.connect` puts there, + or anything with a `sockets` tuple and an async `close(sockets, code, + reason)`. Nothing to do on an unlocked app, which has no sessions to + end, or on one without a bus. + """ + if not getattr(app.state, "auth_locked", False): + return 0 + bus = getattr(app.state, "bus", None) + if bus is None: + return 0 + store, config = app.state.auth, app.state.auth_config + sockets = bus.sockets + + def ended() -> list[Any]: + return [ws for ws in sockets if not credential_live(store, config, ws)] + + # `to_thread`, because the store is SQLite and this is the event loop. + gone = await asyncio.to_thread(ended) + return await bus.close(gone, 1008, "signed out") if gone else 0 + + +async def sweep_ended_sockets(app: Any, every: float = SWEEP) -> None: + """`close_ended_sockets` every `every` seconds, until cancelled. + + The door is checked at the handshake only, and the routes that end a + credential close its sockets themselves. Expiry is seen by no route: a + session or token that runs out ends no request, so its socket streamed + until the tab reconnected. This closes it within `every` seconds. + `connect` starts it on a locked app and cancels it at shutdown. A sweep + that fails is logged and the next one runs, since a loop that died on + one busy database would leave every later expiry open. + """ + while True: + await asyncio.sleep(every) + try: + await close_ended_sockets(app) + except Exception: + log.warning("the socket sweep failed", exc_info=True) + + +# ------------------------------------------------------------ another site + +#: The methods that change something. No `GET` here changes anything (see the +#: module docstring of `auth/router.py`), so these are the ones to guard. +UNSAFE = frozenset({"POST", "PUT", "PATCH", "DELETE"}) + +#: The bodies another site's page may send without the browser asking first: +#: the three CORS-safelisted types, and a body with no type at all. A +#: cross-site request with any other type is preflighted, and nothing here +#: answers a preflight, so it never leaves the browser. +SIMPLE_BODIES = frozenset({"", "text/plain", "application/x-www-form-urlencoded", + "multipart/form-data"}) + +CROSS_SITE = ("This request came from another site's page, and nothing here " + "changes on another site's say-so.") + + +def cross_site(scope: Scope, configured_origin: str = "") -> tuple[int, str] | None: + """Why a request that changes something is refused, or None. + + Two checks, the first for the socket too: + + - **Where it came from.** `Sec-Fetch-Site` when the browser sends it, + which a page cannot set; otherwise `Origin`, which must name this host + or `configured_origin` (`AuthConfig.origin`, for a proxy that rewrites + `Host`). No `Origin` at all is a client that is not a browser page + (`curl`, a script with a token, a test) and passes. + - **What the body is.** A body of a type another site could send without + a preflight is refused, whoever sent it: the API is JSON. + + A read is never refused, wherever it came from. + """ + if scope["type"] == "websocket": + if not _from_here(scope, configured_origin): + return 403, "another site's page cannot open this socket" + return None + if scope.get("method") not in UNSAFE: + return None + if not _from_here(scope, configured_origin): + return 403, CROSS_SITE + kind = _header(scope, b"content-type").split(";")[0].strip().lower() + if _has_body(scope) and kind in SIMPLE_BODIES: + return 415, ("Send the body as application/json, not " + f"{kind or 'without a content type'}.") + return None + + +def _from_here(scope: Scope, configured: str) -> bool: + """Whether the page that sent this is this app's own, as far as the + browser says. + + `Sec-Fetch-Site` decides when present: the browser sets it and a page + cannot, and it stays right behind a proxy that rewrites `Host`, where an + `Origin` comparison would refuse the app's own page. `none` is a request + the user made by typing or from a bookmark. Without it, `Origin` against + `Host` (the Vite dev server forwards `Host` unchanged) or against the + configured origin. `null` is a sandboxed frame or a `file://` page and is + never this app. + """ + site = _header(scope, b"sec-fetch-site") + if site: + return site in ("same-origin", "none") + origin = _header(scope, b"origin") + if not origin: + return True + if origin == "null": + return False + if configured and origin.rstrip("/") == configured.rstrip("/"): + return True + parts = urlsplit(origin) + host = _header(scope, b"host") + return bool(host) and (_authority(parts.scheme, parts.netloc) + == _authority(parts.scheme, host)) + + +def _authority(scheme: str, netloc: str) -> str: + """`host[:port]`, lowercased, without the scheme's default port, so + `Host: app.example.com:443` and `Origin: https://app.example.com` agree.""" + netloc = netloc.lower() + default = {"http": ":80", "ws": ":80", "https": ":443", "wss": ":443"}.get(scheme, "") + return netloc[: -len(default)] if default and netloc.endswith(default) else netloc + + +def _has_body(scope: Scope) -> bool: + length = _header(scope, b"content-length") + # The header's presence, not its value, says a body follows; an empty value + # is malformed and is not given the benefit of the doubt. + chunked = any(key == b"transfer-encoding" for key, _ in scope.get("headers", ())) + return (length.isdigit() and int(length) > 0) or chunked diff --git a/auth/models.py b/auth/models.py index 2512073..1a1d5ec 100644 --- a/auth/models.py +++ b/auth/models.py @@ -1,8 +1,8 @@ """What the Account tab is told, and nothing more. -Three models, and the thing worth noticing about all three is what they cannot +Four models, and the thing worth noticing about all four is what they cannot carry. No token, no hash, no key material — not even the public half of a -passkey. The list of ways into an app is the one page most worth reading and +passkey; of an API token, the first eight characters and never the rest. The list of ways into an app is the one page most worth reading and least worth leaking, so the shape it is rendered from is one that could not leak a credential if it were logged whole. """ @@ -47,6 +47,27 @@ class Passkey(BaseModel): transports: list[str] = Field(default_factory=list) +class ApiToken(BaseModel): + """One token a script signs in with, as the account screen sees it. + + The token itself is shown once, when it is made (`TokenCreated` in + `auth/schemas.py`), and is not here: this is the row, which is what the + revoke button sends back. `hint` is the token's opening, enough to match + the row to the environment variable that holds the whole. + """ + + id: int + #: What you called it. Named for the machine or the job that holds it, so + #: the one to revoke can be told from the others. + label: str = "" + #: The token's first characters. See `auth.store.HINT`. + hint: str = "" + created_at: str = "" + last_used_at: str = "" + #: When it stops working, or "" for a token that does not expire. + expires_at: str = "" + + class Account(BaseModel): """What the account screen knows. Deliberately almost nothing. @@ -79,3 +100,5 @@ class Account(BaseModel): #: honest common case is an insecure origin: WebAuthn refuses anything but #: HTTPS, localhost excepted, so this reads "you need TLS first". passkeys_blocked: str = "" + #: The API tokens, expired ones included, each without its secret. + tokens: list[ApiToken] = Field(default_factory=list) diff --git a/auth/passkeys.py b/auth/passkeys.py index c3b6bbf..2e89024 100644 --- a/auth/passkeys.py +++ b/auth/passkeys.py @@ -291,11 +291,19 @@ def login_verify(config: AuthConfig, request: Request, store: AuthStore, ) challenge = _challenge_from(credential) + # Read before the challenge is spent, and inside a `try`: outside one, a + # `rawId` that is not base64url was a 500 from an endpoint anyone can + # reach, after the challenge had already been used up. + try: + raw_id = base64url_to_bytes(credential.get("rawId", "")) + except (TypeError, ValueError) as exc: + raise PasskeyMalformed("That response was not a passkey: its rawId is " + "not base64url.") from exc if not store.take_challenge(challenge, "login"): raise PasskeyError("That sign-in took too long, or was already used. " "Try again.") - known = store.passkey_for(base64url_to_bytes(credential.get("rawId", ""))) + known = store.passkey_for(raw_id) if known is None: # Deliberately the same sentence as a bad signature. There is one user, # so this leaks little, but "that key is not registered" is an oracle diff --git a/auth/router.py b/auth/router.py index 1450067..57d2aae 100644 --- a/auth/router.py +++ b/auth/router.py @@ -29,18 +29,20 @@ import os from pathlib import Path from urllib.parse import unquote, urlsplit -from fastapi import APIRouter, HTTPException, Request, Response +from fastapi import APIRouter, BackgroundTasks, HTTPException, Request, Response from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse from starlette.requests import HTTPConnection from auth import passkeys as pk from auth.config import AuthConfig from auth.middleware import ( - client_address, cookie_name, cookie_names, is_secure, token_from, + claim_attempt, close_ended_sockets, confirm_password, cookie_name, cookie_names, + is_secure, token_from, warn, ) from auth.models import Account from auth.schemas import ( - LabelBody, LoginBody, PasskeyBody, PasskeyLoginBody, PasswordBody, + LabelBody, LoginBody, Ok, PasskeyAdded, PasskeyBody, PasskeyLoginBody, + PasskeyOptionsBody, PasswordBody, PasswordChanged, SignedOut, TokenBody, TokenCreated, ) from auth.store import AuthStore @@ -63,7 +65,7 @@ NO_STORE = {"Cache-Control": "no-store"} #: The shortest new password the account screen will take. Low, deliberately: #: it is a floor against a typo, not a password policy. The honest advice is in -#: docs/password-protection.md — the generated password is sixteen random +#: documentation/Password Protection.md — the generated password is sixteen random #: characters and anything you choose yourself is the weak half. MIN_LENGTH = 8 @@ -156,19 +158,20 @@ def login_page(request: Request) -> Response: def sign_in(request: Request, response: Response, body: LoginBody) -> dict[str, str]: """Check the password, and if it is right, open a session. - The lockout is read *before* the password is checked, so hammering the - button while locked out does not extend the lockout — see - `AuthStore.locked_for`. A wrong password and an unknown one are the same - answer here for the usual reason, which is thin cover with one account but - costs nothing to keep. + The attempt is claimed *before* the password is derived, which reads the + lockout and counts the guess in one write, so hammering the button while + locked out does not extend the lockout and concurrent guesses cannot all + slip in under one reading of it; see `AuthStore.claim_attempt`. A wrong + password and an unknown one are the same answer here for the usual + reason, which is thin cover with one account but costs nothing to keep. """ if not _locked(request): raise HTTPException(400, "This app is not password-protected.") - _refuse_while_locked(request) + claim_attempt(request) - if not _store(request).check_password(body.password): - _warn(request, "wrong password") + if not _store(request).check_password(body.password, claimed=True): + warn(request, "wrong password") raise HTTPException(401, "That is not the password.") _open_session(request, response) @@ -176,17 +179,22 @@ def sign_in(request: Request, response: Response, body: LoginBody) -> dict[str, @router.post("/logout", include_in_schema=False) -def sign_out(request: Request, response: Response) -> dict[str, bool]: - """End this session and clear the cookie. Other devices are untouched.""" +def sign_out(request: Request, response: Response, tasks: BackgroundTasks) -> Ok: + """End this session and clear the cookie. Other devices are untouched. + + The socket this tab opened is closed too, after the answer; see + `auth.close_ended_sockets`. The same for the four routes below that end + a session or a token.""" token = token_from(request, _config(request)) if token: _store(request).close_session(token) + tasks.add_task(close_ended_sockets, request.app) # Both names, because which one was set depends on `secure_cookie` and on # the scheme the login happened over — and clearing only one of them leaves # a cookie the browser will keep offering. for name in cookie_names(_config(request)): response.delete_cookie(name, path="/") - return {"ok": True} + return Ok() # ---------------------------------------------------------------- the account @@ -205,11 +213,13 @@ def account(request: Request) -> Account: passkeys=store.passkeys(), passkeys_available=pk.available(), passkeys_blocked=pk.blocked(config, request), + tokens=store.tokens(), ) @router.post("/api/account/password") -def change_password(request: Request, body: PasswordBody) -> dict[str, int]: +def change_password(request: Request, body: PasswordBody, + tasks: BackgroundTasks) -> PasswordChanged: """Change it, having proved you know the current one — or set the first. Asking for the current password matters even though you are already signed @@ -223,6 +233,13 @@ def change_password(request: Request, body: PasswordBody) -> dict[str, int]: the change ceremonial — and the cost when that is not the reason is signing in again on your phone, which is the right way round. + API tokens and passkeys stay by default, because the cron job holding a + token is not what the password was changed against. `revoke_all` deletes + every one of them too, for the case the route exists for: an intruder + who had the password could have minted a token that never expires or + registered a passkey, and either outlives the change. The answer counts + what was closed and what remains, so the screen can say so. + Which is also why this is behind the same lockout as the front door, and not only behind a session. `current` is the password, guessed here rather than at `/login`, and a borrowed unlocked laptop is exactly the situation the @@ -244,32 +261,82 @@ def change_password(request: Request, body: PasswordBody) -> dict[str, int]: # app never lands here: `auth.bootstrap` gives it a password at startup, # so `current` is always required for the app that has a door. if store.has_password(): - _refuse_while_locked(request) - if not store.check_password(body.current): - _warn(request, "wrong current password") - raise HTTPException(403, "That is not the current password.") + confirm_password(request, body.current) if len(body.new) < MIN_LENGTH: raise HTTPException(400, f"Use at least {MIN_LENGTH} characters.") store.set_password(body.new) closed = store.close_all(keep=token_from(request, config)) - return {"signed_out": closed} + tokens, keys = store.revoke_credentials() if body.revoke_all else (0, 0) + tokens_left, keys_left = store.counts() + tasks.add_task(close_ended_sockets, request.app) + return PasswordChanged(signed_out=closed, tokens_revoked=tokens, passkeys_revoked=keys, + tokens_left=tokens_left, passkeys_left=keys_left) @router.delete("/api/account/sessions/{session_id}") -def revoke(session_id: int, request: Request) -> dict[str, bool]: +def revoke(session_id: int, request: Request, tasks: BackgroundTasks) -> Ok: """Drop one session. Revoking your own is allowed — it is a logout with an extra click, and refusing it would be a rule to explain for no gain.""" if not _store(request).close_by_id(session_id): raise HTTPException(404, "That session is already gone.") - return {"ok": True} + tasks.add_task(close_ended_sockets, request.app) + return Ok() @router.post("/api/account/sessions/close") -def close_others(request: Request) -> dict[str, int]: +def close_others(request: Request, tasks: BackgroundTasks) -> SignedOut: """Sign out everywhere but here. The reason sessions are rows.""" + closed = _store(request).close_all(keep=token_from(request, _config(request))) + tasks.add_task(close_ended_sockets, request.app) + return SignedOut(signed_out=closed) + + +# --------------------------------------------------------------------- tokens +# +# Three routes, all behind a session and none reachable with a token: the +# middleware answers a bearer request under `/api/account` with 403 +# (`auth.middleware.ACCOUNT`), so a leaked token cannot mint another, revoke +# the owner's sessions or read the list of ways in. The token is used +# anywhere else as `Authorization: Bearer `. + + +@router.post("/api/account/tokens") +def create_token(request: Request, body: TokenBody) -> TokenCreated: + """Mint an API token for a script, once the password is confirmed. + + A session is not enough, for the reason it is not enough for a passkey: a + token outlives every session and a password change, so a borrowed + signed-in browser that could mint one would keep a way in for good. + `current` is checked as `change_password` checks it, behind the same + lockout, and on the same condition. The token is in this answer and + nowhere else; the store keeps its hash. + """ store = _store(request) - return {"signed_out": store.close_all(keep=token_from(request, _config(request)))} + if store.has_password(): + confirm_password(request, body.current) + token_id, token = store.create_token(body.label, body.days) + made = next(t for t in store.tokens() if t.id == token_id) + return TokenCreated(id=token_id, token=token, hint=made.hint, label=made.label, + expires_at=made.expires_at) + + +@router.post("/api/account/tokens/{token_id}/label") +def rename_token(token_id: int, body: LabelBody, request: Request) -> Ok: + if not _store(request).rename_token(token_id, body.label): + raise HTTPException(404, "That token is already gone.") + return Ok() + + +@router.delete("/api/account/tokens/{token_id}") +def drop_token(token_id: int, request: Request, tasks: BackgroundTasks) -> Ok: + """Revoke one. The next request carrying it is refused, whatever it holds + open: a token is looked up on every request, like a session, and a socket + it opened is closed as a session's is.""" + if not _store(request).delete_token(token_id): + raise HTTPException(404, "That token is already gone.") + tasks.add_task(close_ended_sockets, request.app) + return Ok() # ------------------------------------------------------------------- passkeys @@ -281,24 +348,37 @@ def close_others(request: Request) -> dict[str, int]: @router.post("/api/account/passkeys/options") -def passkey_options(request: Request) -> dict[str, object]: - """Step one of registering: a challenge for `navigator.credentials.create`.""" +def passkey_options(request: Request, body: PasskeyOptionsBody) -> dict[str, object]: + """Step one of registering: a challenge for `navigator.credentials.create`, + once the password is confirmed. + + A session is not enough. A passkey outlives every session and a password + change, so a borrowed signed-in browser that could add one would keep a way + in for good. `current` is checked as `change_password` checks it, behind the + same lockout, and on the same condition: an app with no password (loopback, + never locked) has nothing to confirm and no session to borrow, so + registering there before deploying still works. + """ _require_passkeys(request) - return pk.register_options(_config(request), request, _store(request)) + store = _store(request) + if store.has_password(): + confirm_password(request, body.current) + return pk.register_options(_config(request), request, store) @router.post("/api/account/passkeys") -def add_passkey(request: Request, body: PasskeyBody) -> dict[str, int]: +def add_passkey(request: Request, body: PasskeyBody) -> PasskeyAdded: """Step two: check what the authenticator signed, and keep the public key. - Requires a session, like everything else under `/api/account`. Registering a - passkey is granting a new way in, so it is gated on already being in — the - password is what proves that, and the ceremony does not replace it. + Requires a session, like everything else under `/api/account`, and a + challenge from `passkey_options`, which only the password gets. The + challenge is single-use and bound to registering, so this step cannot be + reached without the password having been typed for it. """ _require_passkeys(request) try: - return {"id": pk.register_verify(_config(request), request, _store(request), - body.credential, body.label)} + return PasskeyAdded(id=pk.register_verify(_config(request), request, _store(request), + body.credential, body.label)) except pk.PasskeyError as exc: # `PasskeyMalformed` is one of these and answers the same way: from # behind a session, a body that is not a ceremony and a ceremony that @@ -307,20 +387,20 @@ def add_passkey(request: Request, body: PasskeyBody) -> dict[str, int]: @router.post("/api/account/passkeys/{passkey_id}/label") -def rename_passkey(passkey_id: int, body: LabelBody, request: Request) -> dict[str, bool]: +def rename_passkey(passkey_id: int, body: LabelBody, request: Request) -> Ok: """Name it. A key you cannot name is one you will never dare revoke.""" if not _store(request).rename_passkey(passkey_id, body.label): raise HTTPException(404, "That passkey is already gone.") - return {"ok": True} + return Ok() @router.delete("/api/account/passkeys/{passkey_id}") -def drop_passkey(passkey_id: int, request: Request) -> dict[str, bool]: +def drop_passkey(passkey_id: int, request: Request) -> Ok: """Revoke one. The password is still there, so this cannot lock you out — which is exactly why the password is still there.""" if not _store(request).delete_passkey(passkey_id): raise HTTPException(404, "That passkey is already gone.") - return {"ok": True} + return Ok() @router.post("/login/passkey/options", include_in_schema=False) @@ -363,7 +443,7 @@ def passkey_login(request: Request, response: Response, # been wrong about. raise HTTPException(400, str(exc)) from None except pk.PasskeyError as exc: - _warn(request, "passkey refused") + warn(request, "passkey refused") raise HTTPException(401, str(exc)) from None _open_session(request, response) @@ -406,44 +486,6 @@ def _open_session(request: Request, response: Response) -> None: ) -def _refuse_while_locked(request: Request) -> None: - """The lockout, in front of every place a password can be guessed. - - Read *before* the guess is looked at, so hammering while locked out does not - extend the lockout — see `AuthStore.locked_for`. Called from both doors - rather than living inside `check_password`, because the store counts and - this decides: the same wrong answer is a refusal here and a bootstrap - comparison in `auth.bootstrap`, which must not be able to lock anyone out of - their own restart. - """ - wait = _store(request).locked_for() - if wait: - _warn(request, "attempt while locked out") - raise HTTPException(429, f"Too many attempts. Try again in {_spell(wait)}.", - headers={"Retry-After": str(wait)}) - - -def _warn(request: Request, what: str) -> None: - """Write down that someone got it wrong, and who. - - The whole record of who is knocking. There is no access log worth the name — - uvicorn is run quietly — and no table of attempts, because the log is the - record and a second copy of it would only ever disagree. WARNING so it - survives that level, one line per refusal, and the address first after - `from` so a fail2ban filter is one regex; see docs/password-protection.md. - - The message does not name the package, because the logger already does: - with the usual `%(name)s: %(message)s` this module is `auth.router`, and a - line reading `auth.router: auth: wrong password` says it twice and reads - like a bug in the logging. - - Nothing is *decided* from the address — `AuthStore.check_password` says why - it cannot be — so this is where it earns its keep: at the layer that can - drop the connection instead of answering it. - """ - log.warning("%s from %s", what, client_address(request)) - - def _safe_next(target: str) -> str: r"""Where to go after signing in — only ever inside this app. @@ -481,9 +523,3 @@ def _local(target: str) -> bool: except ValueError: # an unparseable authority, e.g. `//[` return False return not parts.scheme and not parts.netloc - - -def _spell(seconds: int) -> str: - if seconds < 60: - return f"{seconds} seconds" - return f"{round(seconds / 60)} minutes" diff --git a/auth/schemas.py b/auth/schemas.py index f679152..70f3a59 100644 --- a/auth/schemas.py +++ b/auth/schemas.py @@ -1,10 +1,15 @@ -"""The five bodies this package accepts. Small on purpose. +"""The seven bodies this package accepts, and the five small answers it gives. +Small on purpose. A ceremony's `credential` is passed through as an opaque dict — it is the browser's `PublicKeyCredential` serialised by `toJSON()`, and its shape is the WebAuthn spec's business rather than ours. Restating it as a model here would be a second, staler copy of a structure the library already parses and validates properly. + +The answers are models rather than dicts so that the app's OpenAPI document, +which a client generates its types from, names every one of them. The JSON is +what the dicts were. """ from __future__ import annotations @@ -34,6 +39,22 @@ class PasswordBody(BaseModel): current: str = Field(max_length=1000) new: str = Field(max_length=1000) + #: Also delete every API token and passkey. Off by default, because a + #: token's cron job is not what a routine change is against; on when the + #: password may have been someone else's, since what they minted with it + #: outlives the change. None is off, and is the default rather than False + #: so the generated client type leaves the field optional, as it does + #: `TokenBody.days`: openapi-typescript makes a field with a non-null + #: default required, and a client that never asks should not have to say so. + revoke_all: bool | None = None + + +class PasskeyOptionsBody(BaseModel): + """Starting to register a passkey. `current` is the password, required for + the same reason as in `PasswordBody`: a passkey is a permanent way in, and + a borrowed session must not be able to mint one.""" + + current: str = Field(max_length=1000) class PasskeyBody(BaseModel): @@ -51,6 +72,67 @@ class PasskeyLoginBody(BaseModel): class LabelBody(BaseModel): - """Renaming a passkey.""" + """Renaming a passkey or a token.""" + label: str = Field(max_length=100) + + +class TokenBody(BaseModel): + """Minting an API token. `current` is the password, required for the same + reason as in `PasskeyOptionsBody`: a token is a standing way in, and a + borrowed session must not be able to mint one.""" + + current: str = Field(max_length=1000) + #: What to call it: the machine or the job that will hold it. + label: str = Field("", max_length=100) + #: How long it lives, in days. None is a token that does not expire, which + #: is what a cron job wants; bounded above so a typo cannot ask for a + #: thousand years and still be called dated. + days: int | None = Field(None, ge=1, le=3650) + + +class Ok(BaseModel): + """A change that has nothing to report beyond having happened.""" + + ok: bool = True + + +class SignedOut(BaseModel): + """How many other sessions "sign out everywhere else" closed.""" + + signed_out: int + + +class PasswordChanged(BaseModel): + """What a password change closed and what it left, for the screen to say. + + `signed_out` is the other sessions, always closed. The tokens and + passkeys are deleted only when `revoke_all` was asked for, and the + `_left` counts are what is still registered afterwards, expired tokens + included, so an owner who did not ask knows what to review.""" + + signed_out: int + tokens_revoked: int + passkeys_revoked: int + tokens_left: int + passkeys_left: int + + +class PasskeyAdded(BaseModel): + """The row a registered passkey was given, which rename and revoke take.""" + + id: int + + +class TokenCreated(BaseModel): + """A minted token: the one answer in this package that carries a credential. + + `token` is shown once and stored nowhere but as a hash, so a caller that + loses it mints another. The rest is the row as `ApiToken` lists it. + """ + + id: int + token: str + hint: str label: str + expires_at: str diff --git a/auth/static/account.js b/auth/static/account.js index 8bee28e..fe85894 100644 --- a/auth/static/account.js +++ b/auth/static/account.js @@ -4,9 +4,9 @@ * * * That is the whole of it. The element asks `/api/account` what there is to - * know, and draws the four things there are to do about it: change the + * know, and draws the five things there are to do about it: change the * password, look at what is signed in and revoke any of it, register and - * revoke passkeys, and sign out. + * revoke passkeys, make and revoke API tokens for scripts, and sign out. * * One file, and the styles are in it rather than beside it, because the shadow * root scopes them anyway and a second file is a second route, a second cache @@ -79,6 +79,18 @@ button { padding: 2px 9px; cursor: pointer; } +select { + font: inherit; color: inherit; background: transparent; + border: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 25%, transparent); + border-radius: 6px; padding: 3px 7px; +} +select option { color: initial; } +label.check { display: flex; align-items: center; gap: 6px; flex: 1 1 100%; } +label.check input { min-width: 0; margin: 0; } +input.token { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; min-width: 20rem; } +.made { display: flex; flex-direction: column; gap: var(--desk-jobs-gap); } +.made .bar { display: flex; flex-wrap: wrap; gap: var(--desk-jobs-gap); align-items: center; } + button:hover { color: var(--desk-jobs-accent); } button.danger:hover { color: var(--desk-jobs-error); } button[disabled] { opacity: .4; cursor: default; } @@ -87,6 +99,25 @@ button[disabled] { opacity: .4; cursor: default; } font-size: 12px; padding: 0 6px; border-radius: 999px; border: 1px solid currentColor; color: var(--desk-jobs-dim); } + +/* A finger: every button a thumb's height, and no field under 16px, which + * is where iOS zooms the page in on focus and never back out. Sizes only; + * the layout is the width query below, and neither reads the other. */ +@media (pointer: coarse) { + button { min-height: 2.5rem; padding: 4px 12px; } + input, select { font-size: 16px; padding: 7px 9px; } +} + +/* A phone: a session's name and its buttons share a line while they fit and + * the buttons drop under it when they do not, still on the right; a form's + * fields take the width and its buttons share what is left. 40rem is + * app.css's number, on purpose. */ +@media (max-width: 40rem) { + .row { flex-wrap: wrap; align-items: center; } + .row .acts { margin-left: auto; } + form input:not([type="checkbox"]), form select, .bar input { flex: 1 1 100%; min-width: 0; } + form button, .bar button { flex: 1 1 auto; } +} `; /** What the server says when this build has no `webauthn` installed. The @@ -110,6 +141,11 @@ class AuthAccount extends HTMLElement { * the other way -- from an app that was restarted without the extra while * this page was open. */ #passkeysGone = false; + /** The token just made, held until Done: the server shows it once and keeps + * only its hash, so nothing reloaded from `/api/account` can bring it back. */ + #made = null; + /** What Copy last did: "", "done" or "failed". */ + #copy = ""; constructor() { super(); @@ -211,6 +247,7 @@ class AuthAccount extends HTMLElement { this.#panel.append(this.#password(account)); if (account.sessions.length) this.#panel.append(this.#sessions(account)); if (this.#showPasskeys(account)) this.#panel.append(this.#passkeys(account)); + this.#panel.append(this.#tokens(account)); if (account.locked) this.#panel.append(this.#signOut()); } @@ -255,22 +292,30 @@ class AuthAccount extends HTMLElement { const form = document.createElement("form"); const current = field("password", "Current password"); const next = field("password", first ? "Choose a password" : "New password"); + // Tokens and passkeys survive a change unless this is ticked: the cron + // job holding a token is not what a routine change is against, but an + // intruder who had the password may have minted one. + const revoke = document.createElement("input"); + revoke.type = "checkbox"; + const revokeLabel = document.createElement("label"); + revokeLabel.className = "check"; + revokeLabel.append(revoke, "Also revoke every API token and passkey"); const go = document.createElement("button"); go.textContent = first ? "Set password" : "Change password"; go.disabled = this.#busy; - form.append(...(first ? [next, go] : [current, next, go])); + form.append(...(first ? [next, go] : [current, next, revokeLabel, go])); form.addEventListener("submit", (event) => { event.preventDefault(); this.#act(async () => { const result = await this.#api("/api/account/password", { method: "POST", - body: JSON.stringify({ current: current.value, new: next.value }), + body: JSON.stringify({ + current: current.value, new: next.value, revoke_all: !first && revoke.checked, + }), }); current.value = next.value = ""; if (first) return this.#say("Password set."); - this.#say(result.signed_out - ? `Password changed. ${count(result.signed_out, "other session")} signed out.` - : "Password changed."); + this.#say(changed(result)); }); }); section.append(form); @@ -279,7 +324,7 @@ class AuthAccount extends HTMLElement { // makes the change ceremonial. Said here so it is not a surprise. section.append(this.#line(first ? "Nothing asks for it until the app binds an address that is not loopback -- or `auth.enabled: always`. Set it before you deploy, not after." - : "Changing it signs out every other session, and keeps this one.")); + : "Changing it signs out every other session and keeps this one. API tokens and passkeys stay unless you tick the box; tick it if someone else may have had the password.")); return section; } @@ -344,13 +389,142 @@ class AuthAccount extends HTMLElement { section.append(this.#line(account.passkeys_blocked)); return section; } - const add = this.#button("Add a passkey", "", () => this.#register()); + // A passkey outlasts every session, so adding one takes the password -- + // see `passkey_options` in router.py. With none set there is nothing to + // confirm, and the server does not ask. + const asks = Boolean(account.password_set_at); + const form = document.createElement("form"); + const current = field("password", "Password, to add a passkey"); + current.autocomplete = "current-password"; + const add = document.createElement("button"); + add.textContent = "Add a passkey"; add.disabled = this.#busy; - section.append(add); + form.append(...(asks ? [current, add] : [add])); + form.addEventListener("submit", (event) => { + event.preventDefault(); + this.#register(current.value); + }); + section.append(form); return section; } - async #register() { + #tokens(account) { + const section = this.#section("API tokens"); + for (const token of account.tokens || []) { + const row = this.#row( + token.label || "Token", + [`${token.hint}…`, + `added ${when(token.created_at)}`, + token.last_used_at ? `last used ${when(token.last_used_at)}` : "never used", + lifetime(token), + ].join(" · ")); + const acts = row.querySelector(".acts"); + acts.append(this.#button("Rename", "", () => { + const label = prompt("Call this token what?", token.label || ""); + if (label === null) return; + this.#act(async () => { + await this.#api(`/api/account/tokens/${token.id}/label`, { + method: "POST", body: JSON.stringify({ label }), + }); + this.#say("Renamed."); + }); + })); + acts.append(this.#button("Revoke", "danger", () => this.#act(async () => { + await this.#api(`/api/account/tokens/${token.id}`, { method: "DELETE" }); + // The script holding it is locked out on its next request, and + // nothing else changes: the password and the sessions stay. + this.#say("Token revoked."); + }))); + section.append(row); + } + + // A token outlives every session and a password change, so making one + // takes the password, on the same condition as a passkey -- see + // `create_token` in router.py. + const asks = Boolean(account.password_set_at); + const form = document.createElement("form"); + const label = field("text", "Name, e.g. the script that holds it"); + label.required = false; + label.maxLength = 100; + const days = document.createElement("select"); + days.setAttribute("aria-label", "How long it is valid"); + for (const [value, text] of [["", "Does not expire"], ["30", "30 days"], + ["90", "90 days"], ["365", "1 year"]]) { + const option = document.createElement("option"); + option.value = value; + option.textContent = text; + days.append(option); + } + const current = field("password", "Password, to create a token"); + current.autocomplete = "current-password"; + const create = document.createElement("button"); + create.textContent = "Create a token"; + create.disabled = this.#busy; + form.append(label, days, ...(asks ? [current] : []), create); + form.addEventListener("submit", (event) => { + event.preventDefault(); + this.#act(async () => { + const made = await this.#api("/api/account/tokens", { + method: "POST", + body: JSON.stringify({ + current: current.value, label: label.value.trim(), + days: days.value ? Number(days.value) : null, + }), + }); + // In the one answer that made it and nowhere after, so it is kept on + // the element until Done rather than read back from the account. + this.#made = made; + this.#copy = ""; + this.#say(`Token "${made.label || "Token"}" created. Copy it below; it is shown only once.`); + }); + }); + section.append(form); + if (this.#made) section.append(this.#shown(this.#made)); + section.append(this.#line( + "A script sends a token as `Authorization: Bearer`. It cannot manage the account, and it is kept through a password change. Revoke it here when the script no longer needs it.")); + return section; + } + + /** The new token, read-only and selectable, with Copy and a sentence that + * it is the only time. Done drops it from the element, after which the + * page never has it again. */ + #shown(made) { + const box = document.createElement("div"); + box.className = "made"; + const bar = document.createElement("div"); + bar.className = "bar"; + const value = document.createElement("input"); + value.type = "text"; + value.readOnly = true; + value.className = "token"; + value.value = made.token; + value.setAttribute("aria-label", "The new token"); + value.addEventListener("focus", () => value.select()); + bar.append(value, + this.#button("Copy", "", async () => { + try { + await navigator.clipboard.writeText(made.token); + this.#copy = "done"; + } catch { + // No clipboard on an insecure origin, or the browser refused: the + // field is selectable, so the token is still there to take by hand. + this.#copy = "failed"; + } + this.#render(); + }), + this.#button("Done", "", () => { + this.#made = null; + this.#copy = ""; + this.#render(); + })); + box.append(bar, this.#line( + "This is the only time the token is shown. Only a hash is stored, so it cannot be looked up again; if it is lost, revoke it and create another.")); + if (this.#copy === "done") box.append(this.#line("Copied.")); + if (this.#copy === "failed") box.append(this.#note("Could not copy. Select the token and copy it by hand.", true)); + return box; + } + + async #register(current) { const passkey = await loadPasskeyHelper(); if (!passkey || !passkey.supported()) { this.#say("This browser will not create a passkey here. It needs HTTPS, or localhost."); @@ -361,7 +535,9 @@ class AuthAccount extends HTMLElement { // browser's own prompt happens between them, and a cancelled prompt is an // exception rather than an error status -- hence `explain`. await this.#act(async () => { - const options = await this.#api("/api/account/passkeys/options", { method: "POST" }); + const options = await this.#api("/api/account/passkeys/options", { + method: "POST", body: JSON.stringify({ current }), + }); let made; try { made = await passkey.create(options); @@ -485,6 +661,19 @@ function field(type, placeholder) { return input; } +/** What a password change closed and what it left, in a sentence or three. */ +function changed(result) { + const said = ["Password changed."]; + if (result.signed_out) said.push(`${count(result.signed_out, "other session")} signed out.`); + if (result.tokens_revoked || result.passkeys_revoked) { + said.push(`${count(result.tokens_revoked, "API token")} and ${count(result.passkeys_revoked, "passkey")} revoked.`); + } + if (result.tokens_left || result.passkeys_left) { + said.push(`${count(result.tokens_left, "API token")} and ${count(result.passkeys_left, "passkey")} remain; revoke any you do not recognise.`); + } + return said.join(" "); +} + function count(n, thing) { return `${n} ${thing}${n === 1 ? "" : "s"}`; } @@ -498,6 +687,14 @@ function when(stamp) { return at.toLocaleString(); } +/** What a token's row says about its end: no end, one to come, or one that + * has passed and left the row for the owner to clear. */ +function lifetime(token) { + if (!token.expires_at) return "does not expire"; + const gone = new Date(token.expires_at).getTime() <= Date.now(); + return `${gone ? "expired" : "expires"} ${when(token.expires_at)}`; +} + if (!customElements.get("auth-account")) { customElements.define("auth-account", AuthAccount); } diff --git a/auth/store.py b/auth/store.py index e65ea57..4a4f1f0 100644 --- a/auth/store.py +++ b/auth/store.py @@ -1,6 +1,7 @@ -"""One password, and the sessions it opens. Nothing else knows a hash. +"""One password, the sessions it opens, and the tokens that stand in for it +from a script. Nothing else knows a hash. -Four tables in whatever SQLite file it is given — the app's own, normally, so +Five tables in whatever SQLite file it is given — the app's own, normally, so there is one file to back up and SQLite's writer lock keeps auth honest with everything else in it. Every name starts `auth_`, because the file is shared: a `sessions` table is a name an app is entitled to want for itself. @@ -54,7 +55,7 @@ from contextlib import closing from datetime import UTC, datetime, timedelta from pathlib import Path -from auth.models import Passkey, SessionInfo +from auth.models import ApiToken, Passkey, SessionInfo #: scrypt cost. `n` is the work factor, and 2**14 with `r=8` is the widely #: recommended interactive setting: about 16 MB and ~50 ms per guess, which is @@ -86,6 +87,12 @@ _MAX_LOCK = timedelta(minutes=15) #: the ceiling. See `_lockout` for what goes wrong without it. _MAX_STEPS = math.ceil(math.log2(_MAX_LOCK / _FIRST_LOCK)) +#: How much of a token the account screen is shown, so the owner can tell +#: which environment variable holds which row. Eight of forty-three characters +#: from `token_urlsafe(32)` leaves 210 bits unknown, which is still past +#: anybody's ability to guess. +HINT = 8 + #: How stale `last_seen_at` may get before a request bothers to update it. #: Without this, every single request — every socket frame's sibling fetch, #: every poll of a page left open — takes SQLite's write lock to move a @@ -96,7 +103,7 @@ _SEEN_EVERY = timedelta(minutes=5) #: The tables. Created on construction rather than by a migration step, because #: the only schema change this has ever had is "it did not exist yet", and a -#: migration runner for four `CREATE TABLE IF NOT EXISTS` is a thing to +#: migration runner for five `CREATE TABLE IF NOT EXISTS` is a thing to #: maintain in exchange for nothing. SCHEMA = """ CREATE TABLE IF NOT EXISTS auth_credential ( @@ -130,6 +137,15 @@ CREATE TABLE IF NOT EXISTS auth_challenges ( purpose TEXT NOT NULL, expires_at TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS auth_tokens ( + id INTEGER PRIMARY KEY, + token_hash TEXT NOT NULL UNIQUE, + hint TEXT NOT NULL DEFAULT '', + label TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + last_used_at TEXT NOT NULL DEFAULT '', + expires_at TEXT NOT NULL DEFAULT '' +); """ @@ -151,7 +167,7 @@ def _derive(password: str, salt: bytes) -> bytes: class AuthStore: - """The four `auth_*` tables, opened on the path it is handed. + """The five `auth_*` tables, opened on the path it is handed. store = AuthStore("data/app.db") @@ -207,13 +223,8 @@ class AuthStore: ) def locked_for(self) -> int: - """Seconds until the next attempt will be looked at, or 0. - - Read before checking rather than after, so a locked-out caller is told - to wait instead of having a guess counted — otherwise a fast enough - attacker extends their own lockout forever and never notices, and, more - to the point, an honest person hammering the button digs a deeper hole - with every press. + """Seconds until the next attempt will be looked at, or 0. Reads only; + the doors ask `claim_attempt`, which decides and counts in one step. """ with closing(self._connect()) as conn: row = conn.execute( @@ -223,9 +234,61 @@ class AuthStore: remaining = datetime.fromisoformat(row["locked_until"]) - _now() return max(0, int(remaining.total_seconds() + 0.999)) - def check_password(self, password: str) -> bool: + def claim_attempt(self) -> int: + """Claim one guess at the password before it is derived: 0 when the + guess may go ahead, else the seconds until one may. + + Inside one `BEGIN IMMEDIATE`, `locked_until` is read and, when it has + passed, the attempt is counted as a failure up front and the lockout + it would earn is written; `check_password(..., claimed=True)` then + clears both when the guess was right. Read before scrypt and written + after it, thirty wrong guesses in parallel each found the door open + and each got a 401, so a window admitted a threadpool of guesses + rather than `_GRACE`. Now the sixth concurrent claim finds the lockout + the fifth wrote. + + A refused claim writes nothing, so a caller locked out is told to wait + instead of having a guess counted: otherwise a fast enough attacker + extends their own lockout forever and never notices, and an honest + person hammering the button digs a deeper hole with every press. On a + database with no password there is nothing to count and nothing to + lock, and the claim is granted. + """ + with closing(self._connect()) as conn: + conn.execute("BEGIN IMMEDIATE") + try: + row = conn.execute( + "SELECT failures, locked_until FROM auth_credential WHERE id=1" + ).fetchone() + wait = 0 + if row is not None: + now = _now() + if row["locked_until"]: + remaining = datetime.fromisoformat(row["locked_until"]) - now + wait = max(0, int(remaining.total_seconds() + 0.999)) + if not wait: + failures = int(row["failures"]) + 1 + conn.execute( + "UPDATE auth_credential SET failures=?, locked_until=? WHERE id=1", + (failures, _stamp(now + _lockout(failures)) + if failures >= _GRACE else "")) + conn.commit() + except BaseException: + conn.rollback() + raise + return wait + + def check_password(self, password: str, *, claimed: bool = False) -> bool: """Right or wrong, and record which. + `claimed` says the caller counted this guess with `claim_attempt` + already, which is what both doors do: a wrong answer then writes + nothing more and a right one clears the count. Without it a wrong + answer is counted here, after the derivation, which is what a caller + that is not a door wants: `auth.bootstrap` compares the pinned + password, and its comparison cannot lock anyone out because it is + followed by `set_password`, which clears the count. + `hmac.compare_digest` rather than `==`, so the comparison takes the same time whatever the first wrong byte is. That is close to superstition at this scale — the network jitter in front of it is larger than the signal @@ -247,29 +310,42 @@ class AuthStore: owner still gets locked out by their own typos: strictly worse than this, and it would look like protection. So the address is written to the log instead, at WARNING, where fail2ban can act on it at the layer - that actually knows who connected — see `_warn` in `auth/router.py`. + that actually knows who connected — see `warn` in `auth/middleware.py`. What is left for this counter to do is make guessing pointless, which it does whoever is guessing. """ with closing(self._connect()) as conn: - row = conn.execute( - "SELECT salt, hash, failures FROM auth_credential WHERE id=1" - ).fetchone() - if row is None: + # `fetchall`, so no read is left open on this connection when it + # asks for the write lock below. + rows = conn.execute( + "SELECT salt, hash FROM auth_credential WHERE id=1").fetchall() + if not rows: _derive(password, b"no password here") return False - ok = hmac.compare_digest(_derive(password, row["salt"]), row["hash"]) - with conn: + ok = hmac.compare_digest(_derive(password, rows[0]["salt"]), rows[0]["hash"]) + if claimed and not ok: + return False + # The count is raised in the database under the write lock, and + # the lockout is decided from what that raise returned. Read + # before scrypt and written after it, forty guesses in parallel + # each wrote "one more than before" and recorded one failure. + conn.execute("BEGIN IMMEDIATE") + try: if ok: conn.execute( "UPDATE auth_credential SET failures=0, locked_until='' WHERE id=1") - else: - failures = int(row["failures"]) + 1 + elif counted := conn.execute( + "UPDATE auth_credential SET failures = failures + 1 WHERE id=1 " + "RETURNING failures").fetchall(): + failures = int(counted[0][0]) conn.execute( - "UPDATE auth_credential SET failures=?, locked_until=? WHERE id=1", - (failures, _stamp(_now() + _lockout(failures)) - if failures >= _GRACE else ""), - ) + "UPDATE auth_credential SET locked_until=? WHERE id=1", + (_stamp(_now() + _lockout(failures)) + if failures >= _GRACE else "",)) + conn.commit() + except BaseException: + conn.rollback() + raise return ok def changed_at(self) -> str: @@ -368,6 +444,104 @@ class AuthStore: cur = conn.execute("DELETE FROM auth_sessions") return cur.rowcount + def revoke_credentials(self) -> tuple[int, int]: + """Delete every API token and every passkey in one transaction, for a + password change made because the account may be in someone else's + hands. Returns `(tokens, passkeys)` deleted. The password stays, so + this cannot lock the owner out.""" + with closing(self._connect()) as conn, conn: + tokens = conn.execute("DELETE FROM auth_tokens").rowcount + keys = conn.execute("DELETE FROM auth_passkeys").rowcount + return tokens, keys + + def counts(self) -> tuple[int, int]: + """`(tokens, passkeys)` registered, expired tokens included, for a + caller that reports what is left after a password change.""" + with closing(self._connect()) as conn: + tokens = conn.execute("SELECT COUNT(*) FROM auth_tokens").fetchone()[0] + keys = conn.execute("SELECT COUNT(*) FROM auth_passkeys").fetchone()[0] + return int(tokens), int(keys) + + # ---------------------------------------------------------------- tokens + # + # A token is a session for a script: the same 32 random bytes, the same + # SHA-256 in the file, carried as `Authorization: Bearer` instead of a + # cookie. It differs from a session in what it is for. A session is a + # browser that typed the password once and is signed out by a password + # change; a token is minted on purpose, named, optionally dated, and + # survives a password change the way a passkey does, because the cron job + # holding it is not the thing the password was changed against. It is + # revoked by its row, from the account screen, which a token cannot reach + # (`auth.middleware.ACCOUNT`). + + def create_token(self, label: str, days: int | None) -> tuple[int, str]: + """Mint one. Returns `(row id, token)`; the token exists only in that + return value, so the caller shows it once and never again. + + `days` of None is a token that does not expire: the cron job that + holds it is not going to type a new one, and the row's last-used + stamp is what tells an abandoned one from one in use. + """ + token = secrets.token_urlsafe(32) + made = _now() + expires = _stamp(made + timedelta(days=days)) if days else "" + with closing(self._connect()) as conn, conn: + cur = conn.execute( + """INSERT INTO auth_tokens + (token_hash, hint, label, created_at, last_used_at, expires_at) + VALUES (?,?,?,?,'',?)""", + (_token_hash(token), token[:HINT], label[:100], _stamp(made), expires), + ) + return int(cur.lastrowid or 0), token + + def touch_token(self, token: str) -> ApiToken | None: + """The token this bearer value names, if it is live, marking it used. + + Expiry is in the `WHERE` as it is for a session; a blank `expires_at` + is a token that does not. `last_used_at` is written at most once every + `_SEEN_EVERY`, for the reason `touch` gives. + """ + digest = _token_hash(token) + now = _now() + stamp = _stamp(now) + with closing(self._connect()) as conn: + row = conn.execute( + "SELECT * FROM auth_tokens WHERE token_hash=? " + "AND (expires_at = '' OR expires_at > ?)", + (digest, stamp), + ).fetchone() + if row is None: + return None + used = row["last_used_at"] + if not used or now - datetime.fromisoformat(used) >= _SEEN_EVERY: + with conn: + conn.execute( + "UPDATE auth_tokens SET last_used_at=? WHERE token_hash=?", + (stamp, digest)) + used = stamp + return _api_token(row, used) + + def tokens(self) -> list[ApiToken]: + """Every token, newest first, the expired ones included: a row that + ran out is still the owner's to recognise and remove. No hash.""" + with closing(self._connect()) as conn: + rows = conn.execute( + "SELECT * FROM auth_tokens ORDER BY created_at DESC, id DESC").fetchall() + return [_api_token(r, r["last_used_at"]) for r in rows] + + def rename_token(self, token_id: int, label: str) -> bool: + with closing(self._connect()) as conn, conn: + cur = conn.execute("UPDATE auth_tokens SET label=? WHERE id=?", + (label[:100], token_id)) + return cur.rowcount > 0 + + def delete_token(self, token_id: int) -> bool: + """Revoke one. By row id, as a session is: the screen has never seen + the token after the moment it was minted.""" + with closing(self._connect()) as conn, conn: + cur = conn.execute("DELETE FROM auth_tokens WHERE id=?", (token_id,)) + return cur.rowcount > 0 + # -------------------------------------------------------------- passkeys def add_passkey(self, credential_id: bytes, public_key: bytes, @@ -503,3 +677,10 @@ def _session(row: sqlite3.Row, last_seen: str, current: bool) -> SessionInfo: id=row["id"], label=row["label"], created_at=row["created_at"], last_seen_at=last_seen, expires_at=row["expires_at"], current=current, ) + + +def _api_token(row: sqlite3.Row, last_used: str) -> ApiToken: + return ApiToken( + id=row["id"], label=row["label"], hint=row["hint"], created_at=row["created_at"], + last_used_at=last_used, expires_at=row["expires_at"], + ) diff --git a/auth/templates/login.html b/auth/templates/login.html index fe28318..82509c0 100644 --- a/auth/templates/login.html +++ b/auth/templates/login.html @@ -2,7 +2,7 @@ - + {name} — sign in