Skip to main content

spoolframe_protocol/portable/
roots.rs

1//! An identity's roots: the keys that may act for it. A phrase root is
2//! an Ed25519 key from a recovery phrase; a security key root is a FIDO2
3//! key's P-256 credential, which signs only CTAP2 assertions. An identity has
4//! one or more, any one of which is enough, and its genesis
5//! ([`IdentityGenesis`]) names the first.
6//!
7//! What a root signs is a domain string with its NUL, then fixed-width
8//! fields. A phrase root signs those bytes; a
9//! security key is given their SHA-256 as `clientDataHash`, as raw CTAP2
10//! lets the client choose, and signs `authenticatorData ‖ clientDataHash`
11//! under [`PORTABLE_RP`].
12//!
13//! A platform's WebAuthn API (Apple's system security-key API) does not
14//! let the app choose `clientDataHash`: the platform writes a
15//! `clientDataJSON` around the app's `challenge` and the key signs
16//! `authenticatorData ‖ SHA-256(clientDataJSON)`. So a root signature
17//! comes in a second form, [`RootSignature::WebAuthn`], whose challenge
18//! is the same SHA-256 of the same bytes. Both forms verify against the
19//! same [`RootKey::SecurityKey`]: a credential is bound only to its RP id
20//! hash, so a key registered on Linux signs on an iPhone, and the reverse.
21
22use std::fmt;
23
24use ed25519_dalek::VerifyingKey;
25use p256::ecdsa::signature::Verifier;
26use serde::{Deserialize, Deserializer, Serialize, Serializer};
27use sha2::{Digest, Sha256};
28
29use super::{PortableUserId, Signature, parse_hex, write_hex};
30
31/// The relying party a security key root signs under. Domain-shaped and
32/// under `*.spoolframe.app`, so no server's passkey sign-in
33/// (under that server's own RP) can pass as a root's signature.
34pub const PORTABLE_RP: &str = "portable.spoolframe.app";
35
36/// The most roots an identity has at once, and in its genesis.
37pub const MAX_ROOTS: usize = 8;
38
39/// The most root changes a state lists: roots added, and roots removed,
40/// each. Changes are cumulative, as revocations are, so a state carries
41/// them all.
42pub const MAX_ROOT_CHANGES: usize = 64;
43
44/// The longest credential id a security key root may have, in bytes.
45pub const MAX_CREDENTIAL_ID: usize = 128;
46
47/// The longest `authenticatorData` a root signature may carry. An
48/// assertion's is 37 bytes and its extensions; this leaves room for them.
49pub const MAX_AUTHENTICATOR_DATA: usize = 512;
50
51/// The longest DER ECDSA P-256 signature.
52pub const MAX_DER_SIGNATURE: usize = 72;
53
54/// Bytes in a P-256 public key, SEC1 uncompressed: `04 ‖ x ‖ y`.
55pub const P256_PUBLIC_KEY_LEN: usize = 65;
56
57/// The domain of each root's signature over its identity's genesis.
58pub const GENESIS_DOMAIN: &[u8] = b"spoolframe identity genesis v1\0";
59
60/// The domain of an added root's proof that it is held, over its
61/// addition.
62pub const ROOT_ADD_DOMAIN: &[u8] = b"spoolframe root add v1\0";
63
64/// The domain of the adding root's endorsement of a root it adds.
65pub const ROOT_ENDORSE_DOMAIN: &[u8] = b"spoolframe root endorse v1\0";
66
67/// The context the id of an identity with a security key root is derived
68/// in, from its genesis.
69pub const USER_ID_CONTEXT: &str = "spoolframe portable user id v1";
70
71/// `authenticatorData` flag: the user was present (touched the key).
72const FLAG_UP: u8 = 0x01;
73/// `authenticatorData` flag: the user was verified (gave the PIN).
74const FLAG_UV: u8 = 0x04;
75
76/// The longest `clientDataJSON` a WebAuthn root signature or registration
77/// may carry, refused before it is parsed. A platform's is a few hundred
78/// bytes.
79pub const MAX_CLIENT_DATA_JSON: usize = 4096;
80
81/// The longest WebAuthn `attestationObject` a registration may carry,
82/// refused before it is parsed. Room for an attestation certificate chain,
83/// which is carried but not checked.
84pub const MAX_ATTESTATION_OBJECT: usize = 8192;
85
86/// `clientDataJSON` `type` of a WebAuthn assertion.
87const WEBAUTHN_GET: &str = "webauthn.get";
88/// `clientDataJSON` `type` of a WebAuthn registration.
89const WEBAUTHN_CREATE: &str = "webauthn.create";
90/// `authenticatorData` flag: attested credential data follows the counter.
91const FLAG_AT: u8 = 0x40;
92/// `authenticatorData` flag: extensions follow.
93const FLAG_ED: u8 = 0x80;
94
95/// Bytes of `authenticatorData` before its flags: the RP id hash.
96const RP_ID_HASH_LEN: usize = 32;
97/// The shortest `authenticatorData`: RP id hash, flags, counter.
98const MIN_AUTHENTICATOR_DATA: usize = RP_ID_HASH_LEN + 1 + 4;
99
100/// SHA-256 of [`PORTABLE_RP`]: what an assertion's `authenticatorData`
101/// starts with.
102pub fn portable_rp_id_hash() -> [u8; 32] {
103    Sha256::digest(PORTABLE_RP.as_bytes()).into()
104}
105
106/// A key that may act for an identity.
107#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
108pub enum RootKey {
109    /// An Ed25519 key derived from a recovery phrase.
110    Phrase([u8; 32]),
111    /// A FIDO2 security key's credential: its P-256 public key (SEC1
112    /// uncompressed) and its credential id, at most
113    /// [`MAX_CREDENTIAL_ID`] bytes.
114    SecurityKey {
115        public_key: [u8; P256_PUBLIC_KEY_LEN],
116        credential_id: Vec<u8>,
117    },
118}
119
120impl RootKey {
121    /// The phrase root of a phrase identity: the Ed25519 key its id is.
122    pub fn phrase_of(user: &PortableUserId) -> Self {
123        RootKey::Phrase(*user.as_bytes())
124    }
125
126    /// How a root is laid out in what roots sign: `01 ‖ key (32)` for a
127    /// phrase root; `02 ‖ public key (65) ‖ id length (u8) ‖ id` for a
128    /// security key. Each layout says its own length.
129    pub fn bytes(&self) -> Vec<u8> {
130        match self {
131            RootKey::Phrase(key) => {
132                let mut bytes = Vec::with_capacity(33);
133                bytes.push(1);
134                bytes.extend_from_slice(key);
135                bytes
136            }
137            RootKey::SecurityKey {
138                public_key,
139                credential_id,
140            } => {
141                let mut bytes = Vec::with_capacity(1 + 65 + 1 + credential_id.len());
142                bytes.push(2);
143                bytes.extend_from_slice(public_key);
144                bytes.push(u8::try_from(credential_id.len()).expect("a credential id fits a byte"));
145                bytes.extend_from_slice(credential_id);
146                bytes
147            }
148        }
149    }
150
151    /// Whether it is a key a root could be: an Ed25519 point, or a P-256
152    /// point with a credential id within [`MAX_CREDENTIAL_ID`].
153    pub fn is_valid(&self) -> bool {
154        match self {
155            RootKey::Phrase(key) => VerifyingKey::from_bytes(key).is_ok(),
156            RootKey::SecurityKey {
157                public_key,
158                credential_id,
159            } => {
160                !credential_id.is_empty()
161                    && credential_id.len() <= MAX_CREDENTIAL_ID
162                    && p256::ecdsa::VerifyingKey::from_sec1_bytes(public_key).is_ok()
163            }
164        }
165    }
166
167    /// Whether `signature` is this root's over `message`: a strict
168    /// Ed25519 signature from a phrase root; a CTAP2 assertion from a
169    /// security key, under [`PORTABLE_RP`], with the user present and
170    /// verified, over `authenticatorData ‖ SHA-256(message)`; or the same
171    /// key's WebAuthn assertion whose challenge is SHA-256(`message`)
172    /// ([`RootSignature::WebAuthn`]). The
173    /// signature counter is not looked at: a key may report 0, and a
174    /// cloned key is not what this guards against.
175    pub fn verify(&self, message: &[u8], signature: &RootSignature) -> bool {
176        match (self, signature) {
177            (RootKey::Phrase(key), RootSignature::Ed25519(signature)) => {
178                VerifyingKey::from_bytes(key)
179                    .is_ok_and(|key| key.verify_strict(message, signature).is_ok())
180            }
181            (
182                RootKey::SecurityKey { public_key, .. },
183                RootSignature::Ctap {
184                    authenticator_data,
185                    signature,
186                },
187            ) => verify_ctap(public_key, message, authenticator_data, signature),
188            (
189                RootKey::SecurityKey { public_key, .. },
190                RootSignature::WebAuthn {
191                    authenticator_data,
192                    client_data_json,
193                    signature,
194                },
195            ) => verify_webauthn(
196                public_key,
197                message,
198                authenticator_data,
199                client_data_json,
200                signature,
201            )
202            .is_ok(),
203            _ => false,
204        }
205    }
206
207    /// The short code a person compares between screens, in an
208    /// identity's format ([`crate::fingerprint`]): of the phrase root's
209    /// key, or of the BLAKE3 of a security key's [`Self::bytes`].
210    pub fn fingerprint(&self) -> String {
211        match self {
212            RootKey::Phrase(key) => crate::fingerprint::fingerprint(key),
213            RootKey::SecurityKey { .. } => {
214                crate::fingerprint::fingerprint(blake3::hash(&self.bytes()).as_bytes())
215            }
216        }
217    }
218
219    /// What kind of root it is: `phrase` or `security_key`.
220    pub fn kind(&self) -> &'static str {
221        match self {
222            RootKey::Phrase(_) => "phrase",
223            RootKey::SecurityKey { .. } => "security_key",
224        }
225    }
226}
227
228impl fmt::Debug for RootKey {
229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230        write!(f, "RootKey({})", self.fingerprint())
231    }
232}
233
234/// Whether the CTAP2 assertion `authenticator_data`, `der` is
235/// `public_key`'s over `message` (see [`RootKey::verify`]).
236fn verify_ctap(
237    public_key: &[u8; P256_PUBLIC_KEY_LEN],
238    message: &[u8],
239    authenticator_data: &[u8],
240    der: &[u8],
241) -> bool {
242    if authenticator_data.len() < MIN_AUTHENTICATOR_DATA
243        || authenticator_data.len() > MAX_AUTHENTICATOR_DATA
244        || der.len() > MAX_DER_SIGNATURE
245    {
246        return false;
247    }
248    if authenticator_data[..RP_ID_HASH_LEN] != portable_rp_id_hash() {
249        return false;
250    }
251    let flags = authenticator_data[RP_ID_HASH_LEN];
252    if flags & FLAG_UP == 0 || flags & FLAG_UV == 0 {
253        return false;
254    }
255    let (Ok(key), Ok(signature)) = (
256        p256::ecdsa::VerifyingKey::from_sec1_bytes(public_key),
257        p256::ecdsa::Signature::from_der(der),
258    ) else {
259        return false;
260    };
261    let mut signed = Vec::with_capacity(authenticator_data.len() + 32);
262    signed.extend_from_slice(authenticator_data);
263    signed.extend_from_slice(&Sha256::digest(message));
264    key.verify(&signed, &signature).is_ok()
265}
266
267/// Why a WebAuthn assertion or registration is refused.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
269pub enum WebAuthnError {
270    /// A field over its bound ([`MAX_CLIENT_DATA_JSON`],
271    /// [`MAX_ATTESTATION_OBJECT`], [`MAX_AUTHENTICATOR_DATA`],
272    /// [`MAX_DER_SIGNATURE`]), refused before it is parsed.
273    #[error("a WebAuthn field is too long")]
274    TooLong,
275    /// `clientDataJSON` is not a JSON object with string `type` and
276    /// `challenge` (and, if present, a boolean `crossOrigin`).
277    #[error("the clientDataJSON is not WebAuthn client data")]
278    MalformedClientData,
279    /// `webauthn.create` where an assertion was wanted, or the reverse.
280    #[error("the clientDataJSON is of the wrong type")]
281    WrongType,
282    /// The challenge is not the one this signature or registration is for.
283    #[error("the clientDataJSON's challenge is not this message's")]
284    WrongChallenge,
285    /// Made in a cross-origin frame.
286    #[error("the clientDataJSON is cross-origin")]
287    CrossOrigin,
288    /// `authenticatorData` too short to hold its RP id hash, flags and
289    /// counter, or its attested credential data does not parse.
290    #[error("the authenticatorData does not parse")]
291    MalformedAuthenticatorData,
292    /// Not under [`PORTABLE_RP`].
293    #[error("the authenticatorData is another relying party's")]
294    WrongRp,
295    /// Made without the touch (UP) or the PIN (UV).
296    #[error("the key was not touched, or no PIN was given")]
297    NotVerified,
298    /// The signature is not the root's.
299    #[error("the signature does not check out")]
300    BadSignature,
301    /// The `attestationObject` is not CBOR with text `fmt` and bytes
302    /// `authData`.
303    #[error("the attestationObject does not parse")]
304    MalformedAttestation,
305    /// A registration whose `authenticatorData` carries no credential (AT).
306    #[error("the registration carries no credential")]
307    NoCredential,
308    /// A credential id empty or over [`MAX_CREDENTIAL_ID`] bytes.
309    #[error("the credential id is empty or too long")]
310    BadCredentialId,
311    /// A credential public key that is not an ES256 P-256 COSE key.
312    #[error("the credential is not an ES256 P-256 key")]
313    UnsupportedKey,
314}
315
316/// Check `client_data_json` is WebAuthn client data of type `kind` whose
317/// challenge is `challenge` (base64url, no padding: compared as the
318/// canonical encoding, so no other spelling of the same bytes passes).
319///
320/// `origin` is not checked. A native app's platform writes its own origin
321/// (an app may differ from `https://portable.spoolframe.app`), and what
322/// binds a signature to Spoolframe is the RP id hash in
323/// `authenticatorData`, which the platform sets from the RP id the app is
324/// entitled to, and which the verifier checks.
325fn check_client_data(
326    client_data_json: &[u8],
327    kind: &str,
328    challenge: &[u8],
329) -> Result<(), WebAuthnError> {
330    use base64::Engine;
331    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
332
333    if client_data_json.len() > MAX_CLIENT_DATA_JSON {
334        return Err(WebAuthnError::TooLong);
335    }
336    let data =
337        super::client_data::parse(client_data_json).ok_or(WebAuthnError::MalformedClientData)?;
338    let (Some(kind_read), Some(challenge_read)) = (data.kind, data.challenge) else {
339        return Err(WebAuthnError::MalformedClientData);
340    };
341    let cross_origin = data
342        .cross_origin
343        .transpose()
344        .map_err(|()| WebAuthnError::MalformedClientData)?;
345    if kind_read != kind {
346        return Err(WebAuthnError::WrongType);
347    }
348    if challenge_read != URL_SAFE_NO_PAD.encode(challenge) {
349        return Err(WebAuthnError::WrongChallenge);
350    }
351    if cross_origin == Some(true) {
352        return Err(WebAuthnError::CrossOrigin);
353    }
354    Ok(())
355}
356
357/// Check `authenticator_data` is under [`PORTABLE_RP`] with UP and UV;
358/// its flags.
359fn check_authenticator_data(authenticator_data: &[u8]) -> Result<u8, WebAuthnError> {
360    if authenticator_data.len() < MIN_AUTHENTICATOR_DATA {
361        return Err(WebAuthnError::MalformedAuthenticatorData);
362    }
363    if authenticator_data[..RP_ID_HASH_LEN] != portable_rp_id_hash() {
364        return Err(WebAuthnError::WrongRp);
365    }
366    let flags = authenticator_data[RP_ID_HASH_LEN];
367    if flags & FLAG_UP == 0 || flags & FLAG_UV == 0 {
368        return Err(WebAuthnError::NotVerified);
369    }
370    Ok(flags)
371}
372
373/// Whether the WebAuthn assertion is `public_key`'s over `message`, in
374/// order: bounds; `clientDataJSON` of type `webauthn.get` with challenge
375/// SHA-256(`message`), not cross-origin; `authenticatorData` under
376/// [`PORTABLE_RP`] with UP and UV; the ES256 signature over
377/// `authenticatorData ‖ SHA-256(clientDataJSON)`. The counter is not
378/// looked at, as for the CTAP2 form.
379pub(crate) fn verify_webauthn(
380    public_key: &[u8; P256_PUBLIC_KEY_LEN],
381    message: &[u8],
382    authenticator_data: &[u8],
383    client_data_json: &[u8],
384    der: &[u8],
385) -> Result<(), WebAuthnError> {
386    if client_data_json.len() > MAX_CLIENT_DATA_JSON
387        || authenticator_data.len() > MAX_AUTHENTICATOR_DATA
388        || der.len() > MAX_DER_SIGNATURE
389    {
390        return Err(WebAuthnError::TooLong);
391    }
392    check_client_data(client_data_json, WEBAUTHN_GET, &Sha256::digest(message))?;
393    check_authenticator_data(authenticator_data)?;
394    let (Ok(key), Ok(signature)) = (
395        p256::ecdsa::VerifyingKey::from_sec1_bytes(public_key),
396        p256::ecdsa::Signature::from_der(der),
397    ) else {
398        return Err(WebAuthnError::BadSignature);
399    };
400    let mut signed = Vec::with_capacity(authenticator_data.len() + 32);
401    signed.extend_from_slice(authenticator_data);
402    signed.extend_from_slice(&Sha256::digest(client_data_json));
403    key.verify(&signed, &signature)
404        .map_err(|_| WebAuthnError::BadSignature)
405}
406
407/// How a security key made a root's credential, as a device's
408/// key API returns it: what [`Self::root`] reads the root from.
409///
410/// A registration is not a proof that the key is held, and is not sent
411/// anywhere: a root proves itself by signing its identity's genesis, or
412/// its addition ([`root_add_message`]), with an assertion. Its attestation
413/// statement is carried but never checked, whatever its `fmt` (`none`,
414/// `packed`, `apple`, ...), as the raw CTAP2 form's never was: no
415/// authenticator model is required of a root.
416#[derive(Debug, Clone, PartialEq, Eq)]
417pub enum RootRegistration {
418    /// Raw CTAP2 `authenticatorMakeCredential` (libfido2): the credential
419    /// as the transport read it. Its client data hash is the identity's
420    /// handle.
421    Ctap(RootKey),
422    /// A WebAuthn registration, as a platform API returns it (Apple's
423    /// `ASAuthorizationSecurityKeyPublicKeyCredentialRegistration`): the
424    /// `attestationObject` (CBOR) and the exact `clientDataJSON`, whose
425    /// challenge is the identity's handle, as the CTAP2 form's client
426    /// data hash is.
427    WebAuthn {
428        attestation_object: Vec<u8>,
429        client_data_json: Vec<u8>,
430    },
431}
432
433impl RootRegistration {
434    /// The root this registration made for the identity `handle`.
435    ///
436    /// The raw CTAP2 form's root as given: the caller checks it
437    /// ([`RootKey::is_valid`]), as it always has. The WebAuthn form, in
438    /// order: bounds ([`MAX_ATTESTATION_OBJECT`], [`MAX_CLIENT_DATA_JSON`]);
439    /// `clientDataJSON` of type `webauthn.create` with challenge `handle`
440    /// (base64url, no padding), not cross-origin; the `attestationObject`
441    /// a CBOR map with text `fmt`, bytes `authData` and map `attStmt`;
442    /// `authData` under [`PORTABLE_RP`], with UP, UV and attested
443    /// credential data (AT); a credential id of 1 to
444    /// [`MAX_CREDENTIAL_ID`] bytes; an ES256 P-256 COSE key on the curve.
445    ///
446    /// That the credential is resident, with `user.id` = `handle`, is
447    /// asked of the key but cannot be read from a registration (a key does
448    /// not report it there), so it is not checked: a key that ignored it
449    /// is found out when recovery by handle finds nothing.
450    pub fn root(&self, handle: &[u8; HANDLE_LEN]) -> Result<RootKey, WebAuthnError> {
451        match self {
452            RootRegistration::Ctap(root) => Ok(root.clone()),
453            RootRegistration::WebAuthn {
454                attestation_object,
455                client_data_json,
456            } => webauthn_registration_root(attestation_object, client_data_json, handle),
457        }
458    }
459}
460
461fn webauthn_registration_root(
462    attestation_object: &[u8],
463    client_data_json: &[u8],
464    handle: &[u8; HANDLE_LEN],
465) -> Result<RootKey, WebAuthnError> {
466    if attestation_object.len() > MAX_ATTESTATION_OBJECT
467        || client_data_json.len() > MAX_CLIENT_DATA_JSON
468    {
469        return Err(WebAuthnError::TooLong);
470    }
471    check_client_data(client_data_json, WEBAUTHN_CREATE, handle)?;
472    let auth_data = attestation_auth_data(attestation_object)?;
473    let flags = check_authenticator_data(&auth_data)?;
474    if flags & FLAG_AT == 0 {
475        return Err(WebAuthnError::NoCredential);
476    }
477    let malformed = WebAuthnError::MalformedAuthenticatorData;
478    // AAGUID (16), credential id length (u16), credential id, COSE key.
479    let attested = &auth_data[MIN_AUTHENTICATOR_DATA..];
480    let id_len = attested.get(16..18).ok_or(malformed)?;
481    let id_len = usize::from(u16::from_be_bytes([id_len[0], id_len[1]]));
482    if id_len == 0 || id_len > MAX_CREDENTIAL_ID {
483        return Err(WebAuthnError::BadCredentialId);
484    }
485    let credential_id = attested.get(18..18 + id_len).ok_or(malformed)?.to_vec();
486    let mut rest = &attested[18 + id_len..];
487    let cose: ciborium::Value =
488        ciborium::de::from_reader_with_recursion_limit(&mut rest, 4).map_err(|_| malformed)?;
489    // What follows the key is the extensions', if flagged; else nothing.
490    if flags & FLAG_ED == 0 && !rest.is_empty() {
491        return Err(malformed);
492    }
493    let public_key = cose_es256_key(cose)?;
494    let root = RootKey::SecurityKey {
495        public_key,
496        credential_id,
497    };
498    if !root.is_valid() {
499        return Err(WebAuthnError::UnsupportedKey);
500    }
501    Ok(root)
502}
503
504/// The `authData` of a WebAuthn `attestationObject`: a CBOR map, nothing
505/// after it, each key once, with text `fmt`, map `attStmt` (not looked
506/// into) and bytes `authData`.
507fn attestation_auth_data(attestation_object: &[u8]) -> Result<Vec<u8>, WebAuthnError> {
508    use ciborium::Value;
509
510    let malformed = WebAuthnError::MalformedAttestation;
511    let mut rest = attestation_object;
512    let Value::Map(members) =
513        ciborium::de::from_reader_with_recursion_limit(&mut rest, 16).map_err(|_| malformed)?
514    else {
515        return Err(malformed);
516    };
517    if !rest.is_empty() {
518        return Err(malformed);
519    }
520    let (mut fmt, mut statement, mut auth_data) = (false, false, None);
521    for (key, value) in members {
522        let seen = match (key.as_text(), value) {
523            (Some("fmt"), Value::Text(_)) => std::mem::replace(&mut fmt, true),
524            (Some("attStmt"), Value::Map(_)) => std::mem::replace(&mut statement, true),
525            (Some("authData"), Value::Bytes(bytes)) => auth_data.replace(bytes).is_some(),
526            (Some("fmt" | "attStmt" | "authData"), _) => return Err(malformed),
527            _ => false,
528        };
529        if seen {
530            return Err(malformed);
531        }
532    }
533    match auth_data {
534        Some(auth_data) if fmt && statement => Ok(auth_data),
535        _ => Err(malformed),
536    }
537}
538
539/// The SEC1 point of an ES256 P-256 COSE key (RFC 9053): kty 2 (EC2),
540/// alg -7 (ES256), crv 1 (P-256), and 32-byte x and y. A key given twice,
541/// or one that is not an integer, is malformed; any other key or value,
542/// unsupported.
543fn cose_es256_key(cose: ciborium::Value) -> Result<[u8; P256_PUBLIC_KEY_LEN], WebAuthnError> {
544    use ciborium::Value;
545
546    let malformed = WebAuthnError::MalformedAuthenticatorData;
547    let Value::Map(members) = cose else {
548        return Err(malformed);
549    };
550    let mut seen: Vec<i128> = Vec::with_capacity(members.len());
551    let (mut kty, mut alg, mut crv, mut x, mut y) = (None, None, None, None, None);
552    for (key, value) in members {
553        let key = i128::from(key.as_integer().ok_or(malformed)?);
554        if seen.contains(&key) {
555            return Err(malformed);
556        }
557        seen.push(key);
558        let integer = value.as_integer().map(i128::from);
559        match key {
560            1 => kty = integer,
561            3 => alg = integer,
562            -1 => crv = integer,
563            -2 => x = value.into_bytes().ok(),
564            -3 => y = value.into_bytes().ok(),
565            _ => {}
566        }
567    }
568    let (Some(2), Some(-7), Some(1), Some(x), Some(y)) = (kty, alg, crv, x, y) else {
569        return Err(WebAuthnError::UnsupportedKey);
570    };
571    if x.len() != 32 || y.len() != 32 {
572        return Err(WebAuthnError::UnsupportedKey);
573    }
574    let mut point = [0u8; P256_PUBLIC_KEY_LEN];
575    point[0] = 4;
576    point[1..33].copy_from_slice(&x);
577    point[33..].copy_from_slice(&y);
578    Ok(point)
579}
580
581/// A root's signature: a phrase root's Ed25519 one, or a security key's
582/// assertion: raw CTAP2 (its `authenticatorData` and DER ECDSA
583/// signature), or WebAuthn (the same, and the `clientDataJSON` the
584/// platform wrote and the key signed the hash of).
585///
586/// In serde, an Ed25519 signature is 128 hex digits; a CTAP2 assertion
587/// is `{"authenticator_data": hex, "signature": hex}`; a WebAuthn one is
588/// `{"authenticator_data": hex, "client_data_json": hex, "signature":
589/// hex}`.
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum RootSignature {
592    Ed25519(Signature),
593    Ctap {
594        authenticator_data: Vec<u8>,
595        signature: Vec<u8>,
596    },
597    /// A WebAuthn assertion, as a platform API returns it (Apple's
598    /// `ASAuthorizationSecurityKeyPublicKeyCredentialAssertion`): the
599    /// challenge in `client_data_json` is SHA-256 of the message, the
600    /// bytes the CTAP2 form's `clientDataHash` is. The credential id is
601    /// the root's.
602    WebAuthn {
603        authenticator_data: Vec<u8>,
604        /// The exact bytes the platform returned (`rawClientDataJSON`),
605        /// at most [`MAX_CLIENT_DATA_JSON`].
606        client_data_json: Vec<u8>,
607        signature: Vec<u8>,
608    },
609}
610
611impl RootSignature {
612    /// The Ed25519 signature, for a phrase root's.
613    pub fn as_ed25519(&self) -> Option<&Signature> {
614        match self {
615            RootSignature::Ed25519(signature) => Some(signature),
616            RootSignature::Ctap { .. } | RootSignature::WebAuthn { .. } => None,
617        }
618    }
619}
620
621impl From<Signature> for RootSignature {
622    fn from(signature: Signature) -> Self {
623        RootSignature::Ed25519(signature)
624    }
625}
626
627/// Hex for serde, over a byte string of at most `max` bytes.
628pub(crate) mod hex_vec {
629    use super::*;
630
631    struct Hex<'a>(&'a [u8]);
632
633    impl fmt::Display for Hex<'_> {
634        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635            write_hex(f, self.0)
636        }
637    }
638
639    pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
640        s.collect_str(&Hex(bytes))
641    }
642
643    /// Even-length hex, either case, of at most `max` bytes.
644    pub fn parse(text: &str, max: usize) -> Option<Vec<u8>> {
645        if !text.len().is_multiple_of(2) || text.len() > 2 * max || !text.is_ascii() {
646            return None;
647        }
648        (0..text.len() / 2)
649            .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).ok())
650            .collect()
651    }
652}
653
654#[derive(Serialize, Deserialize)]
655#[serde(deny_unknown_fields)]
656struct CtapWire {
657    #[serde(serialize_with = "hex_vec::serialize")]
658    #[serde(deserialize_with = "authenticator_data_hex")]
659    authenticator_data: Vec<u8>,
660    #[serde(serialize_with = "hex_vec::serialize")]
661    #[serde(deserialize_with = "der_hex")]
662    signature: Vec<u8>,
663}
664
665#[derive(Serialize, Deserialize)]
666#[serde(deny_unknown_fields)]
667struct WebAuthnWire {
668    #[serde(serialize_with = "hex_vec::serialize")]
669    #[serde(deserialize_with = "authenticator_data_hex")]
670    authenticator_data: Vec<u8>,
671    #[serde(serialize_with = "hex_vec::serialize")]
672    #[serde(deserialize_with = "client_data_json_hex")]
673    client_data_json: Vec<u8>,
674    #[serde(serialize_with = "hex_vec::serialize")]
675    #[serde(deserialize_with = "der_hex")]
676    signature: Vec<u8>,
677}
678
679fn client_data_json_hex<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
680    let text = String::deserialize(d)?;
681    hex_vec::parse(&text, MAX_CLIENT_DATA_JSON)
682        .ok_or_else(|| serde::de::Error::custom("client data JSON is at most 4096 bytes of hex"))
683}
684
685fn authenticator_data_hex<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
686    let text = String::deserialize(d)?;
687    hex_vec::parse(&text, MAX_AUTHENTICATOR_DATA)
688        .ok_or_else(|| serde::de::Error::custom("authenticator data is at most 512 bytes of hex"))
689}
690
691fn der_hex<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
692    let text = String::deserialize(d)?;
693    hex_vec::parse(&text, MAX_DER_SIGNATURE)
694        .ok_or_else(|| serde::de::Error::custom("a DER signature is at most 72 bytes of hex"))
695}
696
697#[derive(Deserialize)]
698#[serde(untagged)]
699enum RootSignatureWire {
700    Ed25519(String),
701    // Before `Ctap`, and both refuse unknown fields, so neither form reads
702    // as the other.
703    WebAuthn(WebAuthnWire),
704    Ctap(CtapWire),
705}
706
707impl Serialize for RootSignature {
708    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
709        match self {
710            RootSignature::Ed25519(signature) => super::signature_hex::serialize(signature, s),
711            RootSignature::Ctap {
712                authenticator_data,
713                signature,
714            } => CtapWire {
715                authenticator_data: authenticator_data.clone(),
716                signature: signature.clone(),
717            }
718            .serialize(s),
719            RootSignature::WebAuthn {
720                authenticator_data,
721                client_data_json,
722                signature,
723            } => WebAuthnWire {
724                authenticator_data: authenticator_data.clone(),
725                client_data_json: client_data_json.clone(),
726                signature: signature.clone(),
727            }
728            .serialize(s),
729        }
730    }
731}
732
733impl<'de> Deserialize<'de> for RootSignature {
734    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
735        match RootSignatureWire::deserialize(d)? {
736            RootSignatureWire::Ed25519(text) => parse_hex::<{ Signature::BYTE_SIZE }>(&text)
737                .map(|bytes| RootSignature::Ed25519(Signature::from_bytes(&bytes)))
738                .ok_or_else(|| serde::de::Error::custom("a signature is 128 hex digits")),
739            RootSignatureWire::Ctap(CtapWire {
740                authenticator_data,
741                signature,
742            }) => Ok(RootSignature::Ctap {
743                authenticator_data,
744                signature,
745            }),
746            RootSignatureWire::WebAuthn(WebAuthnWire {
747                authenticator_data,
748                client_data_json,
749                signature,
750            }) => Ok(RootSignature::WebAuthn {
751                authenticator_data,
752                client_data_json,
753                signature,
754            }),
755        }
756    }
757}
758
759/// A root in serde: `{"type": "phrase", "public_key": hex}` or
760/// `{"type": "security_key", "public_key": hex, "credential_id": hex}`.
761#[derive(Serialize, Deserialize)]
762#[serde(tag = "type", rename_all = "snake_case")]
763enum RootKeyWire {
764    Phrase {
765        public_key: String,
766    },
767    SecurityKey {
768        public_key: String,
769        credential_id: String,
770    },
771}
772
773impl Serialize for RootKey {
774    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
775        let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
776        match self {
777            RootKey::Phrase(key) => RootKeyWire::Phrase {
778                public_key: hex(key),
779            },
780            RootKey::SecurityKey {
781                public_key,
782                credential_id,
783            } => RootKeyWire::SecurityKey {
784                public_key: hex(public_key),
785                credential_id: hex(credential_id),
786            },
787        }
788        .serialize(s)
789    }
790}
791
792impl<'de> Deserialize<'de> for RootKey {
793    /// Sizes are checked here; whether the keys are points is
794    /// [`RootKey::is_valid`]'s, asked wherever a root is taken in.
795    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
796        let bad = |what: &'static str| serde::de::Error::custom(what);
797        match RootKeyWire::deserialize(d)? {
798            RootKeyWire::Phrase { public_key } => parse_hex::<32>(&public_key)
799                .map(RootKey::Phrase)
800                .ok_or_else(|| bad("a phrase root is 64 hex digits")),
801            RootKeyWire::SecurityKey {
802                public_key,
803                credential_id,
804            } => {
805                let public_key = parse_hex::<P256_PUBLIC_KEY_LEN>(&public_key)
806                    .ok_or_else(|| bad("a security key's public key is 130 hex digits"))?;
807                let credential_id = hex_vec::parse(&credential_id, MAX_CREDENTIAL_ID)
808                    .filter(|id| !id.is_empty())
809                    .ok_or_else(|| bad("a credential id is 1 to 128 bytes of hex"))?;
810                Ok(RootKey::SecurityKey {
811                    public_key,
812                    credential_id,
813                })
814            }
815        }
816    }
817}
818
819/// Why a genesis is not one.
820#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
821pub enum GenesisError {
822    /// No roots, or more than [`MAX_ROOTS`].
823    #[error("an identity has 1 to {MAX_ROOTS} roots")]
824    RootCount,
825    /// Not one signature for each root.
826    #[error("an identity's genesis has one signature for each root")]
827    SignatureCount,
828    /// A root named twice.
829    #[error("an identity's genesis names a root twice")]
830    Duplicate,
831    /// A root that is not a key any root could be.
832    #[error("an identity's genesis names a root that is not a valid key")]
833    InvalidRoot,
834    /// A root did not sign it, as it is.
835    #[error("a root did not sign its identity's genesis")]
836    BadSignature,
837}
838
839/// Bytes in an identity's handle.
840pub const HANDLE_LEN: usize = 32;
841
842/// How an identity begins: its handle, its first roots, and each
843/// root's signature over both, so every root proves it is held. For a
844/// security key identity the handle is random and is also the key's
845/// resident credential's `user.id`, so a key put into a device that has
846/// never seen it says which identity it roots.
847///
848/// The genesis fixes the identity's id ([`Self::user`]): later root
849/// changes, made in its states, never change it.
850#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
851pub struct IdentityGenesis {
852    #[serde(with = "handle_hex")]
853    pub handle: [u8; HANDLE_LEN],
854    pub roots: Vec<RootKey>,
855    /// One for each root, in `roots`' order, over [`Self::message`].
856    pub signatures: Vec<RootSignature>,
857}
858
859/// Hex for serde, over a genesis handle.
860pub(crate) mod handle_hex {
861    use super::*;
862
863    pub fn serialize<S: Serializer>(handle: &[u8; HANDLE_LEN], s: S) -> Result<S::Ok, S::Error> {
864        hex_vec::serialize(handle, s)
865    }
866
867    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; HANDLE_LEN], D::Error> {
868        let text = String::deserialize(d)?;
869        parse_hex(&text).ok_or_else(|| serde::de::Error::custom("a handle is 64 hex digits"))
870    }
871}
872
873impl IdentityGenesis {
874    /// What each root signs: [`GENESIS_DOMAIN`], the handle (32 bytes),
875    /// the count of roots (u8), then each root ([`RootKey::bytes`]) in
876    /// order. `None` for more roots than a byte counts.
877    pub fn message(handle: &[u8; HANDLE_LEN], roots: &[RootKey]) -> Option<Vec<u8>> {
878        let count = u8::try_from(roots.len()).ok()?;
879        let mut message = Vec::with_capacity(GENESIS_DOMAIN.len() + 33 + 100 * roots.len());
880        message.extend_from_slice(GENESIS_DOMAIN);
881        message.extend_from_slice(handle);
882        message.push(count);
883        for root in roots {
884            message.extend_from_slice(&root.bytes());
885        }
886        Some(message)
887    }
888
889    /// Whether it is a genesis: 1 to [`MAX_ROOTS`] valid roots, none
890    /// twice, each with its signature over [`Self::message`].
891    pub fn verify(&self) -> Result<(), GenesisError> {
892        if self.roots.is_empty() || self.roots.len() > MAX_ROOTS {
893            return Err(GenesisError::RootCount);
894        }
895        if self.signatures.len() != self.roots.len() {
896            return Err(GenesisError::SignatureCount);
897        }
898        if !self.roots.iter().all(RootKey::is_valid) {
899            return Err(GenesisError::InvalidRoot);
900        }
901        let mut seen = self.roots.clone();
902        seen.sort();
903        seen.dedup();
904        if seen.len() != self.roots.len() {
905            return Err(GenesisError::Duplicate);
906        }
907        let message = Self::message(&self.handle, &self.roots).ok_or(GenesisError::RootCount)?;
908        if self
909            .roots
910            .iter()
911            .zip(&self.signatures)
912            .all(|(root, signature)| root.verify(&message, signature))
913        {
914            Ok(())
915        } else {
916            Err(GenesisError::BadSignature)
917        }
918    }
919
920    /// The identity's id. A genesis of one phrase root keeps that root's
921    /// public key as its id, so a phrase identity's id never changes; any
922    /// other's is
923    /// `blake3::derive_key(`[`USER_ID_CONTEXT`]`, message)`. Signatures
924    /// are left out, since an ECDSA one differs each time it is made.
925    pub fn user(&self) -> PortableUserId {
926        if let [RootKey::Phrase(key)] = self.roots.as_slice() {
927            return PortableUserId(*key);
928        }
929        let message =
930            Self::message(&self.handle, &self.roots).expect("at most 255 roots in a genesis");
931        PortableUserId(blake3::derive_key(USER_ID_CONTEXT, &message))
932    }
933}
934
935/// What an added root signs to prove it is held, for `user`:
936/// [`ROOT_ADD_DOMAIN`], the user (32 bytes), then the root
937/// ([`RootKey::bytes`]).
938pub fn root_add_message(user: &PortableUserId, root: &RootKey) -> Vec<u8> {
939    let mut message = Vec::with_capacity(ROOT_ADD_DOMAIN.len() + 32 + 100);
940    message.extend_from_slice(ROOT_ADD_DOMAIN);
941    message.extend_from_slice(user.as_bytes());
942    message.extend_from_slice(&root.bytes());
943    message
944}
945
946/// What the root that adds another signs, for `user`:
947/// [`ROOT_ENDORSE_DOMAIN`], the user (32 bytes), the added root
948/// ([`RootKey::bytes`]), then when it was added (i64, big-endian).
949pub fn root_endorse_message(user: &PortableUserId, root: &RootKey, added_at: i64) -> Vec<u8> {
950    let mut message = Vec::with_capacity(ROOT_ENDORSE_DOMAIN.len() + 32 + 100 + 8);
951    message.extend_from_slice(ROOT_ENDORSE_DOMAIN);
952    message.extend_from_slice(user.as_bytes());
953    message.extend_from_slice(&root.bytes());
954    message.extend_from_slice(&added_at.to_be_bytes());
955    message
956}
957
958/// A root added to an identity, self-certifying: who added it and when,
959/// that root's endorsement over [`root_endorse_message`], and the new
960/// root's proof that it is held, over [`root_add_message`]. A state lists
961/// every one so far, so any state carries the whole chain.
962#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
963pub struct AddedRoot {
964    pub root: RootKey,
965    pub added_by: RootKey,
966    /// Unix seconds.
967    pub added_at: i64,
968    pub endorsement: RootSignature,
969    pub possession: RootSignature,
970}
971
972impl AddedRoot {
973    /// Whether its root is valid and both signatures hold: the root's
974    /// over its addition, the adder's over its endorsement.
975    pub fn verify(&self, user: &PortableUserId) -> bool {
976        self.root.is_valid()
977            && self
978                .root
979                .verify(&root_add_message(user, &self.root), &self.possession)
980            && self.added_by.verify(
981                &root_endorse_message(user, &self.root, self.added_at),
982                &self.endorsement,
983            )
984    }
985}
986
987/// A root a state removes, and when (Unix seconds). A removed root never
988/// comes back.
989#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
990pub struct RemovedRoot {
991    pub root: RootKey,
992    pub removed_at: i64,
993}
994
995/// The roots that may act for an identity, as a verifier works them out
996/// from its genesis and every valid state it holds:
997///
998/// - `ever`: the genesis's roots, and every root added by one in `ever`,
999///   until nothing more is added. A state counts only if one of these
1000///   signed it.
1001/// - `removed`: every root a state signed by one in `ever` removes, at
1002///   its earliest `removed_at`. Removal never lapses: a removed root never
1003///   comes back.
1004/// - `members`: the genesis's roots, and every root added by a member
1005///   no later than that member's own removal (`added_at` at or before
1006///   its `removed_at`: times are whole seconds, and a rotation adds the
1007///   new key and drops the old one in the same one), until nothing more
1008///   is added; then without the removed. A credential counts only from a
1009///   member.
1010///
1011/// So a root added by a key later rotated out stays, and one a removed
1012/// key adds after its removal does not. Times are the roots' own word:
1013/// a stolen key that backdates an addition is stopped where its removal
1014/// arrived first, by the verifier refusing the state that brings it
1015/// (the server, and the SDK's `accept_state`). A removed
1016/// root's removals still count, so two roots that remove each other are
1017/// both gone: the identity is locked rather than taken.
1018#[derive(Debug, Clone, Default, PartialEq, Eq)]
1019pub struct RootSet {
1020    pub ever: Vec<RootKey>,
1021    pub removed: Vec<(RootKey, i64)>,
1022    pub members: Vec<RootKey>,
1023}
1024
1025/// A state as the root set reads it: who signed it, what it adds and
1026/// removes. Its signatures are assumed checked.
1027pub struct RootChanges<'a> {
1028    pub signer: &'a RootKey,
1029    pub added: &'a [AddedRoot],
1030    pub removed: &'a [RemovedRoot],
1031}
1032
1033impl RootSet {
1034    /// The set `genesis` begins and `states` change.
1035    pub fn of(genesis: &[RootKey], states: &[RootChanges<'_>]) -> Self {
1036        let additions: Vec<&AddedRoot> = states.iter().flat_map(|s| s.added).collect();
1037        let closure = |admit: &dyn Fn(&[RootKey], &AddedRoot) -> bool| {
1038            let mut set = genesis.to_vec();
1039            loop {
1040                let before = set.len();
1041                for added in &additions {
1042                    if !set.contains(&added.root) && admit(&set, added) {
1043                        set.push(added.root.clone());
1044                    }
1045                }
1046                if set.len() == before {
1047                    return set;
1048                }
1049            }
1050        };
1051        let ever = closure(&|set, added| set.contains(&added.added_by));
1052        let mut removed: Vec<(RootKey, i64)> = Vec::new();
1053        for state in states.iter().filter(|s| ever.contains(s.signer)) {
1054            for root in state.removed {
1055                match removed.iter_mut().find(|(r, _)| *r == root.root) {
1056                    Some((_, at)) => *at = (*at).min(root.removed_at),
1057                    None => removed.push((root.root.clone(), root.removed_at)),
1058                }
1059            }
1060        }
1061        let removed_at =
1062            |root: &RootKey| removed.iter().find(|(r, _)| r == root).map(|(_, at)| *at);
1063        let members = closure(&|set, added| {
1064            set.contains(&added.added_by)
1065                && removed_at(&added.added_by).is_none_or(|at| added.added_at <= at)
1066        })
1067        .into_iter()
1068        .filter(|root| removed_at(root).is_none())
1069        .collect();
1070        RootSet {
1071            ever,
1072            removed,
1073            members,
1074        }
1075    }
1076
1077    /// Whether `root` may act now: a member, not removed.
1078    pub fn holds(&self, root: &RootKey) -> bool {
1079        self.members.contains(root)
1080    }
1081
1082    /// Whether `root` was ever one of the identity's: a state it signed
1083    /// is taken in, for its removals.
1084    pub fn knew(&self, root: &RootKey) -> bool {
1085        self.ever.contains(root)
1086    }
1087
1088    /// Whether `root` is removed.
1089    pub fn is_removed(&self, root: &RootKey) -> bool {
1090        self.removed.iter().any(|(r, _)| r == root)
1091    }
1092
1093    /// Whether `added`, arriving now, adds a root this set does not know
1094    /// whose adder this set has already removed: an addition that came
1095    /// after the removal, whatever time it claims. A verifier refuses the
1096    /// state that brings it, so a stolen key cannot backdate its way past
1097    /// a removal the verifier already holds.
1098    pub fn refuses_additions(&self, added: &[AddedRoot]) -> bool {
1099        added
1100            .iter()
1101            .any(|added| !self.knew(&added.root) && self.is_removed(&added.added_by))
1102    }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    use base64::Engine;
1108    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1109    use p256::ecdsa::signature::Signer;
1110    use p256::ecdsa::{DerSignature, SigningKey};
1111
1112    use super::*;
1113
1114    const MESSAGE: &[u8] = b"spoolframe root add v1\0some bytes";
1115
1116    fn signing(seed: u8) -> SigningKey {
1117        SigningKey::from_bytes(&[seed; 32].into()).unwrap()
1118    }
1119
1120    fn public(key: &SigningKey) -> [u8; P256_PUBLIC_KEY_LEN] {
1121        key.verifying_key()
1122            .to_sec1_point(false)
1123            .as_bytes()
1124            .try_into()
1125            .unwrap()
1126    }
1127
1128    fn client_data(kind: &str, challenge: &[u8]) -> Vec<u8> {
1129        format!(
1130            r#"{{"type":"{kind}","challenge":"{}","origin":"https://portable.spoolframe.app"}}"#,
1131            URL_SAFE_NO_PAD.encode(challenge)
1132        )
1133        .into_bytes()
1134    }
1135
1136    fn authenticator_data(rp: &str, flags: u8) -> Vec<u8> {
1137        let mut data = Sha256::digest(rp.as_bytes()).to_vec();
1138        data.push(flags);
1139        data.extend_from_slice(&7u32.to_be_bytes());
1140        data
1141    }
1142
1143    /// What a platform returns: `key`'s signature over
1144    /// `authenticator_data ‖ SHA-256(client_data_json)`, made properly, so
1145    /// only the part a test changes is wrong.
1146    fn signed(
1147        key: &SigningKey,
1148        authenticator_data: Vec<u8>,
1149        client_data_json: Vec<u8>,
1150    ) -> RootSignature {
1151        let mut bytes = authenticator_data.clone();
1152        bytes.extend_from_slice(&Sha256::digest(&client_data_json));
1153        let signature: DerSignature = key.sign(&bytes);
1154        RootSignature::WebAuthn {
1155            authenticator_data,
1156            client_data_json,
1157            signature: signature.as_bytes().to_vec(),
1158        }
1159    }
1160
1161    fn good(key: &SigningKey, message: &[u8]) -> RootSignature {
1162        signed(
1163            key,
1164            authenticator_data(PORTABLE_RP, 0x05),
1165            client_data(WEBAUTHN_GET, &Sha256::digest(message)),
1166        )
1167    }
1168
1169    fn check(
1170        key: &SigningKey,
1171        message: &[u8],
1172        signature: &RootSignature,
1173    ) -> Result<(), WebAuthnError> {
1174        let RootSignature::WebAuthn {
1175            authenticator_data,
1176            client_data_json,
1177            signature,
1178        } = signature
1179        else {
1180            unreachable!()
1181        };
1182        verify_webauthn(
1183            &public(key),
1184            message,
1185            authenticator_data,
1186            client_data_json,
1187            signature,
1188        )
1189    }
1190
1191    fn root(key: &SigningKey) -> RootKey {
1192        RootKey::SecurityKey {
1193            public_key: public(key),
1194            credential_id: vec![1; 32],
1195        }
1196    }
1197
1198    #[test]
1199    fn a_webauthn_assertion_over_the_message_s_hash_verifies() {
1200        let key = signing(3);
1201        assert_eq!(check(&key, MESSAGE, &good(&key, MESSAGE)), Ok(()));
1202        assert!(root(&key).verify(MESSAGE, &good(&key, MESSAGE)));
1203    }
1204
1205    #[test]
1206    fn a_webauthn_assertion_of_the_wrong_type_is_refused() {
1207        let key = signing(3);
1208        let made = signed(
1209            &key,
1210            authenticator_data(PORTABLE_RP, 0x05),
1211            client_data("payment.get", &Sha256::digest(MESSAGE)),
1212        );
1213        assert_eq!(check(&key, MESSAGE, &made), Err(WebAuthnError::WrongType));
1214    }
1215
1216    /// A registration's client data, signed by the credential's own key
1217    /// as a packed self-attestation is, over the right challenge: the type
1218    /// is what keeps it from passing as an assertion.
1219    #[test]
1220    fn a_webauthn_create_presented_as_an_assertion_is_refused() {
1221        let key = signing(3);
1222        let made = signed(
1223            &key,
1224            authenticator_data(PORTABLE_RP, 0x45),
1225            client_data(WEBAUTHN_CREATE, &Sha256::digest(MESSAGE)),
1226        );
1227        assert_eq!(check(&key, MESSAGE, &made), Err(WebAuthnError::WrongType));
1228    }
1229
1230    #[test]
1231    fn a_webauthn_assertion_with_a_wrong_challenge_is_refused() {
1232        let key = signing(3);
1233        // The message itself, not its hash.
1234        let made = signed(
1235            &key,
1236            authenticator_data(PORTABLE_RP, 0x05),
1237            client_data(WEBAUTHN_GET, MESSAGE),
1238        );
1239        assert_eq!(
1240            check(&key, MESSAGE, &made),
1241            Err(WebAuthnError::WrongChallenge)
1242        );
1243        // The hash, padded: another spelling of the same bytes.
1244        let padded = format!(
1245            r#"{{"type":"webauthn.get","challenge":"{}="}}"#,
1246            URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE))
1247        );
1248        let made = signed(
1249            &key,
1250            authenticator_data(PORTABLE_RP, 0x05),
1251            padded.into_bytes(),
1252        );
1253        assert_eq!(
1254            check(&key, MESSAGE, &made),
1255            Err(WebAuthnError::WrongChallenge)
1256        );
1257    }
1258
1259    #[test]
1260    fn a_webauthn_assertion_over_another_message_is_refused() {
1261        let key = signing(3);
1262        let other = good(&key, b"spoolframe root add v1\0other bytes");
1263        assert_eq!(
1264            check(&key, MESSAGE, &other),
1265            Err(WebAuthnError::WrongChallenge)
1266        );
1267        assert!(!root(&key).verify(MESSAGE, &other));
1268    }
1269
1270    #[test]
1271    fn a_cross_origin_webauthn_assertion_is_refused_and_a_false_one_is_not() {
1272        let key = signing(3);
1273        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1274        let with = |cross: &str| {
1275            signed(
1276                &key,
1277                authenticator_data(PORTABLE_RP, 0x05),
1278                format!(
1279                    r#"{{"type":"webauthn.get","challenge":"{challenge}","crossOrigin":{cross}}}"#
1280                )
1281                .into_bytes(),
1282            )
1283        };
1284        assert_eq!(
1285            check(&key, MESSAGE, &with("true")),
1286            Err(WebAuthnError::CrossOrigin)
1287        );
1288        assert_eq!(check(&key, MESSAGE, &with("false")), Ok(()));
1289    }
1290
1291    /// The origin is not what binds it; any origin with the right RP id
1292    /// hash verifies.
1293    #[test]
1294    fn a_webauthn_assertion_with_another_origin_verifies() {
1295        let key = signing(3);
1296        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1297        let made = signed(
1298            &key,
1299            authenticator_data(PORTABLE_RP, 0x05),
1300            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}","origin":"ios:bundle-id:app.spoolframe"}}"#)
1301                .into_bytes(),
1302        );
1303        assert_eq!(check(&key, MESSAGE, &made), Ok(()));
1304    }
1305
1306    #[test]
1307    fn a_webauthn_assertion_under_another_rp_is_refused() {
1308        let key = signing(3);
1309        let made = signed(
1310            &key,
1311            authenticator_data("spoolframe.app", 0x05),
1312            client_data(WEBAUTHN_GET, &Sha256::digest(MESSAGE)),
1313        );
1314        assert_eq!(check(&key, MESSAGE, &made), Err(WebAuthnError::WrongRp));
1315    }
1316
1317    #[test]
1318    fn a_webauthn_assertion_without_up_or_uv_is_refused() {
1319        let key = signing(3);
1320        for flags in [0x01, 0x04, 0x00] {
1321            let made = signed(
1322                &key,
1323                authenticator_data(PORTABLE_RP, flags),
1324                client_data(WEBAUTHN_GET, &Sha256::digest(MESSAGE)),
1325            );
1326            assert_eq!(
1327                check(&key, MESSAGE, &made),
1328                Err(WebAuthnError::NotVerified),
1329                "{flags:#x}"
1330            );
1331        }
1332    }
1333
1334    #[test]
1335    fn a_webauthn_assertion_with_a_bad_signature_is_refused() {
1336        let key = signing(3);
1337        let RootSignature::WebAuthn {
1338            authenticator_data,
1339            client_data_json,
1340            mut signature,
1341        } = good(&key, MESSAGE)
1342        else {
1343            unreachable!()
1344        };
1345        let last = signature.len() - 1;
1346        signature[last] ^= 1;
1347        let made = RootSignature::WebAuthn {
1348            authenticator_data,
1349            client_data_json,
1350            signature,
1351        };
1352        assert_eq!(
1353            check(&key, MESSAGE, &made),
1354            Err(WebAuthnError::BadSignature)
1355        );
1356    }
1357
1358    #[test]
1359    fn a_webauthn_assertion_from_another_credential_is_refused() {
1360        let (key, other) = (signing(3), signing(4));
1361        assert_eq!(
1362            check(&key, MESSAGE, &good(&other, MESSAGE)),
1363            Err(WebAuthnError::BadSignature)
1364        );
1365        assert!(!root(&key).verify(MESSAGE, &good(&other, MESSAGE)));
1366    }
1367
1368    #[test]
1369    fn an_oversize_client_data_json_is_refused_before_it_parses() {
1370        let key = signing(3);
1371        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1372        let mut json =
1373            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}","pad":""#).into_bytes();
1374        json.resize(MAX_CLIENT_DATA_JSON - 2, b'x');
1375        json.extend_from_slice(b"\"}");
1376        assert_eq!(json.len(), MAX_CLIENT_DATA_JSON);
1377        let at_bound = signed(&key, authenticator_data(PORTABLE_RP, 0x05), json.clone());
1378        assert_eq!(check(&key, MESSAGE, &at_bound), Ok(()));
1379        json.insert(json.len() - 2, b'x');
1380        let over = signed(&key, authenticator_data(PORTABLE_RP, 0x05), json);
1381        assert_eq!(check(&key, MESSAGE, &over), Err(WebAuthnError::TooLong));
1382    }
1383
1384    #[test]
1385    fn malformed_client_data_json_is_refused() {
1386        let key = signing(3);
1387        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1388        for json in [
1389            b"".to_vec(),
1390            b"not json".to_vec(),
1391            b"[]".to_vec(),
1392            b"\xff\xfe".to_vec(),
1393            format!(r#"{{"challenge":"{challenge}"}}"#).into_bytes(),
1394            br#"{"type":"webauthn.get"}"#.to_vec(),
1395            format!(r#"{{"type":1,"challenge":"{challenge}"}}"#).into_bytes(),
1396            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}","crossOrigin":"no"}}"#)
1397                .into_bytes(),
1398            // A member twice: which one a reader takes is not to be guessed.
1399            format!(
1400                r#"{{"type":"webauthn.create","type":"webauthn.get","challenge":"{challenge}"}}"#
1401            )
1402            .into_bytes(),
1403            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}""#).into_bytes(),
1404        ] {
1405            let made = signed(&key, authenticator_data(PORTABLE_RP, 0x05), json.clone());
1406            assert_eq!(
1407                check(&key, MESSAGE, &made),
1408                Err(WebAuthnError::MalformedClientData),
1409                "{}",
1410                String::from_utf8_lossy(&json)
1411            );
1412        }
1413    }
1414
1415    #[test]
1416    fn oversize_or_short_webauthn_fields_are_refused() {
1417        let key = signing(3);
1418        let RootSignature::WebAuthn {
1419            authenticator_data,
1420            client_data_json,
1421            signature,
1422        } = good(&key, MESSAGE)
1423        else {
1424            unreachable!()
1425        };
1426        let mut long_data = authenticator_data.clone();
1427        long_data.resize(MAX_AUTHENTICATOR_DATA + 1, 0);
1428        let mut long_signature = signature.clone();
1429        long_signature.resize(MAX_DER_SIGNATURE + 1, 0);
1430        let public = public(&key);
1431        assert_eq!(
1432            verify_webauthn(&public, MESSAGE, &long_data, &client_data_json, &signature),
1433            Err(WebAuthnError::TooLong)
1434        );
1435        assert_eq!(
1436            verify_webauthn(
1437                &public,
1438                MESSAGE,
1439                &authenticator_data,
1440                &client_data_json,
1441                &long_signature
1442            ),
1443            Err(WebAuthnError::TooLong)
1444        );
1445        assert_eq!(
1446            verify_webauthn(
1447                &public,
1448                MESSAGE,
1449                &authenticator_data[..36],
1450                &client_data_json,
1451                &signature
1452            ),
1453            Err(WebAuthnError::MalformedAuthenticatorData)
1454        );
1455    }
1456
1457    /// A phrase root takes no WebAuthn signature, and a security key root
1458    /// no Ed25519 one.
1459    #[test]
1460    fn a_webauthn_signature_is_no_phrase_root_s() {
1461        let key = signing(3);
1462        let phrase = RootKey::Phrase(
1463            ed25519_dalek::SigningKey::from_bytes(&[5; 32])
1464                .verifying_key()
1465                .to_bytes(),
1466        );
1467        assert!(!phrase.verify(MESSAGE, &good(&key, MESSAGE)));
1468    }
1469
1470    #[test]
1471    fn a_webauthn_signature_round_trips_and_reads_as_neither_other_form() {
1472        let key = signing(3);
1473        let made = good(&key, MESSAGE);
1474        let json = serde_json::to_value(&made).unwrap();
1475        assert_eq!(
1476            json.as_object().unwrap().keys().collect::<Vec<_>>(),
1477            ["authenticator_data", "client_data_json", "signature"]
1478        );
1479        assert_eq!(
1480            serde_json::from_value::<RootSignature>(json.clone()).unwrap(),
1481            made
1482        );
1483        let mut cbor = Vec::new();
1484        ciborium::into_writer(&made, &mut cbor).unwrap();
1485        assert_eq!(
1486            ciborium::from_reader::<RootSignature, _>(cbor.as_slice()).unwrap(),
1487            made
1488        );
1489        // A CTAP2 assertion with an extra member is neither form.
1490        let mut extra = json.clone();
1491        extra.as_object_mut().unwrap().remove("client_data_json");
1492        extra
1493            .as_object_mut()
1494            .unwrap()
1495            .insert("origin".into(), "00".into());
1496        assert!(serde_json::from_value::<RootSignature>(extra).is_err());
1497        // An oversize client data JSON does not read, nor fall back to CTAP2.
1498        let mut over = json;
1499        over["client_data_json"] = "00".repeat(MAX_CLIENT_DATA_JSON + 1).into();
1500        assert!(serde_json::from_value::<RootSignature>(over).is_err());
1501    }
1502
1503    // Registration.
1504
1505    const HANDLE: [u8; HANDLE_LEN] = [0x42; HANDLE_LEN];
1506
1507    fn cose_key(key: &SigningKey) -> ciborium::Value {
1508        use ciborium::Value;
1509        let point = key.verifying_key().to_sec1_point(false);
1510        Value::Map(vec![
1511            (Value::from(1), Value::from(2)),
1512            (Value::from(3), Value::from(-7)),
1513            (Value::from(-1), Value::from(1)),
1514            (Value::from(-2), Value::Bytes(point.x().unwrap().to_vec())),
1515            (Value::from(-3), Value::Bytes(point.y().unwrap().to_vec())),
1516        ])
1517    }
1518
1519    fn cbor(value: &ciborium::Value) -> Vec<u8> {
1520        let mut bytes = Vec::new();
1521        ciborium::into_writer(value, &mut bytes).unwrap();
1522        bytes
1523    }
1524
1525    fn registration_data(rp: &str, flags: u8, credential_id: &[u8], cose: &[u8]) -> Vec<u8> {
1526        let mut data = authenticator_data(rp, flags);
1527        data.extend_from_slice(&[0xaa; 16]);
1528        data.extend_from_slice(&u16::try_from(credential_id.len()).unwrap().to_be_bytes());
1529        data.extend_from_slice(credential_id);
1530        data.extend_from_slice(cose);
1531        data
1532    }
1533
1534    fn attestation(fmt: &str, auth_data: Vec<u8>) -> Vec<u8> {
1535        use ciborium::Value;
1536        cbor(&Value::Map(vec![
1537            (Value::from("fmt"), Value::from(fmt)),
1538            (Value::from("attStmt"), Value::Map(vec![])),
1539            (Value::from("authData"), Value::Bytes(auth_data)),
1540        ]))
1541    }
1542
1543    fn registration(attestation_object: Vec<u8>, client_data_json: Vec<u8>) -> RootRegistration {
1544        RootRegistration::WebAuthn {
1545            attestation_object,
1546            client_data_json,
1547        }
1548    }
1549
1550    fn good_registration(key: &SigningKey) -> RootRegistration {
1551        registration(
1552            attestation(
1553                "none",
1554                registration_data(PORTABLE_RP, 0x45, &[1; 32], &cbor(&cose_key(key))),
1555            ),
1556            client_data(WEBAUTHN_CREATE, &HANDLE),
1557        )
1558    }
1559
1560    #[test]
1561    fn a_webauthn_registration_gives_the_credential_s_root() {
1562        let key = signing(3);
1563        assert_eq!(good_registration(&key).root(&HANDLE), Ok(root(&key)));
1564    }
1565
1566    #[test]
1567    fn a_ctap_registration_gives_its_root_as_it_is() {
1568        let key = signing(3);
1569        assert_eq!(
1570            RootRegistration::Ctap(root(&key)).root(&HANDLE),
1571            Ok(root(&key))
1572        );
1573    }
1574
1575    /// The attestation statement is not checked, whatever its format.
1576    #[test]
1577    fn a_webauthn_registration_s_attestation_statement_is_not_checked() {
1578        use ciborium::Value;
1579        let key = signing(3);
1580        let object = cbor(&Value::Map(vec![
1581            (Value::from("fmt"), Value::from("packed")),
1582            (
1583                Value::from("attStmt"),
1584                Value::Map(vec![
1585                    (Value::from("alg"), Value::from(-7)),
1586                    (Value::from("sig"), Value::Bytes(vec![0; 70])),
1587                ]),
1588            ),
1589            (
1590                Value::from("authData"),
1591                Value::Bytes(registration_data(
1592                    PORTABLE_RP,
1593                    0x45,
1594                    &[1; 32],
1595                    &cbor(&cose_key(&key)),
1596                )),
1597            ),
1598        ]));
1599        assert_eq!(
1600            registration(object, client_data(WEBAUTHN_CREATE, &HANDLE)).root(&HANDLE),
1601            Ok(root(&key))
1602        );
1603    }
1604
1605    #[test]
1606    fn a_webauthn_get_presented_as_a_registration_is_refused() {
1607        let key = signing(3);
1608        let RootRegistration::WebAuthn {
1609            attestation_object, ..
1610        } = good_registration(&key)
1611        else {
1612            unreachable!()
1613        };
1614        let made = registration(attestation_object, client_data(WEBAUTHN_GET, &HANDLE));
1615        assert_eq!(made.root(&HANDLE), Err(WebAuthnError::WrongType));
1616    }
1617
1618    #[test]
1619    fn a_webauthn_registration_for_another_handle_is_refused() {
1620        let key = signing(3);
1621        assert_eq!(
1622            good_registration(&key).root(&[0x43; HANDLE_LEN]),
1623            Err(WebAuthnError::WrongChallenge)
1624        );
1625    }
1626
1627    #[test]
1628    fn a_webauthn_registration_refuses_another_rp_no_up_or_uv_and_no_credential() {
1629        let key = signing(3);
1630        let cose = cbor(&cose_key(&key));
1631        for (rp, flags, refusal) in [
1632            ("spoolframe.app", 0x45, WebAuthnError::WrongRp),
1633            (PORTABLE_RP, 0x41, WebAuthnError::NotVerified),
1634            (PORTABLE_RP, 0x44, WebAuthnError::NotVerified),
1635            (PORTABLE_RP, 0x05, WebAuthnError::NoCredential),
1636        ] {
1637            let data = if flags & FLAG_AT == 0 {
1638                authenticator_data(rp, flags)
1639            } else {
1640                registration_data(rp, flags, &[1; 32], &cose)
1641            };
1642            let made = registration(
1643                attestation("none", data),
1644                client_data(WEBAUTHN_CREATE, &HANDLE),
1645            );
1646            assert_eq!(made.root(&HANDLE), Err(refusal), "{rp} {flags:#x}");
1647        }
1648    }
1649
1650    #[test]
1651    fn a_webauthn_registration_of_a_key_that_is_not_es256_p256_is_refused() {
1652        use ciborium::Value;
1653        let key = signing(3);
1654        let with = |at: usize, value: Value| {
1655            let Value::Map(mut members) = cose_key(&key) else {
1656                unreachable!()
1657            };
1658            members[at].1 = value;
1659            Value::Map(members)
1660        };
1661        let off_curve = {
1662            let Value::Map(mut members) = cose_key(&key) else {
1663                unreachable!()
1664            };
1665            members[4].1 = Value::Bytes(vec![0; 32]);
1666            Value::Map(members)
1667        };
1668        for cose in [
1669            with(0, Value::from(1)),  // OKP
1670            with(1, Value::from(-8)), // EdDSA
1671            with(2, Value::from(2)),  // P-384
1672            with(3, Value::Bytes(vec![1; 31])),
1673            off_curve,
1674        ] {
1675            let made = registration(
1676                attestation(
1677                    "none",
1678                    registration_data(PORTABLE_RP, 0x45, &[1; 32], &cbor(&cose)),
1679                ),
1680                client_data(WEBAUTHN_CREATE, &HANDLE),
1681            );
1682            assert_eq!(
1683                made.root(&HANDLE),
1684                Err(WebAuthnError::UnsupportedKey),
1685                "{cose:?}"
1686            );
1687        }
1688    }
1689
1690    #[test]
1691    fn a_webauthn_registration_with_an_empty_or_long_credential_id_is_refused() {
1692        let key = signing(3);
1693        let cose = cbor(&cose_key(&key));
1694        for id in [vec![], vec![1; MAX_CREDENTIAL_ID + 1]] {
1695            let made = registration(
1696                attestation("none", registration_data(PORTABLE_RP, 0x45, &id, &cose)),
1697                client_data(WEBAUTHN_CREATE, &HANDLE),
1698            );
1699            assert_eq!(made.root(&HANDLE), Err(WebAuthnError::BadCredentialId));
1700        }
1701    }
1702
1703    #[test]
1704    fn an_oversize_webauthn_registration_is_refused_before_it_parses() {
1705        let key = signing(3);
1706        let made = registration(
1707            vec![0; MAX_ATTESTATION_OBJECT + 1],
1708            client_data(WEBAUTHN_CREATE, &HANDLE),
1709        );
1710        assert_eq!(made.root(&HANDLE), Err(WebAuthnError::TooLong));
1711        let RootRegistration::WebAuthn {
1712            attestation_object, ..
1713        } = good_registration(&key)
1714        else {
1715            unreachable!()
1716        };
1717        let made = registration(attestation_object, vec![b' '; MAX_CLIENT_DATA_JSON + 1]);
1718        assert_eq!(made.root(&HANDLE), Err(WebAuthnError::TooLong));
1719    }
1720
1721    #[test]
1722    fn a_malformed_attestation_object_is_refused() {
1723        use ciborium::Value;
1724        let key = signing(3);
1725        let cose = cbor(&cose_key(&key));
1726        let data = registration_data(PORTABLE_RP, 0x45, &[1; 32], &cose);
1727        let mut trailing = attestation("none", data.clone());
1728        trailing.push(0);
1729        let mut nested = Value::Bytes(data.clone());
1730        for _ in 0..1000 {
1731            nested = Value::Array(vec![nested]);
1732        }
1733        for object in [
1734            vec![],
1735            vec![0xff],
1736            b"not cbor".to_vec(),
1737            trailing,
1738            cbor(&Value::Array(vec![])),
1739            cbor(&nested),
1740            // No authData; authData not bytes; fmt not text; a key twice.
1741            cbor(&Value::Map(vec![
1742                (Value::from("fmt"), Value::from("none")),
1743                (Value::from("attStmt"), Value::Map(vec![])),
1744            ])),
1745            cbor(&Value::Map(vec![
1746                (Value::from("fmt"), Value::from("none")),
1747                (Value::from("attStmt"), Value::Map(vec![])),
1748                (Value::from("authData"), Value::from("text")),
1749            ])),
1750            cbor(&Value::Map(vec![
1751                (Value::from("fmt"), Value::from(1)),
1752                (Value::from("attStmt"), Value::Map(vec![])),
1753                (Value::from("authData"), Value::Bytes(data.clone())),
1754            ])),
1755            cbor(&Value::Map(vec![
1756                (Value::from("fmt"), Value::from("none")),
1757                (Value::from("attStmt"), Value::Map(vec![])),
1758                (Value::from("authData"), Value::Bytes(data.clone())),
1759                (Value::from("authData"), Value::Bytes(data.clone())),
1760            ])),
1761        ] {
1762            let made = registration(object.clone(), client_data(WEBAUTHN_CREATE, &HANDLE));
1763            assert_eq!(
1764                made.root(&HANDLE),
1765                Err(WebAuthnError::MalformedAttestation),
1766                "{object:02x?}"
1767            );
1768        }
1769    }
1770
1771    #[test]
1772    fn malformed_attested_credential_data_is_refused() {
1773        let key = signing(3);
1774        let cose = cbor(&cose_key(&key));
1775        let data = registration_data(PORTABLE_RP, 0x45, &[1; 32], &cose);
1776        let mut trailing = data.clone();
1777        trailing.push(0);
1778        let mut cose_twice = registration_data(PORTABLE_RP, 0x45, &[1; 32], &[]);
1779        let ciborium::Value::Map(mut members) = cose_key(&key) else {
1780            unreachable!()
1781        };
1782        members.push(members[0].clone());
1783        cose_twice.extend_from_slice(&cbor(&ciborium::Value::Map(members)));
1784        for data in [
1785            data[..37 + 10].to_vec(),
1786            data[..37 + 18 + 10].to_vec(),
1787            data[..data.len() - 1].to_vec(),
1788            // Bytes after the key, with no extensions flagged.
1789            trailing,
1790            cose_twice,
1791        ] {
1792            let made = registration(
1793                attestation("none", data),
1794                client_data(WEBAUTHN_CREATE, &HANDLE),
1795            );
1796            assert_eq!(
1797                made.root(&HANDLE),
1798                Err(WebAuthnError::MalformedAuthenticatorData)
1799            );
1800        }
1801        // With extensions flagged, what follows the key is theirs.
1802        let mut extended = registration_data(PORTABLE_RP, 0xc5, &[1; 32], &cose);
1803        extended.extend_from_slice(&cbor(&ciborium::Value::Map(vec![])));
1804        let made = registration(
1805            attestation("none", extended),
1806            client_data(WEBAUTHN_CREATE, &HANDLE),
1807        );
1808        assert_eq!(made.root(&HANDLE), Ok(root(&key)));
1809    }
1810}