Bring in pipeline, auth, deploy and docs from the boilerplate

roledesk is built on the boilerplate from here on: pipeline 2.0 (queue and
scheduler), auth (one password, sessions, passkeys), the deploy kit and its
docs, plus the coupling and packaging tests. Downstream copies, unedited.

Refreshed from boilerplate/d56949f7d0f6c0bfe5745478e09007bfad67ae87

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Opus 5.5 committed 2026-09-23 12:29:16 +02:00
1 parent 1f436104f3
commit 9d666d0937
76 files changed
+15235

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
# 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.
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.
The source of truth is `boilerplate/auth/`. Copies elsewhere are copies: take the whole folder, and run its tests where it lands.
```bash
cp -r boilerplate/auth yourproject/auth
python -m pytest yourproject/auth/tests
```
Then add `auth*` to that project's `pyproject.toml` packages, `"auth" = ["templates/*.html", "static/*"]` to its package data, and `auth/tests` to its testpaths. `docs/password-protection.md` in this repository is the reasoning behind every decision below, at length.
## Five lines
```python
from fastapi import FastAPI
import auth
app = FastAPI()
auth.connect(app, auth.AuthStore(config.database), config.auth,
host=config.server.host, open=("/static/",),
stylesheet="/static/app.css")
```
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.
| `connect(app, store, config, ...)` | |
|---|---|
| `store` | an `AuthStore` on whatever database the app keeps. Handing it in rather than building it here is what lets the app decide there is one file. |
| `config` | an `AuthConfig`. The app's own config model carries it as a field; see below. |
| `host=` | the address the server binds — `config.server.host`. What `enabled: auto` decides from, and deliberately not taken from a request, since a `Host` header is written by whoever is talking. |
| `open=` | extra paths reachable without a session, added to `middleware.OPEN`. A name ending in `/` is a prefix; any other is matched whole. `("/static/",)` is what an app with a stylesheet passes. |
| `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:
```html
<script type="module" src="/_auth/account.js"></script>
<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.
## The config block
`AuthConfig` is pydantic and imports nothing from the app, so an app's own config model carries it as a field:
```python
from auth import AuthConfig
class Config(Section):
auth: AuthConfig = Field(default_factory=AuthConfig)
```
```yaml
auth:
enabled: auto # auto | always | never
session_days: 30
secure_cookie: auto # `always` behind a proxy that terminates TLS
rp_id: "" # app.example.com -- passkeys are bound to a domain
rp_name: app # what the authenticator shows you
origin: "" # https://app.example.com
password_env: APP_PASSWORD
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.
`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.
## Getting in the first time
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.
## What the app has to provide
Almost nothing, and that is the point.
- A SQLite path. `AuthStore` creates four `auth_*` tables in whatever file it is given, so it can share the app's own.
- The bind host, for `enabled: auto`.
- Nothing for the open list, as a rule. `/login`, `/login/`, `/_auth/` and `/health` are opened by this package; the app adds `/static/` if it serves one, or the login page arrives unstyled. Everything else stays shut — a module's own scripts and sockets included, so in this repository `/_jobs/jobs.js` and `/ws/jobs` need a session like the pages that load them.
- An error handler that keeps `{"detail": "..."}` for `/api`, `/ws` and `/_auth`, if it has one. Every refusal here is already that shape.
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
**scrypt, not SHA-256.** Memory-hard rather than merely slow: one guess costs 16 MB, which is what takes a stolen database file out of range of a GPU. A wrong answer costs a full derivation too, so the delay an attacker meets is the one the honest user meets.
**A session is 32 random bytes, and the table holds only its SHA-256.** No signing key to generate, store, keep out of backups and rotate; signing out everywhere is one `DELETE`, which no self-contained token can offer without keeping exactly this state.
**The lockout is counted in the file and read before the check.** A counter on the process is a free reset for whoever is guessing, on a server that reloads. Read after instead of before, and hammering the button extends your own lockout — which punishes the owner far harder than the attacker who is not watching. Five wrong answers are free, then 30 s doubling to a quarter of an hour, with the exponent capped so a bot cannot turn arithmetic into a 500.
**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.
**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.
## Tests
```bash
uv run pytest auth/tests
```
The passkey ceremonies are tested against `auth/tests/softkey.py`, a real WebAuthn authenticator that happens to be in software: it produces the same CBOR, the same authenticator data and the same ECDSA signatures a hardware key does, so a wrong origin fails because the origin is signed over and a clone is caught because the counter went backwards. Those tests skip without the extra; what the app does *without* it is `test_without_passkeys.py`, which always runs.
+160
View File
@@ -0,0 +1,160 @@
"""One password on a public hostname, in one call.
app = FastAPI()
store = connect(app, AuthStore("data/app.db"), config.auth,
host=config.server.host, open=("/static/",),
stylesheet="/static/app.css")
That is the middleware in front of everything (the WebSocket included), the
login page, the account API, the `<auth-account>` element, and the startup
bootstrap that makes sure there is a password at all. No user management: there
is one user, they are the person who deployed it, and the only questions are
whether the door is locked and what opens it.
| module | |
|---|---|
| `config.py` | `AuthConfig`: the `auth:` block of the app's `config.yaml` |
| `store.py` | `AuthStore`: scrypt, the lockout, sessions, passkeys, four `auth_*` tables in whatever SQLite file it is given |
| `models.py` | `Account`, `SessionInfo`, `Passkey` — what the account screen is told, which carries no credential |
| `middleware.py` | `RequireLogin`, `locked()`, the open list, the cookie |
| `passkeys.py` | the two WebAuthn ceremonies; `webauthn` is an optional extra, imported lazily |
| `schemas.py` | the five request bodies |
| `router.py` | `/login`, `/logout`, `/api/account/*`, the passkey routes, `/_auth/*.js` |
| `templates/login.html` | the one page served without a session |
| `static/` | `passkey.js` (the browser half of WebAuthn) and `account.js` (`<auth-account>`) |
The reasoning is `docs/password-protection.md`, and this package is that
document in code. `auth/README.md` is how to copy the folder into a project
that has never heard of this one.
"""
from __future__ import annotations
import logging
import os
import secrets
from collections.abc import AsyncIterator, Iterable
from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI
from auth import passkeys
from auth.config import AuthConfig
from auth.middleware import OPEN, RequireLogin, client_address, locked, token_from
from auth.models import Account, Passkey, SessionInfo
from auth.router import router
from auth.store import AuthStore
log = logging.getLogger(__name__)
__all__ = [
"OPEN", "Account", "AuthConfig", "AuthStore", "Passkey", "RequireLogin",
"SessionInfo", "bootstrap", "client_address", "connect", "locked",
"passkeys", "router", "token_from",
]
def connect(app: FastAPI, store: AuthStore, config: AuthConfig, *,
open: Iterable[str] = (), stylesheet: str | None = None,
host: str = "") -> AuthStore:
"""Put `app` behind a password: middleware, routes, element, bootstrap.
Call it first, before the app's own routers. Starlette wraps the whole
router in its middleware whenever the routes were added, so the socket and
every page are covered either way — but written first it is also *read*
first, and nobody reviewing the file has to work out whether the socket is
behind the password.
`store` is an `AuthStore` on whatever database the app keeps; handing it in
rather than building it here is what lets the app decide there is one file.
| keyword | |
|---|---|
| `open` | extra paths reachable without a session, added to `middleware.OPEN`. A name ending in `/` is a prefix; any other is matched whole. `("/static/",)` is what an app with a stylesheet passes. |
| `stylesheet` | a URL the login page links, so it looks like the rest of the app. Optional: the page carries enough inline CSS to be presentable on its own. |
| `host` | the address the server binds — `config.server.host`. What `enabled: auto` decides from, and deliberately not taken from a request, since a `Host` header is written by whoever is talking. |
The lifespan is wrapped rather than replaced, the same way
`pipeline.web.connect` does it, so an app's own lifespan still runs inside
this one: the password exists before the app's startup code, which may want
to say something about it.
Returns the store, for the app to keep if it wants one.
"""
app.state.auth = store
app.state.auth_config = config
#: Whether a session is required. Decided once, here, because it depends on
#: the bind address, which only the caller knows.
app.state.auth_locked = locked(config, host)
app.state.auth_stylesheet = stylesheet or ""
app.include_router(router)
app.add_middleware(RequireLogin, store=store, config=config,
open=tuple(open), host=host)
inner = app.router.lifespan_context
@asynccontextmanager
async def lifespan(this: FastAPI) -> AsyncIterator[Any]:
if app.state.auth_locked:
bootstrap(store, config)
store.purge()
# Outside the `locked` check on purpose: a passkey can be registered on
# a loopback app before it is ever deployed, which is the order this
# encourages, so an unlocked one can still have keys it cannot use.
passkeys.warn_if_missing(store)
async with inner(this) as state:
yield state
app.router.lifespan_context = lifespan
return store
def bootstrap(store: AuthStore, config: AuthConfig) -> None:
"""Make sure there is a password, and say so once if we invented one.
The variable named by `config.password_env` — `APP_PASSWORD` by default —
is authoritative while it is set: if it is in the environment, it *is* the
password, and the account screen says so and declines to change it. That is
a deliberate choice over seeding from it once — a variable that silently
stopped applying the moment you changed the password in the browser would
be worse than either rule, and this way round the environment doubles as
the way back in when you are locked out of your own server.
Re-derived only when the stored hash does not already match, so a restart is
not a write and "password last changed" keeps meaning something.
"""
pinned = os.environ.get(config.password_env, "")
if pinned:
if not store.check_password(pinned):
store.set_password(pinned)
log.info("password set from %s", config.password_env)
return
if store.has_password():
return
password = secrets.token_urlsafe(12)
store.set_password(password)
# At WARNING so it survives the default log level, and banner-shaped because
# it is printed exactly once in the life of a database and being scrolled
# past is the same as not being printed at all.
#
# ASCII, deliberately. This is the one log line whose *contents* someone has
# to read back character by character, and it is read wherever the server
# happens to be running -- a Windows console under cp1252, a `docker logs`
# pipe with no locale set. Box-drawing characters come out as `?` in both,
# which turns the frame around the password into noise around the password.
log.warning(
"\n"
" ------------------------------------------------------------\n"
" This app is locked and had no password, so here is one:\n"
"\n"
" %s\n"
"\n"
" This is the only time it is shown. Change it under Account,\n"
" or set %s to pin one.\n"
" ------------------------------------------------------------",
password, config.password_env,
)
+104
View File
@@ -0,0 +1,104 @@
"""What the app is allowed to say about the door.
Pydantic, and nothing imported from the app around it: a config section is the
one piece of a module folder that a project has to merge into its own settings,
and one that dragged the app's `Config` in with it could not be merged at all.
The app writes `auth: AuthConfig = Field(default_factory=AuthConfig)` and is
done.
There is one user, so there is no user management here — only whether the door
is locked, how long a session lasts, and the three strings a passkey is bound
to. The password is not in this file and never will be: it lives in the
database as an scrypt hash, is changed from the Account tab, and is seeded on
first run either from the environment variable named by `password_env` or by a
generated one printed to the log once.
"""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class AuthConfig(BaseModel):
"""The `auth:` block of `config.yaml`. See docs/password-protection.md."""
#: Unknown keys are refused rather than ignored, the same rule the app's
#: own sections keep: a setting you believe you have changed and have not
#: is the expensive kind of typo.
model_config = ConfigDict(extra="forbid")
#: `auto` is the setting that matters, and it means: locked unless the
#: server is bound to loopback. An app on 127.0.0.1 is reachable by whoever
#: is already sitting at the machine, so a password would be a second lock
#: on an open door; the same app on 0.0.0.0 is reachable by the network,
#: and that is a different application with the same code.
#:
#: Deciding from the bind address rather than defaulting to off is the
#: whole point. The failure this prevents is the one that actually happens:
#: you deploy, it works, and nothing anywhere tells you the door is open.
#: `always` locks it on localhost too and is what a deployment behind a
#: TLS-terminating proxy needs, since there every request looks local to
#: the app and is not. `never` is for putting some other authentication in
#: front of this one, and means exactly what it says.
enabled: Literal["auto", "always", "never"] = "auto"
#: How long a login lasts before it has to be done again. Long, because
#: this is one person on their own devices, and the security value of a
#: short session here is close to zero while the cost -- typing a password
#: into a phone on the bus -- is not.
session_days: int = Field(30, ge=1)
#: Whether the session cookie is marked `Secure`, so a browser will only
#: ever send it back over HTTPS. `auto` sets it when the request itself
#: arrived over HTTPS, which is right when the app terminates TLS and wrong
#: behind a reverse proxy that terminates it for you -- there the app sees
#: plain HTTP and `auto` reads as "no". Set `always` when something else is
#: doing TLS. `never` exists for testing over http on a LAN and is the
#: setting to be uncomfortable with.
secure_cookie: Literal["auto", "always", "never"] = "auto"
# --------------------------------------------------------------- passkeys
#
# A passkey is bound to a *domain*, not to a server, and that binding is the
# entire security property: the browser will only offer a credential back to
# the origin it was created for, which is why a passkey cannot be phished
# the way a password can. Two settings below name that domain, and both are
# blank by default because on a laptop the request itself is the honest
# answer and on a server it is not.
#: The domain passkeys are registered against -- `app.example.com`. Blank
#: derives it from the request's `Host`, which is right in development and
#: is the setting to pin in production: `Host` is client-supplied, and a
#: proxy that passed a forged one through would otherwise move the RP ID.
#:
#: **Changing this invalidates every registered passkey**, because a
#: credential for one domain is not a credential for another. It is not a
#: setting to tune; it is the name of the thing, set once.
rp_id: str = ""
#: What the authenticator shows when it asks you to confirm. Cosmetic, and
#: the one string here a person actually reads.
rp_name: str = "app"
#: The full origin the browser must be at -- `https://app.example.com`.
#: Blank derives it from the request, which behind a TLS-terminating proxy
#: derives `http://` and then rejects every real ceremony as a mismatch.
#: If `secure_cookie: always` applies to you, so does this.
origin: str = ""
# ---------------------------------------------------------- the two names
#
# Named rather than hard-coded because this folder is copied into projects
# that are not called `app`, and two of them on one hostname would otherwise
# share a cookie and overwrite each other's sessions.
#: The environment variable that pins the password. Authoritative while it
#: is set: the Account tab says so and declines to change it. See
#: `auth.bootstrap`.
password_env: str = "APP_PASSWORD"
#: The session cookie's name. `__Host-` is prefixed to it when the cookie
#: will be Secure -- see `auth.middleware.cookie_name`.
cookie: str = "app_session"
+246
View File
@@ -0,0 +1,246 @@
"""The lock on the door: is there a session, and what happens when there isn't.
Three things live here — when the door is locked at all, who gets past it, and
the cookie that says so. The password itself is `auth/store.py`; this module
never sees a hash.
## Why a middleware and not a dependency
The FastAPI-shaped answer is `Depends(current_session)` on every route, and it
is the wrong one here for two reasons.
The first is the WebSocket. `/ws/jobs` is a real socket, and route dependencies
on a WebSocket endpoint are awkward at best — but a cookie rides the handshake
like any other request, so one ASGI middleware in front of everything covers
the socket and the JSON with the same six lines.
The second is the failure mode. A dependency is opt-in: protection is applied
by remembering to apply it, and the cost of forgetting is not a broken page but
a quiet hole — an API served to the internet, and nothing on screen different.
An app adds routers regularly, and the next one should be safe because it
exists, not because someone remembered. So the rule is inverted: everything is
shut, and the few things that must be open are named in one list you can read
at a glance.
## What being locked means
`auto` decides from the bind address, which is the only setting that ever
mattered: bound to loopback, the door is already the machine's own login, and a
password is a second lock on it; bound to anything else, the app is on a
network and needs its own. The alternative — default off, switch it on when you
deploy — fails silently in the exact case it exists for, because an app serving
the internet with no password looks and behaves precisely like one that is fine.
"""
from __future__ import annotations
import asyncio
import ipaddress
import logging
from http.cookies import SimpleCookie
from typing import Any
from urllib.parse import quote
from starlette.requests import HTTPConnection
from starlette.responses import JSONResponse, RedirectResponse, Response
from starlette.types import ASGIApp, Receive, Scope, Send
from auth.config import AuthConfig
from auth.store import AuthStore
log = logging.getLogger(__name__)
#: Reachable without a session, and nothing else is. `/login` has to be, or
#: there is no way in, and the passkey ceremony under `/login/` with it;
#: `/_auth/` carries the two scripts the login page and the account element
#: are; `/health` is for a proxy probe that has no session to offer. The app
#: adds its own — `/static/`, normally, or the login page arrives unstyled.
#:
#: A name ending in `/` is a prefix, any other is matched whole, so `/health`
#: does not open `/healthz` and `/login` does not open `/loginx`. Matched
#: against the path only — a query string cannot widen this.
OPEN: tuple[str, ...] = ("/login", "/login/", "/_auth/", "/health")
def locked(config: AuthConfig, host: str) -> bool:
"""Whether this app should ask for a password. See `AuthConfig.enabled`.
`host` is the address the server binds, which is the app's own
`server.host` setting and not anything a request carries: a `Host` header
is written by whoever is talking, and a door that could be talked out of
being a door is not one.
"""
if config.enabled == "always":
return True
if config.enabled == "never":
return False
return not _loopback(host)
def _loopback(host: str) -> bool:
"""Whether binding here means "this machine only".
`localhost` by name, and anything in 127.0.0.0/8 or ::1 by number. An empty
host, or `0.0.0.0`, or a LAN address is not loopback — and an unparseable
one is treated as not loopback too, because the failure to be careful about
is guessing "private" and being wrong.
"""
if host in ("localhost", "::1"):
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
def cookie_name(config: AuthConfig, scope_secure: bool) -> str:
"""`__Host-` when the cookie will be Secure, plain otherwise.
That prefix is a promise to the browser that the cookie is Secure,
path-scoped to `/` and carries no Domain, and a browser will refuse to
store one that is not — which presents as a login that appears to succeed
and lands you back on the login page, with nothing in any log. So the name
is chosen per deployment rather than fixed.
"""
return f"__Host-{config.cookie}" if is_secure(config, scope_secure) else config.cookie
def cookie_names(config: AuthConfig) -> tuple[str, str]:
"""Both names, secure first. Read and cleared together, because which one
was set depends on `secure_cookie` and on the scheme the login happened
over — and clearing only one leaves a cookie the browser goes on offering."""
return f"__Host-{config.cookie}", config.cookie
def is_secure(config: AuthConfig, scope_secure: bool) -> bool:
setting = config.secure_cookie
if setting == "always":
return True
if setting == "never":
return False
return scope_secure
def token_from(conn: HTTPConnection | Scope, config: AuthConfig) -> str:
"""The session token this request carries, or "".
Both cookie names are looked for, so flipping `secure_cookie` or moving
behind TLS does not strand a live session under the other name.
"""
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
for key, value in scope.get("headers", ()):
if key == b"cookie":
jar = SimpleCookie()
try:
jar.load(value.decode("latin-1"))
except Exception: # a cookie header that is not one
return ""
for name in cookie_names(config):
if name in jar:
return jar[name].value
return ""
def client_address(conn: HTTPConnection | Scope) -> str:
"""Who is asking, as well as it can be known, for the log to say so.
Behind a reverse proxy the peer is a container on the same Docker network
and says nothing about who is at the other end; the address worth writing
down is the first hop of `X-Forwarded-For`, which the proxy sets. Both are
reported when they differ, because the header is only as trustworthy as
whoever sent it — which is why nothing is *decided* from this, only logged.
See `AuthStore.check_password` for that argument in full.
That header is also the one piece of a stranger's own writing that ends up
in the log, so only the characters an address is made of survive the trip:
a line in this log is something fail2ban reads and a person believes, and
neither should be forgeable by whoever is knocking.
"""
scope: Any = conn.scope if isinstance(conn, HTTPConnection) else conn
peer = (scope.get("client") or ("", 0))[0] or "unknown"
for key, value in scope.get("headers", ()):
if key == b"x-forwarded-for":
first = value.decode("latin-1").split(",")[0]
claimed = "".join(c for c in first if c.isalnum() or c in ".:%-")[:45]
if claimed and claimed != peer:
return f"{claimed} via {peer}"
return peer
#: Prefixes whose refusal is JSON rather than a redirect. A caller that asked
#: for data and is sent a login page reads it as a 200 full of HTML where its
#: JSON should be; `{"detail": ...}` with a 401 is something it can act on.
JSON_PREFIXES = ("/api", "/ws", "/_jobs", "/_auth")
class RequireLogin:
"""Everything is shut except the open list. Raw ASGI, so it covers sockets.
Deliberately not `BaseHTTPMiddleware`, which only sees `http` scopes — a
WebSocket would pass straight under it, and `/ws/jobs` streams the state of
every job in the app.
Whether the door is locked at all is decided once, at construction, from
the config and the bind address: neither changes while the process runs,
and deciding per request would mean re-deriving the same answer a thousand
times a minute and having no single place to read it off.
"""
def __init__(self, app: ASGIApp, store: AuthStore, config: AuthConfig,
open: tuple[str, ...] = (), host: str = "") -> None:
self.app = app
self.store = store
self.config = config
self.open = OPEN + tuple(open)
self.locked = locked(config, host)
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket") or not self.locked:
return await self.app(scope, receive, send)
path = scope.get("path", "")
if any(path == p.rstrip("/") or (p.endswith("/") and path.startswith(p))
for p in self.open):
return await self.app(scope, receive, send)
token = token_from(scope, self.config)
# `to_thread`, because the store is SQLite and this is the event loop.
session = await asyncio.to_thread(self.store.touch, token) if token else None
if session is not None:
# Parked on the scope so `/api/account` can flag which row in the
# sessions list is the browser asking, and `/logout` can end the
# right one. Not a header and not a dependency: the middleware is
# the only thing that has verified it.
scope["auth_token"] = token
return await self.app(scope, receive, send)
await self._refuse(scope, receive, send, path)
async def _refuse(self, scope: Scope, receive: Receive, send: Send,
path: str) -> None:
"""No session. Say so in whatever the caller can understand."""
if scope["type"] == "websocket":
# Sent before accepting, which the ASGI server turns into an HTTP
# 403 on the handshake. The reconnect backoff in `<desk-jobs>` then
# does the right thing by itself.
await send({"type": "websocket.close", "code": 1008})
return
response: Response
# A GET of anything that is not an API path is a page being asked for,
# whatever the caller put in `Accept` — curl and a browser want the
# same thing there, and a 401 in place of the login page is a worse
# answer to both. Everything else is JSON, including a POST to a page
# path: a form submitted without a session has nowhere useful to land.
if scope.get("method") == "GET" and not path.startswith(JSON_PREFIXES):
# Carry where they were going, so a bookmarked deep link survives
# the login. Only ever a path from this app's own scope — but it is
# being written into a query string, and the scope has already
# decoded it, so a path holding a `&` or a `%` would arrive at the
# login page as a different path or as nothing. `quote` puts it back
# the way `URLSearchParams` will read it.
target = "/login" + (f"?next={quote(path)}" if path not in ("/", "") else "")
response = RedirectResponse(target, status_code=303)
else:
response = JSONResponse({"detail": "Not signed in"}, status_code=401)
await response(scope, receive, send)
+81
View File
@@ -0,0 +1,81 @@
"""What the Account tab is told, and nothing more.
Three models, and the thing worth noticing about all three is what they cannot
carry. No token, no hash, no key material — not even the public half of a
passkey. The list of ways into an app is the one page most worth reading and
least worth leaking, so the shape it is rendered from is one that could not
leak a credential if it were logged whole.
"""
from __future__ import annotations
from pydantic import BaseModel, Field
class SessionInfo(BaseModel):
"""One live login, for the account screen to list and revoke.
`id` is the row's own integer, which is what the revoke button sends back.
The screen therefore holds nothing that could be replayed as a credential.
"""
id: int
#: The browser that opened it, as it described itself. Advisory — a client
#: writes its own user agent — but it is what tells the laptop from the
#: phone, and an unexpected row here is the signal worth having.
label: str = ""
created_at: str = ""
last_seen_at: str = ""
expires_at: str = ""
#: The session making this request, which the UI must not offer to revoke
#: as though it were one of the others.
current: bool = False
class Passkey(BaseModel):
"""One registered authenticator, as the account screen sees it."""
id: int
#: What you called it. A passkey you cannot name is one you will never dare
#: revoke, because you will not know which key it is.
label: str = ""
created_at: str = ""
last_used_at: str = ""
#: How the authenticator says it can be reached — `usb`, `nfc`, `internal`,
#: `hybrid`. Advisory and self-reported, but it is what tells "the YubiKey"
#: from "this laptop" in a list where both are just names.
transports: list[str] = Field(default_factory=list)
class Account(BaseModel):
"""What the account screen knows. Deliberately almost nothing.
There is one user and they are already signed in, so there is no name, no
email and no id to show — only whether the door is locked, when the password
last changed, and what is currently signed in.
"""
#: Whether the door is locked at all. False on a loopback-bound app under
#: the default `auto`, and the screen says so rather than offering a
#: password change that would not be asked for.
locked: bool = False
#: The environment pins the password, so the browser cannot change it. The
#: variable is named by `AuthConfig.password_env`; see `auth.bootstrap`.
pinned: bool = False
#: Which variable that is, so the screen can name it rather than saying
#: "an environment variable" to somebody who has to go and find it.
pinned_by: str = ""
password_set_at: str = ""
sessions: list[SessionInfo] = Field(default_factory=list)
#: Registered authenticators. Always listed, even when the door is open,
#: because registering one on your laptop before you deploy is the sensible
#: order to do this in.
passkeys: list[Passkey] = Field(default_factory=list)
#: Whether this install can do WebAuthn at all — the `passkeys` extra is
#: optional, and a screen offering a button that 501s is worse than one
#: that says what to install.
passkeys_available: bool = False
#: Why passkeys cannot be *registered* right now, or "" if they can. The
#: honest common case is an insecure origin: WebAuthn refuses anything but
#: HTTPS, localhost excepted, so this reads "you need TLS first".
passkeys_blocked: str = ""
+398
View File
@@ -0,0 +1,398 @@
"""WebAuthn: the two ceremonies, and the three things that decide whether they
can run at all.
A passkey and a YubiKey are the same feature. Both are WebAuthn authenticators;
the difference is only where the private key lives — in the phone's secure
enclave, in the browser profile, or on a stick in a USB port — and none of that
reaches this module. One registration flow covers all of them, which is why
there is no "YubiKey" anywhere in this package.
## What this is worth having
A password can be typed into the wrong site. A passkey cannot: the browser will
only hand a credential back to the origin it was created for, and it checks
that itself, before anything of ours runs. That property is the whole reason
this exists, and it is also the reason for every constraint below — the binding
to an origin is not a detail to be relaxed when it is inconvenient.
## The three things that can stop it
**The package.** `webauthn` is an optional extra, so every import of it is
inside a function and `available()` is what the account screen asks before
offering a button. A missing extra is a sentence about `uv sync`, not a 500.
**The origin.** WebAuthn refuses to run on an insecure origin — `localhost` is
specifically exempted, everything else needs HTTPS. So an app served over plain
HTTP on a LAN address can hold passkeys and verify them, and cannot register
one, and the account screen says so rather than showing a button that fails
inside the browser with an error nobody surfaces.
**The RP ID.** Derived from the request's `Host` when `rp_id` is blank, which
is right on a laptop and wrong the moment anything can forge that header. See
`AuthConfig.rp_id` for why production pins it.
## The password does not go away
Registering a passkey does not remove the password, and this module offers no
way to. A lost key with no fallback is an app nobody can reach — and the
recovery path for that would have to be at least as strong as the password it
replaced, which is to say: the password.
"""
from __future__ import annotations
import json
import logging
from typing import Any
from urllib.parse import urlsplit
from starlette.requests import Request
from auth.config import AuthConfig
from auth.store import AuthStore
log = logging.getLogger(__name__)
#: The one user's handle. A constant, and deliberately so: WebAuthn wants a
#: user id to tell accounts apart, and there is one account. Making it random
#: per install would buy nothing — two apps cannot share an RP ID, since the RP
#: ID *is* the domain — and would cost a stable value to store and migrate. It
#: is also not PII, which the spec asks of this field.
#:
#: One real consequence, and it is the one you want: re-registering on the same
#: authenticator replaces the resident credential rather than adding a second,
#: because (rp_id, user_handle) is what a discoverable credential is keyed on.
USER_HANDLE = b"app"
#: What the authenticator shows in its own list, beside `rp_name`. Not a login
#: — there is no username here — but the field is required and something has to
#: be in it.
USER_NAME = "app"
#: How to get the extra, said once and reused by every message that says it.
#:
#: The parenthetical is not padding. `uv sync --extra passkeys` *replaces* the
#: installed extras rather than adding to them, so running exactly what the
#: obvious instruction says will silently uninstall whatever else the project
#: uses — and the symptom of that is not an error at install time, it is
#: something unrelated failing later on. Anyone following this instruction is by
#: definition not thinking about their other extras, which is exactly when they
#: need to be told.
INSTALL_HINT = ("Run `uv sync --extra passkeys`, listing any other extras you "
"use in the same command — uv replaces the set rather than "
"adding to it — then restart.")
def available() -> bool:
"""Whether the `passkeys` extra is installed."""
try:
import webauthn # noqa: F401
except ImportError:
return False
return True
def warn_if_missing(store: AuthStore) -> None:
"""Say so at startup if there are passkeys here that cannot be used.
The case this exists for: `uv sync` without `--extra passkeys` quietly
removes the package, and the next start has registered keys it cannot
verify. Without this the first sign anything is wrong is a login page with
no passkey button on it — which looks like the passkeys were lost, when they
are sitting in the database intact.
Silent when nothing is registered, because then there is nothing to lose and
nothing to warn about: an install with no passkeys and no `webauthn` is just
an install that does not use passkeys.
"""
if available():
return
registered = store.passkey_ids()
if not registered:
return
log.warning(
"%d passkey(s) are registered but the `passkeys` extra is not "
"installed, so they cannot be used. They are still stored and nothing "
"is lost. %s Until then, sign in with the password.",
len(registered), INSTALL_HINT,
)
def rp_id(config: AuthConfig, request: Request) -> str:
"""The domain to bind credentials to.
The configured value wins. Falling back to the request's host is what makes
development work without configuration — and is why the config docstring
says to pin it in production, since `Host` arrives from the client.
"""
if config.rp_id:
return config.rp_id
return request.url.hostname or "localhost"
def origin(config: AuthConfig, request: Request) -> str:
"""The exact origin the browser must be at, scheme and port included.
Derived from the request when unset, which is right when the app is the
thing the browser connected to and wrong behind a proxy that terminated TLS
— there this derives `http://` and every ceremony fails verification with an
origin mismatch. That is the failure `AuthConfig.origin` exists for.
"""
if config.origin:
return config.origin.rstrip("/")
url = request.url
port = f":{url.port}" if url.port not in (None, 80, 443) else ""
return f"{url.scheme}://{url.hostname}{port}"
def blocked(config: AuthConfig, request: Request) -> str:
"""Why a passkey cannot be *registered* from this request, or "".
Registration is the half that needs a secure context; verification does not,
because by then the browser has already done its own checks. So this is
asked when the account screen renders, not when a login is attempted.
"""
if not available():
return f"Passkeys need the `passkeys` extra, which is not installed. {INSTALL_HINT}"
where = origin(config, request)
host = urlsplit(where).hostname or ""
# The exact rule browsers apply: HTTPS anywhere, or HTTP on loopback.
# `.localhost` is in the same boat by RFC 6761 and Chrome honours it.
secure = (where.startswith("https://") or host == "localhost"
or host.endswith(".localhost") or host == "127.0.0.1" or host == "::1")
if not secure:
return (f"Passkeys need HTTPS. This app is being served at {where}, and "
f"a browser will not create one on an insecure origin. Put TLS "
f"in front of it, then set `auth.origin` in config.yaml.")
return ""
# -------------------------------------------------------------- registration
def register_options(config: AuthConfig, request: Request,
store: AuthStore) -> dict[str, Any]:
"""The challenge for adding a passkey, as the browser's `create()` wants it.
`exclude_credentials` is every key already registered, which is what makes
an authenticator say "you already have one of these" instead of quietly
creating a second credential that `add_passkey` would then reject on the
unique index — an error at the end of a ceremony you had already touched the
key for.
"""
from webauthn import generate_registration_options, options_to_json
from webauthn.helpers.structs import (
AuthenticatorSelectionCriteria, PublicKeyCredentialDescriptor,
ResidentKeyRequirement, UserVerificationRequirement,
)
options = generate_registration_options(
rp_id=rp_id(config, request),
rp_name=config.rp_name,
user_id=USER_HANDLE,
user_name=USER_NAME,
user_display_name=config.rp_name,
exclude_credentials=[PublicKeyCredentialDescriptor(id=cid)
for cid in store.passkey_ids()],
authenticator_selection=AuthenticatorSelectionCriteria(
# `preferred`, not `required`: a resident (discoverable) credential
# is what lets the login page offer "use a passkey" with nothing
# typed first, and it is worth asking for. Requiring it would turn
# away older security keys that have no room to store one, and a
# key that works as a second factor is still worth having.
resident_key=ResidentKeyRequirement.PREFERRED,
# Likewise: ask for a PIN or a fingerprint, do not insist. Insisting
# locks out keys with no PIN set, for a property the password behind
# this does not have either.
user_verification=UserVerificationRequirement.PREFERRED,
),
)
store.remember_challenge(options.challenge, "register")
return json.loads(options_to_json(options))
def register_verify(config: AuthConfig, request: Request, store: AuthStore,
credential: dict[str, Any], label: str) -> int:
"""Check what the authenticator sent back and keep it. Returns the row id.
Raises `PasskeyError` with a sentence fit to show, because every failure
here is either a stale ceremony or a misconfigured origin, and both have a
specific thing to do about them.
"""
from webauthn import verify_registration_response
from webauthn.helpers.exceptions import (
InvalidRegistrationResponse, WebAuthnException,
)
challenge = _challenge_from(credential)
if not store.take_challenge(challenge, "register"):
raise PasskeyError("That registration took too long, or was already "
"used. Press Add a passkey and try again.")
try:
verified = verify_registration_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=rp_id(config, request),
expected_origin=origin(config, request),
)
except InvalidRegistrationResponse as exc:
raise PasskeyError(_explain(exc, config, request)) from None
except (WebAuthnException, ValueError) as exc:
raise PasskeyMalformed(_malformed(exc)) from None
transports = ",".join(
t if isinstance(t, str) else t.value
for t in (credential.get("response", {}).get("transports") or []))
return store.add_passkey(
credential_id=verified.credential_id,
public_key=verified.credential_public_key,
sign_count=verified.sign_count,
transports=transports,
label=label or "Passkey",
)
# ---------------------------------------------------------------- signing in
def login_options(config: AuthConfig, request: Request,
store: AuthStore) -> dict[str, Any]:
"""The challenge for signing in.
`allow_credentials` lists what is registered, which is what makes a security
key light up rather than the browser asking the user to pick from nothing.
For a discoverable credential it is redundant; for a key registered without
one it is the only thing that works.
"""
from webauthn import generate_authentication_options, options_to_json
from webauthn.helpers.structs import (
PublicKeyCredentialDescriptor, UserVerificationRequirement,
)
options = generate_authentication_options(
rp_id=rp_id(config, request),
allow_credentials=[PublicKeyCredentialDescriptor(id=cid)
for cid in store.passkey_ids()],
user_verification=UserVerificationRequirement.PREFERRED,
)
store.remember_challenge(options.challenge, "login")
return json.loads(options_to_json(options))
def login_verify(config: AuthConfig, request: Request, store: AuthStore,
credential: dict[str, Any]) -> int:
"""Check a signature against a registered key. Returns the passkey's id.
Raises `PasskeyError` on anything that is not a good signature from a key
this app knows.
"""
from webauthn import verify_authentication_response
from webauthn.helpers import base64url_to_bytes
from webauthn.helpers.exceptions import (
InvalidAuthenticationResponse, WebAuthnException,
)
challenge = _challenge_from(credential)
if not store.take_challenge(challenge, "login"):
raise PasskeyError("That sign-in took too long, or was already used. "
"Try again.")
known = store.passkey_for(base64url_to_bytes(credential.get("rawId", "")))
if known is None:
# Deliberately the same sentence as a bad signature. There is one user,
# so this leaks little, but "that key is not registered" is an oracle
# for enumerating keys and costs nothing to withhold.
raise PasskeyError("That passkey is not registered here.")
passkey_id, public_key, stored_count = known
try:
verified = verify_authentication_response(
credential=credential,
expected_challenge=challenge,
expected_rp_id=rp_id(config, request),
expected_origin=origin(config, request),
credential_public_key=public_key,
credential_current_sign_count=stored_count,
)
except InvalidAuthenticationResponse as exc:
raise PasskeyError(_explain(exc, config, request)) from None
except (WebAuthnException, ValueError) as exc:
raise PasskeyMalformed(_malformed(exc)) from None
# The clone check — a counter that goes backwards means two authenticators
# are answering for one credential — is the library's, not ours: it is
# inside `verify_authentication_response`, which is handed the stored count
# above and raises before returning. All that is left to do is translate its
# message; see `_explain`.
store.record_passkey_use(passkey_id, verified.new_sign_count)
return passkey_id
# -------------------------------------------------------------------- helpers
class PasskeyError(Exception):
"""A ceremony that did not complete, with a sentence worth showing."""
class PasskeyMalformed(PasskeyError):
"""A body that was never a ceremony — the caller's mistake, not a refusal.
The distinction is only worth making at the login route, where a
`PasskeyError` is a 401 because something was wrong with the *credential*.
Nothing about a request missing half its fields says a credential was
refused, and answering 401 to it invites a retry of a request that cannot
ever work. It is a subclass so that anywhere the difference does not matter
— registering, behind a session — one `except` still covers both.
"""
def _challenge_from(credential: dict[str, Any]) -> bytes:
"""The challenge the browser echoed back inside `clientDataJSON`.
Read from the response rather than remembered per session, because the login
ceremony has no session to remember it in. That is safe *only* because
`take_challenge` then checks it against what was actually handed out, for
the right purpose, unexpired, and deletes it — a challenge this server never
issued matches nothing, and one it did issue works once.
"""
from webauthn.helpers import base64url_to_bytes
try:
raw = credential["response"]["clientDataJSON"]
data = json.loads(base64url_to_bytes(raw))
return base64url_to_bytes(data["challenge"])
except (KeyError, TypeError, ValueError) as exc:
raise PasskeyMalformed("That response was not a passkey.") from exc
def _malformed(exc: Exception) -> str:
"""A body the library could not read at all, said without a stack trace.
`verify_*_response` raises a family of these — `InvalidJSONStructure` for a
missing field, and its siblings for CBOR and key material — and they are not
`Invalid{Registration,Authentication}Response`, so catching only that one
leaves the rest to come out of an unauthenticated endpoint as a 500 with a
traceback. The type is worth keeping in the message; the traceback is not,
because there is no bug here to find.
"""
return f"That was not a passkey response: {type(exc).__name__}: {exc}"
def _explain(exc: Exception, config: AuthConfig, request: Request) -> str:
"""A verification failure, said in terms of what to change.
The library's own message names the mismatch precisely and means nothing to
anyone who has not read the spec; the useful half is which of the two
settings is wrong, which is almost always the origin behind a proxy.
"""
detail = str(exc)
if "sign count" in detail.lower():
# The one failure here that is not a misconfiguration. Two devices are
# answering for one credential and one of them is a copy — or, far more
# often, a key was restored from a backup that predates its own counter.
return ("That passkey looks cloned — its counter went backwards. "
"Revoke it under Account and register a new one.")
if "origin" in detail.lower() or "rp id" in detail.lower():
return (f"This passkey was not created for {origin(config, request)} "
f"(domain {rp_id(config, request)}). Behind a proxy that "
f"terminates TLS, set `auth.origin` and `auth.rp_id` in "
f"config.yaml to the address you actually use.")
return f"That passkey could not be verified: {detail}"
+489
View File
@@ -0,0 +1,489 @@
"""Signing in, signing out, and the one account there is.
The middleware in `auth/middleware.py` decides who gets past the door; this is
the door itself, plus the small screen for changing the key. Everything here is
deliberately about *this* user's own credential — there is no user to create,
none to list, and none to delete, because there is one.
Nothing is read from a module-level global: the store, the config and whether
the door is locked all come off `app.state`, where `connect` put them. That is
what lets two apps in one test process each have their own, and what keeps this
router importable by an app that never calls `connect` at all.
## Why the cookie is `SameSite=Lax` and there is no CSRF token
A CSRF token defends a cookie-authenticated app against another origin
submitting a form on your behalf. `SameSite=Lax` already refuses to send this
cookie on any cross-site request that is not a top-level navigation, and no
`GET` in this package changes anything — so the attack the token would stop
cannot be mounted. Adding one anyway would mean a second secret, a second thing
to rotate, and a second way for a request to fail for reasons the UI has to
explain. Where that reasoning stops being true is a browser old enough to
ignore `SameSite` entirely, which is not one that will run the login page.
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, HTTPException, Request, Response
from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse
from starlette.requests import HTTPConnection
from auth import passkeys as pk
from auth.config import AuthConfig
from auth.middleware import (
client_address, cookie_name, cookie_names, is_secure, token_from,
)
from auth.models import Account
from auth.schemas import (
LabelBody, LoginBody, PasskeyBody, PasskeyLoginBody, PasswordBody,
)
from auth.store import AuthStore
log = logging.getLogger(__name__)
router = APIRouter(tags=["auth"])
#: The page and the two scripts, shipped with the package. Served from routes
#: rather than mounted as a static directory because a router cannot mount one
#: — only an app can — and needing the app to mount something is exactly the
#: line of setup `connect` exists to remove. The same deal `/_jobs/jobs.js`
#: makes in `pipeline/web/jobs.py`.
TEMPLATES = Path(__file__).resolve().parent / "templates"
STATIC = Path(__file__).resolve().parent / "static"
#: The login page must never be cached: a proxy or a browser holding on to it
#: is a form posting to a door that has since been opened, or a page shown to
#: the next person at this machine.
NO_STORE = {"Cache-Control": "no-store"}
#: The shortest new password the account screen will take. Low, deliberately:
#: it is a floor against a typo, not a password policy. The honest advice is in
#: docs/password-protection.md — the generated password is sixteen random
#: characters and anything you choose yourself is the weak half.
MIN_LENGTH = 8
# ------------------------------------------------------- what connect left us
def _store(conn: HTTPConnection) -> AuthStore:
return conn.app.state.auth
def _config(conn: HTTPConnection) -> AuthConfig:
return conn.app.state.auth_config
def _locked(conn: HTTPConnection) -> bool:
"""Whether this app is running with the door locked.
Read off `app.state`, where `connect` put it, rather than recomputed: the
answer depends on the bind address, which the config alone does not know
and a request cannot be asked for.
"""
return bool(conn.app.state.auth_locked)
def _pinned(conn: HTTPConnection) -> str:
"""The password from the environment, or "". See `auth.bootstrap`."""
return os.environ.get(_config(conn).password_env, "")
# ---------------------------------------------------------------- the scripts
@router.get("/_auth/passkey.js", include_in_schema=False)
def passkey_js() -> FileResponse:
"""The browser half of WebAuthn, shared by the login page and the element."""
return _script("passkey.js")
@router.get("/_auth/account.js", include_in_schema=False)
def account_js() -> FileResponse:
"""`<auth-account>`: the account screen, for an app with no UI for it yet.
<script type="module" src="/_auth/account.js"></script>
<auth-account></auth-account>
"""
return _script("account.js")
def _script(name: str) -> FileResponse:
"""Cached for an hour rather than forever. These change when the package is
copied into a project and then hardly ever, and an app that wants them
fingerprinted can serve the files itself from `STATIC`."""
return FileResponse(STATIC / name, media_type="text/javascript",
headers={"Cache-Control": "public, max-age=3600"})
# ------------------------------------------------------------------- the door
@router.get("/login", response_class=HTMLResponse, include_in_schema=False)
def login_page(request: Request) -> Response:
"""The one page served without a session.
Sent only if you ask for it directly with no session cookie; with one,
there is nothing here to do, so it bounces to the front page rather than
offering a form that would replace a session you have.
"""
if not _locked(request):
return RedirectResponse("/", status_code=303)
token = token_from(request, _config(request))
if token and _store(request).touch(token):
return RedirectResponse("/", status_code=303)
config = _config(request)
store = _store(request)
# Whether to draw the passkey button at all. Decided here rather than by
# the page asking, because a button that appears and then discovers there
# is nothing to press is worse than one that was never drawn — and the page
# has no session, so it cannot ask anything else about the account.
offer = "true" if (pk.available() and store.passkey_ids()) else "false"
sheet = request.app.state.auth_stylesheet
html = (TEMPLATES / "login.html").read_text(encoding="utf-8")
html = (html
.replace("{stylesheet}",
f'<link rel="stylesheet" href="{sheet}">' if sheet else "")
.replace("{name}", config.rp_name)
.replace("{passkeys}", offer))
return HTMLResponse(html, headers=NO_STORE)
@router.post("/login", include_in_schema=False)
def sign_in(request: Request, response: Response, body: LoginBody) -> dict[str, str]:
"""Check the password, and if it is right, open a session.
The lockout is read *before* the password is checked, so hammering the
button while locked out does not extend the lockout — see
`AuthStore.locked_for`. A wrong password and an unknown one are the same
answer here for the usual reason, which is thin cover with one account but
costs nothing to keep.
"""
if not _locked(request):
raise HTTPException(400, "This app is not password-protected.")
_refuse_while_locked(request)
if not _store(request).check_password(body.password):
_warn(request, "wrong password")
raise HTTPException(401, "That is not the password.")
_open_session(request, response)
return {"next": _safe_next(body.next)}
@router.post("/logout", include_in_schema=False)
def sign_out(request: Request, response: Response) -> dict[str, bool]:
"""End this session and clear the cookie. Other devices are untouched."""
token = token_from(request, _config(request))
if token:
_store(request).close_session(token)
# Both names, because which one was set depends on `secure_cookie` and on
# the scheme the login happened over — and clearing only one of them leaves
# a cookie the browser will keep offering.
for name in cookie_names(_config(request)):
response.delete_cookie(name, path="/")
return {"ok": True}
# ---------------------------------------------------------------- the account
@router.get("/api/account")
def account(request: Request) -> Account:
"""What there is to know and what can be changed."""
store = _store(request)
config = _config(request)
return Account(
locked=_locked(request),
pinned=bool(_pinned(request)),
pinned_by=config.password_env,
password_set_at=store.changed_at(),
sessions=store.sessions(token_from(request, config)),
passkeys=store.passkeys(),
passkeys_available=pk.available(),
passkeys_blocked=pk.blocked(config, request),
)
@router.post("/api/account/password")
def change_password(request: Request, body: PasswordBody) -> dict[str, int]:
"""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
in: it is what makes a borrowed unlocked laptop not equal to a permanent
takeover of the account. It is asked for whenever there is one, which on a
locked app is always; see the body of the function for the one case where
there is not.
Every *other* session is closed on success. If the reason you are changing
the password is that someone may have it, leaving their session open makes
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.
Which is also why this is behind the same lockout as the front door, and not
only behind a session. `current` is the password, guessed here rather than
at `/login`, and a borrowed unlocked laptop is exactly the situation the
field exists for — so leaving it ungated would leave one door counted and
one door open, at scrypt speed, ending in a password change that signs the
owner out everywhere.
"""
config = _config(request)
if _pinned(request):
raise HTTPException(
409, f"The password is pinned by {config.password_env}. Change it there.")
store = _store(request)
# The first one is set without proving anything, because there is nothing
# to prove: an app with no password is one nothing was asked for, and the
# only way to reach this route is from a session it never demanded. That
# is the unlocked laptop, and setting a password *there* — before the
# thing is ever deployed — is the order this should encourage. A locked
# app never lands here: `auth.bootstrap` gives it a password at startup,
# so `current` is always required for the app that has a door.
if store.has_password():
_refuse_while_locked(request)
if not store.check_password(body.current):
_warn(request, "wrong current password")
raise HTTPException(403, "That is not the current password.")
if len(body.new) < MIN_LENGTH:
raise HTTPException(400, f"Use at least {MIN_LENGTH} characters.")
store.set_password(body.new)
closed = store.close_all(keep=token_from(request, config))
return {"signed_out": closed}
@router.delete("/api/account/sessions/{session_id}")
def revoke(session_id: int, request: Request) -> dict[str, bool]:
"""Drop one session. Revoking your own is allowed — it is a logout with an
extra click, and refusing it would be a rule to explain for no gain."""
if not _store(request).close_by_id(session_id):
raise HTTPException(404, "That session is already gone.")
return {"ok": True}
@router.post("/api/account/sessions/close")
def close_others(request: Request) -> dict[str, int]:
"""Sign out everywhere but here. The reason sessions are rows."""
store = _store(request)
return {"signed_out": store.close_all(keep=token_from(request, _config(request)))}
# ------------------------------------------------------------------- passkeys
#
# Four routes behind the session (register in two steps, rename, revoke) and two
# in front of it (sign in). The ceremony itself is `auth/passkeys.py`; these are
# the round trips it needs, and the translation of its two exceptions into
# status codes.
@router.post("/api/account/passkeys/options")
def passkey_options(request: Request) -> dict[str, object]:
"""Step one of registering: a challenge for `navigator.credentials.create`."""
_require_passkeys(request)
return pk.register_options(_config(request), request, _store(request))
@router.post("/api/account/passkeys")
def add_passkey(request: Request, body: PasskeyBody) -> dict[str, int]:
"""Step two: check what the authenticator signed, and keep the public key.
Requires a session, like everything else under `/api/account`. Registering a
passkey is granting a new way in, so it is gated on already being in — the
password is what proves that, and the ceremony does not replace it.
"""
_require_passkeys(request)
try:
return {"id": pk.register_verify(_config(request), request, _store(request),
body.credential, body.label)}
except pk.PasskeyError as exc:
# `PasskeyMalformed` is one of these and answers the same way: from
# behind a session, a body that is not a ceremony and a ceremony that
# did not check out are both "that did not work, press it again".
raise HTTPException(400, str(exc)) from None
@router.post("/api/account/passkeys/{passkey_id}/label")
def rename_passkey(passkey_id: int, body: LabelBody, request: Request) -> dict[str, bool]:
"""Name it. A key you cannot name is one you will never dare revoke."""
if not _store(request).rename_passkey(passkey_id, body.label):
raise HTTPException(404, "That passkey is already gone.")
return {"ok": True}
@router.delete("/api/account/passkeys/{passkey_id}")
def drop_passkey(passkey_id: int, request: Request) -> dict[str, bool]:
"""Revoke one. The password is still there, so this cannot lock you out —
which is exactly why the password is still there."""
if not _store(request).delete_passkey(passkey_id):
raise HTTPException(404, "That passkey is already gone.")
return {"ok": True}
@router.post("/login/passkey/options", include_in_schema=False)
def passkey_login_options(request: Request) -> dict[str, object]:
"""Step one of signing in. Open, necessarily — there is no session yet.
Handing out a challenge to anyone who asks costs nothing: it is a random
number, single-use, and worth nothing without a private key that never left
the authenticator.
"""
_require_passkeys(request)
store = _store(request)
if not store.passkey_ids():
raise HTTPException(404, "No passkeys are registered on this app.")
return pk.login_options(_config(request), request, store)
@router.post("/login/passkey", include_in_schema=False)
def passkey_login(request: Request, response: Response,
body: PasskeyLoginBody) -> dict[str, str]:
"""Step two: a good signature from a registered key opens a session.
The same session a password opens — one kind of session, whichever door it
came through, so revoking and expiry have one implementation.
Deliberately not behind the password lockout. An attacker hammering the
front door locks it for the owner too (see `AuthStore.check_password` on
why there is one counter), and a passkey that skips that queue is what
makes it survivable. It is safe to skip: there is nothing to guess here,
only a signature to produce.
"""
if not _locked(request):
raise HTTPException(400, "This app is not password-protected.")
_require_passkeys(request)
try:
pk.login_verify(_config(request), request, _store(request), body.credential)
except pk.PasskeyMalformed as exc:
# Not a failed sign-in — a request that was never a ceremony. 400 rather
# than 401, and no warning, because there is no credential here to have
# been wrong about.
raise HTTPException(400, str(exc)) from None
except pk.PasskeyError as exc:
_warn(request, "passkey refused")
raise HTTPException(401, str(exc)) from None
_open_session(request, response)
return {"next": "/"}
def _require_passkeys(request: Request) -> None:
"""501 rather than 500 when the extra is not installed, and a sentence
saying what to install.
"Not implemented" is the honest reading: the route exists and this build
cannot perform it. The account element watches for exactly this status and
takes the passkey section off the screen, so a missing optional dependency
costs a paragraph rather than a broken page.
Only the package is checked here — an insecure origin blocks *registration*
in the browser, not these endpoints, and the account screen has already
said so.
"""
if not pk.available():
raise HTTPException(501, pk.blocked(_config(request), request))
# --------------------------------------------------------------------- helpers
def _open_session(request: Request, response: Response) -> None:
"""One session, one cookie, whichever door was used."""
config = _config(request)
token = _store(request).open_session(
request.headers.get("user-agent", ""), config.session_days)
https = request.url.scheme == "https"
response.set_cookie(
cookie_name(config, https),
token,
max_age=config.session_days * 86400,
httponly=True, # JavaScript cannot read it, so an XSS cannot post it on
secure=is_secure(config, https),
samesite="lax", # see the module docstring on why there is no CSRF token
path="/",
)
def _refuse_while_locked(request: Request) -> None:
"""The lockout, in front of every place a password can be guessed.
Read *before* the guess is looked at, so hammering while locked out does not
extend the lockout — see `AuthStore.locked_for`. Called from both doors
rather than living inside `check_password`, because the store counts and
this decides: the same wrong answer is a refusal here and a bootstrap
comparison in `auth.bootstrap`, which must not be able to lock anyone out of
their own restart.
"""
wait = _store(request).locked_for()
if wait:
_warn(request, "attempt while locked out")
raise HTTPException(429, f"Too many attempts. Try again in {_spell(wait)}.",
headers={"Retry-After": str(wait)})
def _warn(request: Request, what: str) -> None:
"""Write down that someone got it wrong, and who.
The whole record of who is knocking. There is no access log worth the name —
uvicorn is run quietly — and no table of attempts, because the log is the
record and a second copy of it would only ever disagree. WARNING so it
survives that level, one line per refusal, and the address first after
`from` so a fail2ban filter is one regex; see docs/password-protection.md.
The message does not name the package, because the logger already does:
with the usual `%(name)s: %(message)s` this module is `auth.router`, and a
line reading `auth.router: auth: wrong password` says it twice and reads
like a bug in the logging.
Nothing is *decided* from the address — `AuthStore.check_password` says why
it cannot be — so this is where it earns its keep: at the layer that can
drop the connection instead of answering it.
"""
log.warning("%s from %s", what, client_address(request))
def _safe_next(target: str) -> str:
r"""Where to go after signing in — only ever inside this app.
The classic open redirect: a real login page, a real successful sign-in, and
someone else's site afterwards. So this accepts one shape only — a path
beginning with a single `/`, with no host in it — and turns everything else
into `/`.
A backslash is refused because a browser treats it as a slash in exactly
this position: `/\evil.com` is parsed as `//evil.com` and is a host, which
is how a version of this that rejected only a literal `//` sent people to
another site. And the value is checked decoded as well as raw, because it
reaches here through a query string that `URLSearchParams` has already
unescaped once — `%5C` is a backslash to everything downstream of the
address bar, and no `next` this app produces needs an escaped slash to
survive.
"""
if not _local(target) or not _local(unquote(target)):
return "/"
return target
def _local(target: str) -> bool:
r"""Whether this is a path inside this app and nothing else.
`urlsplit` rather than more string tests, because it is the parser the
browser's own rules are written against — it strips the tabs and newlines a
browser strips, so `/\t/evil.com` is seen the way the browser will see it,
as a host, and not as the local path a naive `startswith` reads.
"""
if not target.startswith("/") or target.startswith("//") or "\\" in target:
return False
try:
parts = urlsplit(target)
except ValueError: # an unparseable authority, e.g. `//[`
return False
return not parts.scheme and not parts.netloc
def _spell(seconds: int) -> str:
if seconds < 60:
return f"{seconds} seconds"
return f"{round(seconds / 60)} minutes"
+56
View File
@@ -0,0 +1,56 @@
"""The five bodies this package accepts. Small on purpose.
A ceremony's `credential` is passed through as an opaque dict — it is the
browser's `PublicKeyCredential` serialised by `toJSON()`, and its shape is the
WebAuthn spec's business rather than ours. Restating it as a model here would
be a second, staler copy of a structure the library already parses and
validates properly.
"""
from __future__ import annotations
from typing import Any
from pydantic import BaseModel, Field
class LoginBody(BaseModel):
"""The whole login form. No username field, because there is no username —
asking for one would be theatre, and a wrong guess at it would be an error
message about something that does not exist."""
#: Bounded, because it is the one field an unauthenticated stranger can
#: send: scrypt is memory-hard by design and a megabyte of "password" is a
#: megabyte this process hashes before saying no.
password: str = Field(max_length=1000)
#: Where the middleware was sending them before it asked. Sanitised on the
#: way back out — see `_safe_next` in `auth/router.py`.
next: str = "/"
class PasswordBody(BaseModel):
"""Changing it. `current` is required even though the caller is signed in;
`auth/router.py` says why."""
current: str = Field(max_length=1000)
new: str = Field(max_length=1000)
class PasskeyBody(BaseModel):
"""A finished registration ceremony, on its way to be checked."""
credential: dict[str, Any]
#: What to call it in the list. Suggested by the browser, editable after.
label: str = ""
class PasskeyLoginBody(BaseModel):
"""A finished authentication ceremony. Same reasoning as above."""
credential: dict[str, Any]
class LabelBody(BaseModel):
"""Renaming a passkey."""
label: str
+505
View File
@@ -0,0 +1,505 @@
/* The account screen, for an app that has not written a UI for it.
*
* <script type="module" src="/_auth/account.js"></script>
* <auth-account></auth-account>
*
* 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
* password, look at what is signed in and revoke any of it, register and
* revoke passkeys, and sign out.
*
* One file, and the styles are in it rather than beside it, because the shadow
* root scopes them anyway and a second file is a second route, a second cache
* header and a second thing to forget to copy. Themed from outside through the
* same `--desk-jobs-*` custom properties `<desk-jobs>` reads -- set them once
* on `desk-jobs, desk-schedules, auth-account` and the queue's elements and
* this one look like one application rather than three.
*
* Failures are said in place, next to the button that caused them, *and*
* raised as an `auth-account:error` event carrying the server's own `detail`,
* so an app with toasts can show one without this element knowing what a toast
* is. Same split as `desk-jobs:notice`.
*
* Attributes, both optional:
* base="/api" prefix for the HTTP calls, if the router is mounted deeper
* login="/login" where signing out sends the browser
*/
const CSS = `
:host {
--desk-jobs-bg: #16181d;
--desk-jobs-fg: #e7e9ee;
--desk-jobs-dim: #9aa1ad;
--desk-jobs-accent: #4c8dff;
--desk-jobs-error: #ff6b6b;
--desk-jobs-radius: 10px;
--desk-jobs-font: system-ui, -apple-system, "Segoe UI", sans-serif;
--desk-jobs-gap: 8px;
display: block;
font-family: var(--desk-jobs-font);
font-size: 14px;
color: var(--desk-jobs-fg);
}
:host([hidden]) { display: none; }
.panel { display: flex; flex-direction: column; gap: calc(var(--desk-jobs-gap) * 2); }
section { display: flex; flex-direction: column; gap: var(--desk-jobs-gap); }
h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em;
color: var(--desk-jobs-dim); margin: 0; font-weight: 600; }
.said { color: var(--desk-jobs-dim); }
.said.bad { color: var(--desk-jobs-error); }
.what { font-weight: 600; }
.row {
display: flex; align-items: baseline; justify-content: space-between;
gap: var(--desk-jobs-gap);
padding: 6px 0;
border-top: 1px solid color-mix(in srgb, var(--desk-jobs-fg) 12%, transparent);
}
.row:first-of-type { border-top: 0; }
.row .lines { display: flex; flex-direction: column; min-width: 0; }
.row .acts { display: flex; gap: var(--desk-jobs-gap); flex: none; }
form { display: flex; flex-wrap: wrap; gap: var(--desk-jobs-gap); align-items: center; }
input {
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; min-width: 11rem;
}
button {
font: inherit;
color: var(--desk-jobs-dim);
background: none;
border: 1px solid currentColor;
border-radius: 6px;
padding: 2px 9px;
cursor: pointer;
}
button:hover { color: var(--desk-jobs-accent); }
button.danger:hover { color: var(--desk-jobs-error); }
button[disabled] { opacity: .4; cursor: default; }
.badge {
font-size: 12px; padding: 0 6px; border-radius: 999px;
border: 1px solid currentColor; color: var(--desk-jobs-dim);
}
`;
/** What the server says when this build has no `webauthn` installed. The
* element takes the whole passkey section off the screen rather than leaving
* buttons that can only ever fail -- and 501 is the status that says "this
* route exists and this build cannot do it", which is exactly the case. */
const NOT_BUILT = 501;
class AuthAccount extends HTMLElement {
#root;
#panel;
#account = null;
#busy = false;
/** The one line under the status block: what the last button did, or why it
* did not. Kept on the element rather than in the DOM because every action
* reloads the account and redraws everything. */
#message = "";
#bad = false;
/** Set once the server has answered 501 to a passkey call. `/api/account`
* already says `passkeys_available`, and this is the same answer arriving
* the other way -- from an app that was restarted without the extra while
* this page was open. */
#passkeysGone = false;
constructor() {
super();
this.#root = this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = CSS;
this.#panel = document.createElement("div");
this.#panel.className = "panel";
this.#root.append(style, this.#panel);
}
connectedCallback() { this.#load(); }
get #base() { return this.getAttribute("base") ?? ""; }
get #login() { return this.getAttribute("login") ?? "/login"; }
// ------------------------------------------------------------------ server
/** One fetch helper, so every failure surfaces the same way: the server's
* own sentence, in place and as an event. A 401 means the session ended
* under us, which is a redirect rather than a message. */
async #api(path, options = {}) {
const response = await fetch(this.#base + path, {
credentials: "same-origin",
headers: Object.assign({ Accept: "application/json" },
options.body ? { "Content-Type": "application/json" } : {}),
...options,
});
let data = null;
const text = await response.text();
if (text) { try { data = JSON.parse(text); } catch { data = null; } }
if (!response.ok) {
const error = new Error((data && data.detail)
|| `The server answered ${response.status} and said nothing about why.`);
error.status = response.status;
throw error;
}
return data;
}
async #load() {
try {
this.#account = await this.#api("/api/account");
this.#render();
} catch (err) {
if (err.status === 401) { location.assign(this.#login); return; }
this.#fail(err);
this.#render();
}
}
/** Run one button's worth of work: disable the panel, say what went wrong,
* and reload the account either way -- the server is the only thing that
* knows what the sessions and passkeys are now. */
async #act(work) {
if (this.#busy) return;
this.#busy = true;
this.#message = "";
this.#bad = false;
this.#render();
try {
await work();
} catch (err) {
if (err.status === 401) { location.assign(this.#login); return; }
if (err.status === NOT_BUILT) this.#passkeysGone = true;
this.#fail(err);
} finally {
this.#busy = false;
}
await this.#load();
}
#fail(err) {
this.#message = String(err.message || err);
this.#bad = true;
this.dispatchEvent(new CustomEvent("auth-account:error", {
detail: { detail: this.#message, status: err.status || 0 },
bubbles: true, composed: true,
}));
}
#say(text) {
this.#message = text;
this.#bad = false;
}
// ------------------------------------------------------------------ drawing
#render() {
const account = this.#account;
this.#panel.replaceChildren();
if (!account) {
this.#panel.append(this.#note(this.#message || "Loading…", this.#bad));
return;
}
this.#panel.append(this.#status(account));
if (this.#message) this.#panel.append(this.#note(this.#message, this.#bad));
this.#panel.append(this.#password(account));
if (account.sessions.length) this.#panel.append(this.#sessions(account));
if (this.#showPasskeys(account)) this.#panel.append(this.#passkeys(account));
if (account.locked) this.#panel.append(this.#signOut());
}
#showPasskeys(account) {
return account.passkeys_available && !this.#passkeysGone;
}
#status(account) {
const section = this.#section("This app");
section.append(this.#line(
account.locked
? "Locked. Every request but the login page, the health probe and the static files needs a session."
: "Not locked. The bind address is loopback and `auth.enabled` is `auto`, so anyone who can reach this app is already sitting at the machine."));
if (account.password_set_at) {
section.append(this.#line(`Password last set ${when(account.password_set_at)}.`));
} else {
section.append(this.#line("No password has been set on this database yet."));
}
if (account.pinned) {
section.append(this.#line(
`The password is pinned by ${account.pinned_by || "the environment"}, so it cannot be changed here. Change it there and restart.`));
}
if (account.passkeys_blocked && account.passkeys_available) {
section.append(this.#line(account.passkeys_blocked));
}
return section;
}
#password(account) {
const section = this.#section("Password");
if (account.pinned) {
section.append(this.#line(
`Set by ${account.pinned_by || "the environment"}. Empty that variable, restart, and this form comes back.`));
return section;
}
// Nothing to prove when there is nothing set yet, which is what an
// unlocked app on a laptop looks like before it is ever deployed. Asking
// for a current password there is a field with no right answer, and the
// form could only ever be refused -- see `change_password` in router.py.
const first = !account.password_set_at;
const form = document.createElement("form");
const current = field("password", "Current password");
const next = field("password", first ? "Choose a password" : "New password");
const go = document.createElement("button");
go.textContent = first ? "Set password" : "Change password";
go.disabled = this.#busy;
form.append(...(first ? [next, go] : [current, next, go]));
form.addEventListener("submit", (event) => {
event.preventDefault();
this.#act(async () => {
const result = await this.#api("/api/account/password", {
method: "POST",
body: JSON.stringify({ current: current.value, new: next.value }),
});
current.value = next.value = "";
if (first) return this.#say("Password set.");
this.#say(result.signed_out
? `Password changed. ${count(result.signed_out, "other session")} signed out.`
: "Password changed.");
});
});
section.append(form);
// Every *other* session goes when the password changes: if the reason you
// are changing it is that someone may have it, leaving their session open
// makes the change ceremonial. Said here so it is not a surprise.
section.append(this.#line(first
? "Nothing asks for it until the app binds an address that is not loopback -- or `auth.enabled: always`. Set it before you deploy, not after."
: "Changing it signs out every other session, and keeps this one."));
return section;
}
#sessions(account) {
const section = this.#section("Signed in");
for (const session of account.sessions) {
const row = this.#row(
session.label || "Unnamed browser",
`${session.current ? "This browser · " : ""}last seen ${when(session.last_seen_at)} · started ${when(session.created_at)}`);
if (session.current) row.querySelector(".acts").append(badge("this one"));
row.querySelector(".acts").append(this.#button("Revoke", "danger", () =>
this.#act(async () => {
await this.#api(`/api/account/sessions/${session.id}`, { method: "DELETE" });
// Revoking your own is allowed -- it is a logout with an extra click
// -- and the next request is the one that discovers it.
this.#say("Session revoked.");
})));
section.append(row);
}
if (account.sessions.length > 1) {
section.append(this.#button("Sign out everywhere else", "", () =>
this.#act(async () => {
const result = await this.#api("/api/account/sessions/close", { method: "POST" });
this.#say(`${count(result.signed_out, "session")} signed out.`);
})));
}
return section;
}
#passkeys(account) {
const section = this.#section("Passkeys");
for (const key of account.passkeys) {
const row = this.#row(
key.label || "Passkey",
[key.transports.join(", "),
`added ${when(key.created_at)}`,
key.last_used_at ? `last used ${when(key.last_used_at)}` : "never used",
].filter(Boolean).join(" · "));
const acts = row.querySelector(".acts");
acts.append(this.#button("Rename", "", () => {
const label = prompt("Call this passkey what?", key.label || "");
if (label === null) return;
this.#act(async () => {
await this.#api(`/api/account/passkeys/${key.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/passkeys/${key.id}`, { method: "DELETE" });
// Safe by construction: the password is still there, which is why
// revoking a key can never lock anyone out.
this.#say("Passkey revoked.");
})));
section.append(row);
}
if (account.passkeys_blocked) {
// Registering needs a secure origin; verifying does not. So the list
// above is still worth drawing, and only the button goes.
section.append(this.#line(account.passkeys_blocked));
return section;
}
const add = this.#button("Add a passkey", "", () => this.#register());
add.disabled = this.#busy;
section.append(add);
return section;
}
async #register() {
const passkey = await loadPasskeyHelper();
if (!passkey || !passkey.supported()) {
this.#say("This browser will not create a passkey here. It needs HTTPS, or localhost.");
this.#render();
return;
}
// Two round trips: a challenge, then what the authenticator signed. The
// browser's own prompt happens between them, and a cancelled prompt is an
// exception rather than an error status -- hence `explain`.
await this.#act(async () => {
const options = await this.#api("/api/account/passkeys/options", { method: "POST" });
let made;
try {
made = await passkey.create(options);
} catch (err) {
throw new Error(passkey.explain(err));
}
const label = suggest();
await this.#api("/api/account/passkeys", {
method: "POST", body: JSON.stringify({ credential: made, label }),
});
this.#say(`Registered "${label}". Rename it if that is not what it is.`);
});
}
#signOut() {
const section = this.#section("This session");
section.append(this.#button("Sign out", "danger", async () => {
try {
await this.#api("/logout", { method: "POST" });
} catch { /* the cookie is going either way */ }
location.assign(this.#login);
}));
return section;
}
// --------------------------------------------------------------- furniture
#section(title) {
const section = document.createElement("section");
const head = document.createElement("h3");
head.textContent = title;
section.append(head);
return section;
}
#line(text) {
const line = document.createElement("div");
line.className = "said";
line.textContent = text;
return line;
}
#note(text, bad) {
const line = this.#line(text);
if (bad) line.classList.add("bad");
return line;
}
#row(what, said) {
const row = document.createElement("div");
row.className = "row";
const lines = document.createElement("div");
lines.className = "lines";
const name = document.createElement("span");
name.className = "what";
name.textContent = what;
const under = document.createElement("span");
under.className = "said";
under.textContent = said;
lines.append(name, under);
const acts = document.createElement("div");
acts.className = "acts";
row.append(lines, acts);
return row;
}
#button(text, className, onClick) {
const button = document.createElement("button");
button.textContent = text;
if (className) button.className = className;
button.disabled = this.#busy;
button.addEventListener("click", onClick);
return button;
}
}
/** The WebAuthn helper is a classic script on `window`, shared with the login
* page, which is plain HTML served before any of the app's scripts. Loaded on
* demand rather than up front, so a screen nobody registers a passkey from
* never fetches it. */
let helper = null;
function loadPasskeyHelper() {
if (window.passkey) return Promise.resolve(window.passkey);
helper = helper || new Promise((resolve) => {
const script = document.createElement("script");
script.src = "/_auth/passkey.js";
script.onload = () => resolve(window.passkey || null);
script.onerror = () => resolve(null);
document.head.append(script);
});
return helper;
}
/** A name the authenticator can be told apart by, before anyone renames it.
* Better than "Passkey" and worse than what a person would call it, which is
* why Rename is beside it. */
function suggest() {
const agent = navigator.userAgent || "";
for (const [needle, name] of [["Windows", "Windows"], ["Mac", "Mac"],
["iPhone", "iPhone"], ["iPad", "iPad"],
["Android", "Android"], ["Linux", "Linux"]]) {
if (agent.includes(needle)) return `${name} passkey`;
}
return "Passkey";
}
function badge(text) {
const span = document.createElement("span");
span.className = "badge";
span.textContent = text;
return span;
}
function field(type, placeholder) {
const input = document.createElement("input");
input.type = type;
input.placeholder = placeholder;
input.setAttribute("aria-label", placeholder);
input.required = true;
input.autocomplete = type === "password" ? "new-password" : "off";
return input;
}
function count(n, thing) {
return `${n} ${thing}${n === 1 ? "" : "s"}`;
}
/** An ISO stamp as something to read. Local time, because the person reading
* it is at a machine and the server's UTC is nobody's afternoon. */
function when(stamp) {
if (!stamp) return "never";
const at = new Date(stamp);
if (Number.isNaN(at.getTime())) return stamp;
return at.toLocaleString();
}
if (!customElements.get("auth-account")) {
customElements.define("auth-account", AuthAccount);
}
export { AuthAccount };
+100
View File
@@ -0,0 +1,100 @@
// The browser half of WebAuthn: two ceremonies and the byte-shuffling they need.
//
// Shared by the login page and the account element, which is why it is a file
// rather than inline. Both need exactly these conversions, and getting them
// subtly wrong in one of two copies is the kind of bug that only shows up on
// the device you do not have.
//
// Not a module, and on `window` rather than exported: the login page is plain
// HTML served before any of the app's own scripts, and a classic script is the
// one shape both it and the element can load.
//
// ## Why the conversions exist at all
//
// WebAuthn's JavaScript API speaks ArrayBuffer; its JSON encoding speaks
// base64url. So every challenge and credential id has to be decoded on the way
// into `navigator.credentials` and encoded on the way back out. Newer browsers
// offer `PublicKeyCredential.parseRequestOptionsFromJSON()` and a `toJSON()` on
// the result, which do this for you -- deliberately not used here, because
// feature-detecting them means two code paths through the one part of this that
// is fiddly, and the ten lines below work everywhere without a branch.
//
// The server never sees an ArrayBuffer and never sends one: `options_to_json`
// on one side and these helpers on the other are the whole contract.
const bufFrom = (s) =>
Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')),
c => c.charCodeAt(0)).buffer;
const b64From = (b) =>
btoa(String.fromCharCode(...new Uint8Array(b)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
// `supported` is asked before any button is drawn. `isSecureContext` is the
// browser's own answer to "will WebAuthn run here at all" -- false on plain
// HTTP anywhere but localhost -- and asking it here means the page can say so
// rather than letting `credentials.get()` reject with a DOMException that reads
// like a bug.
const supported = () =>
Boolean(window.PublicKeyCredential) && window.isSecureContext;
async function create(options) {
options.challenge = bufFrom(options.challenge);
options.user.id = bufFrom(options.user.id);
(options.excludeCredentials || []).forEach(c => { c.id = bufFrom(c.id); });
const credential = await navigator.credentials.create({publicKey: options});
return {
id: credential.id,
rawId: b64From(credential.rawId),
type: credential.type,
response: {
clientDataJSON: b64From(credential.response.clientDataJSON),
attestationObject: b64From(credential.response.attestationObject),
// Advisory, and absent on older authenticators -- it is what lets the
// account screen say "usb, nfc" beside a key instead of just a name.
transports: credential.response.getTransports
? credential.response.getTransports() : [],
},
clientExtensionResults: {},
};
}
async function get(options) {
options.challenge = bufFrom(options.challenge);
(options.allowCredentials || []).forEach(c => { c.id = bufFrom(c.id); });
const credential = await navigator.credentials.get({publicKey: options});
return {
id: credential.id,
rawId: b64From(credential.rawId),
type: credential.type,
response: {
clientDataJSON: b64From(credential.response.clientDataJSON),
authenticatorData: b64From(credential.response.authenticatorData),
signature: b64From(credential.response.signature),
userHandle: credential.response.userHandle
? b64From(credential.response.userHandle) : null,
},
clientExtensionResults: {},
};
}
// What a cancelled ceremony should say. Pressing Escape, unplugging the key, or
// letting the prompt time out all arrive as exceptions, and the raw
// DOMException text ("The operation either timed out or was not allowed...")
// reads as a failure of the application rather than as "you cancelled it".
function explain(err) {
if (err && (err.name === 'NotAllowedError' || err.name === 'AbortError')) {
return 'Cancelled - no passkey was used.';
}
if (err && err.name === 'InvalidStateError') {
return 'That authenticator already has a passkey for this app.';
}
if (err && err.name === 'SecurityError') {
return 'This page is not a secure origin, so the browser will not use a passkey here.';
}
return String(err && err.message ? err.message : err).replace('Error: ', '');
}
window.passkey = {supported, create, get, explain};
+505
View File
@@ -0,0 +1,505 @@
"""One password, and the sessions it opens. Nothing else knows a hash.
Four tables in whatever SQLite file it is given — the app's own, normally, so
there is one file to back up and SQLite's writer lock keeps auth honest with
everything else in it. Every name starts `auth_`, because the file is shared:
a `sessions` table is a name an app is entitled to want for itself.
Four decisions worth arguing for, because each of them is the kind of thing
that gets "simplified" later by someone who does not know why it is here.
**The password is never stored, and neither is anything reversible.** What goes
in the file is `scrypt(password, salt)` and the salt. scrypt is in the standard
library, so this costs no dependency, and it is *memory*-hard rather than
merely slow — the parameters below make one guess cost 16 MB, which is what
takes a stolen database file out of range of a GPU. A plain SHA-256 of the
password would fit in the same column and be worth nothing.
**A session token is random, not signed.** The alternative — a signed cookie
carrying the claim, JWT-shaped — needs a signing key that has to be generated,
stored, kept out of logs and backups, and rotated, and it buys statelessness
that a single-user app on one SQLite file has no use for. Here the cookie is 32
random bytes and the database holds only its SHA-256, so:
- the file cannot be read to forge a session, the same way it cannot be read to
recover the password;
- signing out everywhere is one `DELETE`, which no signed token can offer
without keeping exactly the server-side state this already has;
- there is no key to leak.
Hashing the token before storing it is the same move as hashing the password
and for the same reason. It is only SHA-256 rather than scrypt because the
input is already 32 bytes of `secrets`, so there is no guessing to slow down.
**Failed attempts are counted in the file, not in memory.** A counter on the
process resets when the process does, which on a server that reloads or
crash-loops is a free reset for whoever is guessing. See `check_password`.
**Passkeys sit alongside all of that rather than replacing it.** What is stored
for one is a *public* key, which is the whole point — there is no secret here
to protect, because the private half never leaves the authenticator. The
ceremony that uses these rows is `auth/passkeys.py`; this module only keeps
them.
"""
from __future__ import annotations
import hashlib
import hmac
import math
import os
import secrets
import sqlite3
from contextlib import closing
from datetime import UTC, datetime, timedelta
from pathlib import Path
from auth.models import Passkey, SessionInfo
#: scrypt cost. `n` is the work factor, and 2**14 with `r=8` is the widely
#: recommended interactive setting: about 16 MB and ~50 ms per guess, which is
#: imperceptible on a login and ruinous on a dictionary. Raising `n` later is
#: safe — the parameters are not stored, so a change simply invalidates the
#: existing hash and `set_password` writes one at the new cost. Which is worth
#: knowing before raising it: it means the current password stops working and
#: has to be set again.
_N, _R, _P = 2**14, 8, 1
_DKLEN = 32
#: scrypt's own guard against a caller asking for more memory than it meant to.
#: The default ceiling is below what `_N` above needs, so it has to be raised
#: here or every derivation is a `ValueError` — and the failure would be at the
#: door, on the first login, in production.
_MAXMEM = 64 * 1024 * 1024
#: How many wrong answers before the door slows down, and how slow it gets.
#: Five is past a typo and a stale password manager entry, and short of anything
#: systematic. The delay then doubles per failure to a quarter of an hour —
#: enough that guessing is pointless, little enough that locking yourself out on
#: a Sunday is not a crisis.
_GRACE = 5
_FIRST_LOCK = timedelta(seconds=30)
_MAX_LOCK = timedelta(minutes=15)
#: How many doublings can still change the answer. Derived from the two above
#: rather than written down, so re-tuning either of them cannot silently move
#: the ceiling. See `_lockout` for what goes wrong without it.
_MAX_STEPS = math.ceil(math.log2(_MAX_LOCK / _FIRST_LOCK))
#: How stale `last_seen_at` may get before a request bothers to update it.
#: Without this, every single request — every socket frame's sibling fetch,
#: every poll of a page left open — takes SQLite's write lock to move a
#: timestamp nobody reads more precisely than "today", and contends with a
#: worker trying to write actual data. Five minutes is far finer than the
#: account screen's "last seen" line can usefully show.
_SEEN_EVERY = timedelta(minutes=5)
#: The tables. Created on construction rather than by a migration step, because
#: the only schema change this has ever had is "it did not exist yet", and a
#: migration runner for four `CREATE TABLE IF NOT EXISTS` is a thing to
#: maintain in exchange for nothing.
SCHEMA = """
CREATE TABLE IF NOT EXISTS auth_credential (
id INTEGER PRIMARY KEY CHECK (id = 1),
salt BLOB NOT NULL,
hash BLOB NOT NULL,
updated_at TEXT NOT NULL,
failures INTEGER NOT NULL DEFAULT 0,
locked_until TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS auth_sessions (
id INTEGER PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
label TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
last_seen_at TEXT NOT NULL,
expires_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS auth_passkeys (
id INTEGER PRIMARY KEY,
credential_id BLOB NOT NULL UNIQUE,
public_key BLOB NOT NULL,
sign_count INTEGER NOT NULL DEFAULT 0,
transports TEXT NOT NULL DEFAULT '',
label TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
last_used_at TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS auth_challenges (
challenge BLOB PRIMARY KEY,
purpose TEXT NOT NULL,
expires_at TEXT NOT NULL
);
"""
def _now() -> datetime:
return datetime.now(UTC)
def _stamp(when: datetime) -> str:
return when.isoformat()
def _token_hash(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def _derive(password: str, salt: bytes) -> bytes:
return hashlib.scrypt(password.encode(), salt=salt, n=_N, r=_R, p=_P,
dklen=_DKLEN, maxmem=_MAXMEM)
class AuthStore:
"""The four `auth_*` tables, opened on the path it is handed.
store = AuthStore("data/app.db")
Its own connections, opened per call and closed after, rather than one held
open: SQLite in WAL mode is happy with that, a connection per call cannot be
shared across threads by accident, and the middleware runs this on a worker
thread from an async request.
"""
def __init__(self, path: str | os.PathLike[str]) -> None:
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
with closing(self._connect()) as conn, conn:
conn.executescript(SCHEMA)
def _connect(self) -> sqlite3.Connection:
conn = sqlite3.connect(self.path, timeout=10)
conn.row_factory = sqlite3.Row
# WAL so a login is not blocked by whatever else is writing to this
# file — the job queue, most likely, which writes constantly.
conn.execute("PRAGMA journal_mode=WAL")
return conn
# -------------------------------------------------------------- password
def has_password(self) -> bool:
"""Whether this database has ever had one set. False on a fresh file,
which is what makes the app print a generated one at startup."""
with closing(self._connect()) as conn:
return conn.execute(
"SELECT 1 FROM auth_credential WHERE id=1").fetchone() is not None
def set_password(self, password: str) -> None:
"""Set or replace it. A fresh salt every time, so setting the same
password twice does not produce the same row — which is what stops the
file from answering "did it change?" to anyone who kept a copy.
Deliberately does not close existing sessions. Whether a password
change should sign your other devices out is a policy question with a
real answer either way, and it belongs to the caller that knows why the
password is changing; `auth/router.py` decides.
"""
salt = secrets.token_bytes(16)
with closing(self._connect()) as conn, conn:
conn.execute(
"""INSERT INTO auth_credential
(id, salt, hash, updated_at, failures, locked_until)
VALUES (1, ?, ?, ?, 0, '')
ON CONFLICT(id) DO UPDATE SET
salt=excluded.salt, hash=excluded.hash,
updated_at=excluded.updated_at, failures=0, locked_until=''""",
(salt, _derive(password, salt), _stamp(_now())),
)
def locked_for(self) -> int:
"""Seconds until the next attempt will be looked at, or 0.
Read before checking rather than after, so a locked-out caller is told
to wait instead of having a guess counted — otherwise a fast enough
attacker extends their own lockout forever and never notices, and, more
to the point, an honest person hammering the button digs a deeper hole
with every press.
"""
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT locked_until FROM auth_credential WHERE id=1").fetchone()
if row is None or not row["locked_until"]:
return 0
remaining = datetime.fromisoformat(row["locked_until"]) - _now()
return max(0, int(remaining.total_seconds() + 0.999))
def check_password(self, password: str) -> bool:
"""Right or wrong, and record which.
`hmac.compare_digest` rather than `==`, so the comparison takes the same
time whatever the first wrong byte is. That is close to superstition at
this scale — the network jitter in front of it is larger than the signal
— but it is one call, and the habit is worth more than the microseconds.
Note that a wrong answer still costs a full scrypt derivation, including
on a database with no password set at all. That is the point: the delay
an attacker meets is the same one the honest user meets, and it is the
reason `_GRACE` can be as generous as it is.
**There is one counter, not one per caller, and that is on purpose.**
The obvious improvement is to lock out the address that is guessing
instead of the password, so that a stranger cannot keep the owner
waiting at their own door. It cannot be built honestly here. The only
address this app can see is the one its proxy puts in a header — the
peer is a container on the same Docker network — and a header is set by
whoever is talking. Keyed on that, an attacker gets a fresh, empty
counter per request by changing one line of their own request, while the
owner still gets locked out by their own typos: strictly worse than
this, and it would look like protection. So the address is written to
the log instead, at WARNING, where fail2ban can act on it at the layer
that actually knows who connected — see `_warn` in `auth/router.py`.
What is left for this counter to do is make guessing pointless, which it
does whoever is guessing.
"""
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT salt, hash, failures FROM auth_credential WHERE id=1"
).fetchone()
if row is None:
_derive(password, b"no password here")
return False
ok = hmac.compare_digest(_derive(password, row["salt"]), row["hash"])
with conn:
if ok:
conn.execute(
"UPDATE auth_credential SET failures=0, locked_until='' WHERE id=1")
else:
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 ""),
)
return ok
def changed_at(self) -> str:
"""When the password was last set, for the account screen to show."""
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT updated_at FROM auth_credential WHERE id=1").fetchone()
return row["updated_at"] if row else ""
# -------------------------------------------------------------- sessions
def open_session(self, label: str, days: int) -> str:
"""A new session. Returns the raw token — the only time it exists.
`token_urlsafe(32)` is 256 bits from the OS CSPRNG, which is past
anybody's ability to guess and short enough to sit in a cookie.
"""
token = secrets.token_urlsafe(32)
started = _now()
with closing(self._connect()) as conn, conn:
conn.execute(
"""INSERT INTO auth_sessions
(token_hash, label, created_at, last_seen_at, expires_at)
VALUES (?,?,?,?,?)""",
(_token_hash(token), label[:200], _stamp(started), _stamp(started),
_stamp(started + timedelta(days=days))),
)
return token
def touch(self, token: str) -> SessionInfo | None:
"""The session this token names, if it is live, marking it seen.
Expiry is enforced in the `WHERE`, so a session that has run out is
never returned even though its row is still there — the row is cleared
by `purge`, and until then it is simply not a session.
`last_seen_at` is what makes the sessions list worth reading: without it
every row says the same thing, and you cannot tell the laptop you use
daily from the phone you signed in on once. It is written at most once
every `_SEEN_EVERY` — this runs on every request there is, and a
timestamp is not worth the write lock.
"""
digest = _token_hash(token)
now = _now()
stamp = _stamp(now)
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT * FROM auth_sessions WHERE token_hash=? AND expires_at > ?",
(digest, stamp),
).fetchone()
if row is None:
return None
seen = row["last_seen_at"]
if now - datetime.fromisoformat(seen) >= _SEEN_EVERY:
with conn:
conn.execute(
"UPDATE auth_sessions SET last_seen_at=? WHERE token_hash=?",
(stamp, digest))
seen = stamp
return _session(row, seen, current=True)
def sessions(self, current: str = "") -> list[SessionInfo]:
"""Every live session, most recently seen first, with this one flagged."""
digest = _token_hash(current) if current else ""
stamp = _stamp(_now())
with closing(self._connect()) as conn:
rows = conn.execute(
"""SELECT * FROM auth_sessions WHERE expires_at > ?
ORDER BY last_seen_at DESC, id DESC""", (stamp,)).fetchall()
return [_session(r, r["last_seen_at"], current=r["token_hash"] == digest)
for r in rows]
def close_session(self, token: str) -> None:
with closing(self._connect()) as conn, conn:
conn.execute("DELETE FROM auth_sessions WHERE token_hash=?",
(_token_hash(token),))
def close_by_id(self, session_id: int) -> bool:
"""Revoke one session from the account screen. By row id rather than by
token, because the screen has never seen a token and must not."""
with closing(self._connect()) as conn, conn:
cur = conn.execute("DELETE FROM auth_sessions WHERE id=?", (session_id,))
return cur.rowcount > 0
def close_all(self, keep: str = "") -> int:
"""Sign out everywhere, optionally sparing the caller's own session.
The whole reason sessions are rows rather than signed tokens. Returns
how many went, so the UI can say.
"""
with closing(self._connect()) as conn, conn:
if keep:
cur = conn.execute("DELETE FROM auth_sessions WHERE token_hash != ?",
(_token_hash(keep),))
else:
cur = conn.execute("DELETE FROM auth_sessions")
return cur.rowcount
# -------------------------------------------------------------- passkeys
def add_passkey(self, credential_id: bytes, public_key: bytes,
sign_count: int, transports: str, label: str) -> int:
"""Register one. Returns its row id.
`credential_id` is unique, so registering the same authenticator twice
is an error rather than a second row that would make "revoke this one"
ambiguous. The registration ceremony avoids reaching this by handing the
browser an `excludeCredentials` list — see `passkeys.register_options`.
"""
with closing(self._connect()) as conn, conn:
cur = conn.execute(
"""INSERT INTO auth_passkeys
(credential_id, public_key, sign_count, transports, label, created_at)
VALUES (?,?,?,?,?,?)""",
(credential_id, public_key, sign_count, transports,
label[:100], _stamp(_now())),
)
return int(cur.lastrowid or 0)
def passkeys(self) -> list[Passkey]:
"""Every registered authenticator, newest first. No key material: this
is what the account screen lists, and it has no use for a public key."""
with closing(self._connect()) as conn:
rows = conn.execute(
"SELECT * FROM auth_passkeys ORDER BY created_at DESC, id DESC").fetchall()
return [Passkey(id=r["id"], label=r["label"], created_at=r["created_at"],
last_used_at=r["last_used_at"],
transports=[t for t in r["transports"].split(",") if t])
for r in rows]
def passkey_ids(self) -> list[bytes]:
"""Raw credential ids, for the `allowCredentials` and
`excludeCredentials` lists the two ceremonies hand the browser."""
with closing(self._connect()) as conn:
return [r["credential_id"] for r in
conn.execute("SELECT credential_id FROM auth_passkeys")]
def passkey_for(self, credential_id: bytes) -> tuple[int, bytes, int] | None:
"""`(id, public_key, sign_count)` for the credential that just signed,
or None if this app has never seen it."""
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT id, public_key, sign_count FROM auth_passkeys WHERE credential_id=?",
(credential_id,),
).fetchone()
if row is None:
return None
return row["id"], row["public_key"], int(row["sign_count"])
def record_passkey_use(self, passkey_id: int, sign_count: int) -> None:
with closing(self._connect()) as conn, conn:
conn.execute(
"UPDATE auth_passkeys SET sign_count=?, last_used_at=? WHERE id=?",
(sign_count, _stamp(_now()), passkey_id))
def rename_passkey(self, passkey_id: int, label: str) -> bool:
with closing(self._connect()) as conn, conn:
cur = conn.execute("UPDATE auth_passkeys SET label=? WHERE id=?",
(label[:100], passkey_id))
return cur.rowcount > 0
def delete_passkey(self, passkey_id: int) -> bool:
with closing(self._connect()) as conn, conn:
cur = conn.execute("DELETE FROM auth_passkeys WHERE id=?", (passkey_id,))
return cur.rowcount > 0
# ------------------------------------------------------------ challenges
def remember_challenge(self, challenge: bytes, purpose: str,
seconds: int = 300) -> None:
"""Keep a handed-out challenge until it is answered or runs out.
Five minutes is the browser's own ceremony timeout with room to spare;
a challenge outliving that is one nobody is going to answer.
"""
with closing(self._connect()) as conn, conn:
# Expired, unanswered ceremonies must not accumulate until restart:
# the endpoint that hands them out needs no session.
conn.execute("DELETE FROM auth_challenges WHERE expires_at <= ?",
(_stamp(_now()),))
conn.execute(
"INSERT OR REPLACE INTO auth_challenges (challenge, purpose, expires_at) "
"VALUES (?,?,?)",
(challenge, purpose, _stamp(_now() + timedelta(seconds=seconds))))
def take_challenge(self, challenge: bytes, purpose: str) -> bool:
"""Spend it. True if it was outstanding for this purpose, and it is now
gone whether it was or not.
Single-use is the property that matters: without the delete, a captured
response could be replayed for as long as the challenge lived. The
`purpose` is checked too, so a challenge issued for registering cannot
be answered with a login.
"""
with closing(self._connect()) as conn, conn:
cur = conn.execute(
"DELETE FROM auth_challenges WHERE challenge=? AND purpose=? "
"AND expires_at > ?",
(challenge, purpose, _stamp(_now())))
return cur.rowcount > 0
def purge(self) -> int:
"""Drop sessions and challenges that have expired. Nothing depends on
this — `touch`, `sessions` and `take_challenge` all filter on expiry —
so it is housekeeping, run at startup, not a security boundary."""
stamp = _stamp(_now())
with closing(self._connect()) as conn, conn:
cur = conn.execute("DELETE FROM auth_sessions WHERE expires_at <= ?", (stamp,))
gone = cur.rowcount
conn.execute("DELETE FROM auth_challenges WHERE expires_at <= ?", (stamp,))
return gone
def _lockout(failures: int) -> timedelta:
"""30s on the fifth wrong answer, doubling, capped at a quarter hour.
The exponent is capped, not only the delay it produces. `2 ** steps` is an
ordinary Python int and will keep doubling happily past anything a
`timedelta` can hold, so a few dozen wrong answers in a row used to end in
an OverflowError raised out of `check_password` — which is a 500 on every
login attempt until a right password lands, from an attacker who only ever
sent wrong ones. Once the cap has won, further doublings are arithmetic
nobody reads.
"""
steps = min(failures - _GRACE, _MAX_STEPS)
return min(_FIRST_LOCK * (2 ** steps), _MAX_LOCK)
def _session(row: sqlite3.Row, last_seen: str, current: bool) -> SessionInfo:
return SessionInfo(
id=row["id"], label=row["label"], created_at=row["created_at"],
last_seen_at=last_seen, expires_at=row["expires_at"], current=current,
)
+174
View File
@@ -0,0 +1,174 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{name} &mdash; sign in</title>
<!-- 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,
and a login page that only looks right once something else exists is one
more thing to get working before you can get in. The CSS below is enough
on its own, and is overridden by anything the app loads after it. -->
{stylesheet}
<style>
:root { color-scheme: light dark; --ink: #1a1a1f; --paper: #fbfbfd; --line: #d9d9e3; --dim: #63636e; --bad: #b91c1c; }
@media (prefers-color-scheme: dark) {
:root { --ink: #e9e9ef; --paper: #15151a; --line: #33333d; --dim: #9a9aa8; --bad: #f87171; }
}
body.login {
margin: 0; min-height: 100dvh; display: grid; place-items: center;
background: var(--paper); color: var(--ink);
font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}
.signin { width: min(22rem, calc(100vw - 2rem)); padding: 1rem; text-align: center; }
.wordmark { font-size: 1.4rem; font-weight: 700; letter-spacing: 0.02em; margin-bottom: 1.25rem; }
.signin form { display: grid; gap: 0.5rem; text-align: left; }
.signin label { font-size: 0.85rem; color: var(--dim); }
.signin input[type=password] {
font: inherit; padding: 0.5rem 0.6rem; border-radius: 8px;
border: 1px solid var(--line); background: transparent; color: inherit;
}
.signin button {
font: inherit; padding: 0.45rem 0.9rem; border-radius: 8px; cursor: pointer;
border: 1px solid var(--line); background: transparent; color: inherit;
}
.signin button.go { border-color: transparent; background: #4f46e5; color: #fff; }
.signin button[disabled] { opacity: 0.55; cursor: progress; }
.orpass { margin-top: 1rem; display: grid; gap: 0.5rem; justify-items: center; }
.orpass span { color: var(--dim); font-size: 0.85rem; }
.why { margin-top: 1rem; color: var(--bad); }
/* `hidden` is a browser default of `display: none` and any class rule with a
* `display` in it beats that, so both of the elements this page hides need
* saying twice. Without it the passkey button is drawn on an app that has no
* passkeys, and pressing it 404s. */
[hidden] { display: none !important; }
</style>
</head>
<body class="login">
<!-- Its own page rather than an overlay on the app, because the app is the
thing being protected: serving its markup to someone who has not signed in
and hiding it with CSS would put the whole page in the source behind a lock
that is decoration. Nothing here is fetched from the API, and there is
nothing on this page a signed-out browser could not already see. -->
<main class="signin">
<div class="wordmark">{name}</div>
<form id="signin" autocomplete="on">
<!-- A hidden username field with a stable value. There is no username in
this application, but a password manager will not reliably offer to
save a lone password field, and the one it does save has nothing to key
on. This gives it a key without inventing a login. -->
<input type="text" name="username" value="{name}" autocomplete="username"
hidden aria-hidden="true" tabindex="-1">
<label for="password">Password</label>
<input type="password" id="password" name="password" required autofocus
autocomplete="current-password">
<button type="submit" class="go" id="go">Sign in</button>
</form>
<!-- Shown only when this app has a passkey registered *and* the browser can
use one. Hidden by default rather than shown and then removed, so a
browser that cannot do WebAuthn never flashes a button it will withdraw. -->
<div class="orpass" id="orpass" hidden>
<span>or</span>
<button type="button" class="passkey" id="use-passkey">Use a passkey</button>
</div>
<p class="why" id="why" role="alert" hidden></p>
</main>
<script src="/_auth/passkey.js"></script>
<script>
// The password half. The passkey half is `/_auth/passkey.js`, shared with the
// account element, because both need the same base64url conversions.
//
// This page has its own `post()` rather than the app's `api()` helper, and that
// is deliberate: `api()` answers a 401 by sending you here, and a login page
// that redirects to itself on a wrong password is one that silently clears the
// field and looks broken. It is also the one page that has to work before the
// app's own scripts are loaded at all.
const form = document.querySelector('#signin');
const why = document.querySelector('#why');
const go = document.querySelector('#go');
// Read from the address bar rather than posted into the page, so the value is
// never interpolated into markup. The server sanitises it again on the way back
// -- see `_safe_next` -- because this half runs on the attacker's side of the
// fence and proves nothing.
const next = new URLSearchParams(location.search).get('next') || '/';
function fail(message) {
why.textContent = message;
why.hidden = false;
}
// ------------------------------------------------------------------- passkey
// Substituted by `auth/router.py`: is there a passkey registered here at all.
const passkeysOffered = {passkeys};
if (passkeysOffered && window.passkey && window.passkey.supported()) {
const orpass = document.querySelector('#orpass');
const button = document.querySelector('#use-passkey');
orpass.hidden = false;
button.onclick = async () => {
why.hidden = true;
button.disabled = true;
button.textContent = 'Waiting for your passkey...';
try {
const options = await post('/login/passkey/options');
const signed = await window.passkey.get(options);
// Nothing to carry over: a passkey login always lands on the front page.
// `next` exists for the password form because a 401 redirect can carry a
// deep link, and this button is never reached that way.
location.assign((await post('/login/passkey', {credential: signed})).next || '/');
return;
} catch (err) {
fail(window.passkey.explain(err));
}
button.disabled = false;
button.textContent = 'Use a passkey';
};
}
// ------------------------------------------------------------------ password
async function post(path, body) {
const r = await fetch(path, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(body || {}),
});
if (!r.ok) {
let detail = '';
try { detail = (await r.json()).detail || ''; } catch { /* not JSON */ }
throw new Error(detail || `Sign-in failed (${r.status})`);
}
return r.json();
}
form.onsubmit = async (e) => {
e.preventDefault();
const password = document.querySelector('#password').value;
why.hidden = true;
go.disabled = true;
go.textContent = 'Signing in...';
try {
// `location.assign` rather than setting `.href` to the raw value: the
// server has already reduced `next` to a local path, and this keeps the
// navigation an ordinary one.
location.assign((await post('/login', {password, next})).next || '/');
} catch (err) {
fail(String(err).replace('Error: ', ''));
go.disabled = false;
go.textContent = 'Sign in';
form.password.select();
}
};
</script>
</body>
</html>
+20
View File
@@ -0,0 +1,20 @@
"""A package, so `from auth.tests import PASSWORD` works wherever pytest is run
from, and the two lines every module here needs live in one place rather than
in an importable `conftest`.
Excluded from the wheel by `pyproject.toml`: a module folder's tests travel
with the folder when it is copied into a project, not into an installed app.
"""
from __future__ import annotations
from typing import Any
#: Long enough to be a real password and fixed so a failure names it.
PASSWORD = "correct-horse-battery"
def sign_in(client: Any, password: str = PASSWORD, **body: object) -> Any:
"""Through the front door, which is a POST and not a form submit: the login
page is the only page here and it talks to this endpoint with `fetch`."""
return client.post("/login", json={"password": password, **body})
+79
View File
@@ -0,0 +1,79 @@
"""The fixtures: an app that wants a password, and the same one that does not.
The interesting question is asked twice. `locked` is an app that was told it
binds a real address and therefore wants a password; `open_app` is the same
code on loopback, which is what an app on a laptop is. The app itself is
`harness.py`, built here rather than imported, because this folder is not
allowed to reach for `app/`.
"""
from __future__ import annotations
from collections.abc import Callable, Iterator
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from auth import AuthStore
from auth.tests import PASSWORD, sign_in
from auth.tests.harness import build
@pytest.fixture(autouse=True)
def no_pinned_password(monkeypatch: pytest.MonkeyPatch) -> None:
"""The variable pins the password while it is set, which would quietly
change what half of these tests are testing. A test that wants it sets it."""
monkeypatch.delenv("APP_PASSWORD", raising=False)
@pytest.fixture
def make_client(tmp_path: Path) -> Iterator[Callable[..., TestClient]]:
"""`make_client(enabled="always")`: an app, its store seeded, a client on it.
A factory rather than a fixture per shape, because half the tests here are
about one setting being different, and a fixture per setting is a file of
fixtures nobody can hold in their head.
"""
clients: list[TestClient] = []
def make(*, host: str = "0.0.0.0", password: str | None = PASSWORD,
base_url: str = "http://testserver", **settings: object) -> TestClient:
db = tmp_path / f"auth{len(clients)}.db"
if password is not None:
AuthStore(db).set_password(password)
client = TestClient(build(db, host=host, **settings),
follow_redirects=False, base_url=base_url)
clients.append(client)
# Entered, so the lifespan runs and the bootstrap with it. Closed at
# the end of the test, which is what releases the SQLite file on
# Windows before pytest tries to delete the temp directory.
return client.__enter__()
yield make
for client in reversed(clients):
client.__exit__(None, None, None)
@pytest.fixture
def store(tmp_path: Path) -> AuthStore:
return AuthStore(tmp_path / "store.db")
@pytest.fixture
def locked(make_client: Callable[..., TestClient]) -> TestClient:
"""An app that wants a password, with one already set."""
return make_client(enabled="always")
@pytest.fixture
def open_app(make_client: Callable[..., TestClient]) -> TestClient:
"""The same app on loopback under `auto` — no password asked for."""
return make_client(enabled="auto", host="127.0.0.1", password=None)
@pytest.fixture
def signed_in(locked: TestClient) -> TestClient:
"""The locked app, already through the door."""
assert sign_in(locked).status_code == 200
return locked
+68
View File
@@ -0,0 +1,68 @@
"""An app to lock, built here rather than imported.
`auth/` has to survive being copied into a project that has never heard of this
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
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.
That is this file, and it is nine routes.
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
twice in one test.
"""
from __future__ import annotations
import os
from fastapi import FastAPI, WebSocket
from fastapi.responses import PlainTextResponse
from auth import AuthConfig, AuthStore, connect
def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
**settings: object) -> FastAPI:
"""One app, locked or not depending on what it is told the server binds."""
app = FastAPI()
connect(app, AuthStore(db), AuthConfig(**settings), host=host,
open=("/static/",), stylesheet="/static/app.css")
@app.get("/", response_class=PlainTextResponse)
def front() -> str:
return "the front page"
@app.get("/deep/page", response_class=PlainTextResponse)
def deep() -> str:
return "a page someone bookmarked"
@app.get("/api/thing")
def thing() -> dict[str, bool]:
return {"ok": True}
@app.get("/health")
def health() -> dict[str, bool]:
return {"ok": True}
# The neighbours, so "matched whole, not as a prefix" is proved against
# routes that exist rather than against two 404s.
@app.get("/healthz")
def healthz() -> dict[str, bool]:
return {"ok": True}
@app.get("/loginx", response_class=PlainTextResponse)
def loginx() -> str:
return "not the login page"
@app.get("/static/app.css", response_class=PlainTextResponse)
def stylesheet() -> str:
return "body { }"
@app.websocket("/ws/jobs")
async def socket(ws: WebSocket) -> None:
await ws.accept()
await ws.send_json({"type": "jobs"})
await ws.close()
return app
+169
View File
@@ -0,0 +1,169 @@
"""A WebAuthn authenticator in software, so the ceremony can be tested.
Passkeys cannot be exercised the way the rest of this package can. There is no
HTTP call to fake: the interesting half runs inside a browser, talking to a
secure enclave or a stick in a USB port, and neither is available to pytest.
The usual answer is to test the two endpoints for their status codes, assert
nothing about what they actually verify, and find out whether any of it works
after deploying. That is not a test, and this is the alternative.
`SoftKey` is a real authenticator that happens to live in this file. It holds a
P-256 key, and it produces exactly the bytes a hardware key produces -- the same
CBOR attestation object, the same authenticator data with the same flags and
counter, the same ECDSA signature over the same concatenation. `py_webauthn`
verifies it because there is nothing to tell apart: the library's checks are
cryptographic, and this satisfies them by doing the cryptography.
What that buys is that every server-side branch is covered for real. A wrong
origin fails because the signature covers the origin. A replayed response fails
because the challenge is gone. A cloned key is caught because the counter went
backwards. None of those are simulated.
What it cannot cover is the browser's own half: that it refuses insecure
origins, that it will not hand a credential to the wrong site, that the user was
actually asked. Those are the browser's promises, they are the reason passkeys
are worth having, and they are not ours to test.
`cbor2` and `cryptography` are `webauthn`'s own dependencies, so this file
costs the project nothing it did not already have with the extra installed --
and nothing at all without it, since the module that imports this one skips
first.
Reference: WebAuthn Level 3, section 6.1 (authenticator data) and 6.5.4
(packed/none attestation). The layouts below are that spec and nothing else.
"""
from __future__ import annotations
import hashlib
import json
import os
import struct
from base64 import urlsafe_b64encode
from typing import Any
import cbor2
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
#: Flags byte of authenticator data. UP is "a user was present" (they touched
#: it), UV is "a user was verified" (PIN or fingerprint), AT is "attested
#: credential data follows", which is set on registration and never after.
UP, UV, AT = 0x01, 0x04, 0x40
def b64(raw: bytes) -> str:
"""base64url, unpadded -- what WebAuthn puts every byte string in."""
return urlsafe_b64encode(raw).decode().rstrip("=")
class SoftKey:
"""One authenticator holding one credential.
Construct it, `register()` against a challenge, then `sign()` challenges
with it. `sign_count` increments the way a security key's does; pass
`counts=False` to imitate a platform passkey, which is the case that makes
the clone check inapplicable.
"""
def __init__(self, *, sign_count: int = 0, counts: bool = True) -> None:
self.key = ec.generate_private_key(ec.SECP256R1())
self.credential_id = os.urandom(32)
self.sign_count = sign_count
#: Whether the counter moves. A real security key's does; most platform
#: passkeys report a constant 0 and opt out of clone detection.
self.counts = counts
# ------------------------------------------------------------------ keys
def cose_key(self) -> bytes:
"""The public key as a COSE_Key map -- the format `authData` carries.
`1: 2` is key type EC2, `3: -7` is ES256, and `-1: 1` is the P-256
curve; `-2`/`-3` are the affine coordinates, each padded to exactly 32
bytes because a leading zero byte is significant here and `int.to_bytes`
is the only thing that reliably keeps it.
"""
numbers = self.key.public_key().public_numbers()
return cbor2.dumps({
1: 2, 3: -7, -1: 1,
-2: numbers.x.to_bytes(32, "big"),
-3: numbers.y.to_bytes(32, "big"),
})
# --------------------------------------------------------- the ceremonies
def register(self, challenge: bytes, rp_id: str, origin: str,
transports: list[str] | None = None) -> dict[str, Any]:
"""Answer a creation challenge. Returns what `create().toJSON()` would."""
auth_data = (
hashlib.sha256(rp_id.encode()).digest() # rpIdHash
+ bytes([UP | UV | AT]) # flags
+ struct.pack(">I", self.sign_count) # signCount, big-endian
+ b"\x00" * 16 # AAGUID: none, per `none`
+ struct.pack(">H", len(self.credential_id))
+ self.credential_id
+ self.cose_key()
)
attestation = cbor2.dumps(
{"fmt": "none", "attStmt": {}, "authData": auth_data})
return {
"id": b64(self.credential_id),
"rawId": b64(self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": b64(self._client_data("webauthn.create",
challenge, origin)),
"attestationObject": b64(attestation),
"transports": transports or ["internal"],
},
"clientExtensionResults": {},
}
def sign(self, challenge: bytes, rp_id: str, origin: str) -> dict[str, Any]:
"""Answer an authentication challenge. `get().toJSON()`'s shape.
The signature covers `authenticatorData || SHA-256(clientDataJSON)`,
which is what binds one signature to one challenge *and* one origin --
change either and the same key produces a signature that will not
verify. That is the property the tests lean on.
"""
if self.counts:
self.sign_count += 1
auth_data = (
hashlib.sha256(rp_id.encode()).digest()
+ bytes([UP | UV]) # no AT: not a registration
+ struct.pack(">I", self.sign_count)
)
client_data = self._client_data("webauthn.get", challenge, origin)
signature = self.key.sign(
auth_data + hashlib.sha256(client_data).digest(),
ec.ECDSA(hashes.SHA256()),
)
return {
"id": b64(self.credential_id),
"rawId": b64(self.credential_id),
"type": "public-key",
"response": {
"clientDataJSON": b64(client_data),
"authenticatorData": b64(auth_data),
"signature": b64(signature),
"userHandle": b64(b"app"),
},
"clientExtensionResults": {},
}
@staticmethod
def _client_data(ceremony: str, challenge: bytes, origin: str) -> bytes:
"""What the *browser* would assemble and the authenticator signs over.
`crossOrigin` is included because real browsers include it, and the
point of this class is to produce bytes that are not distinguishable
from a real one's.
"""
return json.dumps({
"type": ceremony,
"challenge": b64(challenge),
"origin": origin,
"crossOrigin": False,
}).encode()
+489
View File
@@ -0,0 +1,489 @@
"""The door: who gets past it, what a refusal looks like, and the cookie.
uv run pytest auth/tests/test_door.py -q
"""
from __future__ import annotations
import logging
import sqlite3
from collections.abc import Callable
from contextlib import closing
from urllib.parse import parse_qs, urlsplit
import pytest
from fastapi.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from auth import AuthStore
from auth.middleware import OPEN
from auth.tests import PASSWORD, sign_in
from auth.tests.harness import build
# ---------------------------------------------------------- the open door
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."""
assert open_app.get("/").status_code == 200
assert open_app.get("/api/thing").status_code == 200
with open_app.websocket_connect("/ws/jobs") as socket:
assert socket.receive_json()["type"] == "jobs"
def test_the_account_says_it_is_open(open_app: TestClient):
assert open_app.get("/api/account").json()["locked"] is False
def test_the_login_page_bounces_when_there_is_no_door(open_app: TestClient):
"""A form that would replace a session you do not need."""
page = open_app.get("/login")
assert page.status_code == 303
assert sign_in(open_app).status_code == 400
def test_never_is_open_off_loopback_too(make_client: Callable[..., TestClient]):
"""`never` means exactly what it says: something else is doing the
authentication, and this is not second-guessing it."""
client = make_client(enabled="never", host="0.0.0.0")
assert client.get("/api/thing").status_code == 200
# -------------------------------------------------------- the locked door
def test_everything_is_shut(locked: TestClient):
"""Deny by default: the API, the page, and the one worth naming --
`/openapi.json` is every path, every payload shape and every field name of
the application, handed to whoever asks. It is a GET of something that is
not an API path, so the refusal is the redirect a browser wants."""
assert locked.get("/api/thing").status_code == 401
assert locked.get("/deep/page").status_code == 303
assert locked.get("/openapi.json").status_code == 303
def test_a_page_is_redirected_and_an_api_call_is_not(locked: TestClient):
"""A browser gets sent to the form; a fetch gets a 401 it can act on --
a login page arriving where JSON was asked for is a 200 full of HTML."""
page = locked.get("/")
assert page.status_code == 303
assert page.headers["location"] == "/login"
refused = locked.get("/api/thing")
assert refused.status_code == 401
assert refused.json() == {"detail": "Not signed in"}
assert "application/json" in refused.headers["content-type"]
def test_a_deep_link_survives_the_login_intact(locked: TestClient):
"""`next` is carried in a query string, so a path holding a `&` or a `%`
has to be escaped on the way to the login page -- or it arrives truncated,
or as a different path than the one that was asked for."""
sent = locked.get("/items/a&b%25c")
assert sent.status_code == 303
where = sent.headers["location"]
assert where.startswith("/login?next=")
# What `URLSearchParams` on the login page will read out of that query.
target = parse_qs(urlsplit(where).query)["next"][0]
assert target == "/items/a&b%c"
assert sign_in(locked, next=target).json()["next"] == "/items/a&b%c"
def test_the_open_list_is_the_four_doors_it_says_it_is(locked: TestClient):
"""Deny-by-default is only as good as the list of exceptions is short, so
the list is asserted rather than trusted, and an entry has to be argued for
here before it ships. Four: `/login` and the passkey ceremony under
`/login/`, because there is no other way in; `/_auth/`, which is the two
scripts those pages are; and `/health`, because a proxy's probe has no
session to offer and a healthcheck that needs one is a healthcheck that
reports the login page."""
assert OPEN == ("/login", "/login/", "/_auth/", "/health")
def test_an_open_name_is_matched_whole_and_a_slash_is_a_prefix(locked: TestClient):
"""`/health` does not open `/healthz`, and `/login` does not open
`/loginx` -- both of which are real routes here, so this is a refusal and
not a 404 wearing one."""
assert locked.get("/health").status_code == 200
assert locked.get("/static/app.css").status_code == 200
assert locked.get("/_auth/account.js").status_code == 200
assert locked.post("/login/passkey/options").status_code != 401
assert locked.get("/healthz").status_code == 303
assert locked.get("/loginx").status_code == 303
def test_the_login_page_draws_no_passkey_button_without_a_passkey(locked: TestClient):
"""Two halves, and the second one is why this test exists at all.
The flag is substituted false, so the script never unhides the button --
and the button is `hidden`, which is a browser default of `display: none`
that *any* class rule carrying a `display` overrides. `.orpass` sets
`display: grid`, so the first version of this page offered "Use a passkey"
on an app with no passkeys, and pressing it 404s.
"""
page = locked.get("/login").text
assert "const passkeysOffered = false;" in page
assert "[hidden] { display: none !important; }" in page
def test_a_query_string_cannot_widen_the_open_list(locked: TestClient):
assert locked.get("/api/thing?next=/health").status_code == 401
def test_the_websocket_is_shut_too(locked: TestClient):
"""The reason this is a middleware and not a dependency. A route
dependency would not cover the socket, and the socket is where an app
streams the state of everything it is doing."""
with pytest.raises(WebSocketDisconnect), locked.websocket_connect("/ws/jobs"):
pass
def test_the_websocket_opens_with_a_session(locked: TestClient):
sign_in(locked)
with locked.websocket_connect("/ws/jobs") as socket:
assert socket.receive_json()["type"] == "jobs"
def test_a_wrong_password_is_refused(locked: TestClient):
assert sign_in(locked, "nope").status_code == 401
assert locked.get("/api/thing").status_code == 401
def test_signing_in_opens_everything(locked: TestClient):
assert sign_in(locked).status_code == 200
assert locked.get("/api/thing").status_code == 200
assert locked.get("/").status_code == 200
def test_logout_ends_the_session(signed_in: TestClient):
assert signed_in.post("/logout").status_code == 200
assert signed_in.get("/api/thing").status_code == 401
def test_next_stays_inside_the_app(locked: TestClient):
r"""An open redirect is a real login page, a real sign-in, and someone
else's site afterwards.
The backslash is the one that gets through: a browser parses `/\evil.com`
as `//evil.com`, and the address bar hands `%5C` to the page already
decoded -- so neither is the local path a leading-slash test reads them as.
"""
for target in ("//evil.example.com/", "/\\evil.example.com",
"/%5Cevil.example.com", "https://evil.example.com",
"\\\\evil.example.com", "/\t/evil.example.com"):
assert sign_in(locked, next=target).json()["next"] == "/", target
assert sign_in(locked, next="/deep/page?x=1").json()["next"] == "/deep/page?x=1"
# ------------------------------------------------------------- the cookie
def cookies(response) -> list[str]:
"""The `Set-Cookie` headers, read off the wire.
Off the wire and not out of the jar, because the jar is a browser and does
the very thing under test: httpx refuses to store a `__Host-` cookie that
arrived over plain HTTP, so asking it what it kept cannot tell a correct
header apart from one it threw away.
"""
return [value.lower() for value in response.headers.get_list("set-cookie")]
def test_the_cookie_is_httponly_lax_and_not_secure_over_http(locked: TestClient):
"""An XSS must not be able to read it, another origin must not be able to
make the browser send it -- and a Secure cookie set over plain HTTP is one
the browser never sends back, which is an app nobody can sign in to."""
(sent,) = cookies(sign_in(locked))
assert sent.startswith("app_session=")
assert "httponly" in sent
assert "samesite=lax" in sent
assert "path=/" in sent
assert "secure" not in sent
assert "__host-" not in sent
def test_secure_cookie_always_sends_the_host_prefixed_name(
make_client: Callable[..., TestClient]):
"""`secure_cookie: always` is the setting for a proxy that terminates TLS,
where the app sees plain HTTP and `auto` would read as "no".
Both halves have to move together. `__Host-` is a promise to the browser
that the cookie is Secure, path `/` and carries no Domain, and a browser
silently drops one that is not -- which presents as a login that appears to
work and lands you back on the login page, with nothing in any log.
"""
client = make_client(enabled="always", secure_cookie="always")
(sent,) = cookies(sign_in(client))
assert sent.startswith("__host-app_session=")
assert "secure" in sent
assert "path=/" in sent
assert "domain=" not in sent
def test_a_renamed_cookie_is_used_under_both_names(
make_client: Callable[..., TestClient]):
"""The name is a setting because two apps from this boilerplate on one
hostname would otherwise share a cookie and sign each other out."""
client = make_client(enabled="always", cookie="other_session")
(sent,) = cookies(sign_in(client))
assert sent.startswith("other_session=")
assert client.get("/api/thing").status_code == 200
assert {v.split("=")[0] for v in cookies(client.post("/logout"))} == {
"other_session", "__host-other_session"}
def test_logout_clears_both_names(signed_in: TestClient):
"""Which name was set depends on `secure_cookie` and on the scheme the
login happened over, and neither is known here. Clearing only the one this
request would have set leaves the other in the browser, still offered on
every request -- a signed-out session the door goes on opening for."""
cleared = signed_in.post("/logout")
sent = cookies(cleared)
assert {value.split("=")[0] for value in sent} == {
"app_session", "__host-app_session"}
for value in sent:
assert "max-age=0" in value or "expires=thu, 01 jan 1970" in value
# ------------------------------------------------------------ the account
def test_the_account_lists_this_session(signed_in: TestClient):
account = signed_in.get("/api/account").json()
assert account["locked"] is True
assert account["pinned"] is False
assert sum(s["current"] for s in account["sessions"]) == 1
assert account["password_set_at"]
def test_revoked_elsewhere_means_locked_out_here(signed_in: TestClient):
"""The reason sessions are rows rather than signed tokens: a token that
carries its own claim cannot be taken back."""
account = signed_in.get("/api/account").json()
mine = next(s["id"] for s in account["sessions"] if s["current"])
assert signed_in.delete(f"/api/account/sessions/{mine}").status_code == 200
assert signed_in.get("/api/thing").status_code == 401
assert signed_in.delete(f"/api/account/sessions/{mine}").status_code == 401
def test_closing_the_others_keeps_this_one(signed_in: TestClient):
other = TestClient(signed_in.app, follow_redirects=False)
sign_in(other)
assert other.get("/api/thing").status_code == 200
closed = signed_in.post("/api/account/sessions/close")
assert closed.json() == {"signed_out": 1}
assert signed_in.get("/api/thing").status_code == 200
assert other.get("/api/thing").status_code == 401
def test_changing_the_password_needs_the_old_one(signed_in: TestClient):
bad = signed_in.post("/api/account/password",
json={"current": "wrong", "new": "a-much-longer-one"})
assert bad.status_code == 403
def test_the_first_password_is_set_without_a_current_one(open_app: TestClient):
"""The laptop before it is ever deployed: no password has ever been set,
and the account screen is where you set one. Asking for the current
password there is a field with no right answer, and the form could only
ever be refused -- which is what it did until this test existed. The app
that has a door never reaches this branch: `auth.bootstrap` gives a locked
app a password at startup, so there is always one to prove."""
assert open_app.get("/api/account").json()["password_set_at"] == ""
set_it = open_app.post("/api/account/password",
json={"current": "", "new": "a-much-longer-one"})
assert set_it.status_code == 200
assert open_app.get("/api/account").json()["password_set_at"]
# And the second change asks for the first, the way it always did.
again = open_app.post("/api/account/password",
json={"current": "", "new": "another-long-one"})
assert again.status_code == 403
def test_a_short_new_password_is_refused(signed_in: TestClient):
short = signed_in.post("/api/account/password",
json={"current": PASSWORD, "new": "short"})
assert short.status_code == 400
assert "8 characters" in short.json()["detail"]
def test_changing_it_keeps_you_in_and_signs_others_out(signed_in: TestClient):
"""If the reason you are changing the password is that someone may have it,
leaving their session open makes the change ceremonial."""
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"})
assert changed.status_code == 200
assert changed.json()["signed_out"] == 1
assert signed_in.get("/api/thing").status_code == 200
assert other.get("/api/thing").status_code == 401
signed_in.post("/logout")
assert sign_in(signed_in).status_code == 401
assert sign_in(signed_in, "a-much-longer-one").status_code == 200
def test_the_password_change_is_behind_the_same_lockout(signed_in: TestClient):
"""A session is not an unlimited number of guesses at the password.
`current` is the password, asked for at a second door, and a borrowed
unlocked laptop is the exact situation that field exists for -- so it is
counted and gated like the first door, or the lockout only ever covered the
half an attacker would not bother with.
"""
before = signed_in.get("/api/account").json()["password_set_at"]
for _ in range(5):
wrong = signed_in.post("/api/account/password",
json={"current": "nope", "new": "a-much-longer-one"})
assert wrong.status_code == 403
# The *right* current password now, which must not even be looked at.
refused = signed_in.post("/api/account/password",
json={"current": PASSWORD, "new": "a-much-longer-one"})
assert refused.status_code == 429
assert "Try again" in refused.json()["detail"]
assert refused.headers["retry-after"]
assert signed_in.get("/api/account").json()["password_set_at"] == before
# One credential, one counter: guessing at the account screen locks the
# front door too, which is the whole reason it is worth guessing there.
assert sign_in(signed_in).status_code == 429
# ------------------------------------------------------- the bootstrap
def test_a_generated_password_is_printed_once(
make_client: Callable[..., TestClient], caplog):
"""A locked app with no password invents one and prints it, rather than
starting with the door open or refusing to start at all."""
with caplog.at_level(logging.WARNING):
client = make_client(enabled="always", password=None)
printed = generated(caplog.text)
assert sign_in(client, printed).status_code == 200
def generated(text: str) -> str:
"""Pull the generated password back out of the startup banner. ASCII, so
this reads it the way a person reads it off `docker compose logs`."""
lines = [line.strip() for line in text.splitlines()]
marker = next(i for i, line in enumerate(lines) if "here is one" in line)
return next(line for line in lines[marker + 1:] if line and "-----" not in line)
def test_the_environment_pins_the_password(
make_client: Callable[..., TestClient], monkeypatch):
"""`APP_PASSWORD` is the way back in when a login is lost, and it can only
be that if it wins over what is stored: the case is a password changed in
the browser months ago, the variable set to something else, and a restart.
"""
monkeypatch.setenv("APP_PASSWORD", "the-one-from-the-environment")
client = make_client(enabled="always", password="the-one-set-in-the-browser")
assert sign_in(client, "the-one-set-in-the-browser").status_code == 401
assert sign_in(client, "the-one-from-the-environment").status_code == 200
account = client.get("/api/account").json()
assert account["pinned"] is True
# Named, so the screen can say which variable rather than leaving someone
# to go and find out.
assert account["pinned_by"] == "APP_PASSWORD"
def test_a_pinned_password_cannot_be_changed_from_the_browser(
make_client: Callable[..., TestClient], monkeypatch):
"""The variable is authoritative while it is set, so the screen that would
silently stop applying says so instead."""
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
client = make_client(enabled="always", password=None)
sign_in(client)
refused = client.post("/api/account/password",
json={"current": PASSWORD, "new": "a-much-longer-one"})
assert refused.status_code == 409
assert "APP_PASSWORD" in refused.json()["detail"]
def test_a_pinned_password_that_matches_is_not_written_again(monkeypatch, tmp_path):
"""Re-deriving on every start would make "password last changed" mean "last
restarted", which answers a different question than the one it is asked. A
restart is not a password change."""
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
db = tmp_path / "pinned.db"
with TestClient(build(db, enabled="always")):
pass
first = AuthStore(db).changed_at()
assert first, "the pinned password was never derived at all"
with TestClient(build(db, enabled="always"), follow_redirects=False) as client:
assert sign_in(client).status_code == 200
assert AuthStore(db).changed_at() == first, "a restart rewrote the hash"
def test_the_environment_variable_is_a_setting(
make_client: Callable[..., TestClient], monkeypatch):
"""`auth/` is copied into projects that are not called `app`."""
monkeypatch.setenv("OTHER_PASSWORD", "from-the-other-variable")
client = make_client(enabled="always", password=None,
password_env="OTHER_PASSWORD")
assert sign_in(client, "from-the-other-variable").status_code == 200
assert client.get("/api/account").json()["pinned_by"] == "OTHER_PASSWORD"
def test_expired_sessions_are_purged_at_startup(tmp_path):
"""Housekeeping, not a security boundary -- `touch` already refuses an
expired row. Without it the table grows forever."""
db = tmp_path / "purge.db"
store = AuthStore(db)
store.set_password(PASSWORD)
store.open_session("old", 30)
with closing(sqlite3.connect(db)) as conn, conn:
conn.execute("UPDATE auth_sessions SET expires_at='2000-01-01T00:00:00+00:00'")
with TestClient(build(db, enabled="always")):
pass
with closing(sqlite3.connect(db)) as conn:
assert conn.execute("SELECT COUNT(*) FROM auth_sessions").fetchone()[0] == 0
# ---------------------------------------------------------------- the log
def test_a_refused_login_says_who_it_was(locked: TestClient, caplog):
"""The only record of anyone knocking. If this line is not in the log then
nothing anywhere knows it happened."""
with caplog.at_level(logging.WARNING):
assert sign_in(locked, "nope").status_code == 401
# The logger is `auth.router`, so the line already says which package this
# came from and the message does not say it again.
assert "wrong password from testclient" in caplog.text
assert "auth: wrong password" not in caplog.text
def test_a_refused_password_change_says_so_too(signed_in: TestClient, caplog):
with caplog.at_level(logging.WARNING):
signed_in.post("/api/account/password",
json={"current": "nope", "new": "a-much-longer-one"})
assert "wrong current password" in caplog.text
def test_the_log_prefers_the_address_the_proxy_passed_on(locked: TestClient, caplog):
"""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
is only as good as whoever sent it -- which is also why nothing is decided
from it."""
with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": "203.0.113.9, 10.9.9.9"})
assert "203.0.113.9 via testclient" in caplog.text
def test_a_forwarded_address_cannot_write_the_log_itself(locked: TestClient, caplog):
"""That header is a stranger's own writing on its way into a file that
fail2ban reads and a person believes, so only the characters an address is
made of survive the trip -- one line per refusal, whatever was sent."""
with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": "9.9.9.9 auth: signed in from 1.1.1.1"})
said = [r.getMessage() for r in caplog.records if r.name.startswith("auth")]
assert len(said) == 1
assert said[0].startswith("wrong password from 9.9.9.9")
assert "signed in" not in caplog.text
+373
View File
@@ -0,0 +1,373 @@
"""Passkeys, driven by a real authenticator that happens to be in software.
`softkey.py` says why this is possible and what it does not cover. The short
version: the signatures here are real, so every check the server makes is
exercised for real -- a wrong origin fails because the origin is signed over, a
replay fails because the challenge is spent, a clone is caught because the
counter went backwards.
uv run pytest auth/tests/test_passkeys.py -q
Skipped wholesale without the `passkeys` extra. What the app does when the
extra is *missing* is `test_without_passkeys.py`, which always runs -- it has
to be, or the case is covered by nothing.
"""
from __future__ import annotations
from base64 import urlsafe_b64decode
from collections.abc import Callable
import pytest
from fastapi.testclient import TestClient
from auth.tests import PASSWORD, sign_in
pytest.importorskip("webauthn", reason="the `passkeys` extra is not installed")
from auth.tests.softkey import SoftKey, b64 # noqa: E402 after the skip
#: The tests talk to the app as `localhost`, which is the one host a browser
#: lets WebAuthn run on without HTTPS -- so it is also the one that exercises
#: the real `blocked()` path rather than a configured override.
RP_ID = "localhost"
ORIGIN = "http://localhost"
def unb64(text: str) -> bytes:
return urlsafe_b64decode(text + "=" * (-len(text) % 4))
@pytest.fixture
def client(make_client: Callable[..., TestClient]) -> TestClient:
"""A locked app the browser reaches as `localhost`."""
signed = make_client(enabled="always", base_url=ORIGIN)
assert sign_in(signed).status_code == 200
return signed
def register(client: TestClient, key: SoftKey, label: str = "Test key"):
"""The whole registration ceremony, both round trips."""
options = client.post("/api/account/passkeys/options").json()
made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN)
return client.post("/api/account/passkeys",
json={"credential": made, "label": label})
def login(client: TestClient, key: SoftKey, origin: str = ORIGIN):
"""The whole sign-in ceremony, both round trips."""
options = client.post("/login/passkey/options").json()
signed = key.sign(unb64(options["challenge"]), RP_ID, origin)
return client.post("/login/passkey", json={"credential": signed})
# --------------------------------------------------------------- registering
def test_registering_needs_a_session(client: TestClient):
"""A passkey is a new way in, so adding one is gated on already being in."""
client.post("/logout")
assert client.post("/api/account/passkeys/options").status_code == 401
def test_a_passkey_registers_and_is_listed(client: TestClient):
assert register(client, SoftKey(), label="YubiKey 5C").status_code == 200
account = client.get("/api/account").json()
assert [p["label"] for p in account["passkeys"]] == ["YubiKey 5C"]
assert account["passkeys"][0]["transports"] == ["internal"]
# No key material reaches the screen -- not even the public half.
assert "public_key" not in account["passkeys"][0]
def test_the_public_key_is_stored_and_the_private_one_is_not(client: TestClient):
key = SoftKey()
register(client, key)
# The private key never left the authenticator, so nothing derived from it
# can be in the file. Its public point, necessarily, is.
private = key.key.private_numbers().private_value.to_bytes(32, "big")
blob = client.app.state.auth.path.read_bytes()
assert private not in blob
assert key.credential_id in blob
def test_a_second_registration_is_excluded_not_duplicated(client: TestClient):
"""The browser is told what is already registered, so an authenticator can
say "you have one of these" rather than making a second."""
key = SoftKey()
register(client, key)
options = client.post("/api/account/passkeys/options").json()
assert [c["id"] for c in options["excludeCredentials"]] == [b64(key.credential_id)]
def test_a_stale_challenge_is_refused(client: TestClient):
"""A challenge is single-use, so the same response cannot be sent twice."""
key = SoftKey()
options = client.post("/api/account/passkeys/options").json()
made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN)
assert client.post("/api/account/passkeys", json={"credential": made}).status_code == 200
replay = client.post("/api/account/passkeys", json={"credential": made})
assert replay.status_code == 400
assert "already used" in replay.json()["detail"]
def test_a_challenge_this_server_never_issued_is_refused(client: TestClient):
"""The response is well-formed and correctly signed. It is still not ours."""
made = SoftKey().register(b"a challenge from nowhere", RP_ID, ORIGIN)
assert client.post("/api/account/passkeys",
json={"credential": made}).status_code == 400
# ---------------------------------------------------------------- signing in
def test_a_registered_passkey_signs_in(client: TestClient):
key = SoftKey()
register(client, key)
client.post("/logout")
assert client.get("/api/thing").status_code == 401
assert login(client, key).status_code == 200
assert client.get("/api/thing").status_code == 200
def test_a_passkey_session_is_an_ordinary_session(client: TestClient):
"""One kind of session whichever door it came through, so revoking and
expiry have one implementation rather than two."""
key = SoftKey()
register(client, key)
client.post("/logout")
login(client, key)
sessions = client.get("/api/account").json()["sessions"]
assert sum(s["current"] for s in sessions) == 1
client.post("/logout")
assert client.get("/api/thing").status_code == 401
def test_an_unregistered_key_is_refused(client: TestClient):
register(client, SoftKey())
client.post("/logout")
assert login(client, SoftKey()).status_code == 401
def test_a_signature_for_another_origin_is_refused(client: TestClient):
"""The heart of why a passkey cannot be phished: the origin is inside what
gets signed, so a signature made for one site is void at another."""
key = SoftKey()
register(client, key)
client.post("/logout")
assert login(client, key, origin="https://app.example.evil").status_code == 401
assert client.get("/api/thing").status_code == 401
def test_a_replayed_signature_is_refused(client: TestClient):
"""Captured off the wire and sent again -- the challenge is already spent."""
key = SoftKey()
register(client, key)
client.post("/logout")
options = client.post("/login/passkey/options").json()
signed = key.sign(unb64(options["challenge"]), RP_ID, ORIGIN)
assert client.post("/login/passkey", json={"credential": signed}).status_code == 200
client.post("/logout")
assert client.post("/login/passkey", json={"credential": signed}).status_code == 401
def test_a_cloned_key_is_caught(client: TestClient):
"""A counter that goes backwards means two authenticators are answering for
one credential. Only detectable when the authenticator uses the counter."""
key = SoftKey(counts=True)
register(client, key)
client.post("/logout")
assert login(client, key).status_code == 200
client.post("/logout")
key.sign_count = 0 # the clone, which started its own count
key.counts = False
refused = login(client, key)
assert refused.status_code == 401
assert "cloned" in refused.json()["detail"]
def test_a_platform_passkey_that_never_counts_still_works(client: TestClient):
"""Most phones report a constant 0. Treating that as a regression would
reject every real sign-in from one, so it must not."""
key = SoftKey(counts=False)
register(client, key)
client.post("/logout")
for _ in range(3):
assert login(client, key).status_code == 200
client.post("/logout")
def test_a_malformed_body_is_a_400_and_not_a_traceback(client: TestClient):
"""`webauthn` raises a whole family of exceptions and only one of them is
`InvalidAuthenticationResponse`. Catching that one and nothing else leaves a
body with a field missing to come out of an endpoint that needs no session
as a 500 with a stack trace in the log -- from anyone on the internet, as
often as they like.
"""
key = SoftKey()
register(client, key)
client.post("/logout")
options = client.post("/login/passkey/options").json()
signed = key.sign(unb64(options["challenge"]), RP_ID, ORIGIN)
del signed["response"]["authenticatorData"]
refused = client.post("/login/passkey", json={"credential": signed})
assert refused.status_code == 400
assert "not a passkey" in refused.json()["detail"]
# 400 and not 401: nothing here was a credential, so nothing was refused.
assert client.get("/api/thing").status_code == 401
assert client.post("/login/passkey", json={"credential": {}}).status_code == 400
def test_no_passkeys_registered_says_so(client: TestClient):
client.post("/logout")
assert client.post("/login/passkey/options").status_code == 404
# -------------------------------------------------- one purpose per challenge
def test_a_registration_challenge_cannot_be_answered_at_the_login_door(
client: TestClient):
"""A challenge is issued for one ceremony and is good for that one only.
Without the purpose check the two doors share one pool of random numbers,
and the door that needs no session can spend a challenge that was handed out
behind one. Everything else about the response is real here -- a registered
key, a live challenge, a signature this server would accept -- so the
purpose is the only thing standing between the two.
"""
key = SoftKey()
register(client, key)
theirs = client.post("/api/account/passkeys/options").json()
client.post("/logout")
signed = key.sign(unb64(theirs["challenge"]), RP_ID, ORIGIN)
assert client.post("/login/passkey", json={"credential": signed}).status_code == 401
assert client.get("/api/thing").status_code == 401
def test_a_login_challenge_cannot_be_answered_at_the_registration_door(
client: TestClient):
"""The same rule the other way round, which is the half that is easy to
forget: `/login/passkey/options` needs no session, so its challenges are the
ones a stranger can have as many of as they like."""
key = SoftKey()
register(client, key)
theirs = client.post("/login/passkey/options").json()
made = key.register(unb64(theirs["challenge"]), RP_ID, ORIGIN)
assert client.post("/api/account/passkeys",
json={"credential": made}).status_code == 400
def test_an_expired_challenge_is_refused(client: TestClient):
"""The bound on how long a captured `options` response is worth anything."""
key = SoftKey()
register(client, key)
client.post("/logout")
options = client.post("/login/passkey/options").json()
assert expire(client) == 1
signed = key.sign(unb64(options["challenge"]), RP_ID, ORIGIN)
refused = client.post("/login/passkey", json={"credential": signed})
assert refused.status_code == 401
assert "too long" in refused.json()["detail"]
assert client.get("/api/thing").status_code == 401
def expire(client: TestClient) -> int:
"""Backdate every outstanding challenge, as five minutes of doing nothing
would. Written rather than waited for: the alternative is a test that sleeps
for the ceremony timeout."""
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(client.app.state.auth.path)) as conn, conn:
return conn.execute("UPDATE auth_challenges SET expires_at=?",
("2000-01-01T00:00:00+00:00",)).rowcount
# ------------------------------------------------------------------ managing
def test_a_passkey_can_be_renamed_and_revoked(client: TestClient):
key = SoftKey()
passkey_id = register(client, key).json()["id"]
assert client.post(f"/api/account/passkeys/{passkey_id}/label",
json={"label": "The one on my keyring"}).status_code == 200
assert client.get("/api/account").json()["passkeys"][0]["label"] \
== "The one on my keyring"
assert client.delete(f"/api/account/passkeys/{passkey_id}").status_code == 200
assert client.get("/api/account").json()["passkeys"] == []
# Revoked means revoked. With none left there is nothing to sign with, so
# the ceremony stops at the first round trip rather than the second.
client.post("/logout")
assert client.post("/login/passkey/options").status_code == 404
def test_revoking_a_passkey_cannot_lock_you_out(client: TestClient):
"""The password stays, which is the whole reason revoking is safe."""
passkey_id = register(client, SoftKey()).json()["id"]
client.delete(f"/api/account/passkeys/{passkey_id}")
client.post("/logout")
assert sign_in(client).status_code == 200
def test_registering_does_not_disable_the_password(client: TestClient):
register(client, SoftKey())
client.post("/logout")
assert sign_in(client, PASSWORD).status_code == 200
# ------------------------------------------------------------- the settings
def test_localhost_is_a_secure_context(client: TestClient):
"""The one host a browser lets WebAuthn run on without HTTPS, so the
account screen must not claim otherwise."""
account = client.get("/api/account").json()
assert account["passkeys_available"] is True
assert account["passkeys_blocked"] == ""
def test_plain_http_off_localhost_is_refused_with_a_reason(
make_client: Callable[..., TestClient]):
"""The case that will actually happen: served over HTTP on a LAN address,
where the browser would refuse and surface nothing useful."""
client = make_client(enabled="always", base_url="http://192.168.1.10:8787")
sign_in(client)
said = client.get("/api/account").json()["passkeys_blocked"]
assert "HTTPS" in said
assert "192.168.1.10" in said
def test_a_configured_rp_id_and_origin_win(make_client: Callable[..., TestClient]):
"""What a deployment behind a TLS-terminating proxy needs: the app sees
plain HTTP and must still bind credentials to the real origin."""
client = make_client(enabled="always", rp_id="app.example.com",
origin="https://app.example.com")
sign_in(client)
options = client.post("/api/account/passkeys/options").json()
assert options["rp"]["id"] == "app.example.com"
assert client.get("/api/account").json()["passkeys_blocked"] == ""
key = SoftKey()
made = key.register(unb64(options["challenge"]),
"app.example.com", "https://app.example.com")
assert client.post("/api/account/passkeys",
json={"credential": made}).status_code == 200
def test_a_passkey_login_on_an_unlocked_app_is_a_400(open_app: TestClient):
"""There is no session to open when there is no door, and this must not
quietly hand one out anyway: that would be a second, unauthenticated way to
mint the very thing the middleware checks."""
refused = open_app.post("/login/passkey", json={"credential": {}})
assert refused.status_code == 400
assert "not password-protected" in refused.json()["detail"]
assert open_app.app.state.auth.sessions() == []
+227
View File
@@ -0,0 +1,227 @@
"""The file underneath the door: what it holds, and what it refuses to hold.
uv run pytest auth/tests/test_store.py -q
"""
from __future__ import annotations
import sqlite3
from contextlib import closing
from datetime import UTC, datetime, timedelta
from pathlib import Path
from auth import AuthStore
from auth.store import _GRACE, _MAX_LOCK, _lockout
from auth.tests import PASSWORD
def rows(store: AuthStore, sql: str) -> list[tuple]:
# `closing`, not `with conn:` alone -- that only commits, and a connection
# left open is a file Windows will not let a temp dir delete.
with closing(sqlite3.connect(store.path)) as conn:
return [tuple(r) for r in conn.execute(sql)]
# ------------------------------------------------------------- what is stored
def test_the_password_is_not_in_the_file(store: AuthStore):
"""The point of the whole exercise."""
store.set_password(PASSWORD)
assert PASSWORD.encode() not in store.path.read_bytes()
assert store.check_password(PASSWORD) is True
def test_a_session_token_is_not_in_the_file_either(store: AuthStore):
token = store.open_session("pytest", 30)
assert token.encode() not in store.path.read_bytes()
assert store.touch(token) is not None
def test_the_salt_differs_per_set(store: AuthStore):
"""Setting the same password twice must not produce the same row, or the
file answers "did it change?" to anyone holding an old copy."""
store.set_password(PASSWORD)
first = rows(store, "SELECT salt, hash FROM auth_credential")
store.set_password(PASSWORD)
assert rows(store, "SELECT salt, hash FROM auth_credential") != first
assert store.check_password(PASSWORD) is True
def test_the_tables_are_namespaced(store: AuthStore):
"""They share a file with the app's own tables and the job queue's, so a
plain `sessions` is a name this package is not entitled to take."""
named = {name for (name,) in rows(
store, "SELECT name FROM sqlite_master WHERE type='table'")}
assert {"auth_credential", "auth_sessions", "auth_passkeys",
"auth_challenges"} <= named
assert not {n for n in named if not n.startswith(("auth_", "sqlite_"))}
def test_a_database_with_no_password_refuses_without_raising(store: AuthStore):
"""And it still costs a derivation, so "is there a password here at all"
is not a question the door answers by being quick about it."""
assert store.has_password() is False
assert store.check_password(PASSWORD) is False
# -------------------------------------------------------------- the lockout
def test_five_wrong_answers_are_free_and_the_sixth_is_not(store: AuthStore):
store.set_password(PASSWORD)
for _ in range(_GRACE - 1):
assert store.check_password("wrong") is False
assert store.locked_for() == 0, "the grace ran out early"
assert store.check_password("wrong") is False
assert store.locked_for() > 0
def test_the_right_password_clears_it(store: AuthStore):
"""A lockout is a delay on guessing, not a second thing to recover from."""
store.set_password(PASSWORD)
for _ in range(_GRACE):
store.check_password("wrong")
assert store.locked_for() > 0
assert store.check_password(PASSWORD) is True
assert store.locked_for() == 0
def test_the_lockout_is_read_before_the_check_not_after(store: AuthStore):
"""The order the whole thing turns on: `locked_for` is a question about the
file as it stands, so a caller can be told to wait *instead of* having a
guess counted. Were it read after, every press while locked out would
extend the lockout -- which punishes the owner hammering the button far
harder than the attacker who is not watching.
"""
store.set_password(PASSWORD)
for _ in range(_GRACE):
store.check_password("wrong")
waiting = store.locked_for()
assert waiting > 0
# Asking twice does not move it. Nothing in `locked_for` writes.
assert store.locked_for() == waiting
assert rows(store, "SELECT failures FROM auth_credential") == [(_GRACE,)]
def test_the_delay_doubles_and_then_stops(store: AuthStore):
"""Capped at the exponent, not only at the delay it produces: `2 ** steps`
goes on growing after the cap has stopped mattering, and sixty wrong
answers used to overflow the `timedelta` and raise out of `check_password`
-- a 500 on every login attempt, from an attacker who only ever sent wrong
passwords."""
assert _lockout(_GRACE) == timedelta(seconds=30)
assert _lockout(_GRACE + 1) == timedelta(seconds=60)
assert _lockout(_GRACE + 200) == _MAX_LOCK
store.set_password(PASSWORD)
for _ in range(60):
assert store.check_password("wrong") is False
assert 0 < store.locked_for() <= _MAX_LOCK.total_seconds()
assert store.check_password(PASSWORD) is True
# -------------------------------------------------------------- the sessions
def test_a_session_is_live_until_it_is_not(store: AuthStore):
token = store.open_session("pytest", 30)
session = store.touch(token)
assert session is not None and session.current is True
assert [s.label for s in store.sessions()] == ["pytest"]
def test_an_expired_session_is_not_a_session(store: AuthStore):
"""Expiry is enforced in the `WHERE`, not by the sweep: a row that has run
out stops working the moment it does, whether or not anything purged it."""
token = store.open_session("pytest", 30)
with closing(sqlite3.connect(store.path)) as conn, conn:
conn.execute("UPDATE auth_sessions SET expires_at='2000-01-01T00:00:00+00:00'")
assert store.touch(token) is None
assert store.sessions() == []
assert store.purge() == 1
assert rows(store, "SELECT id FROM auth_sessions") == []
def test_revoking_one_session_leaves_the_others(store: AuthStore):
mine = store.open_session("mine", 30)
theirs = store.open_session("phone", 30)
(row,) = [s for s in store.sessions(mine) if not s.current]
assert store.close_by_id(row.id) is True
assert store.close_by_id(row.id) is False, "a second revoke invented a row"
assert store.touch(theirs) is None
assert store.touch(mine) is not None
def test_close_all_can_spare_the_caller(store: AuthStore):
"""The whole reason sessions are rows rather than signed tokens."""
mine = store.open_session("mine", 30)
store.open_session("phone", 30)
store.open_session("laptop", 30)
assert store.close_all(keep=mine) == 2
assert [s.label for s in store.sessions(mine)] == ["mine"]
assert store.close_all() == 1
assert store.sessions() == []
def test_the_current_session_is_flagged_and_only_that_one(store: AuthStore):
mine = store.open_session("mine", 30)
store.open_session("phone", 30)
assert sum(s.current for s in store.sessions(mine)) == 1
assert sum(s.current for s in store.sessions()) == 0
def test_last_seen_is_not_written_on_every_touch(store: AuthStore):
"""This runs on every request there is. A timestamp nobody reads more
precisely than "today" is not worth SQLite's write lock."""
token = store.open_session("pytest", 30)
first = rows(store, "SELECT last_seen_at FROM auth_sessions")
store.touch(token)
assert rows(store, "SELECT last_seen_at FROM auth_sessions") == first
old = (datetime.now(UTC) - timedelta(hours=1)).isoformat()
with closing(sqlite3.connect(store.path)) as conn, conn:
conn.execute("UPDATE auth_sessions SET last_seen_at=?", (old,))
store.touch(token)
assert rows(store, "SELECT last_seen_at FROM auth_sessions") != [(old,)]
# ------------------------------------------------------ passkeys, as rows
def test_a_passkey_is_kept_renamed_and_revoked(store: AuthStore):
key_id = store.add_passkey(b"cred-id", b"public-key", 3, "usb,nfc", "YubiKey")
(key,) = store.passkeys()
assert (key.label, key.transports) == ("YubiKey", ["usb", "nfc"])
assert store.passkey_ids() == [b"cred-id"]
assert store.passkey_for(b"cred-id") == (key_id, b"public-key", 3)
assert store.passkey_for(b"never seen") is None
assert store.rename_passkey(key_id, "The one on my keyring") is True
assert store.passkeys()[0].label == "The one on my keyring"
store.record_passkey_use(key_id, 4)
assert store.passkey_for(b"cred-id")[2] == 4
assert store.passkeys()[0].last_used_at
assert store.delete_passkey(key_id) is True
assert store.delete_passkey(key_id) is False
assert store.passkeys() == []
def test_a_challenge_is_single_use_and_knows_what_it_was_for(store: AuthStore):
store.remember_challenge(b"one", "register")
assert store.take_challenge(b"one", "login") is False, "purposes are not pooled"
assert store.take_challenge(b"one", "register") is True
assert store.take_challenge(b"one", "register") is False, "it was spent"
def test_an_abandoned_challenge_is_swept_by_the_next_one(store: AuthStore):
"""The endpoint that hands these out needs no session, so a ceremony nobody
finished must not sit in the table until a restart."""
store.remember_challenge(b"abandoned", "login", seconds=-1)
store.remember_challenge(b"fresh", "login")
assert rows(store, "SELECT challenge FROM auth_challenges") == [(b"fresh",)]
def test_the_store_makes_its_own_folder(tmp_path: Path):
"""`data/app.db` on a fresh clone: the directory is not there yet, and the
first thing that opens the file is whatever runs first."""
store = AuthStore(tmp_path / "nowhere" / "yet" / "app.db")
assert store.path.exists()
assert store.has_password() is False
+100
View File
@@ -0,0 +1,100 @@
"""The app as it is with `webauthn` not installed.
These live in their own module rather than in `test_passkeys.py` on purpose:
that one is skipped wholesale when the extra is missing, which is exactly the
situation being tested here. The behaviour without the package has to be
covered by tests that always run, or it is covered by nothing.
The extra is removed by putting `None` in `sys.modules`, which is what makes
`import webauthn` raise `ImportError` -- so `available()` is exercised rather
than stubbed, and every lazy import inside the ceremonies is too.
uv run pytest auth/tests/test_without_passkeys.py -q
"""
from __future__ import annotations
import logging
import sys
from collections.abc import Callable, Iterator
import pytest
from fastapi.testclient import TestClient
from auth import AuthStore, passkeys
from auth.tests import PASSWORD, sign_in
from auth.tests.harness import build
@pytest.fixture
def no_extra(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""`import webauthn` raises ImportError, as it does without the extra."""
monkeypatch.setitem(sys.modules, "webauthn", None)
assert passkeys.available() is False
yield
def test_the_account_screen_says_what_to_install(no_extra, signed_in: TestClient):
account = signed_in.get("/api/account").json()
assert account["passkeys_available"] is False
said = account["passkeys_blocked"]
assert "uv sync --extra passkeys" in said
# And the half that is easy to drop as verbose: run that command on its own
# and uv uninstalls every other extra, which fails silently and later.
assert "replaces the set" in said
def test_the_account_screen_still_loads(no_extra, signed_in: TestClient):
"""The whole point: a missing optional dependency is a sentence on a
screen, not a 500 that takes the account page with it."""
assert signed_in.get("/api/account").status_code == 200
def test_the_passkey_routes_answer_501_rather_than_crashing(
no_extra, signed_in: TestClient):
"""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."""
for path in ("/api/account/passkeys/options", "/login/passkey/options"):
answer = signed_in.post(path)
assert answer.status_code == 501, path
assert "passkeys" in answer.json()["detail"]
assert "uv sync" in answer.json()["detail"]
def test_the_login_page_offers_no_button_it_cannot_honour(
no_extra, locked: TestClient):
"""`{passkeys}` is substituted false, so the button is never drawn -- rather
than drawn and then failing inside the browser."""
page = locked.get("/login").text
assert "const passkeysOffered = false;" in page
def test_the_password_still_works_without_the_extra(no_extra, locked: TestClient):
"""The reason none of this is an emergency."""
assert sign_in(locked, PASSWORD).status_code == 200
assert locked.get("/api/thing").status_code == 200
def test_startup_says_so_when_registered_keys_cannot_be_used(
no_extra, tmp_path, caplog):
"""`uv sync` without the extra silently removes the package. The next start
has keys it cannot verify, and the log is where that should surface --
before anyone is standing at a login page wondering where the button went.
"""
db = tmp_path / "keys.db"
store = AuthStore(db)
store.set_password(PASSWORD)
store.add_passkey(b"cred-id", b"public-key", 0, "usb", "YubiKey")
with caplog.at_level(logging.WARNING), TestClient(build(db, enabled="always")):
pass
assert "uv sync --extra passkeys" in caplog.text
assert "nothing is lost" in caplog.text
def test_startup_is_quiet_when_there_are_no_passkeys(
no_extra, make_client: Callable[..., TestClient], caplog):
"""An install that simply does not use passkeys has nothing to be told."""
with caplog.at_level(logging.WARNING):
make_client(enabled="always")
assert "--extra passkeys" not in caplog.text