"""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}"