Files
WolfandClaude Opus 5.5 9d666d0937 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>
2026-09-23 12:29:16 +02:00

374 lines
15 KiB
Python

"""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() == []