Skip to main content

spoolframe_protocol/portable/
roots.rs

1//! An identity's roots (P7-08): the keys that may act for it. A phrase
2//! root is P7-01's Ed25519 key; a security key root is a FIDO2 key's
3//! 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 keeps the layouts of P7-02: a domain string with its
8//! NUL, then fixed-width 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 PX-14's `*.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    /// P7-01's root: 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 (P7-08), 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, as P7-02 wrote it,
587/// so a phrase root's credential and state read as they always did; a
588/// CTAP2 assertion is `{"authenticator_data": hex, "signature": hex}`; a
589/// WebAuthn one is `{"authenticator_data": hex, "client_data_json": hex,
590/// "signature": hex}` (wire revision 14, additive: no struct grows).
591#[derive(Debug, Clone, PartialEq, Eq)]
592pub enum RootSignature {
593    Ed25519(Signature),
594    Ctap {
595        authenticator_data: Vec<u8>,
596        signature: Vec<u8>,
597    },
598    /// A WebAuthn assertion, as a platform API returns it (Apple's
599    /// `ASAuthorizationSecurityKeyPublicKeyCredentialAssertion`): the
600    /// challenge in `client_data_json` is SHA-256 of the message, the
601    /// bytes the CTAP2 form's `clientDataHash` is. The credential id is
602    /// the root's.
603    WebAuthn {
604        authenticator_data: Vec<u8>,
605        /// The exact bytes the platform returned (`rawClientDataJSON`),
606        /// at most [`MAX_CLIENT_DATA_JSON`].
607        client_data_json: Vec<u8>,
608        signature: Vec<u8>,
609    },
610}
611
612impl RootSignature {
613    /// The Ed25519 signature, for a phrase root's.
614    pub fn as_ed25519(&self) -> Option<&Signature> {
615        match self {
616            RootSignature::Ed25519(signature) => Some(signature),
617            RootSignature::Ctap { .. } | RootSignature::WebAuthn { .. } => None,
618        }
619    }
620}
621
622impl From<Signature> for RootSignature {
623    fn from(signature: Signature) -> Self {
624        RootSignature::Ed25519(signature)
625    }
626}
627
628/// Hex for serde, over a byte string of at most `max` bytes.
629pub(crate) mod hex_vec {
630    use super::*;
631
632    struct Hex<'a>(&'a [u8]);
633
634    impl fmt::Display for Hex<'_> {
635        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636            write_hex(f, self.0)
637        }
638    }
639
640    pub fn serialize<S: Serializer>(bytes: &[u8], s: S) -> Result<S::Ok, S::Error> {
641        s.collect_str(&Hex(bytes))
642    }
643
644    /// Even-length hex, either case, of at most `max` bytes.
645    pub fn parse(text: &str, max: usize) -> Option<Vec<u8>> {
646        if !text.len().is_multiple_of(2) || text.len() > 2 * max || !text.is_ascii() {
647            return None;
648        }
649        (0..text.len() / 2)
650            .map(|i| u8::from_str_radix(&text[2 * i..2 * i + 2], 16).ok())
651            .collect()
652    }
653}
654
655#[derive(Serialize, Deserialize)]
656#[serde(deny_unknown_fields)]
657struct CtapWire {
658    #[serde(serialize_with = "hex_vec::serialize")]
659    #[serde(deserialize_with = "authenticator_data_hex")]
660    authenticator_data: Vec<u8>,
661    #[serde(serialize_with = "hex_vec::serialize")]
662    #[serde(deserialize_with = "der_hex")]
663    signature: Vec<u8>,
664}
665
666#[derive(Serialize, Deserialize)]
667#[serde(deny_unknown_fields)]
668struct WebAuthnWire {
669    #[serde(serialize_with = "hex_vec::serialize")]
670    #[serde(deserialize_with = "authenticator_data_hex")]
671    authenticator_data: Vec<u8>,
672    #[serde(serialize_with = "hex_vec::serialize")]
673    #[serde(deserialize_with = "client_data_json_hex")]
674    client_data_json: Vec<u8>,
675    #[serde(serialize_with = "hex_vec::serialize")]
676    #[serde(deserialize_with = "der_hex")]
677    signature: Vec<u8>,
678}
679
680fn client_data_json_hex<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
681    let text = String::deserialize(d)?;
682    hex_vec::parse(&text, MAX_CLIENT_DATA_JSON)
683        .ok_or_else(|| serde::de::Error::custom("client data JSON is at most 4096 bytes of hex"))
684}
685
686fn authenticator_data_hex<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
687    let text = String::deserialize(d)?;
688    hex_vec::parse(&text, MAX_AUTHENTICATOR_DATA)
689        .ok_or_else(|| serde::de::Error::custom("authenticator data is at most 512 bytes of hex"))
690}
691
692fn der_hex<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
693    let text = String::deserialize(d)?;
694    hex_vec::parse(&text, MAX_DER_SIGNATURE)
695        .ok_or_else(|| serde::de::Error::custom("a DER signature is at most 72 bytes of hex"))
696}
697
698#[derive(Deserialize)]
699#[serde(untagged)]
700enum RootSignatureWire {
701    Ed25519(String),
702    // Before `Ctap`, and both refuse unknown fields, so neither form reads
703    // as the other.
704    WebAuthn(WebAuthnWire),
705    Ctap(CtapWire),
706}
707
708impl Serialize for RootSignature {
709    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
710        match self {
711            RootSignature::Ed25519(signature) => super::signature_hex::serialize(signature, s),
712            RootSignature::Ctap {
713                authenticator_data,
714                signature,
715            } => CtapWire {
716                authenticator_data: authenticator_data.clone(),
717                signature: signature.clone(),
718            }
719            .serialize(s),
720            RootSignature::WebAuthn {
721                authenticator_data,
722                client_data_json,
723                signature,
724            } => WebAuthnWire {
725                authenticator_data: authenticator_data.clone(),
726                client_data_json: client_data_json.clone(),
727                signature: signature.clone(),
728            }
729            .serialize(s),
730        }
731    }
732}
733
734impl<'de> Deserialize<'de> for RootSignature {
735    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
736        match RootSignatureWire::deserialize(d)? {
737            RootSignatureWire::Ed25519(text) => parse_hex::<{ Signature::BYTE_SIZE }>(&text)
738                .map(|bytes| RootSignature::Ed25519(Signature::from_bytes(&bytes)))
739                .ok_or_else(|| serde::de::Error::custom("a signature is 128 hex digits")),
740            RootSignatureWire::Ctap(CtapWire {
741                authenticator_data,
742                signature,
743            }) => Ok(RootSignature::Ctap {
744                authenticator_data,
745                signature,
746            }),
747            RootSignatureWire::WebAuthn(WebAuthnWire {
748                authenticator_data,
749                client_data_json,
750                signature,
751            }) => Ok(RootSignature::WebAuthn {
752                authenticator_data,
753                client_data_json,
754                signature,
755            }),
756        }
757    }
758}
759
760/// A root in serde: `{"type": "phrase", "public_key": hex}` or
761/// `{"type": "security_key", "public_key": hex, "credential_id": hex}`.
762#[derive(Serialize, Deserialize)]
763#[serde(tag = "type", rename_all = "snake_case")]
764enum RootKeyWire {
765    Phrase {
766        public_key: String,
767    },
768    SecurityKey {
769        public_key: String,
770        credential_id: String,
771    },
772}
773
774impl Serialize for RootKey {
775    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
776        let hex = |bytes: &[u8]| bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
777        match self {
778            RootKey::Phrase(key) => RootKeyWire::Phrase {
779                public_key: hex(key),
780            },
781            RootKey::SecurityKey {
782                public_key,
783                credential_id,
784            } => RootKeyWire::SecurityKey {
785                public_key: hex(public_key),
786                credential_id: hex(credential_id),
787            },
788        }
789        .serialize(s)
790    }
791}
792
793impl<'de> Deserialize<'de> for RootKey {
794    /// Sizes are checked here; whether the keys are points is
795    /// [`RootKey::is_valid`]'s, asked wherever a root is taken in.
796    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
797        let bad = |what: &'static str| serde::de::Error::custom(what);
798        match RootKeyWire::deserialize(d)? {
799            RootKeyWire::Phrase { public_key } => parse_hex::<32>(&public_key)
800                .map(RootKey::Phrase)
801                .ok_or_else(|| bad("a phrase root is 64 hex digits")),
802            RootKeyWire::SecurityKey {
803                public_key,
804                credential_id,
805            } => {
806                let public_key = parse_hex::<P256_PUBLIC_KEY_LEN>(&public_key)
807                    .ok_or_else(|| bad("a security key's public key is 130 hex digits"))?;
808                let credential_id = hex_vec::parse(&credential_id, MAX_CREDENTIAL_ID)
809                    .filter(|id| !id.is_empty())
810                    .ok_or_else(|| bad("a credential id is 1 to 128 bytes of hex"))?;
811                Ok(RootKey::SecurityKey {
812                    public_key,
813                    credential_id,
814                })
815            }
816        }
817    }
818}
819
820/// Why a genesis is not one.
821#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
822pub enum GenesisError {
823    /// No roots, or more than [`MAX_ROOTS`].
824    #[error("an identity has 1 to {MAX_ROOTS} roots")]
825    RootCount,
826    /// Not one signature for each root.
827    #[error("an identity's genesis has one signature for each root")]
828    SignatureCount,
829    /// A root named twice.
830    #[error("an identity's genesis names a root twice")]
831    Duplicate,
832    /// A root that is not a key any root could be.
833    #[error("an identity's genesis names a root that is not a valid key")]
834    InvalidRoot,
835    /// A root did not sign it, as it is.
836    #[error("a root did not sign its identity's genesis")]
837    BadSignature,
838}
839
840/// Bytes in an identity's handle.
841pub const HANDLE_LEN: usize = 32;
842
843/// How an identity begins (P7-08): its handle, its first roots, and each
844/// root's signature over both, so every root proves it is held. For a
845/// security key identity the handle is random and is also the key's
846/// resident credential's `user.id`, so a key put into a device that has
847/// never seen it says which identity it roots.
848///
849/// The genesis fixes the identity's id ([`Self::user`]): later root
850/// changes, made in its states, never change it.
851#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
852pub struct IdentityGenesis {
853    #[serde(with = "handle_hex")]
854    pub handle: [u8; HANDLE_LEN],
855    pub roots: Vec<RootKey>,
856    /// One for each root, in `roots`' order, over [`Self::message`].
857    pub signatures: Vec<RootSignature>,
858}
859
860/// Hex for serde, over a genesis handle (P7-08).
861pub(crate) mod handle_hex {
862    use super::*;
863
864    pub fn serialize<S: Serializer>(handle: &[u8; HANDLE_LEN], s: S) -> Result<S::Ok, S::Error> {
865        hex_vec::serialize(handle, s)
866    }
867
868    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<[u8; HANDLE_LEN], D::Error> {
869        let text = String::deserialize(d)?;
870        parse_hex(&text).ok_or_else(|| serde::de::Error::custom("a handle is 64 hex digits"))
871    }
872}
873
874impl IdentityGenesis {
875    /// What each root signs: [`GENESIS_DOMAIN`], the handle (32 bytes),
876    /// the count of roots (u8), then each root ([`RootKey::bytes`]) in
877    /// order. `None` for more roots than a byte counts.
878    pub fn message(handle: &[u8; HANDLE_LEN], roots: &[RootKey]) -> Option<Vec<u8>> {
879        let count = u8::try_from(roots.len()).ok()?;
880        let mut message = Vec::with_capacity(GENESIS_DOMAIN.len() + 33 + 100 * roots.len());
881        message.extend_from_slice(GENESIS_DOMAIN);
882        message.extend_from_slice(handle);
883        message.push(count);
884        for root in roots {
885            message.extend_from_slice(&root.bytes());
886        }
887        Some(message)
888    }
889
890    /// Whether it is a genesis: 1 to [`MAX_ROOTS`] valid roots, none
891    /// twice, each with its signature over [`Self::message`].
892    pub fn verify(&self) -> Result<(), GenesisError> {
893        if self.roots.is_empty() || self.roots.len() > MAX_ROOTS {
894            return Err(GenesisError::RootCount);
895        }
896        if self.signatures.len() != self.roots.len() {
897            return Err(GenesisError::SignatureCount);
898        }
899        if !self.roots.iter().all(RootKey::is_valid) {
900            return Err(GenesisError::InvalidRoot);
901        }
902        let mut seen = self.roots.clone();
903        seen.sort();
904        seen.dedup();
905        if seen.len() != self.roots.len() {
906            return Err(GenesisError::Duplicate);
907        }
908        let message = Self::message(&self.handle, &self.roots).ok_or(GenesisError::RootCount)?;
909        if self
910            .roots
911            .iter()
912            .zip(&self.signatures)
913            .all(|(root, signature)| root.verify(&message, signature))
914        {
915            Ok(())
916        } else {
917            Err(GenesisError::BadSignature)
918        }
919    }
920
921    /// The identity's id. A genesis of one phrase root keeps P7-01's id,
922    /// that root's public key (the user's decision, 2026-10-11: no phrase
923    /// identity moves); any other's is
924    /// `blake3::derive_key(`[`USER_ID_CONTEXT`]`, message)`. Signatures
925    /// are left out, since an ECDSA one differs each time it is made.
926    pub fn user(&self) -> PortableUserId {
927        if let [RootKey::Phrase(key)] = self.roots.as_slice() {
928            return PortableUserId(*key);
929        }
930        let message =
931            Self::message(&self.handle, &self.roots).expect("at most 255 roots in a genesis");
932        PortableUserId(blake3::derive_key(USER_ID_CONTEXT, &message))
933    }
934}
935
936/// What an added root signs to prove it is held, for `user`:
937/// [`ROOT_ADD_DOMAIN`], the user (32 bytes), then the root
938/// ([`RootKey::bytes`]).
939pub fn root_add_message(user: &PortableUserId, root: &RootKey) -> Vec<u8> {
940    let mut message = Vec::with_capacity(ROOT_ADD_DOMAIN.len() + 32 + 100);
941    message.extend_from_slice(ROOT_ADD_DOMAIN);
942    message.extend_from_slice(user.as_bytes());
943    message.extend_from_slice(&root.bytes());
944    message
945}
946
947/// What the root that adds another signs, for `user`:
948/// [`ROOT_ENDORSE_DOMAIN`], the user (32 bytes), the added root
949/// ([`RootKey::bytes`]), then when it was added (i64, big-endian).
950pub fn root_endorse_message(user: &PortableUserId, root: &RootKey, added_at: i64) -> Vec<u8> {
951    let mut message = Vec::with_capacity(ROOT_ENDORSE_DOMAIN.len() + 32 + 100 + 8);
952    message.extend_from_slice(ROOT_ENDORSE_DOMAIN);
953    message.extend_from_slice(user.as_bytes());
954    message.extend_from_slice(&root.bytes());
955    message.extend_from_slice(&added_at.to_be_bytes());
956    message
957}
958
959/// A root added to an identity, self-certifying: who added it and when,
960/// that root's endorsement over [`root_endorse_message`], and the new
961/// root's proof that it is held, over [`root_add_message`]. A state lists
962/// every one so far, so any state carries the whole chain.
963#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
964pub struct AddedRoot {
965    pub root: RootKey,
966    pub added_by: RootKey,
967    /// Unix seconds.
968    pub added_at: i64,
969    pub endorsement: RootSignature,
970    pub possession: RootSignature,
971}
972
973impl AddedRoot {
974    /// Whether its root is valid and both signatures hold: the root's
975    /// over its addition, the adder's over its endorsement.
976    pub fn verify(&self, user: &PortableUserId) -> bool {
977        self.root.is_valid()
978            && self
979                .root
980                .verify(&root_add_message(user, &self.root), &self.possession)
981            && self.added_by.verify(
982                &root_endorse_message(user, &self.root, self.added_at),
983                &self.endorsement,
984            )
985    }
986}
987
988/// A root a state removes, and when (Unix seconds). A removed root never
989/// comes back.
990#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
991pub struct RemovedRoot {
992    pub root: RootKey,
993    pub removed_at: i64,
994}
995
996/// The roots that may act for an identity, as a verifier works them out
997/// from its genesis and every valid state it holds (P7-08):
998///
999/// - `ever`: the genesis's roots, and every root added by one in `ever`,
1000///   until nothing more is added. A state counts only if one of these
1001///   signed it.
1002/// - `removed`: every root a state signed by one in `ever` removes, at
1003///   its earliest `removed_at`. Removal never lapses: a removed root never
1004///   comes back.
1005/// - `members`: the genesis's roots, and every root added by a member
1006///   no later than that member's own removal (`added_at` at or before
1007///   its `removed_at`: times are whole seconds, and a rotation adds the
1008///   new key and drops the old one in the same one), until nothing more
1009///   is added; then without the removed. A credential counts only from a
1010///   member.
1011///
1012/// So a root added by a key later rotated out stays, and one a removed
1013/// key adds after its removal does not. Times are the roots' own word:
1014/// a stolen key that backdates an addition is stopped where its removal
1015/// arrived first, by the verifier refusing the state that brings it
1016/// (`spoolframe_server`'s store, the SDK's `accept_state`). A removed
1017/// root's removals still count, so two roots that remove each other are
1018/// both gone: the identity is locked rather than taken (P7-07 reviews
1019/// this).
1020#[derive(Debug, Clone, Default, PartialEq, Eq)]
1021pub struct RootSet {
1022    pub ever: Vec<RootKey>,
1023    pub removed: Vec<(RootKey, i64)>,
1024    pub members: Vec<RootKey>,
1025}
1026
1027/// A state as the root set reads it: who signed it, what it adds and
1028/// removes. Its signatures are assumed checked.
1029pub struct RootChanges<'a> {
1030    pub signer: &'a RootKey,
1031    pub added: &'a [AddedRoot],
1032    pub removed: &'a [RemovedRoot],
1033}
1034
1035impl RootSet {
1036    /// The set `genesis` begins and `states` change.
1037    pub fn of(genesis: &[RootKey], states: &[RootChanges<'_>]) -> Self {
1038        let additions: Vec<&AddedRoot> = states.iter().flat_map(|s| s.added).collect();
1039        let closure = |admit: &dyn Fn(&[RootKey], &AddedRoot) -> bool| {
1040            let mut set = genesis.to_vec();
1041            loop {
1042                let before = set.len();
1043                for added in &additions {
1044                    if !set.contains(&added.root) && admit(&set, added) {
1045                        set.push(added.root.clone());
1046                    }
1047                }
1048                if set.len() == before {
1049                    return set;
1050                }
1051            }
1052        };
1053        let ever = closure(&|set, added| set.contains(&added.added_by));
1054        let mut removed: Vec<(RootKey, i64)> = Vec::new();
1055        for state in states.iter().filter(|s| ever.contains(s.signer)) {
1056            for root in state.removed {
1057                match removed.iter_mut().find(|(r, _)| *r == root.root) {
1058                    Some((_, at)) => *at = (*at).min(root.removed_at),
1059                    None => removed.push((root.root.clone(), root.removed_at)),
1060                }
1061            }
1062        }
1063        let removed_at =
1064            |root: &RootKey| removed.iter().find(|(r, _)| r == root).map(|(_, at)| *at);
1065        let members = closure(&|set, added| {
1066            set.contains(&added.added_by)
1067                && removed_at(&added.added_by).is_none_or(|at| added.added_at <= at)
1068        })
1069        .into_iter()
1070        .filter(|root| removed_at(root).is_none())
1071        .collect();
1072        RootSet {
1073            ever,
1074            removed,
1075            members,
1076        }
1077    }
1078
1079    /// Whether `root` may act now: a member, not removed.
1080    pub fn holds(&self, root: &RootKey) -> bool {
1081        self.members.contains(root)
1082    }
1083
1084    /// Whether `root` was ever one of the identity's: a state it signed
1085    /// is taken in, for its removals.
1086    pub fn knew(&self, root: &RootKey) -> bool {
1087        self.ever.contains(root)
1088    }
1089
1090    /// Whether `root` is removed.
1091    pub fn is_removed(&self, root: &RootKey) -> bool {
1092        self.removed.iter().any(|(r, _)| r == root)
1093    }
1094
1095    /// Whether `added`, arriving now, adds a root this set does not know
1096    /// whose adder this set has already removed: an addition that came
1097    /// after the removal, whatever time it claims. A verifier refuses the
1098    /// state that brings it, so a stolen key cannot backdate its way past
1099    /// a removal the verifier already holds.
1100    pub fn refuses_additions(&self, added: &[AddedRoot]) -> bool {
1101        added
1102            .iter()
1103            .any(|added| !self.knew(&added.root) && self.is_removed(&added.added_by))
1104    }
1105}
1106
1107#[cfg(test)]
1108mod tests {
1109    use base64::Engine;
1110    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
1111    use p256::ecdsa::signature::Signer;
1112    use p256::ecdsa::{DerSignature, SigningKey};
1113
1114    use super::*;
1115
1116    const MESSAGE: &[u8] = b"spoolframe root add v1\0some bytes";
1117
1118    fn signing(seed: u8) -> SigningKey {
1119        SigningKey::from_bytes(&[seed; 32].into()).unwrap()
1120    }
1121
1122    fn public(key: &SigningKey) -> [u8; P256_PUBLIC_KEY_LEN] {
1123        key.verifying_key()
1124            .to_sec1_point(false)
1125            .as_bytes()
1126            .try_into()
1127            .unwrap()
1128    }
1129
1130    fn client_data(kind: &str, challenge: &[u8]) -> Vec<u8> {
1131        format!(
1132            r#"{{"type":"{kind}","challenge":"{}","origin":"https://portable.spoolframe.app"}}"#,
1133            URL_SAFE_NO_PAD.encode(challenge)
1134        )
1135        .into_bytes()
1136    }
1137
1138    fn authenticator_data(rp: &str, flags: u8) -> Vec<u8> {
1139        let mut data = Sha256::digest(rp.as_bytes()).to_vec();
1140        data.push(flags);
1141        data.extend_from_slice(&7u32.to_be_bytes());
1142        data
1143    }
1144
1145    /// What a platform returns: `key`'s signature over
1146    /// `authenticator_data ‖ SHA-256(client_data_json)`, made properly, so
1147    /// only the part a test changes is wrong.
1148    fn signed(
1149        key: &SigningKey,
1150        authenticator_data: Vec<u8>,
1151        client_data_json: Vec<u8>,
1152    ) -> RootSignature {
1153        let mut bytes = authenticator_data.clone();
1154        bytes.extend_from_slice(&Sha256::digest(&client_data_json));
1155        let signature: DerSignature = key.sign(&bytes);
1156        RootSignature::WebAuthn {
1157            authenticator_data,
1158            client_data_json,
1159            signature: signature.as_bytes().to_vec(),
1160        }
1161    }
1162
1163    fn good(key: &SigningKey, message: &[u8]) -> RootSignature {
1164        signed(
1165            key,
1166            authenticator_data(PORTABLE_RP, 0x05),
1167            client_data(WEBAUTHN_GET, &Sha256::digest(message)),
1168        )
1169    }
1170
1171    fn check(
1172        key: &SigningKey,
1173        message: &[u8],
1174        signature: &RootSignature,
1175    ) -> Result<(), WebAuthnError> {
1176        let RootSignature::WebAuthn {
1177            authenticator_data,
1178            client_data_json,
1179            signature,
1180        } = signature
1181        else {
1182            unreachable!()
1183        };
1184        verify_webauthn(
1185            &public(key),
1186            message,
1187            authenticator_data,
1188            client_data_json,
1189            signature,
1190        )
1191    }
1192
1193    fn root(key: &SigningKey) -> RootKey {
1194        RootKey::SecurityKey {
1195            public_key: public(key),
1196            credential_id: vec![1; 32],
1197        }
1198    }
1199
1200    #[test]
1201    fn a_webauthn_assertion_over_the_message_s_hash_verifies() {
1202        let key = signing(3);
1203        assert_eq!(check(&key, MESSAGE, &good(&key, MESSAGE)), Ok(()));
1204        assert!(root(&key).verify(MESSAGE, &good(&key, MESSAGE)));
1205    }
1206
1207    #[test]
1208    fn a_webauthn_assertion_of_the_wrong_type_is_refused() {
1209        let key = signing(3);
1210        let made = signed(
1211            &key,
1212            authenticator_data(PORTABLE_RP, 0x05),
1213            client_data("payment.get", &Sha256::digest(MESSAGE)),
1214        );
1215        assert_eq!(check(&key, MESSAGE, &made), Err(WebAuthnError::WrongType));
1216    }
1217
1218    /// A registration's client data, signed by the credential's own key
1219    /// as a packed self-attestation is, over the right challenge: the type
1220    /// is what keeps it from passing as an assertion.
1221    #[test]
1222    fn a_webauthn_create_presented_as_an_assertion_is_refused() {
1223        let key = signing(3);
1224        let made = signed(
1225            &key,
1226            authenticator_data(PORTABLE_RP, 0x45),
1227            client_data(WEBAUTHN_CREATE, &Sha256::digest(MESSAGE)),
1228        );
1229        assert_eq!(check(&key, MESSAGE, &made), Err(WebAuthnError::WrongType));
1230    }
1231
1232    #[test]
1233    fn a_webauthn_assertion_with_a_wrong_challenge_is_refused() {
1234        let key = signing(3);
1235        // The message itself, not its hash.
1236        let made = signed(
1237            &key,
1238            authenticator_data(PORTABLE_RP, 0x05),
1239            client_data(WEBAUTHN_GET, MESSAGE),
1240        );
1241        assert_eq!(
1242            check(&key, MESSAGE, &made),
1243            Err(WebAuthnError::WrongChallenge)
1244        );
1245        // The hash, padded: another spelling of the same bytes.
1246        let padded = format!(
1247            r#"{{"type":"webauthn.get","challenge":"{}="}}"#,
1248            URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE))
1249        );
1250        let made = signed(
1251            &key,
1252            authenticator_data(PORTABLE_RP, 0x05),
1253            padded.into_bytes(),
1254        );
1255        assert_eq!(
1256            check(&key, MESSAGE, &made),
1257            Err(WebAuthnError::WrongChallenge)
1258        );
1259    }
1260
1261    #[test]
1262    fn a_webauthn_assertion_over_another_message_is_refused() {
1263        let key = signing(3);
1264        let other = good(&key, b"spoolframe root add v1\0other bytes");
1265        assert_eq!(
1266            check(&key, MESSAGE, &other),
1267            Err(WebAuthnError::WrongChallenge)
1268        );
1269        assert!(!root(&key).verify(MESSAGE, &other));
1270    }
1271
1272    #[test]
1273    fn a_cross_origin_webauthn_assertion_is_refused_and_a_false_one_is_not() {
1274        let key = signing(3);
1275        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1276        let with = |cross: &str| {
1277            signed(
1278                &key,
1279                authenticator_data(PORTABLE_RP, 0x05),
1280                format!(
1281                    r#"{{"type":"webauthn.get","challenge":"{challenge}","crossOrigin":{cross}}}"#
1282                )
1283                .into_bytes(),
1284            )
1285        };
1286        assert_eq!(
1287            check(&key, MESSAGE, &with("true")),
1288            Err(WebAuthnError::CrossOrigin)
1289        );
1290        assert_eq!(check(&key, MESSAGE, &with("false")), Ok(()));
1291    }
1292
1293    /// The origin is not what binds it; any origin with the right RP id
1294    /// hash verifies.
1295    #[test]
1296    fn a_webauthn_assertion_with_another_origin_verifies() {
1297        let key = signing(3);
1298        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1299        let made = signed(
1300            &key,
1301            authenticator_data(PORTABLE_RP, 0x05),
1302            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}","origin":"ios:bundle-id:app.spoolframe"}}"#)
1303                .into_bytes(),
1304        );
1305        assert_eq!(check(&key, MESSAGE, &made), Ok(()));
1306    }
1307
1308    #[test]
1309    fn a_webauthn_assertion_under_another_rp_is_refused() {
1310        let key = signing(3);
1311        let made = signed(
1312            &key,
1313            authenticator_data("spoolframe.app", 0x05),
1314            client_data(WEBAUTHN_GET, &Sha256::digest(MESSAGE)),
1315        );
1316        assert_eq!(check(&key, MESSAGE, &made), Err(WebAuthnError::WrongRp));
1317    }
1318
1319    #[test]
1320    fn a_webauthn_assertion_without_up_or_uv_is_refused() {
1321        let key = signing(3);
1322        for flags in [0x01, 0x04, 0x00] {
1323            let made = signed(
1324                &key,
1325                authenticator_data(PORTABLE_RP, flags),
1326                client_data(WEBAUTHN_GET, &Sha256::digest(MESSAGE)),
1327            );
1328            assert_eq!(
1329                check(&key, MESSAGE, &made),
1330                Err(WebAuthnError::NotVerified),
1331                "{flags:#x}"
1332            );
1333        }
1334    }
1335
1336    #[test]
1337    fn a_webauthn_assertion_with_a_bad_signature_is_refused() {
1338        let key = signing(3);
1339        let RootSignature::WebAuthn {
1340            authenticator_data,
1341            client_data_json,
1342            mut signature,
1343        } = good(&key, MESSAGE)
1344        else {
1345            unreachable!()
1346        };
1347        let last = signature.len() - 1;
1348        signature[last] ^= 1;
1349        let made = RootSignature::WebAuthn {
1350            authenticator_data,
1351            client_data_json,
1352            signature,
1353        };
1354        assert_eq!(
1355            check(&key, MESSAGE, &made),
1356            Err(WebAuthnError::BadSignature)
1357        );
1358    }
1359
1360    #[test]
1361    fn a_webauthn_assertion_from_another_credential_is_refused() {
1362        let (key, other) = (signing(3), signing(4));
1363        assert_eq!(
1364            check(&key, MESSAGE, &good(&other, MESSAGE)),
1365            Err(WebAuthnError::BadSignature)
1366        );
1367        assert!(!root(&key).verify(MESSAGE, &good(&other, MESSAGE)));
1368    }
1369
1370    #[test]
1371    fn an_oversize_client_data_json_is_refused_before_it_parses() {
1372        let key = signing(3);
1373        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1374        let mut json =
1375            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}","pad":""#).into_bytes();
1376        json.resize(MAX_CLIENT_DATA_JSON - 2, b'x');
1377        json.extend_from_slice(b"\"}");
1378        assert_eq!(json.len(), MAX_CLIENT_DATA_JSON);
1379        let at_bound = signed(&key, authenticator_data(PORTABLE_RP, 0x05), json.clone());
1380        assert_eq!(check(&key, MESSAGE, &at_bound), Ok(()));
1381        json.insert(json.len() - 2, b'x');
1382        let over = signed(&key, authenticator_data(PORTABLE_RP, 0x05), json);
1383        assert_eq!(check(&key, MESSAGE, &over), Err(WebAuthnError::TooLong));
1384    }
1385
1386    #[test]
1387    fn malformed_client_data_json_is_refused() {
1388        let key = signing(3);
1389        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(MESSAGE));
1390        for json in [
1391            b"".to_vec(),
1392            b"not json".to_vec(),
1393            b"[]".to_vec(),
1394            b"\xff\xfe".to_vec(),
1395            format!(r#"{{"challenge":"{challenge}"}}"#).into_bytes(),
1396            br#"{"type":"webauthn.get"}"#.to_vec(),
1397            format!(r#"{{"type":1,"challenge":"{challenge}"}}"#).into_bytes(),
1398            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}","crossOrigin":"no"}}"#)
1399                .into_bytes(),
1400            // A member twice: which one a reader takes is not to be guessed.
1401            format!(
1402                r#"{{"type":"webauthn.create","type":"webauthn.get","challenge":"{challenge}"}}"#
1403            )
1404            .into_bytes(),
1405            format!(r#"{{"type":"webauthn.get","challenge":"{challenge}""#).into_bytes(),
1406        ] {
1407            let made = signed(&key, authenticator_data(PORTABLE_RP, 0x05), json.clone());
1408            assert_eq!(
1409                check(&key, MESSAGE, &made),
1410                Err(WebAuthnError::MalformedClientData),
1411                "{}",
1412                String::from_utf8_lossy(&json)
1413            );
1414        }
1415    }
1416
1417    #[test]
1418    fn oversize_or_short_webauthn_fields_are_refused() {
1419        let key = signing(3);
1420        let RootSignature::WebAuthn {
1421            authenticator_data,
1422            client_data_json,
1423            signature,
1424        } = good(&key, MESSAGE)
1425        else {
1426            unreachable!()
1427        };
1428        let mut long_data = authenticator_data.clone();
1429        long_data.resize(MAX_AUTHENTICATOR_DATA + 1, 0);
1430        let mut long_signature = signature.clone();
1431        long_signature.resize(MAX_DER_SIGNATURE + 1, 0);
1432        let public = public(&key);
1433        assert_eq!(
1434            verify_webauthn(&public, MESSAGE, &long_data, &client_data_json, &signature),
1435            Err(WebAuthnError::TooLong)
1436        );
1437        assert_eq!(
1438            verify_webauthn(
1439                &public,
1440                MESSAGE,
1441                &authenticator_data,
1442                &client_data_json,
1443                &long_signature
1444            ),
1445            Err(WebAuthnError::TooLong)
1446        );
1447        assert_eq!(
1448            verify_webauthn(
1449                &public,
1450                MESSAGE,
1451                &authenticator_data[..36],
1452                &client_data_json,
1453                &signature
1454            ),
1455            Err(WebAuthnError::MalformedAuthenticatorData)
1456        );
1457    }
1458
1459    /// A phrase root takes no WebAuthn signature, and a security key root
1460    /// no Ed25519 one.
1461    #[test]
1462    fn a_webauthn_signature_is_no_phrase_root_s() {
1463        let key = signing(3);
1464        let phrase = RootKey::Phrase(
1465            ed25519_dalek::SigningKey::from_bytes(&[5; 32])
1466                .verifying_key()
1467                .to_bytes(),
1468        );
1469        assert!(!phrase.verify(MESSAGE, &good(&key, MESSAGE)));
1470    }
1471
1472    #[test]
1473    fn a_webauthn_signature_round_trips_and_reads_as_neither_other_form() {
1474        let key = signing(3);
1475        let made = good(&key, MESSAGE);
1476        let json = serde_json::to_value(&made).unwrap();
1477        assert_eq!(
1478            json.as_object().unwrap().keys().collect::<Vec<_>>(),
1479            ["authenticator_data", "client_data_json", "signature"]
1480        );
1481        assert_eq!(
1482            serde_json::from_value::<RootSignature>(json.clone()).unwrap(),
1483            made
1484        );
1485        let mut cbor = Vec::new();
1486        ciborium::into_writer(&made, &mut cbor).unwrap();
1487        assert_eq!(
1488            ciborium::from_reader::<RootSignature, _>(cbor.as_slice()).unwrap(),
1489            made
1490        );
1491        // A CTAP2 assertion with an extra member is neither form.
1492        let mut extra = json.clone();
1493        extra.as_object_mut().unwrap().remove("client_data_json");
1494        extra
1495            .as_object_mut()
1496            .unwrap()
1497            .insert("origin".into(), "00".into());
1498        assert!(serde_json::from_value::<RootSignature>(extra).is_err());
1499        // An oversize client data JSON does not read, nor fall back to CTAP2.
1500        let mut over = json;
1501        over["client_data_json"] = "00".repeat(MAX_CLIENT_DATA_JSON + 1).into();
1502        assert!(serde_json::from_value::<RootSignature>(over).is_err());
1503    }
1504
1505    // Registration.
1506
1507    const HANDLE: [u8; HANDLE_LEN] = [0x42; HANDLE_LEN];
1508
1509    fn cose_key(key: &SigningKey) -> ciborium::Value {
1510        use ciborium::Value;
1511        let point = key.verifying_key().to_sec1_point(false);
1512        Value::Map(vec![
1513            (Value::from(1), Value::from(2)),
1514            (Value::from(3), Value::from(-7)),
1515            (Value::from(-1), Value::from(1)),
1516            (Value::from(-2), Value::Bytes(point.x().unwrap().to_vec())),
1517            (Value::from(-3), Value::Bytes(point.y().unwrap().to_vec())),
1518        ])
1519    }
1520
1521    fn cbor(value: &ciborium::Value) -> Vec<u8> {
1522        let mut bytes = Vec::new();
1523        ciborium::into_writer(value, &mut bytes).unwrap();
1524        bytes
1525    }
1526
1527    fn registration_data(rp: &str, flags: u8, credential_id: &[u8], cose: &[u8]) -> Vec<u8> {
1528        let mut data = authenticator_data(rp, flags);
1529        data.extend_from_slice(&[0xaa; 16]);
1530        data.extend_from_slice(&u16::try_from(credential_id.len()).unwrap().to_be_bytes());
1531        data.extend_from_slice(credential_id);
1532        data.extend_from_slice(cose);
1533        data
1534    }
1535
1536    fn attestation(fmt: &str, auth_data: Vec<u8>) -> Vec<u8> {
1537        use ciborium::Value;
1538        cbor(&Value::Map(vec![
1539            (Value::from("fmt"), Value::from(fmt)),
1540            (Value::from("attStmt"), Value::Map(vec![])),
1541            (Value::from("authData"), Value::Bytes(auth_data)),
1542        ]))
1543    }
1544
1545    fn registration(attestation_object: Vec<u8>, client_data_json: Vec<u8>) -> RootRegistration {
1546        RootRegistration::WebAuthn {
1547            attestation_object,
1548            client_data_json,
1549        }
1550    }
1551
1552    fn good_registration(key: &SigningKey) -> RootRegistration {
1553        registration(
1554            attestation(
1555                "none",
1556                registration_data(PORTABLE_RP, 0x45, &[1; 32], &cbor(&cose_key(key))),
1557            ),
1558            client_data(WEBAUTHN_CREATE, &HANDLE),
1559        )
1560    }
1561
1562    #[test]
1563    fn a_webauthn_registration_gives_the_credential_s_root() {
1564        let key = signing(3);
1565        assert_eq!(good_registration(&key).root(&HANDLE), Ok(root(&key)));
1566    }
1567
1568    #[test]
1569    fn a_ctap_registration_gives_its_root_as_it_is() {
1570        let key = signing(3);
1571        assert_eq!(
1572            RootRegistration::Ctap(root(&key)).root(&HANDLE),
1573            Ok(root(&key))
1574        );
1575    }
1576
1577    /// The attestation statement is not checked, whatever its format.
1578    #[test]
1579    fn a_webauthn_registration_s_attestation_statement_is_not_checked() {
1580        use ciborium::Value;
1581        let key = signing(3);
1582        let object = cbor(&Value::Map(vec![
1583            (Value::from("fmt"), Value::from("packed")),
1584            (
1585                Value::from("attStmt"),
1586                Value::Map(vec![
1587                    (Value::from("alg"), Value::from(-7)),
1588                    (Value::from("sig"), Value::Bytes(vec![0; 70])),
1589                ]),
1590            ),
1591            (
1592                Value::from("authData"),
1593                Value::Bytes(registration_data(
1594                    PORTABLE_RP,
1595                    0x45,
1596                    &[1; 32],
1597                    &cbor(&cose_key(&key)),
1598                )),
1599            ),
1600        ]));
1601        assert_eq!(
1602            registration(object, client_data(WEBAUTHN_CREATE, &HANDLE)).root(&HANDLE),
1603            Ok(root(&key))
1604        );
1605    }
1606
1607    #[test]
1608    fn a_webauthn_get_presented_as_a_registration_is_refused() {
1609        let key = signing(3);
1610        let RootRegistration::WebAuthn {
1611            attestation_object, ..
1612        } = good_registration(&key)
1613        else {
1614            unreachable!()
1615        };
1616        let made = registration(attestation_object, client_data(WEBAUTHN_GET, &HANDLE));
1617        assert_eq!(made.root(&HANDLE), Err(WebAuthnError::WrongType));
1618    }
1619
1620    #[test]
1621    fn a_webauthn_registration_for_another_handle_is_refused() {
1622        let key = signing(3);
1623        assert_eq!(
1624            good_registration(&key).root(&[0x43; HANDLE_LEN]),
1625            Err(WebAuthnError::WrongChallenge)
1626        );
1627    }
1628
1629    #[test]
1630    fn a_webauthn_registration_refuses_another_rp_no_up_or_uv_and_no_credential() {
1631        let key = signing(3);
1632        let cose = cbor(&cose_key(&key));
1633        for (rp, flags, refusal) in [
1634            ("spoolframe.app", 0x45, WebAuthnError::WrongRp),
1635            (PORTABLE_RP, 0x41, WebAuthnError::NotVerified),
1636            (PORTABLE_RP, 0x44, WebAuthnError::NotVerified),
1637            (PORTABLE_RP, 0x05, WebAuthnError::NoCredential),
1638        ] {
1639            let data = if flags & FLAG_AT == 0 {
1640                authenticator_data(rp, flags)
1641            } else {
1642                registration_data(rp, flags, &[1; 32], &cose)
1643            };
1644            let made = registration(
1645                attestation("none", data),
1646                client_data(WEBAUTHN_CREATE, &HANDLE),
1647            );
1648            assert_eq!(made.root(&HANDLE), Err(refusal), "{rp} {flags:#x}");
1649        }
1650    }
1651
1652    #[test]
1653    fn a_webauthn_registration_of_a_key_that_is_not_es256_p256_is_refused() {
1654        use ciborium::Value;
1655        let key = signing(3);
1656        let with = |at: usize, value: Value| {
1657            let Value::Map(mut members) = cose_key(&key) else {
1658                unreachable!()
1659            };
1660            members[at].1 = value;
1661            Value::Map(members)
1662        };
1663        let off_curve = {
1664            let Value::Map(mut members) = cose_key(&key) else {
1665                unreachable!()
1666            };
1667            members[4].1 = Value::Bytes(vec![0; 32]);
1668            Value::Map(members)
1669        };
1670        for cose in [
1671            with(0, Value::from(1)),  // OKP
1672            with(1, Value::from(-8)), // EdDSA
1673            with(2, Value::from(2)),  // P-384
1674            with(3, Value::Bytes(vec![1; 31])),
1675            off_curve,
1676        ] {
1677            let made = registration(
1678                attestation(
1679                    "none",
1680                    registration_data(PORTABLE_RP, 0x45, &[1; 32], &cbor(&cose)),
1681                ),
1682                client_data(WEBAUTHN_CREATE, &HANDLE),
1683            );
1684            assert_eq!(
1685                made.root(&HANDLE),
1686                Err(WebAuthnError::UnsupportedKey),
1687                "{cose:?}"
1688            );
1689        }
1690    }
1691
1692    #[test]
1693    fn a_webauthn_registration_with_an_empty_or_long_credential_id_is_refused() {
1694        let key = signing(3);
1695        let cose = cbor(&cose_key(&key));
1696        for id in [vec![], vec![1; MAX_CREDENTIAL_ID + 1]] {
1697            let made = registration(
1698                attestation("none", registration_data(PORTABLE_RP, 0x45, &id, &cose)),
1699                client_data(WEBAUTHN_CREATE, &HANDLE),
1700            );
1701            assert_eq!(made.root(&HANDLE), Err(WebAuthnError::BadCredentialId));
1702        }
1703    }
1704
1705    #[test]
1706    fn an_oversize_webauthn_registration_is_refused_before_it_parses() {
1707        let key = signing(3);
1708        let made = registration(
1709            vec![0; MAX_ATTESTATION_OBJECT + 1],
1710            client_data(WEBAUTHN_CREATE, &HANDLE),
1711        );
1712        assert_eq!(made.root(&HANDLE), Err(WebAuthnError::TooLong));
1713        let RootRegistration::WebAuthn {
1714            attestation_object, ..
1715        } = good_registration(&key)
1716        else {
1717            unreachable!()
1718        };
1719        let made = registration(attestation_object, vec![b' '; MAX_CLIENT_DATA_JSON + 1]);
1720        assert_eq!(made.root(&HANDLE), Err(WebAuthnError::TooLong));
1721    }
1722
1723    #[test]
1724    fn a_malformed_attestation_object_is_refused() {
1725        use ciborium::Value;
1726        let key = signing(3);
1727        let cose = cbor(&cose_key(&key));
1728        let data = registration_data(PORTABLE_RP, 0x45, &[1; 32], &cose);
1729        let mut trailing = attestation("none", data.clone());
1730        trailing.push(0);
1731        let mut nested = Value::Bytes(data.clone());
1732        for _ in 0..1000 {
1733            nested = Value::Array(vec![nested]);
1734        }
1735        for object in [
1736            vec![],
1737            vec![0xff],
1738            b"not cbor".to_vec(),
1739            trailing,
1740            cbor(&Value::Array(vec![])),
1741            cbor(&nested),
1742            // No authData; authData not bytes; fmt not text; a key twice.
1743            cbor(&Value::Map(vec![
1744                (Value::from("fmt"), Value::from("none")),
1745                (Value::from("attStmt"), Value::Map(vec![])),
1746            ])),
1747            cbor(&Value::Map(vec![
1748                (Value::from("fmt"), Value::from("none")),
1749                (Value::from("attStmt"), Value::Map(vec![])),
1750                (Value::from("authData"), Value::from("text")),
1751            ])),
1752            cbor(&Value::Map(vec![
1753                (Value::from("fmt"), Value::from(1)),
1754                (Value::from("attStmt"), Value::Map(vec![])),
1755                (Value::from("authData"), Value::Bytes(data.clone())),
1756            ])),
1757            cbor(&Value::Map(vec![
1758                (Value::from("fmt"), Value::from("none")),
1759                (Value::from("attStmt"), Value::Map(vec![])),
1760                (Value::from("authData"), Value::Bytes(data.clone())),
1761                (Value::from("authData"), Value::Bytes(data.clone())),
1762            ])),
1763        ] {
1764            let made = registration(object.clone(), client_data(WEBAUTHN_CREATE, &HANDLE));
1765            assert_eq!(
1766                made.root(&HANDLE),
1767                Err(WebAuthnError::MalformedAttestation),
1768                "{object:02x?}"
1769            );
1770        }
1771    }
1772
1773    #[test]
1774    fn malformed_attested_credential_data_is_refused() {
1775        let key = signing(3);
1776        let cose = cbor(&cose_key(&key));
1777        let data = registration_data(PORTABLE_RP, 0x45, &[1; 32], &cose);
1778        let mut trailing = data.clone();
1779        trailing.push(0);
1780        let mut cose_twice = registration_data(PORTABLE_RP, 0x45, &[1; 32], &[]);
1781        let ciborium::Value::Map(mut members) = cose_key(&key) else {
1782            unreachable!()
1783        };
1784        members.push(members[0].clone());
1785        cose_twice.extend_from_slice(&cbor(&ciborium::Value::Map(members)));
1786        for data in [
1787            data[..37 + 10].to_vec(),
1788            data[..37 + 18 + 10].to_vec(),
1789            data[..data.len() - 1].to_vec(),
1790            // Bytes after the key, with no extensions flagged.
1791            trailing,
1792            cose_twice,
1793        ] {
1794            let made = registration(
1795                attestation("none", data),
1796                client_data(WEBAUTHN_CREATE, &HANDLE),
1797            );
1798            assert_eq!(
1799                made.root(&HANDLE),
1800                Err(WebAuthnError::MalformedAuthenticatorData)
1801            );
1802        }
1803        // With extensions flagged, what follows the key is theirs.
1804        let mut extended = registration_data(PORTABLE_RP, 0xc5, &[1; 32], &cose);
1805        extended.extend_from_slice(&cbor(&ciborium::Value::Map(vec![])));
1806        let made = registration(
1807            attestation("none", extended),
1808            client_data(WEBAUTHN_CREATE, &HANDLE),
1809        );
1810        assert_eq!(made.root(&HANDLE), Ok(root(&key)));
1811    }
1812}