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:
1 parent
1f436104f3
commit
9d666d0937
76 files changed
+15235
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user