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

+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