1use 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
31pub const PORTABLE_RP: &str = "portable.spoolframe.app";
35
36pub const MAX_ROOTS: usize = 8;
38
39pub const MAX_ROOT_CHANGES: usize = 64;
43
44pub const MAX_CREDENTIAL_ID: usize = 128;
46
47pub const MAX_AUTHENTICATOR_DATA: usize = 512;
50
51pub const MAX_DER_SIGNATURE: usize = 72;
53
54pub const P256_PUBLIC_KEY_LEN: usize = 65;
56
57pub const GENESIS_DOMAIN: &[u8] = b"spoolframe identity genesis v1\0";
59
60pub const ROOT_ADD_DOMAIN: &[u8] = b"spoolframe root add v1\0";
63
64pub const ROOT_ENDORSE_DOMAIN: &[u8] = b"spoolframe root endorse v1\0";
66
67pub const USER_ID_CONTEXT: &str = "spoolframe portable user id v1";
70
71const FLAG_UP: u8 = 0x01;
73const FLAG_UV: u8 = 0x04;
75
76pub const MAX_CLIENT_DATA_JSON: usize = 4096;
80
81pub const MAX_ATTESTATION_OBJECT: usize = 8192;
85
86const WEBAUTHN_GET: &str = "webauthn.get";
88const WEBAUTHN_CREATE: &str = "webauthn.create";
90const FLAG_AT: u8 = 0x40;
92const FLAG_ED: u8 = 0x80;
94
95const RP_ID_HASH_LEN: usize = 32;
97const MIN_AUTHENTICATOR_DATA: usize = RP_ID_HASH_LEN + 1 + 4;
99
100pub fn portable_rp_id_hash() -> [u8; 32] {
103 Sha256::digest(PORTABLE_RP.as_bytes()).into()
104}
105
106#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
108pub enum RootKey {
109 Phrase([u8; 32]),
111 SecurityKey {
115 public_key: [u8; P256_PUBLIC_KEY_LEN],
116 credential_id: Vec<u8>,
117 },
118}
119
120impl RootKey {
121 pub fn phrase_of(user: &PortableUserId) -> Self {
123 RootKey::Phrase(*user.as_bytes())
124 }
125
126 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 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 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 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 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
234fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
269pub enum WebAuthnError {
270 #[error("a WebAuthn field is too long")]
274 TooLong,
275 #[error("the clientDataJSON is not WebAuthn client data")]
278 MalformedClientData,
279 #[error("the clientDataJSON is of the wrong type")]
281 WrongType,
282 #[error("the clientDataJSON's challenge is not this message's")]
284 WrongChallenge,
285 #[error("the clientDataJSON is cross-origin")]
287 CrossOrigin,
288 #[error("the authenticatorData does not parse")]
291 MalformedAuthenticatorData,
292 #[error("the authenticatorData is another relying party's")]
294 WrongRp,
295 #[error("the key was not touched, or no PIN was given")]
297 NotVerified,
298 #[error("the signature does not check out")]
300 BadSignature,
301 #[error("the attestationObject does not parse")]
304 MalformedAttestation,
305 #[error("the registration carries no credential")]
307 NoCredential,
308 #[error("the credential id is empty or too long")]
310 BadCredentialId,
311 #[error("the credential is not an ES256 P-256 key")]
313 UnsupportedKey,
314}
315
316fn 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
357fn 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
373pub(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#[derive(Debug, Clone, PartialEq, Eq)]
417pub enum RootRegistration {
418 Ctap(RootKey),
422 WebAuthn {
428 attestation_object: Vec<u8>,
429 client_data_json: Vec<u8>,
430 },
431}
432
433impl RootRegistration {
434 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 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 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
504fn 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
539fn 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#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum RootSignature {
592 Ed25519(Signature),
593 Ctap {
594 authenticator_data: Vec<u8>,
595 signature: Vec<u8>,
596 },
597 WebAuthn {
603 authenticator_data: Vec<u8>,
604 client_data_json: Vec<u8>,
607 signature: Vec<u8>,
608 },
609}
610
611impl RootSignature {
612 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
627pub(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 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 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#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
821pub enum GenesisError {
822 #[error("an identity has 1 to {MAX_ROOTS} roots")]
824 RootCount,
825 #[error("an identity's genesis has one signature for each root")]
827 SignatureCount,
828 #[error("an identity's genesis names a root twice")]
830 Duplicate,
831 #[error("an identity's genesis names a root that is not a valid key")]
833 InvalidRoot,
834 #[error("a root did not sign its identity's genesis")]
836 BadSignature,
837}
838
839pub const HANDLE_LEN: usize = 32;
841
842#[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 pub signatures: Vec<RootSignature>,
857}
858
859pub(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 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 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 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
935pub 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
946pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
963pub struct AddedRoot {
964 pub root: RootKey,
965 pub added_by: RootKey,
966 pub added_at: i64,
968 pub endorsement: RootSignature,
969 pub possession: RootSignature,
970}
971
972impl AddedRoot {
973 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
990pub struct RemovedRoot {
991 pub root: RootKey,
992 pub removed_at: i64,
993}
994
995#[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
1025pub struct RootChanges<'a> {
1028 pub signer: &'a RootKey,
1029 pub added: &'a [AddedRoot],
1030 pub removed: &'a [RemovedRoot],
1031}
1032
1033impl RootSet {
1034 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 pub fn holds(&self, root: &RootKey) -> bool {
1079 self.members.contains(root)
1080 }
1081
1082 pub fn knew(&self, root: &RootKey) -> bool {
1085 self.ever.contains(root)
1086 }
1087
1088 pub fn is_removed(&self, root: &RootKey) -> bool {
1090 self.removed.iter().any(|(r, _)| r == root)
1091 }
1092
1093 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 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 #[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 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 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 #[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 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 #[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 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 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 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 #[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)), with(1, Value::from(-8)), with(2, Value::from(2)), 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 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 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 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}