Take auth/ whole from boilerplate 09e144d: the lockout claimed before the scrypt, APP_PASSWORD recovery closing every session, Starlette's cookie parser, the rightmost forwarded hop in the log, revoke_all on a password change, a 421 for a non-loopback Host on an open app, API tokens in auth_tokens behind Authorization: Bearer, and sockets closed with their credential

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-10-27 11:51:21 +01:00
1 parent 83e965dfeb
commit 244e57ac29
19 files changed
+2288 -214

No files matched your search

+19 -9
View File
@@ -1,6 +1,6 @@
# auth # 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. 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 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 ## 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. 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, ...)` | | | `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. | | `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. | | `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. | | `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. | | `stylesheet=` | a URL the login page links, so it looks like the rest of the app. Optional: the page carries enough inline CSS to be presentable on its own. |
The account screen is two lines in a template, the same deal `<desk-jobs>` makes: The account screen is two lines in a template, the same deal `<desk-jobs>` makes:
@@ -44,7 +45,7 @@ The account screen is two lines in a template, the same deal `<desk-jobs>` makes
<auth-account></auth-account> <auth-account></auth-account>
``` ```
It draws the lot — locked or not, change the password, the sessions with revoke and close-others, the passkeys with register, rename and revoke, and sign out — and it is themed from outside by the same `--desk-jobs-*` custom properties the queue's elements read, so `desk-jobs, desk-schedules, auth-account { ... }` in one stylesheet is all three. 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 ## The config block
@@ -69,7 +70,7 @@ auth:
cookie: app_session 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. `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`. 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 ## What the app has to provide
Almost nothing, and that is the point. 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`. - 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. - 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. - 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. 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 ## 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. **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. **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 <addr>`, stripped to the characters an address is made of — and decided from at the layer that knows who connected. `docs/password-protection.md` has the nginx and fail2ban half. **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 <addr>`, 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. **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. **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 <token>` 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 ## Tests
```bash ```bash
+58 -19
View File
@@ -9,27 +9,30 @@ That is the middleware in front of everything (the WebSocket included), the
login page, the account API, the `<auth-account>` element, and the startup login page, the account API, the `<auth-account>` element, and the startup
bootstrap that makes sure there is a password at all. No user management: there 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 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 | | | module | |
|---|---| |---|---|
| `config.py` | `AuthConfig`: the `auth:` block of the app's `config.yaml` | | `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 | | `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` — what the account screen is told, which carries no credential | | `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 | | `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 | | `passkeys.py` | the two WebAuthn ceremonies; `webauthn` is an optional extra, imported lazily |
| `schemas.py` | the five request bodies | | `schemas.py` | the seven request bodies |
| `router.py` | `/login`, `/logout`, `/api/account/*`, the passkey routes, `/_auth/*.js` | | `router.py` | `/login`, `/logout`, `/api/account/*`, the passkey and token routes, `/_auth/*.js` |
| `templates/login.html` | the one page served without a session | | `templates/login.html` | the one page served without a session |
| `static/` | `passkey.js` (the browser half of WebAuthn) and `account.js` (`<auth-account>`) | | `static/` | `passkey.js` (the browser half of WebAuthn) and `account.js` (`<auth-account>`) |
The reasoning is `docs/password-protection.md`, and this package is that The reasoning is the boilerplate's `documentation/Password Protection.md`, and this package is that
document in code. `auth/README.md` is how to copy the folder into a project document in code. `auth/README.md` is how to copy the folder into a project
that has never heard of this one. that has never heard of this one.
""" """
from __future__ import annotations from __future__ import annotations
import asyncio
import contextlib
import logging import logging
import os import os
import secrets import secrets
@@ -41,23 +44,29 @@ from fastapi import FastAPI
from auth import passkeys from auth import passkeys
from auth.config import AuthConfig from auth.config import AuthConfig
from auth.middleware import OPEN, RequireLogin, client_address, locked, token_from from auth.middleware import (
from auth.models import Account, Passkey, SessionInfo 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.router import router
from auth.store import AuthStore from auth.store import AuthStore
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
__all__ = [ __all__ = [
"OPEN", "Account", "AuthConfig", "AuthStore", "Passkey", "RequireLogin", "ACCOUNT", "CURRENT_HEADER", "OPEN", "Account", "ApiToken", "AuthConfig", "AuthStore",
"SessionInfo", "bootstrap", "client_address", "connect", "locked", "Passkey", "RequireLogin", "SessionInfo", "bearer_from", "bootstrap", "client_address",
"passkeys", "router", "token_from", "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, *, def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *,
open: Iterable[str] = (), stylesheet: str | None = None, open: Iterable[str] = (), session_only: Iterable[str] = (),
host: str = "") -> AuthStore: stylesheet: str | None = None, host: str = "") -> AuthStore:
"""Put `app` behind a password: middleware, routes, element, bootstrap. """Put `app` behind a password: middleware, routes, element, bootstrap.
Call it first, before the app's own routers. Starlette wraps the whole 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 | | | 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. | | `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. | | `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. | | `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 The lifespan is wrapped rather than replaced, the same way
`pipeline.web.connect` does it, so an app's own lifespan still runs inside `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 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. 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. #: the bind address, which only the caller knows.
app.state.auth_locked = locked(config, host) app.state.auth_locked = locked(config, host)
app.state.auth_stylesheet = stylesheet or "" 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.include_router(router)
app.add_middleware(RequireLogin, store=store, config=config, 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 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 # 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. # encourages, so an unlocked one can still have keys it cannot use.
passkeys.warn_if_missing(store) passkeys.warn_if_missing(store)
async with inner(this) as state: # Expiry ends no request, so no route closes the socket it ended.
yield state 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 app.router.lifespan_context = lifespan
return store 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 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. 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, "") pinned = os.environ.get(config.password_env, "")
if pinned: if pinned:
if not store.check_password(pinned): if not store.check_password(pinned):
replaced = store.has_password()
store.set_password(pinned) 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 return
if store.has_password(): if store.has_password():
+8 -8
View File
@@ -22,7 +22,7 @@ from pydantic import BaseModel, ConfigDict, Field
class AuthConfig(BaseModel): 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 #: 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 #: 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 #: Deciding from the bind address rather than defaulting to off is the
#: whole point. The failure this prevents is the one that actually happens: #: 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. #: 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 #: `always` locks it on localhost too and is what a deployment sets, so the
#: TLS-terminating proxy needs, since there every request looks local to #: lock does not depend on the bind address or on how the process was
#: the app and is not. `never` is for putting some other authentication in #: started. `never` is for putting some other authentication in
#: front of this one, and means exactly what it says. #: front of this one, and means exactly what it says.
enabled: Literal["auto", "always", "never"] = "auto" 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 #: 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 #: 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 #: arrived over HTTPS, which behind a reverse proxy that terminates TLS
#: behind a reverse proxy that terminates it for you -- there the app sees #: holds only while the server trusts `X-Forwarded-Proto` from it; the app
#: plain HTTP and `auto` reads as "no". Set `always` when something else is #: alone cannot tell. Set `always` when something else is doing TLS.
#: doing TLS. `never` exists for testing over http on a LAN and is the #: `never` exists for testing over http on a LAN and is the
#: setting to be uncomfortable with. #: setting to be uncomfortable with.
secure_cookie: Literal["auto", "always", "never"] = "auto" secure_cookie: Literal["auto", "always", "never"] = "auto"
+511 -28
View File
@@ -1,8 +1,10 @@
"""The lock on the door: is there a session, and what happens when there isn't. """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 Six things live here — when the door is locked at all, who gets past it, the
the cookie that says so. The password itself is `auth/store.py`; this module cookie and the bearer header that say so, the rule that another site's page
never sees a hash. 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 ## 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 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 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. 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 <token>`, 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 from __future__ import annotations
@@ -37,11 +99,11 @@ from __future__ import annotations
import asyncio import asyncio
import ipaddress import ipaddress
import logging import logging
from http.cookies import SimpleCookie
from typing import Any 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.responses import JSONResponse, RedirectResponse, Response
from starlette.types import ASGIApp, Receive, Scope, Send 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. #: against the path only — a query string cannot widen this.
OPEN: tuple[str, ...] = ("/login", "/login/", "/_auth/", "/health") 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: def locked(config: AuthConfig, host: str) -> bool:
"""Whether this app should ask for a password. See `AuthConfig.enabled`. """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 Both cookie names are looked for, so flipping `secure_cookie` or moving
behind TLS does not strand a live session under the other name. 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 scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
for key, value in scope.get("headers", ()): for key, value in scope.get("headers", ()):
if key == b"cookie": if key == b"cookie":
jar = SimpleCookie() jar = cookie_parser(value.decode("latin-1"))
try:
jar.load(value.decode("latin-1"))
except Exception: # a cookie header that is not one
return ""
for name in cookie_names(config): for name in cookie_names(config):
if name in jar: if jar.get(name):
return jar[name].value return jar[name]
return "" 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: def client_address(conn: HTTPConnection | Scope) -> str:
"""Who is asking, as well as it can be known, for the log to say so. """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 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 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 down is the rightmost hop of `X-Forwarded-For`, the one the proxy in front
reported when they differ, because the header is only as trustworthy as of this app appended for the connection it accepted; every hop left of it
whoever sent it — which is why nothing is *decided* from this, only logged. was in the request when it arrived and is whatever the caller wrote. nginx's
See `AuthStore.check_password` for that argument in full. `$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: 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 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 scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
peer = (scope.get("client") or ("", 0))[0] or "unknown" peer = (scope.get("client") or ("", 0))[0] or "unknown"
forwarded = real = ""
for key, value in scope.get("headers", ()): 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": if key == b"x-forwarded-for":
first = value.decode("latin-1").split(",")[0] forwarded = value.decode("latin-1")
claimed = "".join(c for c in first if c.isalnum() or c in ".:%-")[:45] elif key == b"x-real-ip":
if claimed and claimed != peer: real = value.decode("latin-1")
return f"{claimed} via {peer}" 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 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 #: 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 #: 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. #: 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, 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.app = app
self.store = store self.store = store
self.config = config self.config = config
self.open = OPEN + tuple(open) 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) 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: 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) return await self.app(scope, receive, send)
path = scope.get("path", "") path = scope.get("path", "")
if any(path == p.rstrip("/") or (p.endswith("/") and path.startswith(p)) if matches(path, self.open):
for p in self.open):
return await self.app(scope, receive, send) return await self.app(scope, receive, send)
token = token_from(scope, self.config) token = token_from(scope, self.config)
@@ -214,8 +373,34 @@ class RequireLogin:
scope["auth_token"] = token scope["auth_token"] = token
return await self.app(scope, receive, send) 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) 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, async def _refuse(self, scope: Scope, receive: Receive, send: Send,
path: str) -> None: path: str) -> None:
"""No session. Say so in whatever the caller can understand.""" """No session. Say so in whatever the caller can understand."""
@@ -244,3 +429,301 @@ class RequireLogin:
else: else:
response = JSONResponse({"detail": "Not signed in"}, status_code=401) response = JSONResponse({"detail": "Not signed in"}, status_code=401)
await response(scope, receive, send) 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
+25 -2
View File
@@ -1,8 +1,8 @@
"""What the Account tab is told, and nothing more. """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 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 least worth leaking, so the shape it is rendered from is one that could not
leak a credential if it were logged whole. leak a credential if it were logged whole.
""" """
@@ -47,6 +47,27 @@ class Passkey(BaseModel):
transports: list[str] = Field(default_factory=list) 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): class Account(BaseModel):
"""What the account screen knows. Deliberately almost nothing. """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 #: honest common case is an insecure origin: WebAuthn refuses anything but
#: HTTPS, localhost excepted, so this reads "you need TLS first". #: HTTPS, localhost excepted, so this reads "you need TLS first".
passkeys_blocked: str = "" passkeys_blocked: str = ""
#: The API tokens, expired ones included, each without its secret.
tokens: list[ApiToken] = Field(default_factory=list)
+9 -1
View File
@@ -291,11 +291,19 @@ def login_verify(config: AuthConfig, request: Request, store: AuthStore,
) )
challenge = _challenge_from(credential) 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"): if not store.take_challenge(challenge, "login"):
raise PasskeyError("That sign-in took too long, or was already used. " raise PasskeyError("That sign-in took too long, or was already used. "
"Try again.") "Try again.")
known = store.passkey_for(base64url_to_bytes(credential.get("rawId", ""))) known = store.passkey_for(raw_id)
if known is None: if known is None:
# Deliberately the same sentence as a bad signature. There is one user, # 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 # so this leaks little, but "that key is not registered" is an oracle
+119 -83
View File
@@ -29,18 +29,20 @@ import os
from pathlib import Path from pathlib import Path
from urllib.parse import unquote, urlsplit 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 fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
from starlette.requests import HTTPConnection from starlette.requests import HTTPConnection
from auth import passkeys as pk from auth import passkeys as pk
from auth.config import AuthConfig from auth.config import AuthConfig
from auth.middleware import ( 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.models import Account
from auth.schemas import ( 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 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: #: 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 #: 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. #: characters and anything you choose yourself is the weak half.
MIN_LENGTH = 8 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]: def sign_in(request: Request, response: Response, body: LoginBody) -> dict[str, str]:
"""Check the password, and if it is right, open a session. """Check the password, and if it is right, open a session.
The lockout is read *before* the password is checked, so hammering the The attempt is claimed *before* the password is derived, which reads the
button while locked out does not extend the lockout — see lockout and counts the guess in one write, so hammering the button while
`AuthStore.locked_for`. A wrong password and an unknown one are the same locked out does not extend the lockout and concurrent guesses cannot all
answer here for the usual reason, which is thin cover with one account but slip in under one reading of it; see `AuthStore.claim_attempt`. A wrong
costs nothing to keep. 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): if not _locked(request):
raise HTTPException(400, "This app is not password-protected.") raise HTTPException(400, "This app is not password-protected.")
_refuse_while_locked(request) claim_attempt(request)
if not _store(request).check_password(body.password): if not _store(request).check_password(body.password, claimed=True):
_warn(request, "wrong password") warn(request, "wrong password")
raise HTTPException(401, "That is not the password.") raise HTTPException(401, "That is not the password.")
_open_session(request, response) _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) @router.post("/logout", include_in_schema=False)
def sign_out(request: Request, response: Response) -> dict[str, bool]: def sign_out(request: Request, response: Response, tasks: BackgroundTasks) -> Ok:
"""End this session and clear the cookie. Other devices are untouched.""" """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)) token = token_from(request, _config(request))
if token: if token:
_store(request).close_session(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 # 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 # the scheme the login happened over — and clearing only one of them leaves
# a cookie the browser will keep offering. # a cookie the browser will keep offering.
for name in cookie_names(_config(request)): for name in cookie_names(_config(request)):
response.delete_cookie(name, path="/") response.delete_cookie(name, path="/")
return {"ok": True} return Ok()
# ---------------------------------------------------------------- the account # ---------------------------------------------------------------- the account
@@ -205,11 +213,13 @@ def account(request: Request) -> Account:
passkeys=store.passkeys(), passkeys=store.passkeys(),
passkeys_available=pk.available(), passkeys_available=pk.available(),
passkeys_blocked=pk.blocked(config, request), passkeys_blocked=pk.blocked(config, request),
tokens=store.tokens(),
) )
@router.post("/api/account/password") @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. """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 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 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. 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 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 only behind a session. `current` is the password, guessed here rather than
at `/login`, and a borrowed unlocked laptop is exactly the situation the 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, # app never lands here: `auth.bootstrap` gives it a password at startup,
# so `current` is always required for the app that has a door. # so `current` is always required for the app that has a door.
if store.has_password(): if store.has_password():
_refuse_while_locked(request) confirm_password(request, body.current)
if not store.check_password(body.current):
_warn(request, "wrong current password")
raise HTTPException(403, "That is not the current password.")
if len(body.new) < MIN_LENGTH: if len(body.new) < MIN_LENGTH:
raise HTTPException(400, f"Use at least {MIN_LENGTH} characters.") raise HTTPException(400, f"Use at least {MIN_LENGTH} characters.")
store.set_password(body.new) store.set_password(body.new)
closed = store.close_all(keep=token_from(request, config)) 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}") @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 """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.""" extra click, and refusing it would be a rule to explain for no gain."""
if not _store(request).close_by_id(session_id): if not _store(request).close_by_id(session_id):
raise HTTPException(404, "That session is already gone.") 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") @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.""" """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 <token>`.
@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) 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 # ------------------------------------------------------------------- passkeys
@@ -281,24 +348,37 @@ def close_others(request: Request) -> dict[str, int]:
@router.post("/api/account/passkeys/options") @router.post("/api/account/passkeys/options")
def passkey_options(request: Request) -> dict[str, object]: def passkey_options(request: Request, body: PasskeyOptionsBody) -> dict[str, object]:
"""Step one of registering: a challenge for `navigator.credentials.create`.""" """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) _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") @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. """Step two: check what the authenticator signed, and keep the public key.
Requires a session, like everything else under `/api/account`. Registering a Requires a session, like everything else under `/api/account`, and a
passkey is granting a new way in, so it is gated on already being in — the challenge from `passkey_options`, which only the password gets. The
password is what proves that, and the ceremony does not replace it. 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) _require_passkeys(request)
try: try:
return {"id": pk.register_verify(_config(request), request, _store(request), return PasskeyAdded(id=pk.register_verify(_config(request), request, _store(request),
body.credential, body.label)} body.credential, body.label))
except pk.PasskeyError as exc: except pk.PasskeyError as exc:
# `PasskeyMalformed` is one of these and answers the same way: from # `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 # 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") @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.""" """Name it. A key you cannot name is one you will never dare revoke."""
if not _store(request).rename_passkey(passkey_id, body.label): if not _store(request).rename_passkey(passkey_id, body.label):
raise HTTPException(404, "That passkey is already gone.") raise HTTPException(404, "That passkey is already gone.")
return {"ok": True} return Ok()
@router.delete("/api/account/passkeys/{passkey_id}") @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 — """Revoke one. The password is still there, so this cannot lock you out —
which is exactly why the password is still there.""" which is exactly why the password is still there."""
if not _store(request).delete_passkey(passkey_id): if not _store(request).delete_passkey(passkey_id):
raise HTTPException(404, "That passkey is already gone.") raise HTTPException(404, "That passkey is already gone.")
return {"ok": True} return Ok()
@router.post("/login/passkey/options", include_in_schema=False) @router.post("/login/passkey/options", include_in_schema=False)
@@ -363,7 +443,7 @@ def passkey_login(request: Request, response: Response,
# been wrong about. # been wrong about.
raise HTTPException(400, str(exc)) from None raise HTTPException(400, str(exc)) from None
except pk.PasskeyError as exc: except pk.PasskeyError as exc:
_warn(request, "passkey refused") warn(request, "passkey refused")
raise HTTPException(401, str(exc)) from None raise HTTPException(401, str(exc)) from None
_open_session(request, response) _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: def _safe_next(target: str) -> str:
r"""Where to go after signing in — only ever inside this app. 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. `//[` except ValueError: # an unparseable authority, e.g. `//[`
return False return False
return not parts.scheme and not parts.netloc 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"
+84 -2
View File
@@ -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 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 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 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 be a second, staler copy of a structure the library already parses and
validates properly. 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 from __future__ import annotations
@@ -34,6 +39,22 @@ class PasswordBody(BaseModel):
current: str = Field(max_length=1000) current: str = Field(max_length=1000)
new: 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): class PasskeyBody(BaseModel):
@@ -51,6 +72,67 @@ class PasskeyLoginBody(BaseModel):
class LabelBody(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 label: str
expires_at: str
+209 -12
View File
@@ -4,9 +4,9 @@
* <auth-account></auth-account> * <auth-account></auth-account>
* *
* That is the whole of it. The element asks `/api/account` what there is to * 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 * 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 * 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 * root scopes them anyway and a second file is a second route, a second cache
@@ -79,6 +79,18 @@ button {
padding: 2px 9px; padding: 2px 9px;
cursor: pointer; 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:hover { color: var(--desk-jobs-accent); }
button.danger:hover { color: var(--desk-jobs-error); } button.danger:hover { color: var(--desk-jobs-error); }
button[disabled] { opacity: .4; cursor: default; } 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; font-size: 12px; padding: 0 6px; border-radius: 999px;
border: 1px solid currentColor; color: var(--desk-jobs-dim); 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 /** 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 * the other way -- from an app that was restarted without the extra while
* this page was open. */ * this page was open. */
#passkeysGone = false; #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() { constructor() {
super(); super();
@@ -211,6 +247,7 @@ class AuthAccount extends HTMLElement {
this.#panel.append(this.#password(account)); this.#panel.append(this.#password(account));
if (account.sessions.length) this.#panel.append(this.#sessions(account)); if (account.sessions.length) this.#panel.append(this.#sessions(account));
if (this.#showPasskeys(account)) this.#panel.append(this.#passkeys(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()); if (account.locked) this.#panel.append(this.#signOut());
} }
@@ -255,22 +292,30 @@ class AuthAccount extends HTMLElement {
const form = document.createElement("form"); const form = document.createElement("form");
const current = field("password", "Current password"); const current = field("password", "Current password");
const next = field("password", first ? "Choose a password" : "New 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"); const go = document.createElement("button");
go.textContent = first ? "Set password" : "Change password"; go.textContent = first ? "Set password" : "Change password";
go.disabled = this.#busy; 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) => { form.addEventListener("submit", (event) => {
event.preventDefault(); event.preventDefault();
this.#act(async () => { this.#act(async () => {
const result = await this.#api("/api/account/password", { const result = await this.#api("/api/account/password", {
method: "POST", 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 = ""; current.value = next.value = "";
if (first) return this.#say("Password set."); if (first) return this.#say("Password set.");
this.#say(result.signed_out this.#say(changed(result));
? `Password changed. ${count(result.signed_out, "other session")} signed out.`
: "Password changed.");
}); });
}); });
section.append(form); section.append(form);
@@ -279,7 +324,7 @@ class AuthAccount extends HTMLElement {
// makes the change ceremonial. Said here so it is not a surprise. // makes the change ceremonial. Said here so it is not a surprise.
section.append(this.#line(first 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." ? "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; return section;
} }
@@ -344,13 +389,142 @@ class AuthAccount extends HTMLElement {
section.append(this.#line(account.passkeys_blocked)); section.append(this.#line(account.passkeys_blocked));
return section; 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; 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; 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(); const passkey = await loadPasskeyHelper();
if (!passkey || !passkey.supported()) { if (!passkey || !passkey.supported()) {
this.#say("This browser will not create a passkey here. It needs HTTPS, or localhost."); 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 // browser's own prompt happens between them, and a cancelled prompt is an
// exception rather than an error status -- hence `explain`. // exception rather than an error status -- hence `explain`.
await this.#act(async () => { 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; let made;
try { try {
made = await passkey.create(options); made = await passkey.create(options);
@@ -485,6 +661,19 @@ function field(type, placeholder) {
return input; 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) { function count(n, thing) {
return `${n} ${thing}${n === 1 ? "" : "s"}`; return `${n} ${thing}${n === 1 ? "" : "s"}`;
} }
@@ -498,6 +687,14 @@ function when(stamp) {
return at.toLocaleString(); 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")) { if (!customElements.get("auth-account")) {
customElements.define("auth-account", AuthAccount); customElements.define("auth-account", AuthAccount);
} }
+207 -26
View File
@@ -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 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: 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. 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 datetime import UTC, datetime, timedelta
from pathlib import Path 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 #: 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 #: 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. #: the ceiling. See `_lockout` for what goes wrong without it.
_MAX_STEPS = math.ceil(math.log2(_MAX_LOCK / _FIRST_LOCK)) _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. #: 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, #: 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 #: 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 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 #: 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. #: maintain in exchange for nothing.
SCHEMA = """ SCHEMA = """
CREATE TABLE IF NOT EXISTS auth_credential ( CREATE TABLE IF NOT EXISTS auth_credential (
@@ -130,6 +137,15 @@ CREATE TABLE IF NOT EXISTS auth_challenges (
purpose TEXT NOT NULL, purpose TEXT NOT NULL,
expires_at 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: 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") store = AuthStore("data/app.db")
@@ -207,13 +223,8 @@ class AuthStore:
) )
def locked_for(self) -> int: def locked_for(self) -> int:
"""Seconds until the next attempt will be looked at, or 0. """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.
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.
""" """
with closing(self._connect()) as conn: with closing(self._connect()) as conn:
row = conn.execute( row = conn.execute(
@@ -223,9 +234,61 @@ class AuthStore:
remaining = datetime.fromisoformat(row["locked_until"]) - _now() remaining = datetime.fromisoformat(row["locked_until"]) - _now()
return max(0, int(remaining.total_seconds() + 0.999)) 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. """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 `hmac.compare_digest` rather than `==`, so the comparison takes the same
time whatever the first wrong byte is. That is close to superstition at 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 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 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 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 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 What is left for this counter to do is make guessing pointless, which it
does whoever is guessing. does whoever is guessing.
""" """
with closing(self._connect()) as conn: with closing(self._connect()) as conn:
row = conn.execute( # `fetchall`, so no read is left open on this connection when it
"SELECT salt, hash, failures FROM auth_credential WHERE id=1" # asks for the write lock below.
).fetchone() rows = conn.execute(
if row is None: "SELECT salt, hash FROM auth_credential WHERE id=1").fetchall()
if not rows:
_derive(password, b"no password here") _derive(password, b"no password here")
return False return False
ok = hmac.compare_digest(_derive(password, row["salt"]), row["hash"]) ok = hmac.compare_digest(_derive(password, rows[0]["salt"]), rows[0]["hash"])
with conn: 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: if ok:
conn.execute( conn.execute(
"UPDATE auth_credential SET failures=0, locked_until='' WHERE id=1") "UPDATE auth_credential SET failures=0, locked_until='' WHERE id=1")
else: elif counted := conn.execute(
failures = int(row["failures"]) + 1 "UPDATE auth_credential SET failures = failures + 1 WHERE id=1 "
"RETURNING failures").fetchall():
failures = int(counted[0][0])
conn.execute( conn.execute(
"UPDATE auth_credential SET failures=?, locked_until=? WHERE id=1", "UPDATE auth_credential SET locked_until=? WHERE id=1",
(failures, _stamp(_now() + _lockout(failures)) (_stamp(_now() + _lockout(failures))
if failures >= _GRACE else ""), if failures >= _GRACE else "",))
) conn.commit()
except BaseException:
conn.rollback()
raise
return ok return ok
def changed_at(self) -> str: def changed_at(self) -> str:
@@ -368,6 +444,104 @@ class AuthStore:
cur = conn.execute("DELETE FROM auth_sessions") cur = conn.execute("DELETE FROM auth_sessions")
return cur.rowcount 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 # -------------------------------------------------------------- passkeys
def add_passkey(self, credential_id: bytes, public_key: bytes, 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"], id=row["id"], label=row["label"], created_at=row["created_at"],
last_seen_at=last_seen, expires_at=row["expires_at"], current=current, 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"],
)
+8 -1
View File
@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>{name} &mdash; sign in</title> <title>{name} &mdash; sign in</title>
<!-- The app's own stylesheet, if it passed one to `connect`. Optional on <!-- The app's own stylesheet, if it passed one to `connect`. Optional on
purpose: this folder is copied into projects that have no stylesheet yet, purpose: this folder is copied into projects that have no stylesheet yet,
@@ -42,6 +42,13 @@ body.login {
* saying twice. Without it the passkey button is drawn on an app that has no * saying twice. Without it the passkey button is drawn on an app that has no
* passkeys, and pressing it 404s. */ * passkeys, and pressing it 404s. */
[hidden] { display: none !important; } [hidden] { display: none !important; }
/* A phone: the form clears the notch and the home indicator, and a finger
* gets a thumb's height of button and a field that does not make iOS zoom. */
body.login { padding: env(safe-area-inset-top) 0 env(safe-area-inset-bottom); }
@media (pointer: coarse) {
.signin input[type=password] { font-size: 16px; padding: 0.6rem 0.7rem; }
.signin button { min-height: 2.75rem; }
}
</style> </style>
</head> </head>
<body class="login"> <body class="login">
+5 -2
View File
@@ -68,8 +68,11 @@ def locked(make_client: Callable[..., TestClient]) -> TestClient:
@pytest.fixture @pytest.fixture
def open_app(make_client: Callable[..., TestClient]) -> TestClient: def open_app(make_client: Callable[..., TestClient]) -> TestClient:
"""The same app on loopback under `auto` — no password asked for.""" """The same app on loopback under `auto` — no password asked for. Reached
return make_client(enabled="auto", host="127.0.0.1", password=None) as 127.0.0.1, which is the name an unlocked app answers a browser under
(`auth.middleware._rebound`)."""
return make_client(enabled="auto", host="127.0.0.1", password=None,
base_url="http://127.0.0.1")
@pytest.fixture @pytest.fixture
+44 -5
View File
@@ -5,7 +5,8 @@ one, so its tests are not allowed to reach for `app/` or `pipeline/` either --
`tests/test_coupling.py` reads the imports of every file under this folder and `tests/test_coupling.py` reads the imports of every file under this folder and
says so. What they need is a FastAPI app with a page, an API route, a socket, says so. What they need is a FastAPI app with a page, an API route, a socket,
and a couple of neighbours to prove the open list is matched the way it claims. and a couple of neighbours to prove the open list is matched the way it claims.
That is this file, and it is nine routes. That is this file, and it is nine routes and a stand-in for the broadcaster
the socket subscribes to.
A module rather than a conftest fixture because two tests build the same A module rather than a conftest fixture because two tests build the same
database twice, to see what a restart does, and a fixture cannot be asked for database twice, to see what a restart does, and a fixture cannot be asked for
@@ -15,11 +16,32 @@ twice in one test.
from __future__ import annotations from __future__ import annotations
import os import os
from collections.abc import Iterable
from fastapi import FastAPI, WebSocket from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import PlainTextResponse from fastapi.responses import PlainTextResponse
from auth import AuthConfig, AuthStore, connect from auth import AuthConfig, AuthStore, confirm_current, connect
class Bus:
"""What `auth.close_ended_sockets` reads off `app.state.bus`: the open
sockets and a way to close some. A stand-in for `pipeline.web.broadcaster.
Broadcaster`, which this folder may not import, with its two members."""
def __init__(self) -> None:
self.held: set[WebSocket] = set()
@property
def sockets(self) -> tuple[WebSocket, ...]:
return tuple(self.held)
async def close(self, sockets: Iterable[WebSocket], code: int, reason: str = "") -> int:
gone = [ws for ws in sockets if ws in self.held]
for ws in gone:
self.held.discard(ws)
await ws.close(code, reason)
return len(gone)
def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0", def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
@@ -28,6 +50,7 @@ def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
app = FastAPI() app = FastAPI()
connect(app, AuthStore(db), AuthConfig(**settings), host=host, connect(app, AuthStore(db), AuthConfig(**settings), host=host,
open=("/static/",), stylesheet="/static/app.css") open=("/static/",), stylesheet="/static/app.css")
app.state.bus = bus = Bus()
@app.get("/", response_class=PlainTextResponse) @app.get("/", response_class=PlainTextResponse)
def front() -> str: def front() -> str:
@@ -41,6 +64,13 @@ def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
def thing() -> dict[str, bool]: def thing() -> dict[str, bool]:
return {"ok": True} return {"ok": True}
@app.post("/thing/replace")
def replace(request: Request) -> dict[str, bool]:
"""A route that swaps the database as a file would: the current
password first, in its header, before any body."""
confirm_current(request)
return {"ok": True}
@app.get("/health") @app.get("/health")
def health() -> dict[str, bool]: def health() -> dict[str, bool]:
return {"ok": True} return {"ok": True}
@@ -61,8 +91,17 @@ def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
@app.websocket("/ws/jobs") @app.websocket("/ws/jobs")
async def socket(ws: WebSocket) -> None: async def socket(ws: WebSocket) -> None:
"""Held open until the client leaves or the bus closes it, as the
app's `/ws/jobs` is."""
await ws.accept() await ws.accept()
await ws.send_json({"type": "jobs"}) bus.held.add(ws)
await ws.close() try:
await ws.send_json({"type": "jobs"})
while True:
await ws.receive_text()
except WebSocketDisconnect:
pass
finally:
bus.held.discard(ws)
return app return app
+217 -8
View File
@@ -8,15 +8,19 @@ from __future__ import annotations
import logging import logging
import sqlite3 import sqlite3
from collections.abc import Callable from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing from contextlib import closing
from urllib.parse import parse_qs, urlsplit from urllib.parse import parse_qs, urlsplit
import pytest import pytest
from fastapi import Request
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from starlette.requests import HTTPConnection
from starlette.websockets import WebSocketDisconnect from starlette.websockets import WebSocketDisconnect
from auth import AuthStore from auth import AuthStore
from auth.middleware import OPEN from auth.middleware import OPEN
from auth.store import _GRACE
from auth.tests import PASSWORD, sign_in from auth.tests import PASSWORD, sign_in
from auth.tests.harness import build from auth.tests.harness import build
@@ -27,7 +31,9 @@ def test_loopback_under_auto_needs_no_password(open_app: TestClient):
"""The default on a laptop: the machine's own login is already the door.""" """The default on a laptop: the machine's own login is already the door."""
assert open_app.get("/").status_code == 200 assert open_app.get("/").status_code == 200
assert open_app.get("/api/thing").status_code == 200 assert open_app.get("/api/thing").status_code == 200
with open_app.websocket_connect("/ws/jobs") as socket: # The handshake names `testserver` unless told otherwise, and an unlocked
# app answers only to the names it is reached under.
with open_app.websocket_connect("/ws/jobs", headers={"host": "127.0.0.1"}) as socket:
assert socket.receive_json()["type"] == "jobs" assert socket.receive_json()["type"] == "jobs"
@@ -49,6 +55,49 @@ def test_never_is_open_off_loopback_too(make_client: Callable[..., TestClient]):
assert client.get("/api/thing").status_code == 200 assert client.get("/api/thing").status_code == 200
# ------------------------------------------------ a proxy on the same machine
@pytest.mark.parametrize("header", [
{"x-forwarded-for": "203.0.113.9"}, {"x-forwarded-proto": "https"},
{"x-forwarded-host": "app.example.com"}, {"forwarded": "for=203.0.113.9"},
])
def test_an_open_app_refuses_what_a_proxy_forwarded(open_app: TestClient, header):
"""`auto` on loopback is open because only this machine can reach it. A
reverse proxy on the same machine makes that false while every request
still comes from 127.0.0.1; its headers are the only sign, so a request
carrying one is refused rather than served unlocked."""
refused = open_app.get("/api/thing", headers=header)
assert refused.status_code == 421
assert "auth.enabled: always" in refused.json()["detail"]
assert open_app.get("/api/thing").status_code == 200
def test_the_proxy_refusal_is_logged_once(open_app: TestClient, caplog):
with caplog.at_level(logging.WARNING):
for _ in range(3):
open_app.get("/api/thing", headers={"x-forwarded-for": "203.0.113.9"})
said = [r.getMessage() for r in caplog.records if "proxied" in r.getMessage()]
assert len(said) == 1 and "auth.enabled: always" in said[0]
def test_the_proxy_refusal_covers_the_socket(open_app: TestClient):
with pytest.raises(WebSocketDisconnect), \
open_app.websocket_connect("/ws/jobs", headers={"x-forwarded-for": "203.0.113.9"}):
pass
def test_a_locked_or_never_locked_app_serves_a_proxy(
locked: TestClient, make_client: Callable[..., TestClient]):
"""`always` has its own door and `never` is the operator's word: neither
is second-guessed from the headers."""
forwarded = {"x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https"}
assert locked.post("/login", json={"password": PASSWORD},
headers=forwarded).status_code == 200
assert locked.get("/api/thing", headers=forwarded).status_code == 200
never = make_client(enabled="never", host="127.0.0.1")
assert never.get("/api/thing", headers=forwarded).status_code == 200
# -------------------------------------------------------- the locked door # -------------------------------------------------------- the locked door
def test_everything_is_shut(locked: TestClient): def test_everything_is_shut(locked: TestClient):
@@ -150,6 +199,21 @@ def test_a_wrong_password_is_refused(locked: TestClient):
assert locked.get("/api/thing").status_code == 401 assert locked.get("/api/thing").status_code == 401
def test_wrong_guesses_in_parallel_meet_the_lockout(locked: TestClient):
"""The lockout was read before the derivation and the failure written
after it, so thirty wrong guesses at once all found the door open and all
got a 401. Each is claimed before it is derived now: the first `_GRACE`
are looked at and the rest are told to wait."""
def guess(_: int) -> int:
# A client per thread, so no two share a cookie jar or a portal.
return sign_in(TestClient(locked.app), "nope").status_code
with ThreadPoolExecutor(max_workers=30) as pool:
said = list(pool.map(guess, range(30)))
assert said.count(401) == _GRACE, said
assert said.count(429) == 30 - _GRACE, said
def test_signing_in_opens_everything(locked: TestClient): def test_signing_in_opens_everything(locked: TestClient):
assert sign_in(locked).status_code == 200 assert sign_in(locked).status_code == 200
assert locked.get("/api/thing").status_code == 200 assert locked.get("/api/thing").status_code == 200
@@ -352,6 +416,84 @@ def test_the_password_change_is_behind_the_same_lockout(signed_in: TestClient):
assert sign_in(signed_in).status_code == 429 assert sign_in(signed_in).status_code == 429
def test_an_app_route_asks_for_the_password_through_the_package(
signed_in: TestClient, caplog):
"""A route outside the package that must take the current password (a
restore, whose body is the database file) calls `confirm_password`
rather than writing its own check, so it is counted and gated like the
front door."""
from auth import confirm_password, warn
@signed_in.app.post("/api/restore")
def restore(request: Request) -> dict[str, bool]:
confirm_password(request, request.headers.get("x-current-password", ""))
return {"ok": True}
with caplog.at_level(logging.WARNING):
wrong = signed_in.post("/api/restore", headers={"x-current-password": "nope"})
assert wrong.status_code == 403
assert "wrong current password from testclient" in caplog.text
assert {r.name for r in caplog.records if "from testclient" in r.getMessage()} == {
"auth.middleware"}
assert signed_in.post("/api/restore",
headers={"x-current-password": PASSWORD}).status_code == 200
for _ in range(5):
signed_in.post("/api/restore", headers={"x-current-password": "nope"})
refused = signed_in.post("/api/restore", headers={"x-current-password": PASSWORD})
assert refused.status_code == 429 and refused.headers["retry-after"]
assert sign_in(signed_in).status_code == 429
caplog.clear()
with caplog.at_level(logging.WARNING):
warn(HTTPConnection({"type": "http", "client": ("203.0.113.9", 1), "headers": []}),
"restore refused")
assert "restore refused from 203.0.113.9" in caplog.text
def test_a_file_route_without_the_header_is_refused_and_counts_nothing(
signed_in: TestClient, caplog):
"""A restore's body is the database, so the password rides in a header,
and a session alone is not enough: the restored file brings its own hash.
A missing header is a missing field and not a guess, so five of them leave
the right password working, at this route and at the front door."""
with caplog.at_level(logging.WARNING):
missing = signed_in.post("/thing/replace")
empty = signed_in.post("/thing/replace", headers={"x-current-password": ""})
for refused in (missing, empty):
assert refused.status_code == 403
assert "X-Current-Password" in refused.json()["detail"]
assert "no current password for POST /thing/replace from testclient" in caplog.text
for _ in range(5):
assert signed_in.post("/thing/replace").status_code == 403
assert signed_in.post("/thing/replace",
headers={"x-current-password": PASSWORD}).status_code == 200
assert sign_in(signed_in).status_code == 200
def test_a_file_route_counts_a_wrong_header(signed_in: TestClient, caplog):
with caplog.at_level(logging.WARNING):
wrong = signed_in.post("/thing/replace", headers={"x-current-password": "nope"})
assert wrong.status_code == 403
assert "wrong current password from testclient" in caplog.text
for _ in range(4):
signed_in.post("/thing/replace", headers={"x-current-password": "nope"})
refused = signed_in.post("/thing/replace", headers={"x-current-password": PASSWORD})
assert refused.status_code == 429 and refused.headers["retry-after"]
assert sign_in(signed_in).status_code == 429
def test_a_file_route_takes_the_right_header(signed_in: TestClient):
right = signed_in.post("/thing/replace", headers={"x-current-password": PASSWORD})
assert right.status_code == 200 and right.json() == {"ok": True}
def test_a_file_route_on_an_app_with_no_password_needs_no_header(open_app: TestClient):
"""The laptop that was never locked has nothing to confirm."""
assert open_app.post("/thing/replace").status_code == 200
# ------------------------------------------------------- the bootstrap # ------------------------------------------------------- the bootstrap
def test_a_generated_password_is_printed_once( def test_a_generated_password_is_printed_once(
@@ -429,6 +571,51 @@ def test_the_environment_variable_is_a_setting(
assert client.get("/api/account").json()["pinned_by"] == "OTHER_PASSWORD" assert client.get("/api/account").json()["pinned_by"] == "OTHER_PASSWORD"
def test_recovery_through_the_environment_signs_everyone_out(
tmp_path, monkeypatch, caplog):
"""`APP_PASSWORD` is the way back in when the password is lost, and the
reason it is lost may be that someone else has it and is signed in. So a
pinned password that replaces the stored one closes every session. Tokens
and passkeys stay, since the environment cannot tell whose they are, and
the log says how many so the owner knows to review them."""
db = tmp_path / "recovered.db"
store = AuthStore(db)
store.set_password("the-one-the-intruder-has")
intruder = store.open_session("intruder", 30)
_, token = store.create_token("intruder's cron", None)
store.add_passkey(b"cred", b"key", 0, "", "intruder's key")
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
with caplog.at_level(logging.WARNING), \
TestClient(build(db, enabled="always"), follow_redirects=False) as client:
assert client.get("/api/thing",
headers={"cookie": f"app_session={intruder}"}).status_code == 401
assert client.get("/api/thing",
headers={"authorization": f"Bearer {token}"}).status_code == 200
assert sign_in(client).status_code == 200
mine = client.cookies["app_session"]
said = [r for r in caplog.records if "password reset from APP_PASSWORD" in r.getMessage()]
assert len(said) == 1 and said[0].levelno == logging.WARNING
assert "closed 1 sessions; 1 API tokens and 1 passkeys remain" in said[0].getMessage()
# A restart with the same variable matches and closes nothing.
caplog.clear()
with caplog.at_level(logging.WARNING), TestClient(build(db, enabled="always")) as client:
assert client.get("/api/thing",
headers={"cookie": f"app_session={mine}"}).status_code == 200
assert "password reset" not in caplog.text
def test_a_first_password_from_the_environment_is_not_a_recovery(
make_client: Callable[..., TestClient], monkeypatch, caplog):
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
with caplog.at_level(logging.INFO):
client = make_client(enabled="always", password=None)
assert "password set from APP_PASSWORD" in caplog.text
assert "password reset" not in caplog.text
assert sign_in(client).status_code == 200
def test_expired_sessions_are_purged_at_startup(tmp_path): def test_expired_sessions_are_purged_at_startup(tmp_path):
"""Housekeeping, not a security boundary -- `touch` already refuses an """Housekeeping, not a security boundary -- `touch` already refuses an
expired row. Without it the table grows forever.""" expired row. Without it the table grows forever."""
@@ -452,8 +639,8 @@ def test_a_refused_login_says_who_it_was(locked: TestClient, caplog):
nothing anywhere knows it happened.""" nothing anywhere knows it happened."""
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
assert sign_in(locked, "nope").status_code == 401 assert sign_in(locked, "nope").status_code == 401
# The logger is `auth.router`, so the line already says which package this # The logger is `auth.middleware`, so the line already says which package
# came from and the message does not say it again. # this came from and the message does not say it again.
assert "wrong password from testclient" in caplog.text assert "wrong password from testclient" in caplog.text
assert "auth: wrong password" not in caplog.text assert "auth: wrong password" not in caplog.text
@@ -465,15 +652,37 @@ def test_a_refused_password_change_says_so_too(signed_in: TestClient, caplog):
assert "wrong current password" in caplog.text assert "wrong current password" in caplog.text
def test_the_log_prefers_the_address_the_proxy_passed_on(locked: TestClient, caplog): def test_the_log_names_the_hop_the_proxy_added(locked: TestClient, caplog):
"""Behind a proxy the peer is a container on its own network and says """Behind a proxy the peer is a container on its own network and says
nothing about who is at the other end. Both are written, because the header nothing about who is at the other end. The proxy appends the address it
is only as good as whoever sent it -- which is also why nothing is decided accepted the connection from to whatever `X-Forwarded-For` the caller
from it.""" sent, so the rightmost hop is the proxy's word and every hop left of it
the caller's: logging the first let an attacker name whom fail2ban bans.
Both the hop and the peer are written, because the header is only as good
as whoever set it -- which is also why nothing is decided from it."""
with caplog.at_level(logging.WARNING): with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"}, locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": "203.0.113.9, 10.9.9.9"}) headers={"x-forwarded-for": "203.0.113.9, 10.9.9.9"})
assert "203.0.113.9 via testclient" in caplog.text (said,) = [r.getMessage() for r in caplog.records if r.name == "auth.middleware"]
assert said == "wrong password from 10.9.9.9 via testclient"
assert "203.0.113.9" not in caplog.text
def test_the_log_falls_back_to_x_real_ip(locked: TestClient, caplog):
"""A proxy that sets `X-Real-IP` sets it outright. Read only when there is
no `X-Forwarded-For`, which a proxy that sends both keeps current too."""
with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"},
headers={"x-real-ip": "198.51.100.7"})
locked.post("/login", json={"password": "nope"},
headers={"x-real-ip": "198.51.100.7",
"x-forwarded-for": "203.0.113.9, 192.0.2.1"})
locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": " ", "x-real-ip": "198.51.100.7"})
said = [r.getMessage() for r in caplog.records if r.name == "auth.middleware"]
assert said == ["wrong password from 198.51.100.7 via testclient",
"wrong password from 192.0.2.1 via testclient",
"wrong password from 198.51.100.7 via testclient"]
def test_a_forwarded_address_cannot_write_the_log_itself(locked: TestClient, caplog): def test_a_forwarded_address_cannot_write_the_log_itself(locked: TestClient, caplog):
+63 -6
View File
@@ -32,6 +32,8 @@ from auth.tests.softkey import SoftKey, b64 # noqa: E402 after the skip
#: the real `blocked()` path rather than a configured override. #: the real `blocked()` path rather than a configured override.
RP_ID = "localhost" RP_ID = "localhost"
ORIGIN = "http://localhost" ORIGIN = "http://localhost"
#: What starting a registration takes besides a session: the password.
CONFIRM = {"current": PASSWORD}
def unb64(text: str) -> bytes: def unb64(text: str) -> bytes:
@@ -48,7 +50,7 @@ def client(make_client: Callable[..., TestClient]) -> TestClient:
def register(client: TestClient, key: SoftKey, label: str = "Test key"): def register(client: TestClient, key: SoftKey, label: str = "Test key"):
"""The whole registration ceremony, both round trips.""" """The whole registration ceremony, both round trips."""
options = client.post("/api/account/passkeys/options").json() options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN) made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN)
return client.post("/api/account/passkeys", return client.post("/api/account/passkeys",
json={"credential": made, "label": label}) json={"credential": made, "label": label})
@@ -66,7 +68,45 @@ def login(client: TestClient, key: SoftKey, origin: str = ORIGIN):
def test_registering_needs_a_session(client: TestClient): def test_registering_needs_a_session(client: TestClient):
"""A passkey is a new way in, so adding one is gated on already being in.""" """A passkey is a new way in, so adding one is gated on already being in."""
client.post("/logout") client.post("/logout")
assert client.post("/api/account/passkeys/options").status_code == 401 assert client.post("/api/account/passkeys/options", json=CONFIRM).status_code == 401
def test_registering_needs_the_password_too(client: TestClient, caplog):
"""A passkey outlives every session and a password change, so a borrowed
signed-in browser must not be able to add one: a wrong or missing password
gets no challenge, is logged like the other doors, and is counted."""
with caplog.at_level("WARNING"):
wrong = client.post("/api/account/passkeys/options", json={"current": "nope"})
assert wrong.status_code == 403
assert "wrong current password" in caplog.text
assert client.post("/api/account/passkeys/options", json={}).status_code == 422
assert client.post("/api/account/passkeys/options").status_code == 422
assert client.get("/api/account").json()["passkeys"] == []
def test_registering_is_behind_the_same_lockout(client: TestClient):
"""Guessing at the passkey door locks the front door too, and once locked
the right password is not looked at."""
for _ in range(5):
assert client.post("/api/account/passkeys/options",
json={"current": "nope"}).status_code == 403
refused = client.post("/api/account/passkeys/options", json=CONFIRM)
assert refused.status_code == 429
client.post("/logout")
assert sign_in(client).status_code == 429
def test_an_app_with_no_password_registers_without_one(
make_client: Callable[..., TestClient]):
"""Loopback under `auto` and never locked: there is no password to confirm
and no session to borrow, so registering before deploying still works."""
open_app = make_client(host="127.0.0.1", password=None, base_url=ORIGIN)
assert not open_app.app.state.auth.has_password()
options = open_app.post("/api/account/passkeys/options", json={"current": ""})
assert options.status_code == 200
made = SoftKey().register(unb64(options.json()["challenge"]), RP_ID, ORIGIN)
assert open_app.post("/api/account/passkeys",
json={"credential": made}).status_code == 200
def test_a_passkey_registers_and_is_listed(client: TestClient): def test_a_passkey_registers_and_is_listed(client: TestClient):
@@ -95,14 +135,14 @@ def test_a_second_registration_is_excluded_not_duplicated(client: TestClient):
say "you have one of these" rather than making a second.""" say "you have one of these" rather than making a second."""
key = SoftKey() key = SoftKey()
register(client, key) register(client, key)
options = client.post("/api/account/passkeys/options").json() options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
assert [c["id"] for c in options["excludeCredentials"]] == [b64(key.credential_id)] assert [c["id"] for c in options["excludeCredentials"]] == [b64(key.credential_id)]
def test_a_stale_challenge_is_refused(client: TestClient): def test_a_stale_challenge_is_refused(client: TestClient):
"""A challenge is single-use, so the same response cannot be sent twice.""" """A challenge is single-use, so the same response cannot be sent twice."""
key = SoftKey() key = SoftKey()
options = client.post("/api/account/passkeys/options").json() options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN) made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN)
assert client.post("/api/account/passkeys", json={"credential": made}).status_code == 200 assert client.post("/api/account/passkeys", json={"credential": made}).status_code == 200
@@ -224,6 +264,23 @@ def test_a_malformed_body_is_a_400_and_not_a_traceback(client: TestClient):
assert client.post("/login/passkey", json={"credential": {}}).status_code == 400 assert client.post("/login/passkey", json={"credential": {}}).status_code == 400
def test_a_raw_id_that_is_not_base64url_is_a_400_and_spends_nothing(client: TestClient):
"""`rawId` was decoded unguarded after the challenge was taken, so `"a"`
was a 500 from an endpoint anyone can reach and the challenge was gone.
Now it is refused before the challenge is spent: the same challenge,
answered properly, still signs in."""
key = SoftKey()
register(client, key)
client.post("/logout")
options = client.post("/login/passkey/options").json()
signed = key.sign(unb64(options["challenge"]), RP_ID, ORIGIN)
refused = client.post("/login/passkey", json={"credential": {**signed, "rawId": "a"}})
assert refused.status_code == 400
assert "rawId is not base64url" in refused.json()["detail"]
assert client.post("/login/passkey", json={"credential": signed}).status_code == 200
def test_no_passkeys_registered_says_so(client: TestClient): def test_no_passkeys_registered_says_so(client: TestClient):
client.post("/logout") client.post("/logout")
assert client.post("/login/passkey/options").status_code == 404 assert client.post("/login/passkey/options").status_code == 404
@@ -243,7 +300,7 @@ def test_a_registration_challenge_cannot_be_answered_at_the_login_door(
""" """
key = SoftKey() key = SoftKey()
register(client, key) register(client, key)
theirs = client.post("/api/account/passkeys/options").json() theirs = client.post("/api/account/passkeys/options", json=CONFIRM).json()
client.post("/logout") client.post("/logout")
signed = key.sign(unb64(theirs["challenge"]), RP_ID, ORIGIN) signed = key.sign(unb64(theirs["challenge"]), RP_ID, ORIGIN)
@@ -352,7 +409,7 @@ def test_a_configured_rp_id_and_origin_win(make_client: Callable[..., TestClient
client = make_client(enabled="always", rp_id="app.example.com", client = make_client(enabled="always", rp_id="app.example.com",
origin="https://app.example.com") origin="https://app.example.com")
sign_in(client) sign_in(client)
options = client.post("/api/account/passkeys/options").json() options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
assert options["rp"]["id"] == "app.example.com" assert options["rp"]["id"] == "app.example.com"
assert client.get("/api/account").json()["passkeys_blocked"] == "" assert client.get("/api/account").json()["passkeys_blocked"] == ""
+170
View File
@@ -0,0 +1,170 @@
"""A socket whose credential ends is closed: by the route that ended it, or by
the sweep when it expired.
uv run pytest auth/tests/test_sockets.py -q
The door is checked at the handshake only, so before this a signed-out tab,
a revoked token or an expired session kept its socket streaming until the tab
reconnected. Every socket here is opened on the client the route is called
on: a client that is not entered runs its requests on an event loop of their
own, and the route's background task could not close a socket living there.
"""
from __future__ import annotations
import asyncio
import contextlib
import logging
import sqlite3
from contextlib import closing
from pathlib import Path
from typing import Any
import pytest
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
import auth.middleware
from auth import AuthConfig, close_ended_sockets, sweep_ended_sockets
from auth.tests import PASSWORD
from auth.tests.harness import build
#: The cookie a login over plain http sets.
COOKIE = AuthConfig().cookie
LONG_AGO = "2000-01-01T00:00:00+00:00"
def closed_with(ws: Any) -> int:
"""Read frames until the server closes the socket; the close code.
Blocks on a socket the server left open, since the test client's receive
has no timeout, so each test asks the bus first, which does not block."""
for _ in range(50):
try:
ws.receive_json()
except WebSocketDisconnect as closed:
return closed.code
raise AssertionError("the socket stayed open")
def sweep_now(client: TestClient) -> int:
"""`close_ended_sockets` on the loop the client's sockets live on."""
assert client.portal is not None
return client.portal.call(close_ended_sockets, client.app)
def expire(client: TestClient, table: str) -> None:
with closing(sqlite3.connect(client.app.state.auth.path)) as conn, conn:
conn.execute(f"UPDATE {table} SET expires_at=?", (LONG_AGO,))
# --------------------------------------------------------------- the routes
def test_signing_out_closes_the_socket_the_session_opened(signed_in: TestClient):
with signed_in.websocket_connect("/ws/jobs") as ws:
assert ws.receive_json()["type"] == "jobs"
assert signed_in.post("/logout").status_code == 200
assert signed_in.app.state.bus.sockets == ()
assert closed_with(ws) == 1008
def test_revoking_a_token_closes_its_socket(signed_in: TestClient):
"""The cookie is taken out so the bearer header is what opens the socket;
with the cookie in, the session would be what it stands on."""
made = signed_in.post("/api/account/tokens",
json={"current": PASSWORD, "label": "cron"}).json()
here = signed_in.cookies[COOKIE]
signed_in.cookies.clear()
with signed_in.websocket_connect(
"/ws/jobs", headers={"authorization": f"Bearer {made['token']}"}) as ws:
assert ws.receive_json()["type"] == "jobs"
signed_in.cookies.set(COOKIE, here)
assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 200
assert signed_in.app.state.bus.sockets == ()
assert closed_with(ws) == 1008
def test_closing_the_others_closes_their_sockets_and_keeps_this_one(
signed_in: TestClient):
here = signed_in.cookies[COOKIE]
there = signed_in.app.state.auth.open_session("phone", 1)
def as_(token: str) -> None:
signed_in.cookies.clear()
signed_in.cookies.set(COOKIE, token)
as_(there)
with signed_in.websocket_connect("/ws/jobs") as theirs:
assert theirs.receive_json()["type"] == "jobs"
as_(here)
with signed_in.websocket_connect("/ws/jobs") as mine:
assert mine.receive_json()["type"] == "jobs"
closed = signed_in.post("/api/account/sessions/close")
assert closed.json() == {"signed_out": 1}
assert len(signed_in.app.state.bus.sockets) == 1, "this tab's is open"
assert closed_with(theirs) == 1008
# ---------------------------------------------------------------- expiry
def test_an_expired_session_loses_its_socket(signed_in: TestClient):
"""Expiry ends no request, so no route sees it; the sweep's call does."""
with signed_in.websocket_connect("/ws/jobs") as ws:
assert ws.receive_json()["type"] == "jobs"
assert sweep_now(signed_in) == 0, "a live session keeps its socket"
expire(signed_in, "auth_sessions")
assert sweep_now(signed_in) == 1
assert closed_with(ws) == 1008
def test_nothing_is_closed_on_an_unlocked_app_or_one_without_a_bus(
open_app: TestClient, signed_in: TestClient):
with open_app.websocket_connect("/ws/jobs", headers={"host": "127.0.0.1"}) as ws:
assert ws.receive_json()["type"] == "jobs"
assert sweep_now(open_app) == 0
del signed_in.app.state.bus
expire(signed_in, "auth_sessions")
assert sweep_now(signed_in) == 0
def test_the_sweep_runs_on_its_clock_and_survives_a_failure(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture):
calls: list[object] = []
async def counted(app: object) -> int:
calls.append(app)
if len(calls) == 1:
raise sqlite3.OperationalError("database is locked")
return 0
monkeypatch.setattr(auth.middleware, "close_ended_sockets", counted)
async def run() -> asyncio.Task[None]:
task = asyncio.create_task(sweep_ended_sockets("the app", every=0.01))
for _ in range(200):
if len(calls) >= 2:
break
await asyncio.sleep(0.01)
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
return task
with caplog.at_level(logging.WARNING):
task = asyncio.run(run())
assert len(calls) >= 2 and calls[0] == "the app"
assert "the socket sweep failed" in caplog.text
assert task.cancelled()
def test_a_locked_app_sweeps_while_it_is_up(tmp_path: Path):
app = build(tmp_path / "a.db", enabled="always")
assert app.state.auth_sweep is None
with TestClient(app):
sweep = app.state.auth_sweep
assert isinstance(sweep, asyncio.Task) and not sweep.done()
assert sweep.done() and sweep.cancelled()
def test_an_unlocked_app_has_no_sweep(open_app: TestClient):
assert open_app.app.state.auth_sweep is None
+66 -1
View File
@@ -53,7 +53,7 @@ def test_the_tables_are_namespaced(store: AuthStore):
named = {name for (name,) in rows( named = {name for (name,) in rows(
store, "SELECT name FROM sqlite_master WHERE type='table'")} store, "SELECT name FROM sqlite_master WHERE type='table'")}
assert {"auth_credential", "auth_sessions", "auth_passkeys", assert {"auth_credential", "auth_sessions", "auth_passkeys",
"auth_challenges"} <= named "auth_challenges", "auth_tokens"} <= named
assert not {n for n in named if not n.startswith(("auth_", "sqlite_"))} assert not {n for n in named if not n.startswith(("auth_", "sqlite_"))}
@@ -119,6 +119,71 @@ def test_the_delay_doubles_and_then_stops(store: AuthStore):
assert store.check_password(PASSWORD) is True assert store.check_password(PASSWORD) is True
def test_wrong_guesses_in_parallel_are_each_counted(store: AuthStore):
"""`failures` was read, scrypt ran, and the read plus one was written, so
forty wrong guesses at once recorded one failure and no lockout. The raise
is one statement under the write lock now."""
from concurrent.futures import ThreadPoolExecutor
store.set_password(PASSWORD)
with ThreadPoolExecutor(max_workers=16) as pool:
said = list(pool.map(lambda _: store.check_password("wrong"), range(40)))
assert said == [False] * 40
assert rows(store, "SELECT failures FROM auth_credential") == [(40,)]
assert store.locked_for() > 0
def test_parallel_claims_admit_the_grace_and_no_more(store: AuthStore):
"""What both doors do: claim, then derive. A claim reads the lockout and
counts the attempt in one write transaction, so thirty claims at once
admit `_GRACE` guesses and tell the rest to wait, where a read before the
derivation and a write after it admitted all thirty."""
from concurrent.futures import ThreadPoolExecutor
store.set_password(PASSWORD)
def guess(_: int) -> str:
if store.claim_attempt():
return "wait"
return "right" if store.check_password("wrong", claimed=True) else "wrong"
with ThreadPoolExecutor(max_workers=30) as pool:
said = list(pool.map(guess, range(30)))
assert said.count("wrong") == _GRACE and said.count("wait") == 30 - _GRACE
assert rows(store, "SELECT failures FROM auth_credential") == [(_GRACE,)]
def test_a_claimed_right_password_clears_the_count(store: AuthStore):
"""Counted up front, credited back: the fifth claim writes the lockout
before the derivation, and a right answer then clears it."""
store.set_password(PASSWORD)
for _ in range(_GRACE - 1):
assert store.claim_attempt() == 0
assert store.check_password("wrong", claimed=True) is False
assert store.claim_attempt() == 0
assert store.locked_for() > 0, "the fifth claim did not write the lockout"
assert store.check_password(PASSWORD, claimed=True) is True
assert store.locked_for() == 0
assert rows(store, "SELECT failures, locked_until FROM auth_credential") == [(0, "")]
def test_a_claim_while_locked_counts_nothing(store: AuthStore):
"""Hammering while locked out does not extend the lockout."""
store.set_password(PASSWORD)
for _ in range(_GRACE):
assert store.claim_attempt() == 0
store.check_password("wrong", claimed=True)
before = rows(store, "SELECT failures, locked_until FROM auth_credential")
for _ in range(10):
assert store.claim_attempt() > 0
assert rows(store, "SELECT failures, locked_until FROM auth_credential") == before
def test_a_claim_on_a_database_with_no_password_is_granted(store: AuthStore):
assert store.claim_attempt() == 0
assert store.check_password(PASSWORD, claimed=True) is False
# -------------------------------------------------------------- the sessions # -------------------------------------------------------------- the sessions
def test_a_session_is_live_until_it_is_not(store: AuthStore): def test_a_session_is_live_until_it_is_not(store: AuthStore):
+465
View File
@@ -0,0 +1,465 @@
"""API tokens: the third way in, for a script, and what it cannot do.
uv run pytest auth/tests/test_tokens.py -q
A token is minted with the password, carried as `Authorization: Bearer`, looked
up on every request like a session, and shut out of the account routes. The
same-site rule the middleware applies to every request is here too, because a
script's token is the one credential a browser never carries for it.
"""
from __future__ import annotations
import logging
import sqlite3
from collections.abc import Callable
from contextlib import closing
from datetime import UTC, datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from auth import AuthStore
from auth.middleware import ACCOUNT, _rebound, cross_site
from auth.store import HINT
from auth.tests import PASSWORD, sign_in
CONFIRM = {"current": PASSWORD}
def mint(client: TestClient, label: str = "cron", **body: object) -> dict:
answer = client.post("/api/account/tokens", json={**CONFIRM, "label": label, **body})
assert answer.status_code == 200, answer.text
return answer.json()
def bearer(token: str) -> dict[str, str]:
return {"authorization": f"Bearer {token}"}
# ------------------------------------------------------------------ the store
def test_the_token_is_not_in_the_file(store: AuthStore):
"""Hashed like a session token, and for the same reason: the file lets
nobody in."""
token_id, token = store.create_token("cron", None)
assert token.encode() not in store.path.read_bytes()
assert store.touch_token(token) is not None
assert store.touch_token(token).id == token_id
def test_the_list_shows_the_opening_and_nothing_else(store: AuthStore):
_, token = store.create_token("cron", None)
(listed,) = store.tokens()
assert listed.hint == token[:HINT] and len(listed.hint) == HINT
assert listed.label == "cron" and listed.expires_at == "" and listed.last_used_at == ""
assert "token" not in listed.model_dump()
def test_a_dated_token_runs_out(store: AuthStore):
_, token = store.create_token("short", 30)
(listed,) = store.tokens()
expires = datetime.fromisoformat(listed.expires_at)
assert timedelta(days=29) < expires - datetime.now(UTC) <= timedelta(days=30)
with closing(sqlite3.connect(store.path)) as conn, conn:
conn.execute("UPDATE auth_tokens SET expires_at='2000-01-01T00:00:00+00:00'")
assert store.touch_token(token) is None
# Still listed, so the owner sees the row that ran out and removes it.
assert len(store.tokens()) == 1
def test_using_a_token_stamps_it_once_in_a_while(store: AuthStore):
_, token = store.create_token("cron", None)
first = store.touch_token(token)
assert first is not None and first.last_used_at
with closing(sqlite3.connect(store.path)) as conn, conn:
conn.execute("UPDATE auth_tokens SET last_used_at='2000-01-01T00:00:00+00:00'")
again = store.touch_token(token)
assert again is not None and again.last_used_at > "2000-01-02"
def test_a_token_is_renamed_and_revoked_by_its_row(store: AuthStore):
token_id, token = store.create_token("cron", None)
assert store.rename_token(token_id, "the laptop") is True
assert store.tokens()[0].label == "the laptop"
assert store.delete_token(token_id) is True
assert store.touch_token(token) is None
assert store.delete_token(token_id) is False
def test_a_token_is_not_a_session(store: AuthStore):
"""Two tables, two lookups: a token in the cookie opens nothing, and a
session token in the header opens nothing."""
_, token = store.create_token("cron", None)
session = store.open_session("browser", 30)
assert store.touch(token) is None
assert store.touch_token(session) is None
# ----------------------------------------------------------------- minting
def test_minting_needs_a_session(locked: TestClient):
assert locked.post("/api/account/tokens", json=CONFIRM).status_code == 401
def test_minting_needs_the_password_too(signed_in: TestClient, caplog):
"""A token outlives every session and a password change, so a borrowed
signed-in browser must not be able to mint one."""
with caplog.at_level(logging.WARNING):
wrong = signed_in.post("/api/account/tokens", json={"current": "nope"})
assert wrong.status_code == 403
assert "wrong current password" in caplog.text
assert signed_in.get("/api/account").json()["tokens"] == []
def test_minting_is_behind_the_same_lockout(signed_in: TestClient):
for _ in range(5):
signed_in.post("/api/account/tokens", json={"current": "nope"})
refused = signed_in.post("/api/account/tokens", json=CONFIRM)
assert refused.status_code == 429
assert sign_in(signed_in).status_code == 429
def test_an_app_with_no_password_mints_without_one(open_app: TestClient):
"""The laptop before it is deployed, as with a passkey."""
made = open_app.post("/api/account/tokens", json={"current": "", "label": "here"})
assert made.status_code == 200 and made.json()["token"]
def test_the_token_is_shown_once_and_listed_by_its_opening(signed_in: TestClient):
made = mint(signed_in, "cron", days=90)
assert made["hint"] == made["token"][:HINT] and made["label"] == "cron"
assert made["expires_at"]
(listed,) = signed_in.get("/api/account").json()["tokens"]
assert listed["id"] == made["id"] and listed["hint"] == made["hint"]
assert "token" not in listed
def test_the_label_and_the_days_are_bounded(signed_in: TestClient):
assert signed_in.post("/api/account/tokens",
json={**CONFIRM, "days": 0}).status_code == 422
assert signed_in.post("/api/account/tokens",
json={**CONFIRM, "days": 4000}).status_code == 422
assert signed_in.post("/api/account/tokens",
json={**CONFIRM, "label": "x" * 101}).status_code == 422
# ------------------------------------------------------------- the bearer
def test_a_token_opens_the_api_and_the_socket(signed_in: TestClient):
token = mint(signed_in)["token"]
script = TestClient(signed_in.app, follow_redirects=False)
assert script.get("/api/thing").status_code == 401
assert script.get("/api/thing", headers=bearer(token)).status_code == 200
with script.websocket_connect("/ws/jobs", headers=bearer(token)) as socket:
assert socket.receive_json()["type"] == "jobs"
def test_a_token_cannot_reach_the_account(signed_in: TestClient):
"""A leaked token must not be able to mint another, revoke the owner's
sessions, or read the list of ways in; and `/logout` is a session's."""
token = mint(signed_in)["token"]
script = TestClient(signed_in.app, follow_redirects=False)
for method, path in (("GET", "/api/account"),
("POST", "/api/account/tokens"),
("POST", "/api/account/sessions/close"),
("DELETE", "/api/account/sessions/1"),
("POST", "/api/account/password"),
("POST", "/logout")):
refused = script.request(method, path, headers=bearer(token), json=CONFIRM)
assert refused.status_code == 403, f"{method} {path}: {refused.status_code}"
assert "not the account" in refused.json()["detail"]
# And the names are matched whole: `/api/accounts` is not the account.
assert script.get("/api/accountx", headers=bearer(token)).status_code == 404
assert ACCOUNT == ("/api/account", "/api/account/", "/logout")
def test_a_cookie_session_wins_over_a_bad_header(signed_in: TestClient):
"""A browser extension that adds a stale header must not sign a browser out."""
assert signed_in.get("/api/account", headers=bearer("stale")).status_code == 200
def test_a_bad_token_is_a_401_and_a_line_in_the_log(locked: TestClient, caplog):
with caplog.at_level(logging.WARNING):
refused = locked.get("/api/thing", headers=bearer("not-a-token"))
assert refused.status_code == 401
assert refused.json()["detail"] == "That token is not valid here."
assert "bad token from testclient" in caplog.text
# JSON whatever was asked for: a script, not a browser, sent this header.
assert locked.get("/deep/page", headers=bearer("not-a-token")).status_code == 401
# And nothing is counted against the password: the right one still opens.
assert sign_in(locked).status_code == 200
def test_only_the_bearer_scheme_is_read(locked: TestClient):
assert locked.get("/api/thing",
headers={"authorization": "Basic dXNlcjpwYXNz"}).status_code == 401
assert locked.get("/api/thing?token=x").status_code == 401
def test_a_revoked_token_is_refused_on_the_next_request(signed_in: TestClient):
made = mint(signed_in)
script = TestClient(signed_in.app, follow_redirects=False)
assert script.get("/api/thing", headers=bearer(made["token"])).status_code == 200
assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 200
assert script.get("/api/thing", headers=bearer(made["token"])).status_code == 401
assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 404
def test_a_token_survives_a_password_change(signed_in: TestClient):
"""Like a passkey: the cron job holding it is not what the password was
changed against. The account screen is where to revoke it, and the answer
says how many remain so the screen can say so."""
token = mint(signed_in)["token"]
changed = signed_in.post("/api/account/password",
json={"current": PASSWORD, "new": "a-much-longer-one"})
assert changed.status_code == 200
assert changed.json() == {"signed_out": 0, "tokens_revoked": 0, "passkeys_revoked": 0,
"tokens_left": 1, "passkeys_left": 0}
script = TestClient(signed_in.app, follow_redirects=False)
assert script.get("/api/thing", headers=bearer(token)).status_code == 200
def test_a_password_change_can_revoke_every_token_and_passkey(signed_in: TestClient):
"""The case the route exists for: whoever had the password may have
minted a token that never expires or registered a passkey, and either
outlives the change. `revoke_all` deletes them with it."""
token = mint(signed_in)["token"]
mint(signed_in, "another")
signed_in.app.state.auth.add_passkey(b"cred", b"key", 0, "", "someone's key")
other = TestClient(signed_in.app, follow_redirects=False)
sign_in(other)
changed = signed_in.post("/api/account/password", json={
"current": PASSWORD, "new": "a-much-longer-one", "revoke_all": True})
assert changed.status_code == 200
assert changed.json() == {"signed_out": 1, "tokens_revoked": 2, "passkeys_revoked": 1,
"tokens_left": 0, "passkeys_left": 0}
script = TestClient(signed_in.app, follow_redirects=False)
assert script.get("/api/thing", headers=bearer(token)).status_code == 401
account = signed_in.get("/api/account").json()
assert account["tokens"] == [] and account["passkeys"] == []
assert other.get("/api/thing").status_code == 401
assert signed_in.get("/api/thing").status_code == 200
def test_a_wrong_password_revokes_nothing(signed_in: TestClient):
token = mint(signed_in)["token"]
refused = signed_in.post("/api/account/password", json={
"current": "nope", "new": "a-much-longer-one", "revoke_all": True})
assert refused.status_code == 403
script = TestClient(signed_in.app, follow_redirects=False)
assert script.get("/api/thing", headers=bearer(token)).status_code == 200
def test_a_token_is_renamed_from_the_account(signed_in: TestClient):
made = mint(signed_in)
renamed = signed_in.post(f"/api/account/tokens/{made['id']}/label",
json={"label": "the pi"})
assert renamed.status_code == 200
assert signed_in.get("/api/account").json()["tokens"][0]["label"] == "the pi"
assert signed_in.post("/api/account/tokens/999/label",
json={"label": "x"}).status_code == 404
def test_an_open_app_ignores_the_header(open_app: TestClient):
"""Unlocked, there is no door for a token to open; a stale one is not an error."""
assert open_app.get("/api/thing", headers=bearer("whatever")).status_code == 200
# ------------------------------------------------------------ another site
EVIL = "http://evil.example"
def test_another_sites_page_cannot_post_to_an_unlocked_app(open_app: TestClient):
"""No session cookie to withhold on loopback, so `SameSite` protected
nothing: a `text/plain` POST needs no preflight and reached every route
that takes no body."""
assert open_app.post("/api/account/sessions/close").status_code == 200
assert open_app.post("/api/account/sessions/close",
headers={"origin": "http://127.0.0.1"}).status_code == 200
assert open_app.post("/api/account/sessions/close",
headers={"sec-fetch-site": "same-origin"}).status_code == 200
for headers in ({"origin": EVIL}, {"origin": "null"},
{"sec-fetch-site": "cross-site"}, {"sec-fetch-site": "same-site"},
{"origin": "http://127.0.0.1", "sec-fetch-site": "cross-site"}):
refused = open_app.post("/api/account/sessions/close", headers=headers)
assert refused.status_code == 403, headers
assert "another site" in refused.json()["detail"]
plain = open_app.post("/api/account/sessions/close", content=b"x",
headers={"content-type": "text/plain"})
assert plain.status_code == 415 and "application/json" in plain.json()["detail"]
form = open_app.post("/api/account/sessions/close", content=b"a=1",
headers={"content-type": "application/x-www-form-urlencoded"})
assert form.status_code == 415
# A read is never refused, wherever it came from.
assert open_app.get("/api/thing", headers={"origin": EVIL}).status_code == 200
def test_a_transfer_encoding_header_is_a_body_whatever_its_value():
"""Its presence says a body follows; an empty value is malformed and is
not given the benefit of the doubt."""
for value in (b"chunked", b""):
scope = {"type": "http", "method": "POST",
"headers": [(b"content-type", b"text/plain"),
(b"transfer-encoding", value)]}
refused = cross_site(scope)
assert refused is not None and refused[0] == 415, value
scope["headers"] = [(b"content-type", b"text/plain")]
assert cross_site(scope) is None
def test_another_sites_page_cannot_open_the_socket(open_app: TestClient):
"""A WebSocket handshake is not subject to CORS, so any page could open
`/ws/jobs` on a loopback app and read every job and notice."""
with pytest.raises(WebSocketDisconnect), \
open_app.websocket_connect("/ws/jobs", headers={"origin": EVIL}):
pass
# The test client's handshake names `testserver` whatever the base URL,
# so the app's own page is spelt out: a loopback host, and its origin.
with open_app.websocket_connect("/ws/jobs", headers={
"host": "127.0.0.1", "origin": "http://127.0.0.1"}) as ws:
assert ws.receive_json()["type"] == "jobs"
def test_the_configured_origin_is_accepted_behind_a_proxy_that_rewrites_host(
make_client: Callable[..., TestClient]):
client = make_client(enabled="auto", host="127.0.0.1", password=None,
origin="https://app.example.com", base_url="http://127.0.0.1")
assert client.post("/api/account/sessions/close",
headers={"origin": "https://app.example.com"}).status_code == 200
assert client.post("/api/account/sessions/close",
headers={"origin": EVIL}).status_code == 403
def test_the_rule_holds_on_a_locked_app_too(signed_in: TestClient):
"""A locked app with `secure_cookie: never` on a LAN is a real deployment,
and the two header reads cost nothing."""
assert signed_in.post("/api/account/sessions/close",
headers={"origin": EVIL}).status_code == 403
assert signed_in.post("/api/account/sessions/close").status_code == 200
# ------------------------------------------------- what a token must not reach
def test_an_app_names_what_a_token_may_not_reach(tmp_path):
"""A route that hands out or replaces the database as a file holds the
password hash and the token rows, so `connect(session_only=...)` shuts it
to a token the way the account is shut."""
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
from auth import AuthConfig, AuthStore, connect
app = FastAPI()
db = tmp_path / "s.db"
store = AuthStore(db)
store.set_password(PASSWORD)
connect(app, store, AuthConfig(enabled="always"), host="0.0.0.0",
session_only=("/api/backups", "/api/backups/", "/api/restore"))
@app.get("/api/backups/{name}", response_class=PlainTextResponse)
def download(name: str) -> str:
return "the whole database"
@app.post("/api/restore", response_class=PlainTextResponse)
def restore() -> str:
return "swapped"
@app.get("/api/thing")
def thing() -> dict[str, bool]:
return {"ok": True}
_, token = store.create_token("cron", None)
with TestClient(app, follow_redirects=False) as client:
assert client.get("/api/thing", headers=bearer(token)).status_code == 200
assert client.get("/api/backups/x.db.gz", headers=bearer(token)).status_code == 403
assert client.post("/api/restore", headers=bearer(token)).status_code == 403
sign_in(client)
assert client.get("/api/backups/x.db.gz").status_code == 200
# ---------------------------------------------------------- a rebound name
def test_a_rebinding_page_is_refused_on_an_unlocked_app(open_app: TestClient):
"""A page on `rebind.example`, pointed at 127.0.0.1, sends a `Host` and
an `Origin` that agree, and `Sec-Fetch-Site: same-origin`, so the
same-site rule cannot tell it from the app's own page. The name can:
a loopback app is reached as localhost, and a script naming anything
else for it is refused with the proxy's 421."""
page = {"host": "rebind.example:8787", "origin": "http://rebind.example:8787",
"sec-fetch-site": "same-origin"}
refused = open_app.post("/api/account/tokens", json={"current": ""}, headers=page)
assert refused.status_code == 421
assert "localhost" in refused.json()["detail"]
assert open_app.get("/api/thing", headers=page).status_code == 421
with pytest.raises(WebSocketDisconnect), \
open_app.websocket_connect("/ws/jobs", headers=page):
pass
# The app's own page, at any loopback name, is untouched, and so is a
# client that is not a page when it names one.
for host in ("localhost:8787", "127.0.0.1", "[::1]:8787", "app.localhost"):
own = {"host": host, "origin": f"http://{host}", "sec-fetch-site": "same-origin"}
assert open_app.get("/api/thing", headers=own).status_code == 200, host
assert open_app.get("/api/thing", headers={"host": host}).status_code == 200, host
assert open_app.post("/api/account/sessions/close",
headers={"host": "localhost"}).status_code == 200
def test_a_rebound_request_without_page_headers_is_refused_too(open_app: TestClient):
"""A browser that sends no `Sec-Fetch-Site`, and no `Origin` on a read, is
still a rebound page reading the API. The `Host` is judged whatever else
the request carries, so a name that is not loopback is refused, and so is
a `Host` that names nothing."""
for host in ("rebind.example", "rebind.example:8787", "testserver", "["):
refused = open_app.get("/api/thing", headers={"host": host})
assert refused.status_code == 421, host
assert open_app.post("/api/account/sessions/close",
headers={"host": "rebind.example"}).status_code == 421
with pytest.raises(WebSocketDisconnect), \
open_app.websocket_connect("/ws/jobs", headers={"host": "rebind.example"}):
pass
assert _rebound({"type": "http", "headers": []}, "") is True
def test_the_configured_origin_is_a_name_the_unlocked_app_answers_to(
make_client: Callable[..., TestClient]):
client = make_client(enabled="auto", host="127.0.0.1", password=None,
origin="https://app.example.com")
page = {"host": "app.example.com", "origin": "https://app.example.com",
"sec-fetch-site": "same-origin"}
assert client.get("/api/thing", headers=page).status_code == 200
page["host"] = page["origin"] = "other.example.com"
assert client.get("/api/thing", headers=page).status_code == 421
# -------------------------------------------------------- a cookie that is not one
def test_a_cookie_header_that_is_not_one_is_read_as_no_cookie(locked: TestClient):
"""The middleware is in front of every request, so a header it cannot
read must be no cookie and not a 500 on every call that carried it."""
for header in ("a@b=1", ";;;", "=", '"', "app_session=", "app_session"):
refused = locked.get("/api/thing", headers={"cookie": header})
assert refused.status_code == 401, header
def test_a_malformed_neighbour_cookie_does_not_sign_the_owner_out(signed_in: TestClient):
"""`SimpleCookie.load` returned an empty jar for the whole header when any
cookie in it had a space or JSON in its value, so a sibling app on the
parent domain setting `theme=dark mode` locked the owner into a login
loop. Read per pair, the session beside it still opens the door."""
from http.cookies import SimpleCookie
session = signed_in.cookies["app_session"]
jar = SimpleCookie()
jar.load(f"theme=dark mode; app_session={session}")
assert "app_session" not in jar, "the stdlib parser was the bug"
browser = TestClient(signed_in.app, follow_redirects=False)
for neighbour in ("theme=dark mode", 'x={"a":1}'):
for header in (f"{neighbour}; app_session={session}",
f"app_session={session}; {neighbour}"):
answer = browser.get("/api/thing", headers={"cookie": header})
assert answer.status_code == 200, header
+1 -1
View File
@@ -55,7 +55,7 @@ def test_the_passkey_routes_answer_501_rather_than_crashing(
"""501 is what the element watches for -- "this route exists and this build """501 is what the element watches for -- "this route exists and this build
cannot perform it" -- and it takes the passkey section off the screen.""" cannot perform it" -- and it takes the passkey section off the screen."""
for path in ("/api/account/passkeys/options", "/login/passkey/options"): for path in ("/api/account/passkeys/options", "/login/passkey/options"):
answer = signed_in.post(path) answer = signed_in.post(path, json={"current": PASSWORD})
assert answer.status_code == 501, path assert answer.status_code == 501, path
assert "passkeys" in answer.json()["detail"] assert "passkeys" in answer.json()["detail"]
assert "uv sync" in answer.json()["detail"] assert "uv sync" in answer.json()["detail"]