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)]
592pub enum RootSignature {
593 Ed25519(Signature),
594 Ctap {
595 authenticator_data: Vec<u8>,
596 signature: Vec<u8>,
597 },
598 WebAuthn {
604 authenticator_data: Vec<u8>,
605 client_data_json: Vec<u8>,
608 signature: Vec<u8>,
609 },
610}
611
612impl RootSignature {
613 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
628pub(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 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 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#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
822pub enum GenesisError {
823 #[error("an identity has 1 to {MAX_ROOTS} roots")]
825 RootCount,
826 #[error("an identity's genesis has one signature for each root")]
828 SignatureCount,
829 #[error("an identity's genesis names a root twice")]
831 Duplicate,
832 #[error("an identity's genesis names a root that is not a valid key")]
834 InvalidRoot,
835 #[error("a root did not sign its identity's genesis")]
837 BadSignature,
838}
839
840pub const HANDLE_LEN: usize = 32;
842
843#[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 pub signatures: Vec<RootSignature>,
858}
859
860pub(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 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 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 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
936pub 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
947pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
964pub struct AddedRoot {
965 pub root: RootKey,
966 pub added_by: RootKey,
967 pub added_at: i64,
969 pub endorsement: RootSignature,
970 pub possession: RootSignature,
971}
972
973impl AddedRoot {
974 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
991pub struct RemovedRoot {
992 pub root: RootKey,
993 pub removed_at: i64,
994}
995
996#[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
1027pub struct RootChanges<'a> {
1030 pub signer: &'a RootKey,
1031 pub added: &'a [AddedRoot],
1032 pub removed: &'a [RemovedRoot],
1033}
1034
1035impl RootSet {
1036 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 pub fn holds(&self, root: &RootKey) -> bool {
1081 self.members.contains(root)
1082 }
1083
1084 pub fn knew(&self, root: &RootKey) -> bool {
1087 self.ever.contains(root)
1088 }
1089
1090 pub fn is_removed(&self, root: &RootKey) -> bool {
1092 self.removed.iter().any(|(r, _)| r == root)
1093 }
1094
1095 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 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 #[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 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 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 #[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 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 #[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 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 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 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 #[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)), with(1, Value::from(-8)), with(2, Value::from(2)), 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 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 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 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}