response.rs (106496B)
1 extern crate alloc; 2 use crate::{ 3 request::{register::{PublicKeyCredentialUserEntity, UserHandle}, Challenge, RpId, Url}, 4 response::{ 5 auth::error::{ 6 AuthCeremonyErr, AuthenticatorDataErr as AuthAuthDataErr, 7 AuthenticatorExtensionOutputErr as AuthAuthExtErr, 8 }, 9 error::{CollectedClientDataErr, CredentialIdErr}, 10 register::error::{AttestationObjectErr, AttestedCredentialDataErr, AuthenticatorDataErr as RegAuthDataErr, AuthenticatorExtensionOutputErr as RegAuthExtErr, PubKeyErr, RegCeremonyErr}, 11 }, 12 }; 13 use alloc::borrow::Cow; 14 use core::{ 15 borrow::Borrow, 16 cmp::Ordering, 17 convert::Infallible, 18 fmt::{self, Display, Formatter}, 19 hash::{Hash, Hasher}, 20 str, 21 }; 22 use data_encoding::BASE64URL_NOPAD; 23 use rsa::sha2::{digest::OutputSizeUser as _, Sha256}; 24 #[cfg(feature = "serde_relaxed")] 25 use ser_relaxed::SerdeJsonErr; 26 /// Contains functionality for completing the 27 /// [authentication ceremony](https://www.w3.org/TR/webauthn-3/#authentication-ceremony). 28 /// 29 /// # Examples 30 /// 31 /// ```no_run 32 /// # use core::convert; 33 /// # use data_encoding::BASE64URL_NOPAD; 34 /// # use webauthn_rp::{ 35 /// # hash::hash_set::FixedCapHashSet, 36 /// # request::{auth::{error::InvalidTimeout, DiscoverableAuthenticationClientState, DiscoverableCredentialRequestOptions, AuthenticationVerificationOptions}, error::AsciiDomainErr, register::{UserHandle, USER_HANDLE_MAX_LEN, UserHandle64}, AsciiDomain, BackupReq, RpId}, 37 /// # response::{auth::{error::AuthCeremonyErr, DiscoverableAuthentication64}, error::CollectedClientDataErr, register::{AuthenticatorExtensionOutputStaticState, ClientExtensionsOutputsStaticState, CredentialProtectionPolicy, DynamicState, Ed25519PubKey, CompressedPubKey, StaticState}, AuthenticatorAttachment, Backup, CollectedClientData, CredentialId}, 38 /// # AuthenticatedCredential, CredentialErr 39 /// # }; 40 /// # #[derive(Debug)] 41 /// # enum E { 42 /// # CollectedClientData(CollectedClientDataErr), 43 /// # RpId(AsciiDomainErr), 44 /// # InvalidTimeout(InvalidTimeout), 45 /// # SerdeJson(serde_json::Error), 46 /// # MissingUserHandle, 47 /// # MissingCeremony, 48 /// # UnknownCredential, 49 /// # Credential(CredentialErr), 50 /// # AuthCeremony(AuthCeremonyErr), 51 /// # } 52 /// # impl From<AsciiDomainErr> for E { 53 /// # fn from(value: AsciiDomainErr) -> Self { 54 /// # Self::RpId(value) 55 /// # } 56 /// # } 57 /// # impl From<CollectedClientDataErr> for E { 58 /// # fn from(value: CollectedClientDataErr) -> Self { 59 /// # Self::CollectedClientData(value) 60 /// # } 61 /// # } 62 /// # impl From<InvalidTimeout> for E { 63 /// # fn from(value: InvalidTimeout) -> Self { 64 /// # Self::InvalidTimeout(value) 65 /// # } 66 /// # } 67 /// # impl From<serde_json::Error> for E { 68 /// # fn from(value: serde_json::Error) -> Self { 69 /// # Self::SerdeJson(value) 70 /// # } 71 /// # } 72 /// # impl From<CredentialErr> for E { 73 /// # fn from(value: CredentialErr) -> Self { 74 /// # Self::Credential(value) 75 /// # } 76 /// # } 77 /// # impl From<AuthCeremonyErr> for E { 78 /// # fn from(value: AuthCeremonyErr) -> Self { 79 /// # Self::AuthCeremony(value) 80 /// # } 81 /// # } 82 /// let mut ceremonies = FixedCapHashSet::new(128); 83 /// let rp_id = RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?); 84 /// let (server, client) = DiscoverableCredentialRequestOptions::passkey(&rp_id).start_ceremony()?; 85 /// assert!( 86 /// ceremonies.insert_remove_all_expired(server).map_or(false, convert::identity) 87 /// ); 88 /// # #[cfg(feature = "serde")] 89 /// let authentication = serde_json::from_str::<DiscoverableAuthentication64>(get_authentication_json(client).as_str())?; 90 /// # #[cfg(feature = "serde")] 91 /// let user_handle = authentication.response().user_handle(); 92 /// # #[cfg(feature = "serde")] 93 /// let (static_state, dynamic_state) = get_credential(authentication.raw_id(), &user_handle).ok_or(E::UnknownCredential)?; 94 /// # #[cfg(all(feature = "custom", feature = "serde"))] 95 /// let mut cred = AuthenticatedCredential::new(authentication.raw_id(), &user_handle, static_state, dynamic_state)?; 96 /// # #[cfg(all(feature = "custom", feature = "serde"))] 97 /// if ceremonies.take(&authentication.challenge()?).ok_or(E::MissingCeremony)?.verify(&rp_id, &authentication, &mut cred, &AuthenticationVerificationOptions::<&str, &str>::default())? { 98 /// update_cred(authentication.raw_id(), cred.dynamic_state()); 99 /// } 100 /// /// Send `DiscoverableAuthenticationClientState` and receive `DiscoverableAuthentication64` JSON from client. 101 /// # #[cfg(feature = "serde")] 102 /// fn get_authentication_json(client: DiscoverableAuthenticationClientState<'_, '_, '_>) -> String { 103 /// // ⋮ 104 /// # let client_data_json = BASE64URL_NOPAD.encode(serde_json::json!({ 105 /// # "type": "webauthn.get", 106 /// # "challenge": client.options().public_key.challenge, 107 /// # "origin": format!("https://{}", client.options().public_key.rp_id.as_ref()), 108 /// # "crossOrigin": false 109 /// # }).to_string().as_bytes()); 110 /// # serde_json::json!({ 111 /// # "id": "AAAAAAAAAAAAAAAAAAAAAA", 112 /// # "rawId": "AAAAAAAAAAAAAAAAAAAAAA", 113 /// # "response": { 114 /// # "clientDataJSON": client_data_json, 115 /// # "authenticatorData": "", 116 /// # "signature": "", 117 /// # "userHandle": "AA" 118 /// # }, 119 /// # "clientExtensionResults": {}, 120 /// # "type": "public-key" 121 /// # }).to_string() 122 /// } 123 /// /// Gets the `AuthenticatedCredential` parts associated with `id` and `user_handle` from the database. 124 /// fn get_credential(id: CredentialId<&[u8]>, user_handle: &UserHandle64) -> Option<(StaticState<CompressedPubKey<[u8; 32], [u8; 32], [u8; 48], Vec<u8>>>, DynamicState)> { 125 /// // ⋮ 126 /// # Some((StaticState { credential_public_key: CompressedPubKey::Ed25519(Ed25519PubKey::from([0; 32])), extensions: AuthenticatorExtensionOutputStaticState { cred_protect: CredentialProtectionPolicy::UserVerificationRequired, hmac_secret: None, }, client_extension_results: ClientExtensionsOutputsStaticState { prf: None, }, }, DynamicState { user_verified: true, backup: Backup::NotEligible, sign_count: 1, authenticator_attachment: AuthenticatorAttachment::None })) 127 /// } 128 /// /// Updates the current `DynamicState` associated with `id` in the database to 129 /// /// `dyn_state`. 130 /// fn update_cred(id: CredentialId<&[u8]>, dyn_state: DynamicState) { 131 /// // ⋮ 132 /// } 133 /// # Ok::<_, E>(()) 134 /// ``` 135 pub mod auth; 136 /// Contains functionality to (de)serialize data to a data store. 137 #[cfg_attr(docsrs, doc(cfg(feature = "bin")))] 138 #[cfg(feature = "bin")] 139 pub mod bin; 140 /// Contains constants useful for 141 /// [CTAP2 canonical CBOR encoding form](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#ctap2-canonical-cbor-encoding-form). 142 mod cbor; 143 /// Contains functionality that needs to be accessible when `bin` or `serde` are not enabled. 144 #[cfg_attr(docsrs, doc(cfg(feature = "custom")))] 145 #[cfg(feature = "custom")] 146 pub mod custom; 147 /// Contains error types. 148 pub mod error; 149 /// Contains functionality for completing the 150 /// [registration ceremony](https://www.w3.org/TR/webauthn-3/#registration-ceremony). 151 /// 152 /// # Examples 153 /// 154 /// ```no_run 155 /// # use core::convert; 156 /// # use data_encoding::BASE64URL_NOPAD; 157 /// # use webauthn_rp::{ 158 /// # hash::hash_set::FixedCapHashSet, 159 /// # request::{register::{error::CreationOptionsErr, CredentialCreationOptions, PublicKeyCredentialUserEntity, RegistrationClientState, UserHandle, UserHandle64, USER_HANDLE_MAX_LEN, RegistrationVerificationOptions}, error::AsciiDomainErr, AsciiDomain, PublicKeyCredentialDescriptor, RpId}, 160 /// # response::{register::{error::RegCeremonyErr, Registration}, error::CollectedClientDataErr, CollectedClientData}, 161 /// # RegisteredCredential 162 /// # }; 163 /// # #[derive(Debug)] 164 /// # enum E { 165 /// # CollectedClientData(CollectedClientDataErr), 166 /// # RpId(AsciiDomainErr), 167 /// # CreationOptions(CreationOptionsErr), 168 /// # SerdeJson(serde_json::Error), 169 /// # MissingCeremony, 170 /// # RegCeremony(RegCeremonyErr), 171 /// # } 172 /// # impl From<AsciiDomainErr> for E { 173 /// # fn from(value: AsciiDomainErr) -> Self { 174 /// # Self::RpId(value) 175 /// # } 176 /// # } 177 /// # impl From<CollectedClientDataErr> for E { 178 /// # fn from(value: CollectedClientDataErr) -> Self { 179 /// # Self::CollectedClientData(value) 180 /// # } 181 /// # } 182 /// # impl From<CreationOptionsErr> for E { 183 /// # fn from(value: CreationOptionsErr) -> Self { 184 /// # Self::CreationOptions(value) 185 /// # } 186 /// # } 187 /// # impl From<serde_json::Error> for E { 188 /// # fn from(value: serde_json::Error) -> Self { 189 /// # Self::SerdeJson(value) 190 /// # } 191 /// # } 192 /// # impl From<RegCeremonyErr> for E { 193 /// # fn from(value: RegCeremonyErr) -> Self { 194 /// # Self::RegCeremony(value) 195 /// # } 196 /// # } 197 /// # #[cfg(feature = "custom")] 198 /// let mut ceremonies = FixedCapHashSet::new(128); 199 /// let rp_id = RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?); 200 /// # #[cfg(feature = "custom")] 201 /// let user_handle = get_user_handle(); 202 /// # #[cfg(feature = "custom")] 203 /// let user = get_user_entity(&user_handle); 204 /// # #[cfg(feature = "custom")] 205 /// let creds = get_registered_credentials(user_handle); 206 /// # #[cfg(feature = "custom")] 207 /// let (server, client) = CredentialCreationOptions::passkey(&rp_id, user, creds).start_ceremony()?; 208 /// # #[cfg(feature = "custom")] 209 /// assert!( 210 /// ceremonies.insert_remove_all_expired(server).map_or(false, convert::identity) 211 /// ); 212 /// # #[cfg(all(feature = "serde_relaxed", feature = "custom"))] 213 /// let registration = serde_json::from_str::<Registration>(get_registration_json(client).as_str())?; 214 /// let ver_opts = RegistrationVerificationOptions::<&str, &str>::default(); 215 /// # #[cfg(all(feature = "custom", feature = "serde_relaxed"))] 216 /// insert_cred(ceremonies.take(®istration.challenge()?).ok_or(E::MissingCeremony)?.verify(&rp_id, ®istration, &ver_opts)?); 217 /// /// Extract `UserHandle` from session cookie if this is not the first credential registered. 218 /// # #[cfg(feature = "custom")] 219 /// fn get_user_handle() -> UserHandle64 { 220 /// // ⋮ 221 /// # [0; USER_HANDLE_MAX_LEN].into() 222 /// } 223 /// /// Fetch `PublicKeyCredentialUserEntity` info associated with `user`. 224 /// /// 225 /// /// If this is the first time a credential is being registered, then `PublicKeyCredentialUserEntity` 226 /// /// will need to be constructed with `name` and `display_name` passed from the client and `UserHandle::new` 227 /// /// used for `id`. Once created, this info can be stored such that the entity information 228 /// /// does not need to be requested for subsequent registrations. 229 /// # #[cfg(feature = "custom")] 230 /// fn get_user_entity(user: &UserHandle<USER_HANDLE_MAX_LEN>) -> PublicKeyCredentialUserEntity<'_, '_, '_, USER_HANDLE_MAX_LEN> { 231 /// // ⋮ 232 /// # PublicKeyCredentialUserEntity { 233 /// # name: "foo".try_into().unwrap(), 234 /// # id: user, 235 /// # display_name: None, 236 /// # } 237 /// } 238 /// /// Send `RegistrationClientState` and receive `Registration` JSON from client. 239 /// # #[cfg(feature = "serde")] 240 /// fn get_registration_json(client: RegistrationClientState<'_, '_, '_, '_, '_, '_, USER_HANDLE_MAX_LEN>) -> String { 241 /// // ⋮ 242 /// # let client_data_json = BASE64URL_NOPAD.encode(serde_json::json!({ 243 /// # "type": "webauthn.create", 244 /// # "challenge": client.options().public_key.challenge, 245 /// # "origin": format!("https://{}", client.options().public_key.rp_id.as_ref()), 246 /// # "crossOrigin": false 247 /// # }).to_string().as_bytes()); 248 /// # serde_json::json!({ 249 /// # "response": { 250 /// # "clientDataJSON": client_data_json, 251 /// # "attestationObject": "" 252 /// # } 253 /// # }).to_string() 254 /// } 255 /// /// Fetch the `PublicKeyCredentialDescriptor`s associated with `user`. 256 /// /// 257 /// /// This doesn't need to be called when this is the first credential registered for `user`; instead 258 /// /// an empty `Vec` should be passed. 259 /// fn get_registered_credentials( 260 /// user: UserHandle<USER_HANDLE_MAX_LEN>, 261 /// ) -> Vec<PublicKeyCredentialDescriptor<Vec<u8>>> { 262 /// // ⋮ 263 /// # Vec::new() 264 /// } 265 /// /// Inserts `RegisteredCredential::into_parts` into the database. 266 /// fn insert_cred(cred: RegisteredCredential<'_, USER_HANDLE_MAX_LEN>) { 267 /// // ⋮ 268 /// } 269 /// # Ok::<_, E>(()) 270 /// ``` 271 pub mod register; 272 /// Contains functionality to (de)serialize data to/from a client. 273 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] 274 #[cfg(feature = "serde")] 275 mod ser; 276 /// Contains functionality to deserialize data from a client in a "relaxed" way. 277 #[cfg_attr(docsrs, doc(cfg(feature = "serde_relaxed")))] 278 #[cfg(feature = "serde_relaxed")] 279 pub mod ser_relaxed; 280 /// [Backup eligibility](https://www.w3.org/TR/webauthn-3/#backup-eligibility) and 281 /// [backup state](https://www.w3.org/TR/webauthn-3/#backup-state). 282 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 283 pub enum Backup { 284 /// [BE and BS](https://www.w3.org/TR/webauthn-3/#authdata-flags) flags are `0`. 285 NotEligible, 286 /// [BE and BS](https://www.w3.org/TR/webauthn-3/#authdata-flags) flags are `1` and `0` respectively. 287 Eligible, 288 /// [BE and BS](https://www.w3.org/TR/webauthn-3/#authdata-flags) flags are `1`. 289 Exists, 290 } 291 impl PartialEq<&Self> for Backup { 292 #[inline] 293 fn eq(&self, other: &&Self) -> bool { 294 *self == **other 295 } 296 } 297 impl PartialEq<Backup> for &Backup { 298 #[inline] 299 fn eq(&self, other: &Backup) -> bool { 300 **self == *other 301 } 302 } 303 /// [`AuthenticatorTransport`](https://www.w3.org/TR/webauthn-3/#enumdef-authenticatortransport). 304 #[derive(Clone, Copy, Debug)] 305 pub enum AuthenticatorTransport { 306 /// [`ble`](https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-ble). 307 Ble, 308 /// [`hybrid`](https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-hybrid). 309 Hybrid, 310 /// [`internal`](https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-internal). 311 Internal, 312 /// [`nfc`](https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-nfc). 313 Nfc, 314 /// [`smart-card`](https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-smart-card). 315 SmartCard, 316 /// [`usb`](https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-usb). 317 Usb, 318 } 319 impl AuthenticatorTransport { 320 /// Returns the encoded [`u8`] that `self` represents. 321 const fn to_u8(self) -> u8 { 322 match self { 323 Self::Ble => 0x1, 324 Self::Hybrid => 0x2, 325 Self::Internal => 0x4, 326 Self::Nfc => 0x8, 327 Self::SmartCard => 0x10, 328 Self::Usb => 0x20, 329 } 330 } 331 } 332 /// Set of [`AuthenticatorTransport`]s. 333 #[derive(Clone, Copy, Debug)] 334 pub struct AuthTransports(u8); 335 impl AuthTransports { 336 /// An empty `AuthTransports`. 337 #[cfg_attr(docsrs, doc(cfg(feature = "custom")))] 338 #[cfg(feature = "custom")] 339 pub const NONE: Self = Self::new(); 340 /// An `AuthTransports` containing all possible [`AuthenticatorTransport`]s. 341 #[cfg_attr(docsrs, doc(cfg(feature = "custom")))] 342 #[cfg(feature = "custom")] 343 pub const ALL: Self = Self::all(); 344 /// Construct an empty `AuthTransports`. 345 #[cfg(any(feature = "bin", feature = "custom", feature = "serde"))] 346 pub(super) const fn new() -> Self { 347 Self(0) 348 } 349 #[cfg(any(feature = "bin", feature = "custom"))] 350 /// Construct an `AuthTransports` containing all `AuthenticatorTransport`s. 351 const fn all() -> Self { 352 Self::new() 353 .add_transport(AuthenticatorTransport::Ble) 354 .add_transport(AuthenticatorTransport::Hybrid) 355 .add_transport(AuthenticatorTransport::Internal) 356 .add_transport(AuthenticatorTransport::Nfc) 357 .add_transport(AuthenticatorTransport::SmartCard) 358 .add_transport(AuthenticatorTransport::Usb) 359 } 360 /// Returns the number of [`AuthenticatorTransport`]s in `self`. 361 /// 362 /// # Examples 363 /// 364 /// ``` 365 /// # use webauthn_rp::response::AuthTransports; 366 /// # #[cfg(feature = "custom")] 367 /// assert_eq!(AuthTransports::ALL.count(), 6); 368 /// ``` 369 #[inline] 370 #[must_use] 371 pub const fn count(self) -> u32 { 372 self.0.count_ones() 373 } 374 /// Returns `true` iff there are no [`AuthenticatorTransport`]s in `self`. 375 /// 376 /// # Examples 377 /// 378 /// ``` 379 /// # use webauthn_rp::response::AuthTransports; 380 /// # #[cfg(feature = "custom")] 381 /// assert!(AuthTransports::NONE.is_empty()); 382 /// ``` 383 #[inline] 384 #[must_use] 385 pub const fn is_empty(self) -> bool { 386 self.0 == 0 387 } 388 /// Returns `true` iff `self` contains `transport`. 389 /// 390 /// # Examples 391 /// 392 /// ``` 393 /// # use webauthn_rp::response::{AuthTransports, AuthenticatorTransport}; 394 /// # #[cfg(feature = "custom")] 395 /// assert!(AuthTransports::ALL.contains(AuthenticatorTransport::Ble)); 396 /// ``` 397 #[inline] 398 #[must_use] 399 pub const fn contains(self, transport: AuthenticatorTransport) -> bool { 400 let val = transport.to_u8(); 401 self.0 & val == val 402 } 403 /// Returns a copy of `self` with `transport` added. 404 /// 405 /// `self` is returned iff `transport` already exists. 406 #[cfg(any(feature = "bin", feature = "custom", feature = "serde"))] 407 const fn add_transport(self, transport: AuthenticatorTransport) -> Self { 408 Self(self.0 | transport.to_u8()) 409 } 410 /// Returns a copy of `self` with `transport` added. 411 /// 412 /// `self` is returned iff `transport` already exists. 413 /// 414 /// # Examples 415 /// 416 /// ``` 417 /// # use webauthn_rp::response::{AuthTransports, AuthenticatorTransport}; 418 /// assert_eq!( 419 /// AuthTransports::NONE 420 /// .add(AuthenticatorTransport::Usb) 421 /// .count(), 422 /// 1 423 /// ); 424 /// assert_eq!( 425 /// AuthTransports::ALL.add(AuthenticatorTransport::Usb).count(), 426 /// 6 427 /// ); 428 /// ``` 429 #[cfg_attr(docsrs, doc(cfg(feature = "custom")))] 430 #[cfg(feature = "custom")] 431 #[inline] 432 #[must_use] 433 pub const fn add(self, transport: AuthenticatorTransport) -> Self { 434 self.add_transport(transport) 435 } 436 /// Returns a copy of `self` with `transport` removed. 437 /// 438 /// `self` is returned iff `transport` did not exist. 439 /// 440 /// # Examples 441 /// 442 /// ``` 443 /// # use webauthn_rp::response::{AuthTransports, AuthenticatorTransport}; 444 /// assert_eq!( 445 /// AuthTransports::ALL 446 /// .remove(AuthenticatorTransport::Internal) 447 /// .count(), 448 /// 5 449 /// ); 450 /// assert_eq!( 451 /// AuthTransports::NONE.remove(AuthenticatorTransport::Usb).count(), 452 /// 0 453 /// ); 454 /// ``` 455 #[cfg_attr(docsrs, doc(cfg(feature = "custom")))] 456 #[cfg(feature = "custom")] 457 #[inline] 458 #[must_use] 459 pub const fn remove(self, transport: AuthenticatorTransport) -> Self { 460 Self(self.0 & !transport.to_u8()) 461 } 462 } 463 /// [`AuthenticatorAttachment`](https://www.w3.org/TR/webauthn-3/#enumdef-authenticatorattachment). 464 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 465 pub enum AuthenticatorAttachment { 466 /// No attachment information. 467 None, 468 /// [`platform`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorattachment-platform). 469 Platform, 470 /// [`cross-platform`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorattachment-cross-platform). 471 CrossPlatform, 472 } 473 impl PartialEq<&Self> for AuthenticatorAttachment { 474 #[inline] 475 fn eq(&self, other: &&Self) -> bool { 476 *self == **other 477 } 478 } 479 impl PartialEq<AuthenticatorAttachment> for &AuthenticatorAttachment { 480 #[inline] 481 fn eq(&self, other: &AuthenticatorAttachment) -> bool { 482 **self == *other 483 } 484 } 485 /// The maximum number of bytes that can make up a Credential ID 486 /// [per WebAuthn](https://www.w3.org/TR/webauthn-3/#credential-id). 487 pub const CRED_ID_MAX_LEN: usize = 1023; 488 /// The minimum number of bytes that can make up a Credential ID 489 /// [per WebAuthn](https://www.w3.org/TR/webauthn-3/#credential-id). 490 /// 491 /// The spec does not call out this value directly instead it states the following: 492 /// 493 /// > Credential IDs are generated by authenticators in two forms: 494 /// > 495 /// > * At least 16 bytes that include at least 100 bits of entropy, or 496 /// > * The [public key credential source](https://www.w3.org/TR/webauthn-3/#public-key-credential-source), 497 /// > without its Credential ID or mutable items, encrypted so only its managing 498 /// > authenticator can decrypt it. This form allows the authenticator to be nearly 499 /// > stateless, by having the Relying Party store any necessary state. 500 /// 501 /// One of the immutable items of the public key credential source is the private key 502 /// which for any real-world signature algorithm will always be at least 16 bytes. 503 pub const CRED_ID_MIN_LEN: usize = 16; 504 /// A [Credential ID](https://www.w3.org/TR/webauthn-3/#credential-id) that is made up of 505 /// [`CRED_ID_MIN_LEN`]–[`CRED_ID_MAX_LEN`] bytes. 506 #[derive(Clone, Copy, Debug)] 507 pub struct CredentialId<T>(T); 508 impl<T> CredentialId<T> { 509 /// Returns the contained data consuming `self`. 510 #[inline] 511 pub fn into_inner(self) -> T { 512 self.0 513 } 514 /// Returns the contained data. 515 #[inline] 516 pub const fn inner(&self) -> &T { 517 &self.0 518 } 519 } 520 impl<'a> CredentialId<&'a [u8]> { 521 /// Creates a `CredentialId` from a `slice`. 522 #[expect(single_use_lifetimes, reason = "false positive")] 523 fn from_slice<'b: 'a>(value: &'b [u8]) -> Result<Self, CredentialIdErr> { 524 if (CRED_ID_MIN_LEN..=CRED_ID_MAX_LEN).contains(&value.len()) { 525 Ok(Self(value)) 526 } else { 527 Err(CredentialIdErr) 528 } 529 } 530 } 531 impl<T: AsRef<[u8]>> AsRef<[u8]> for CredentialId<T> { 532 #[inline] 533 fn as_ref(&self) -> &[u8] { 534 self.0.as_ref() 535 } 536 } 537 impl<T: Borrow<[u8]>> Borrow<[u8]> for CredentialId<T> { 538 #[inline] 539 fn borrow(&self) -> &[u8] { 540 self.0.borrow() 541 } 542 } 543 impl<'a: 'b, 'b> From<&'a CredentialId<Vec<u8>>> for CredentialId<&'b Vec<u8>> { 544 #[inline] 545 fn from(value: &'a CredentialId<Vec<u8>>) -> Self { 546 Self(&value.0) 547 } 548 } 549 impl<'a: 'b, 'b> From<CredentialId<&'a Vec<u8>>> for CredentialId<&'b [u8]> { 550 #[inline] 551 fn from(value: CredentialId<&'a Vec<u8>>) -> Self { 552 Self(value.0.as_slice()) 553 } 554 } 555 impl<'a: 'b, 'b> From<&'a CredentialId<Vec<u8>>> for CredentialId<&'b [u8]> { 556 #[inline] 557 fn from(value: &'a CredentialId<Vec<u8>>) -> Self { 558 Self(value.0.as_slice()) 559 } 560 } 561 impl From<CredentialId<&[u8]>> for CredentialId<Vec<u8>> { 562 #[inline] 563 fn from(value: CredentialId<&[u8]>) -> Self { 564 Self(value.0.to_owned()) 565 } 566 } 567 impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<CredentialId<T>> for CredentialId<T2> { 568 #[inline] 569 fn eq(&self, other: &CredentialId<T>) -> bool { 570 self.0 == other.0 571 } 572 } 573 impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<CredentialId<T>> for &CredentialId<T2> { 574 #[inline] 575 fn eq(&self, other: &CredentialId<T>) -> bool { 576 **self == *other 577 } 578 } 579 impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<&CredentialId<T>> for CredentialId<T2> { 580 #[inline] 581 fn eq(&self, other: &&CredentialId<T>) -> bool { 582 *self == **other 583 } 584 } 585 impl<T: Eq> Eq for CredentialId<T> {} 586 impl<T: Hash> Hash for CredentialId<T> { 587 #[inline] 588 fn hash<H: Hasher>(&self, state: &mut H) { 589 self.0.hash(state); 590 } 591 } 592 impl<T: PartialOrd<T2>, T2: PartialOrd<T>> PartialOrd<CredentialId<T>> for CredentialId<T2> { 593 #[inline] 594 fn partial_cmp(&self, other: &CredentialId<T>) -> Option<Ordering> { 595 self.0.partial_cmp(&other.0) 596 } 597 } 598 impl<T: Ord> Ord for CredentialId<T> { 599 #[inline] 600 fn cmp(&self, other: &Self) -> Ordering { 601 self.0.cmp(&other.0) 602 } 603 } 604 // We define a separate type to ensure challenges sent to the client are always randomly generated; 605 // otherwise one could deserialize arbitrary data into a `Challenge`. 606 /// Copy of [`Challenge`] sent back from the client. 607 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 608 pub struct SentChallenge(pub u128); 609 impl PartialEq<&Self> for SentChallenge { 610 #[inline] 611 fn eq(&self, other: &&Self) -> bool { 612 *self == **other 613 } 614 } 615 impl PartialEq<SentChallenge> for &SentChallenge { 616 #[inline] 617 fn eq(&self, other: &SentChallenge) -> bool { 618 **self == *other 619 } 620 } 621 impl PartialOrd for SentChallenge { 622 #[inline] 623 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 624 Some(self.cmp(other)) 625 } 626 } 627 impl Ord for SentChallenge { 628 #[inline] 629 fn cmp(&self, other: &Self) -> Ordering { 630 self.0.cmp(&other.0) 631 } 632 } 633 impl Hash for SentChallenge { 634 #[inline] 635 fn hash<H: Hasher>(&self, state: &mut H) { 636 state.write_u128(self.0); 637 } 638 } 639 /// An [`origin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-origin) or 640 /// [`topOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-toporigin). 641 #[derive(Debug, Eq)] 642 pub struct Origin<'a>(pub Cow<'a, str>); 643 impl PartialEq<Origin<'_>> for Origin<'_> { 644 #[inline] 645 fn eq(&self, other: &Origin<'_>) -> bool { 646 self.0 == other.0 647 } 648 } 649 impl PartialEq<&Origin<'_>> for Origin<'_> { 650 #[inline] 651 fn eq(&self, other: &&Origin<'_>) -> bool { 652 *self == **other 653 } 654 } 655 impl PartialEq<Origin<'_>> for &Origin<'_> { 656 #[inline] 657 fn eq(&self, other: &Origin<'_>) -> bool { 658 **self == *other 659 } 660 } 661 impl PartialEq<str> for Origin<'_> { 662 #[inline] 663 fn eq(&self, other: &str) -> bool { 664 self.0.as_ref() == other 665 } 666 } 667 impl PartialEq<Origin<'_>> for str { 668 #[inline] 669 fn eq(&self, other: &Origin<'_>) -> bool { 670 *other == *self 671 } 672 } 673 impl PartialEq<&str> for Origin<'_> { 674 #[inline] 675 fn eq(&self, other: &&str) -> bool { 676 *self == **other 677 } 678 } 679 impl PartialEq<Origin<'_>> for &str { 680 #[inline] 681 fn eq(&self, other: &Origin<'_>) -> bool { 682 **self == *other 683 } 684 } 685 impl PartialEq<String> for Origin<'_> { 686 #[inline] 687 fn eq(&self, other: &String) -> bool { 688 self.0 == *other 689 } 690 } 691 impl PartialEq<Origin<'_>> for String { 692 #[inline] 693 fn eq(&self, other: &Origin<'_>) -> bool { 694 *other == *self 695 } 696 } 697 impl PartialEq<Url> for Origin<'_> { 698 #[inline] 699 fn eq(&self, other: &Url) -> bool { 700 self.0.as_ref() == other.as_ref() 701 } 702 } 703 impl PartialEq<Origin<'_>> for Url { 704 #[inline] 705 fn eq(&self, other: &Origin<'_>) -> bool { 706 *other == *self 707 } 708 } 709 impl PartialEq<&Url> for Origin<'_> { 710 #[inline] 711 fn eq(&self, other: &&Url) -> bool { 712 *self == **other 713 } 714 } 715 impl PartialEq<Origin<'_>> for &Url { 716 #[inline] 717 fn eq(&self, other: &Origin<'_>) -> bool { 718 **self == *other 719 } 720 } 721 /// [Authenticator data flags](https://www.w3.org/TR/webauthn-3/#authdata-flags). 722 #[derive(Clone, Copy, Debug)] 723 pub struct Flag { 724 /// [`UP` flag](https://www.w3.org/TR/webauthn-3/#authdata-flags-up). 725 /// 726 /// Note this is always `true` when part of [`auth::AuthenticatorData::flags`]. 727 pub user_present: bool, 728 /// [`UV` flag](https://www.w3.org/TR/webauthn-3/#concept-user-verified). 729 pub user_verified: bool, 730 /// [`BE`](https://www.w3.org/TR/webauthn-3/#backup-eligibility) and 731 /// [`BS`](https://www.w3.org/TR/webauthn-3/#backup-state) flags. 732 pub backup: Backup, 733 } 734 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 735 pub(super) trait AuthData<'a>: Sized { 736 /// Error returned by [`Self::user_is_not_present`]. 737 /// 738 /// This should be [`Infallible`] in the event user must not always be present. 739 type UpBitErr; 740 /// [`attestedCredentialData`](https://www.w3.org/TR/webauthn-3/#authdata-attestedcredentialdata). 741 type CredData; 742 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions). 743 type Ext: AuthExtOutput + Copy; 744 /// Errors iff the user must always be present. 745 fn user_is_not_present() -> Result<(), Self::UpBitErr>; 746 /// `true` iff `AT` bit (i.e., bit 6) in [`Self::flag_data`] can and must be set to 1. 747 fn contains_at_bit() -> bool; 748 /// Constructor. 749 fn new(rp_id_hash: &'a [u8], flags: Flag, sign_count: u32, attested_credential_data: Self::CredData, extensions: Self::Ext) -> Self; 750 /// [`rpIdHash`](https://www.w3.org/TR/webauthn-3/#authdata-rpidhash). 751 fn rp_hash(&self) -> &'a [u8]; 752 /// [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags). 753 fn flag(&self) -> Flag; 754 } 755 /// [`CollectedClientData`](https://www.w3.org/TR/webauthn-3/#dictdef-collectedclientdata). 756 #[derive(Debug)] 757 pub struct CollectedClientData<'a> { 758 /// [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-challenge). 759 pub challenge: SentChallenge, 760 /// [`origin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-origin). 761 pub origin: Origin<'a>, 762 /// [`crossOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-crossorigin). 763 pub cross_origin: bool, 764 /// [`topOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-toporigin). 765 /// 766 /// When `CollectedClientData` is constructed via [`Self::from_client_data_json`], this can only be 767 /// `Some` if [`Self::cross_origin`]; and if `Some`, it will be different than [`Self::origin`]. 768 pub top_origin: Option<Origin<'a>>, 769 } 770 impl<'a> CollectedClientData<'a> { 771 /// Parses `json` based on the 772 /// [limited verification algorithm](https://www.w3.org/TR/webauthn-3/#clientdatajson-verification). 773 /// 774 /// Additionally, [`topOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-toporigin) is only 775 /// allowed to exist if it has a different value than 776 /// [`origin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-origin) and 777 /// [`crossOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-crossorigin) is `true`. 778 /// 779 /// `REGISTRATION` iff [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type) must be 780 /// `"webauthn.create"`; otherwise it must be `"webauthn.get"`. 781 /// 782 /// # Errors 783 /// 784 /// Errors iff `json` cannot be parsed based on the aforementioned requirements. 785 /// 786 /// # Examples 787 /// 788 /// ``` 789 /// # use webauthn_rp::response::{error::CollectedClientDataErr, CollectedClientData}; 790 /// assert!(!CollectedClientData::from_client_data_json::<true>(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice())?.cross_origin); 791 /// assert!(!CollectedClientData::from_client_data_json::<false>(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice())?.cross_origin); 792 /// # Ok::<_, CollectedClientDataErr>(()) 793 /// ``` 794 #[expect(single_use_lifetimes, reason = "false positive")] 795 #[inline] 796 pub fn from_client_data_json<'b: 'a, const REGISTRATION: bool>(json: &'b [u8]) -> Result<Self, CollectedClientDataErr> { 797 LimitedVerificationParser::<REGISTRATION>::parse(json) 798 } 799 /// Parses `json` in a "relaxed" way. 800 /// 801 /// Unlike [`Self::from_client_data_json`] which requires `json` to be an output from the 802 /// [JSON-compatible serialization of client data](https://www.w3.org/TR/webauthn-3/#clientdatajson-serialization), 803 /// this parses `json` based entirely on the 804 /// [`CollectedClientData`](https://www.w3.org/TR/webauthn-3/#dictdef-collectedclientdata) Web IDL `dictionary`. 805 /// 806 /// L1 clients predate the JSON-compatible serialization of client data; additionally there are L2 and L3 807 /// clients that don't adhere to the JSON-compatible serialization of client data despite being required to. 808 /// These clients serialize `CollectedClientData` so that it's valid JSON and conforms to the Web IDL `dictionary` 809 /// and nothing more. Furthermore, when not relying on the 810 /// [limited verification algorithm](https://www.w3.org/TR/webauthn-3/#clientdatajson-verification), the spec 811 /// requires the data to be decoded in a way equivalent to 812 /// [UTF-8 decode](https://encoding.spec.whatwg.org/#utf-8-decode) which both interprets a leading zero 813 /// width no-breaking space (i.e., U+FEFF) as a byte-order mark (BOM) as well as replaces any sequences of 814 /// invalid UTF-8 code units with the replacement character (i.e., U+FFFD). That is precisely what this 815 /// function does. 816 /// 817 /// # Errors 818 /// 819 /// Errors iff any of the following is true: 820 /// * The payload is not valid JSON _after_ ignoring a leading U+FEFF and replacing any sequences of invalid 821 /// UTF-8 code units with U+FFFD. 822 /// * The JSON does not conform to the Web IDL `dictionary`. 823 /// * [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type) is not `"webauthn.create"` 824 /// or `"webauthn.get"` when `REGISTRATION` and `!REGISTRATION` respectively. 825 /// * [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-challenge) is not a 826 /// base64url-encoded [`Challenge`]. 827 /// * Existence of duplicate keys for the keys that are expected. 828 /// 829 /// # Examples 830 /// 831 /// ``` 832 /// # use webauthn_rp::response::{ser_relaxed::SerdeJsonErr, CollectedClientData}; 833 /// assert!(!CollectedClientData::from_client_data_json_relaxed::<true>(b"\xef\xbb\xbf{ 834 /// \"type\": \"webauthn.create\", 835 /// \"origin\": \"https://example.com\", 836 /// \"f\xffo\": 123, 837 /// \"topOrigin\": \"https://example.com\", 838 /// \"challenge\": \"AAAAAAAAAAAAAAAAAAAAAA\" 839 /// }")?.cross_origin); 840 /// # Ok::<_, SerdeJsonErr>(()) 841 /// ``` 842 #[expect(single_use_lifetimes, reason = "false positive")] 843 #[cfg_attr(docsrs, doc(cfg(feature = "serde_relaxed")))] 844 #[cfg(feature = "serde_relaxed")] 845 #[inline] 846 pub fn from_client_data_json_relaxed<'b: 'a, const REGISTRATION: bool>(json: &'b [u8]) -> Result<Self, SerdeJsonErr> { 847 ser_relaxed::RelaxedClientDataJsonParser::<REGISTRATION>::parse(json) 848 } 849 } 850 /// Parser of 851 /// [`JSON-compatible serialization of client data`](https://www.w3.org/TR/webauthn-3/#collectedclientdata-json-compatible-serialization-of-client-data). 852 trait ClientDataJsonParser { 853 /// Error returned by [`Self::parse`]. 854 type Err; 855 /// Parses `json` into `CollectedClientData` based on the value of 856 /// [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type). 857 /// 858 /// # Errors 859 /// 860 /// Errors iff `json` cannot be parsed into a `CollectedClientData`. 861 fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err>; 862 /// Extracts [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-challenge) 863 /// from `json`. 864 /// 865 /// Note `json` should be minimally parsed such that only `challenge` is extracted; thus 866 /// `Ok` being returned does _not_ mean `json` is in fact valid. 867 fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err>; 868 } 869 /// [`ClientDataJsonParser`] based on the 870 /// [limited verification algorithm](https://www.w3.org/TR/webauthn-3/#clientdatajson-verification) 871 /// with the following additional requirements: 872 /// * Unknown keys are not allowed. 873 /// * The entire payload is parsed; thus the payload is guaranteed to be valid UTF-8 and JSON. 874 /// * [`CollectedClientData::top_origin`] can only be `Some` if 875 /// [`crossOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-crossorigin). 876 /// * If `CollectedClientData::top_origin` is `Some`, then it does not equal [`CollectedClientData::origin`]. 877 /// 878 /// `REGISTRATION` iff [`ClientDataJsonParser::parse`] requires 879 /// [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type) to be `"webauthn.create"`; 880 /// otherwise it must be `"webauthn.get"`. 881 struct LimitedVerificationParser<const REGISTRATION: bool>; 882 impl<const R: bool> LimitedVerificationParser<R> { 883 /// Parses `val` as a JSON string with possibly trailing data. `val` MUST NOT begin with an opening quote. Upon 884 /// encountering the first non-escaped quote, the parsed value is returned in addition to the remaining 885 /// portion of `val` _after_ the closing quote. The limited verification algorithm is adhered to; thus the 886 /// _only_ Unicode scalar values that are allowed (and must) be hex-escaped are U+0000 to U+001F inclusively. 887 /// Similarly only `b'\\'` and `b'"'` are allowed (and must) be escaped with `b'\\'`. 888 #[expect(unsafe_code, reason = "comment justifies its correctness")] 889 #[expect(clippy::arithmetic_side_effects, clippy::indexing_slicing, reason = "comments justify their correctness")] 890 fn parse_string(val: &[u8]) -> Result<(Cow<'_, str>, &'_ [u8]), CollectedClientDataErr> { 891 /// Tracks the state of the current Unicode scalar value that is being parsed. 892 enum State { 893 /// We are not parsing `'"'`, `'\\'`, or U+0000 to U+001F. 894 Normal, 895 /// We just encountered the escape character. 896 Escape, 897 /// We just encountered `b"\\u"`. 898 UnicodeEscape, 899 /// We just encountered `b"\\u0"`. 900 UnicodeHex1, 901 /// We just encountered `b"\\u00"`. 902 UnicodeHex2, 903 /// We just encountered `b"\\u000"` or `b"\\u001"`. The contained `u8` is `0` iff the former; otherwise 904 /// `0x10`. 905 UnicodeHex3(u8), 906 } 907 // We parse this as UTF-8 only at the end iff it is not empty. This contains all the potential Unicode scalar 908 // values after de-escaping. 909 let mut utf8 = Vec::new(); 910 // We check for all `u8`s already; thus we might as well check if we encounter a non-ASCII `u8`. 911 // If we don't, then we can rely on `str::from_utf8_unchecked`. 912 let mut all_ascii = true; 913 // This tracks the start index of the next slice to add. We add slices iff we encounter the escape character or 914 // we return the parsed `Cow` (i.e., encounter an unescaped `b'"'`). 915 let mut cur_idx = 0; 916 // The state of the yet-to-be-parsed Unicode scalar value. 917 let mut state = State::Normal; 918 for (counter, &b) in val.iter().enumerate() { 919 match state { 920 State::Normal => { 921 match b { 922 b'"' => { 923 if utf8.is_empty() { 924 if all_ascii { 925 // `cur_idx` is 0 or 1. The latter is true iff `val` starts with a 926 // `b'\\'` or `b'"'` but contains no other escaped characters. 927 let s = &val[cur_idx..counter]; 928 // SAFETY: 929 // `all_ascii` is `false` iff we encountered any `u8` that was not 930 // an ASCII `u8`; thus we know `s` is valid ASCII which in turn means 931 // it's valid UTF-8. 932 let v = unsafe { str::from_utf8_unchecked(s) }; 933 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 934 return Ok((Cow::Borrowed(v), &val[counter + 1..])); 935 } 936 // `cur_idx` is 0 or 1. The latter is true iff `val` starts with a 937 // `b'\\'` or `b'"'` but contains no other escaped characters. 938 return str::from_utf8(&val[cur_idx..counter]) 939 .map_err(CollectedClientDataErr::Utf8) 940 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 941 .map(|v| (Cow::Borrowed(v), &val[counter + 1..])); 942 } 943 // `val.len() > counter && counter >= cur_idx`, so indexing is fine and overflow 944 // cannot happen. 945 utf8.extend_from_slice(&val[cur_idx..counter]); 946 if all_ascii { 947 // SAFETY: 948 // `all_ascii` is `false` iff we encountered any `u8` that was not 949 // an ASCII `u8`; thus we know `utf8` is valid ASCII which in turn means 950 // it's valid UTF-8. 951 let v = unsafe { String::from_utf8_unchecked(utf8) }; 952 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 953 return Ok((Cow::Owned(v), &val[counter + 1..])); 954 } 955 return String::from_utf8(utf8) 956 .map_err(CollectedClientDataErr::Utf8Owned) 957 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 958 .map(|v| (Cow::Owned(v), &val[counter + 1..])); 959 } 960 b'\\' => { 961 // Write the current slice of data. 962 utf8.extend_from_slice(&val[cur_idx..counter]); 963 state = State::Escape; 964 } 965 // ASCII is a subset of UTF-8 and this is a subset of ASCII. The code unit that is used for an 966 // ASCII Unicode scalar value _never_ appears in multi-code-unit Unicode scalar values; thus we 967 // error immediately. 968 ..=0x1f => return Err(CollectedClientDataErr::InvalidEscapedString), 969 128.. => all_ascii = false, 970 _ => (), 971 } 972 } 973 State::Escape => { 974 match b { 975 b'"' | b'\\' => { 976 // We start the next slice here since we need to add it. 977 cur_idx = counter; 978 state = State::Normal; 979 } 980 b'u' => { 981 state = State::UnicodeEscape; 982 } 983 _ => { 984 return Err(CollectedClientDataErr::InvalidEscapedString); 985 } 986 } 987 } 988 State::UnicodeEscape => { 989 if b != b'0' { 990 return Err(CollectedClientDataErr::InvalidEscapedString); 991 } 992 state = State::UnicodeHex1; 993 } 994 State::UnicodeHex1 => { 995 if b != b'0' { 996 return Err(CollectedClientDataErr::InvalidEscapedString); 997 } 998 state = State::UnicodeHex2; 999 } 1000 State::UnicodeHex2 => { 1001 state = State::UnicodeHex3(match b { 1002 b'0' => 0, 1003 b'1' => 0x10, 1004 _ => return Err(CollectedClientDataErr::InvalidEscapedString), 1005 }); 1006 } 1007 State::UnicodeHex3(v) => { 1008 match b { 1009 // Only and all _lowercase_ hex is allowed. 1010 b'0'..=b'9' | b'a'..=b'f' => { 1011 // When `b < b'a'`, then `b >= b'0'`; and `b'a' > 87`; thus underflow cannot happen. 1012 // Note `b'a' - 10 == 87`. 1013 utf8.push(v | (b - if b < b'a' { b'0' } else { 87 })); 1014 // `counter < val.len()`, so overflow cannot happen. 1015 cur_idx = counter + 1; 1016 state = State::Normal; 1017 } 1018 _ => return Err(CollectedClientDataErr::InvalidEscapedString), 1019 } 1020 } 1021 } 1022 } 1023 // We never encountered an unescaped `b'"'`; thus we could not parse a string. 1024 Err(CollectedClientDataErr::InvalidObject) 1025 } 1026 } 1027 impl<const R: bool> ClientDataJsonParser for LimitedVerificationParser<R> { 1028 type Err = CollectedClientDataErr; 1029 #[expect(clippy::panic_in_result_fn, reason = "want to crash when there is a bug")] 1030 #[expect(clippy::little_endian_bytes, reason = "Challenge::serialize and this need to be consistent across architectures")] 1031 #[expect(clippy::too_many_lines, reason = "110 lines is fine")] 1032 fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err> { 1033 // `{"type":"webauthn.<create|get>","challenge":"<22 bytes>","origin":"<bytes>","crossOrigin":<true|false>[,"topOrigin":"<bytes>"][,<anything>]}`. 1034 /// First portion of `value`. 1035 const HEADER: &[u8; 18] = br#"{"type":"webauthn."#; 1036 /// `get`. 1037 const GET: &[u8; 3] = b"get"; 1038 /// `create`. 1039 const CREATE: &[u8; 6] = b"create"; 1040 /// Value after type before the start of the base64url-encoded challenge. 1041 const AFTER_TYPE: &[u8; 15] = br#"","challenge":""#; 1042 /// Value after challenge before the start of the origin value. 1043 const AFTER_CHALLENGE: &[u8; 12] = br#"","origin":""#; 1044 /// Value after origin before the start of the crossOrigin value. 1045 const AFTER_ORIGIN: &[u8; 15] = br#","crossOrigin":"#; 1046 /// `true`. 1047 const TRUE: &[u8; 4] = b"true"; 1048 /// `false`. 1049 const FALSE: &[u8; 5] = b"false"; 1050 /// Value after crossOrigin before the start of the topOrigin value. 1051 const AFTER_CROSS: &[u8; 13] = br#""topOrigin":""#; 1052 json.split_last().ok_or(CollectedClientDataErr::Len).and_then(|(last, last_rem)| { 1053 if *last == b'}' { 1054 last_rem.split_at_checked(HEADER.len()).ok_or(CollectedClientDataErr::Len).and_then(|(header, header_rem)| { 1055 if header == HEADER { 1056 if R { 1057 header_rem.split_at_checked(CREATE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(create, create_rem)| { 1058 if create == CREATE { 1059 Ok(create_rem) 1060 } else { 1061 Err(CollectedClientDataErr::Type) 1062 } 1063 }) 1064 } else { 1065 header_rem.split_at_checked(GET.len()).ok_or(CollectedClientDataErr::Len).and_then(|(get, get_rem)| { 1066 if get == GET { 1067 Ok(get_rem) 1068 } else { 1069 Err(CollectedClientDataErr::Type) 1070 } 1071 }) 1072 }.and_then(|type_rem| { 1073 type_rem.split_at_checked(AFTER_TYPE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(chall_key, chall_key_rem)| { 1074 if chall_key == AFTER_TYPE { 1075 chall_key_rem.split_at_checked(Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|(base64_chall, base64_chall_rem)| { 1076 let mut chall = [0; 16]; 1077 BASE64URL_NOPAD.decode_mut(base64_chall, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).and_then(|chall_len| { 1078 assert_eq!(chall_len, 16, "there is a bug in BASE64URL_NOPAD::decode_mut"); 1079 base64_chall_rem.split_at_checked(AFTER_CHALLENGE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(origin_key, origin_key_rem)| { 1080 if origin_key == AFTER_CHALLENGE { 1081 Self::parse_string(origin_key_rem).and_then(|(origin, origin_rem)| { 1082 origin_rem.split_at_checked(AFTER_ORIGIN.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_key, cross_key_rem)| { 1083 if cross_key == AFTER_ORIGIN { 1084 // `FALSE.len() > TRUE.len()`, so we check for `FALSE` in `and_then`. 1085 cross_key_rem.split_at_checked(TRUE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_true, cross_true_rem)| { 1086 if cross_true == TRUE { 1087 Ok((true, cross_true_rem)) 1088 } else { 1089 cross_key_rem.split_at_checked(FALSE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_false, cross_false_rem)| { 1090 if cross_false == FALSE { 1091 Ok((false, cross_false_rem)) 1092 } else { 1093 Err(CollectedClientDataErr::CrossOrigin) 1094 } 1095 }) 1096 }.and_then(|(cross, cross_rem)| { 1097 cross_rem.split_first().map_or(Ok((cross, None)), |(comma, comma_rem)| { 1098 if *comma == b',' { 1099 comma_rem.split_at_checked(AFTER_CROSS.len()).map_or(Ok((cross, None)), |(top, top_rem)| { 1100 if top == AFTER_CROSS { 1101 if cross { 1102 Self::parse_string(top_rem).and_then(|(top_origin, top_origin_rem)| { 1103 top_origin_rem.first().map_or(Ok(()), |v| { 1104 if *v == b',' { 1105 Ok(()) 1106 } else { 1107 Err(CollectedClientDataErr::InvalidObject) 1108 } 1109 }).and_then(|()| { 1110 if origin == top_origin { 1111 Err(CollectedClientDataErr::TopOriginSameAsOrigin) 1112 } else { 1113 Ok((true, Some(Origin(top_origin)))) 1114 } 1115 }) 1116 }) 1117 } else { 1118 Err(CollectedClientDataErr::TopOriginWithoutCrossOrigin) 1119 } 1120 } else { 1121 Ok((cross, None)) 1122 } 1123 }) 1124 } else { 1125 Err(CollectedClientDataErr::InvalidObject) 1126 } 1127 }).map(|(cross_origin, top_origin)| CollectedClientData { challenge: SentChallenge(u128::from_le_bytes(chall)), origin: Origin(origin), cross_origin, top_origin, }) 1128 }) 1129 }) 1130 } else { 1131 Err(CollectedClientDataErr::CrossOriginKey) 1132 } 1133 }) 1134 }) 1135 } else { 1136 Err(CollectedClientDataErr::OriginKey) 1137 } 1138 }) 1139 }) 1140 }) 1141 } else { 1142 Err(CollectedClientDataErr::ChallengeKey) 1143 } 1144 }) 1145 }) 1146 } else { 1147 Err(CollectedClientDataErr::InvalidStart) 1148 } 1149 }) 1150 } else { 1151 Err(CollectedClientDataErr::InvalidObject) 1152 } 1153 }) 1154 } 1155 #[expect(clippy::panic_in_result_fn, reason = "want to crash when there is a bug")] 1156 #[expect(clippy::arithmetic_side_effects, reason = "comment justifies correctness")] 1157 #[expect(clippy::little_endian_bytes, reason = "Challenge::serialize and this need to be consistent across architectures")] 1158 fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err> { 1159 // Index 39. 1160 // `{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA"...`. 1161 // Index 36. 1162 // `{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA"...`. 1163 let idx = if R { 39 } else { 36 }; 1164 // This maxes at 39 + 22 = 61; thus overflow is not an issue. 1165 json.get(idx..idx + Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|chall_slice| { 1166 let mut chall = [0; 16]; 1167 BASE64URL_NOPAD.decode_mut(chall_slice, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).map(|len| { 1168 assert_eq!(len, 16, "there is a bug in BASE64URL_NOPAD::decode_mut"); 1169 SentChallenge(u128::from_le_bytes(chall)) 1170 }) 1171 }) 1172 } 1173 } 1174 /// Authenticator extension outputs; 1175 pub(super) trait AuthExtOutput { 1176 /// MUST return `true` iff there is no data. 1177 fn missing(self) -> bool; 1178 } 1179 /// Successful return type from [`FromCbor::from_cbor`]. 1180 struct CborSuccess<'a, T> { 1181 /// Value parsed from the slice. 1182 value: T, 1183 /// Remaining unprocessed data. 1184 remaining: &'a [u8], 1185 } 1186 /// Types that parse 1187 /// [CTAP2 canonical CBOR encoding form](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#ctap2-canonical-cbor-encoding-form) 1188 /// data without necessarily consuming all the data. 1189 /// 1190 /// The purpose of this `trait` is to allow chains of types to progressively consume `cbor` by passing 1191 /// [`CborSuccess::remaining`] into the next `FromCbor` type. 1192 trait FromCbor<'a>: Sized { 1193 /// Error when conversion fails. 1194 type Err; 1195 /// Parses `cbor` into `Self`. 1196 /// 1197 /// # Errors 1198 /// 1199 /// Errors if `cbor` cannot be parsed into `Self:`. 1200 fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err>; 1201 } 1202 /// Error returned from [`A::from_cbor`] `where A: AuthData`. 1203 enum AuthenticatorDataErr<UpErr, CredData, AuthExt> { 1204 /// The `slice` had an invalid length. 1205 Len, 1206 /// [UP](https://www.w3.org/TR/webauthn-3/#authdata-flags-at) bit was 0. 1207 UserNotPresent(UpErr), 1208 /// Bit 1 in [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags) is not 0. 1209 FlagsBit1Not0, 1210 /// Bit 5 in [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags) is not 0. 1211 FlagsBit5Not0, 1212 /// [AT](https://www.w3.org/TR/webauthn-3/#authdata-flags-at) bit was 0 during registration or was 1 1213 /// during authentication. 1214 AttestedCredentialData, 1215 /// [BE](https://www.w3.org/TR/webauthn-3/#authdata-flags-be) and 1216 /// [BS](https://www.w3.org/TR/webauthn-3/#authdata-flags-bs) bits were 0 and 1 respectively. 1217 BackupWithoutEligibility, 1218 /// Error returned from [`AttestedCredentialData::from_cbor`]. 1219 AttestedCredential(CredData), 1220 /// Error returned from [`register::AuthenticatorExtensionOutput::from_cbor`] and 1221 /// [`auth::AuthenticatorExtensionOutput::from_cbor`]. 1222 AuthenticatorExtension(AuthExt), 1223 /// [ED](https://www.w3.org/TR/webauthn-3/#authdata-flags-ed) bit was 0, but 1224 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions) existed. 1225 NoExtensionBitWithData, 1226 /// [ED](https://www.w3.org/TR/webauthn-3/#authdata-flags-ed) bit was 1, but 1227 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions) did not exist. 1228 ExtensionBitWithoutData, 1229 /// There was trailing data that could not be deserialized. 1230 TrailingData, 1231 } 1232 impl<U, C: Display, A: Display> Display for AuthenticatorDataErr<U, C, A> { 1233 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1234 match *self { 1235 Self::Len => f.write_str("authenticator data had an invalid length"), 1236 Self::UserNotPresent(_) => f.write_str("user was not present"), 1237 Self::FlagsBit1Not0 => f.write_str("flags 1-bit was 1"), 1238 Self::FlagsBit5Not0 => f.write_str("flags 5-bit was 1"), 1239 Self::AttestedCredentialData => f.write_str("attested credential data was included during authentication or was not included during registration"), 1240 Self::BackupWithoutEligibility => { 1241 f.write_str("backup state bit was 1 despite backup eligibility being 0") 1242 } 1243 Self::AttestedCredential(ref err) => err.fmt(f), 1244 Self::AuthenticatorExtension(ref err) => err.fmt(f), 1245 Self::NoExtensionBitWithData => { 1246 f.write_str("extension bit was 0 despite extensions existing") 1247 } 1248 Self::ExtensionBitWithoutData => { 1249 f.write_str("extension bit was 1 despite no extensions existing") 1250 } 1251 Self::TrailingData => { 1252 f.write_str("slice had trailing data that could not be deserialized") 1253 } 1254 } 1255 } 1256 } 1257 impl From<AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>> for RegAuthDataErr { 1258 #[inline] 1259 fn from(value: AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>) -> Self { 1260 match value { 1261 AuthenticatorDataErr::Len => Self::Len, 1262 AuthenticatorDataErr::UserNotPresent(v) => match v {}, 1263 AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0, 1264 AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0, 1265 AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataNotIncluded, 1266 AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility, 1267 AuthenticatorDataErr::AttestedCredential(err) => Self::AttestedCredential(err), 1268 AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err), 1269 AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData, 1270 AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData, 1271 AuthenticatorDataErr::TrailingData => Self::TrailingData, 1272 } 1273 } 1274 } 1275 impl From<AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>> for AuthAuthDataErr { 1276 #[inline] 1277 fn from(value: AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>) -> Self { 1278 match value { 1279 AuthenticatorDataErr::Len => Self::Len, 1280 AuthenticatorDataErr::UserNotPresent(()) => Self::UserNotPresent, 1281 AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0, 1282 AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0, 1283 AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataIncluded, 1284 AuthenticatorDataErr::AttestedCredential(val) => match val {}, 1285 AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility, 1286 AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err), 1287 AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData, 1288 AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData, 1289 AuthenticatorDataErr::TrailingData => Self::TrailingData, 1290 } 1291 } 1292 } 1293 impl<'a, A> FromCbor<'a> for A 1294 where 1295 A: AuthData<'a>, 1296 A::CredData: FromCbor<'a>, 1297 A::Ext: FromCbor<'a>, 1298 { 1299 type Err = AuthenticatorDataErr<A::UpBitErr, <A::CredData as FromCbor<'a>>::Err, <A::Ext as FromCbor<'a>>::Err>; 1300 #[expect(clippy::big_endian_bytes, reason = "CBOR integers are in big-endian")] 1301 fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err> { 1302 /// Length of `signCount`. 1303 const SIGN_COUNT_LEN: usize = 4; 1304 /// `UP` bit (i.e., bit 0) set to 1. 1305 const UP: u8 = 0b0000_0001; 1306 /// `RFU1` bit (i.e., bit 1) set to 1. 1307 const RFU1: u8 = UP << 1; 1308 /// `UV` bit (i.e., bit 2) set to 1. 1309 const UV: u8 = RFU1 << 1; 1310 /// `BE` bit (i.e., bit 3) set to 1. 1311 const BE: u8 = UV << 1; 1312 /// `BS` bit (i.e., bit 4) set to 1. 1313 const BS: u8 = BE << 1; 1314 /// `RFU2` bit (i.e., bit 5) set to 1. 1315 const RFU2: u8 = BS << 1; 1316 /// `AT` bit (i.e., bit 6) set to 1. 1317 const AT: u8 = RFU2 << 1; 1318 /// `ED` bit (i.e., bit 7) set to 1. 1319 const ED: u8 = AT << 1; 1320 cbor.split_at_checked(Sha256::output_size()).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(rp_id_slice, rp_id_rem)| { 1321 rp_id_rem.split_first().ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(&flag, flag_rem)| { 1322 let user_present = flag & UP == UP; 1323 if user_present { 1324 Ok(()) 1325 } else { 1326 A::user_is_not_present().map_err(AuthenticatorDataErr::UserNotPresent) 1327 } 1328 .and_then(|()| { 1329 if flag & RFU1 == 0 { 1330 if flag & RFU2 == 0 { 1331 let at_bit = A::contains_at_bit(); 1332 if flag & AT == AT { 1333 if at_bit { 1334 Ok(()) 1335 } else { 1336 Err(AuthenticatorDataErr::AttestedCredentialData) 1337 } 1338 } else if at_bit { 1339 Err(AuthenticatorDataErr::AttestedCredentialData) 1340 } else { 1341 Ok(()) 1342 }.and_then(|()| { 1343 let bs = flag & BS == BS; 1344 if flag & BE == BE { 1345 if bs { 1346 Ok(Backup::Exists) 1347 } else { 1348 Ok(Backup::Eligible) 1349 } 1350 } else if bs { 1351 Err(AuthenticatorDataErr::BackupWithoutEligibility) 1352 } else { 1353 Ok(Backup::NotEligible) 1354 } 1355 .and_then(|backup| { 1356 flag_rem.split_at_checked(SIGN_COUNT_LEN).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(count_slice, count_rem)| { 1357 A::CredData::from_cbor(count_rem).map_err(AuthenticatorDataErr::AttestedCredential).and_then(|att_data| { 1358 A::Ext::from_cbor(att_data.remaining).map_err(AuthenticatorDataErr::AuthenticatorExtension).and_then(|ext| { 1359 if ext.remaining.is_empty() { 1360 let ed = flag & ED == ED; 1361 if ext.value.missing() { 1362 if ed { 1363 Err(AuthenticatorDataErr::ExtensionBitWithoutData) 1364 } else { 1365 Ok(()) 1366 } 1367 } else if ed { 1368 Ok(()) 1369 } else { 1370 Err(AuthenticatorDataErr::NoExtensionBitWithData) 1371 }.map(|()| { 1372 let mut sign_count = [0; SIGN_COUNT_LEN]; 1373 sign_count.copy_from_slice(count_slice); 1374 // `signCount` is in big-endian. 1375 CborSuccess { value: A::new(rp_id_slice, Flag { user_present, user_verified: flag & UV == UV, backup, }, u32::from_be_bytes(sign_count), att_data.value, ext.value), remaining: ext.remaining, } 1376 }) 1377 } else { 1378 Err(AuthenticatorDataErr::TrailingData) 1379 } 1380 }) 1381 }) 1382 }) 1383 }) 1384 }) 1385 } else { 1386 Err(AuthenticatorDataErr::FlagsBit5Not0) 1387 } 1388 } else { 1389 Err(AuthenticatorDataErr::FlagsBit1Not0) 1390 } 1391 }) 1392 }) 1393 }) 1394 } 1395 } 1396 /// Data returned by [`AuthDataContainer::from_data`]. 1397 pub(super) struct ParsedAuthData<'a, A> { 1398 /// The data the CBOR is parsed into. 1399 data: A, 1400 /// The raw authenticator data and 32-bytes of trailing data. 1401 auth_data_and_32_trailing_bytes: &'a [u8], 1402 } 1403 /// Error returned by [`AuthResponse::parse_data_and_verify_sig`]. 1404 pub(super) enum AuthRespErr<AuthDataErr> { 1405 /// Variant returned when parsing 1406 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1407 /// into [`CollectedClientData`] fails. 1408 CollectedClientData(CollectedClientDataErr), 1409 /// Variant returned when parsing 1410 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1411 /// in a "relaxed" way into [`CollectedClientData`] fails. 1412 #[cfg(feature = "serde_relaxed")] 1413 CollectedClientDataRelaxed(SerdeJsonErr), 1414 /// Variant returned when parsing [`AuthResponse::Auth`] fails. 1415 Auth(AuthDataErr), 1416 /// Variant when the [`CompressedPubKey`] or [`UncompressePubKey`] is not valid. 1417 PubKey(PubKeyErr), 1418 /// Variant returned when the signature, if one exists, associated with 1419 /// [`Self::AuthResponse`] is invalid. 1420 Signature, 1421 } 1422 impl<A: Display> Display for AuthRespErr<A> { 1423 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1424 match *self { 1425 Self::CollectedClientData(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"), 1426 #[cfg(feature = "serde_relaxed")] 1427 Self::CollectedClientDataRelaxed(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"), 1428 Self::Auth(ref err) => write!(f, "auth data could not be parsed: {err}"), 1429 Self::PubKey(err) => err.fmt(f), 1430 Self::Signature => f.write_str("the signature over the authenticator data and CollectedClientData could not be verified"), 1431 } 1432 } 1433 } 1434 impl From<AuthRespErr<AttestationObjectErr>> for RegCeremonyErr { 1435 #[inline] 1436 fn from(value: AuthRespErr<AttestationObjectErr>) -> Self { 1437 match value { 1438 AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err), 1439 #[cfg(feature = "serde_relaxed")] 1440 AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err), 1441 AuthRespErr::Auth(err) => Self::AttestationObject(err), 1442 AuthRespErr::PubKey(err) => Self::PubKey(err), 1443 AuthRespErr::Signature => Self::AttestationSignature, 1444 } 1445 } 1446 } 1447 impl From<AuthRespErr<AuthAuthDataErr>> for AuthCeremonyErr { 1448 #[inline] 1449 fn from(value: AuthRespErr<AuthAuthDataErr>) -> Self { 1450 match value { 1451 AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err), 1452 #[cfg(feature = "serde_relaxed")] 1453 AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err), 1454 AuthRespErr::Auth(err) => Self::AuthenticatorData(err), 1455 AuthRespErr::PubKey(err) => Self::PubKey(err), 1456 AuthRespErr::Signature => Self::AssertionSignature, 1457 } 1458 } 1459 } 1460 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data) 1461 /// container. 1462 /// 1463 /// Note [`Self::Auth`] may be `Self`. 1464 pub(super) trait AuthDataContainer<'a>: Sized { 1465 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1466 type Auth: AuthData<'a>; 1467 /// Error returned from [`Self::from_data`]. 1468 type Err; 1469 /// Converts `data` into [`ParsedAuthData`]. 1470 /// 1471 /// # Errors 1472 /// 1473 /// Errors iff `data` cannot be converted into `ParsedAuthData`. 1474 fn from_data(data: &'a [u8]) -> Result<ParsedAuthData<'a, Self>, Self::Err>; 1475 /// Returns the contained 1476 /// [authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1477 fn authenticator_data(&self) -> &Self::Auth; 1478 } 1479 /// [`AuthenticatorResponse`](https://www.w3.org/TR/webauthn-3/#authenticatorresponse). 1480 pub(super) trait AuthResponse { 1481 /// [Attestation object](https://www.w3.org/TR/webauthn-3/#attestation-object) or 1482 /// [authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1483 type Auth<'a>: AuthDataContainer<'a> where Self: 'a; 1484 /// Public key to use to verify the contained signature. 1485 type CredKey<'a>; 1486 /// Parses 1487 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1488 /// based on `RELAXED` and [`Self::Auth`] via [`AuthDataContainer::from_data`] in addition to 1489 /// verifying any possible signature over the concatenation of the raw 1490 /// [`AuthDataContainer::Auth`] and `clientDataJSON` using `key` or the contained 1491 /// public key if one exists. If `Self` contains a public key and should not be passed one, then it should set 1492 /// [`Self::CredKey`] to `()`. 1493 /// 1494 /// # Errors 1495 /// 1496 /// Errors iff parsing `clientDataJSON` errors, [`AuthDataContainer::from_data`] does, or the signature 1497 /// is invalid. 1498 /// 1499 /// # Panics 1500 /// 1501 /// `panic`s iff `relaxed` and `serde_relaxed` is not enabled. 1502 #[expect( 1503 clippy::type_complexity, 1504 reason = "type aliases with bounds are even more problematic at least until lazy_type_alias is stable" 1505 )] 1506 fn parse_data_and_verify_sig(&self, key: Self::CredKey<'_>, relaxed: bool) -> Result<(CollectedClientData<'_>, Self::Auth<'_>), AuthRespErr<<Self::Auth<'_> as AuthDataContainer<'_>>::Err>>; 1507 } 1508 /// Ceremony response (i.e., [`PublicKeyCredential`](https://www.w3.org/TR/webauthn-3/#publickeycredential)). 1509 pub(super) trait Response { 1510 /// [`AuthenticatorResponse`](https://www.w3.org/TR/webauthn-3/#authenticatorresponse). 1511 type Auth: AuthResponse; 1512 /// [`response`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredential-response). 1513 fn auth(&self) -> &Self::Auth; 1514 } 1515 /// Error returned from [`Ceremony::partial_validate`]. 1516 pub(super) enum CeremonyErr<AuthDataErr> { 1517 /// Timeout occurred. 1518 Timeout, 1519 /// Read [`AuthRespErr`] for information. 1520 AuthResp(AuthRespErr<AuthDataErr>), 1521 /// Origin did not validate. 1522 OriginMismatch, 1523 /// Cross origin was `true` but was not allowed to be. 1524 CrossOrigin, 1525 /// Top origin did not validate. 1526 TopOriginMismatch, 1527 /// Challenges don't match. 1528 ChallengeMismatch, 1529 /// `rpIdHash` does not match the SHA-256 hash of the [`RpId`]. 1530 RpIdHashMismatch, 1531 /// User was not verified despite being required to. 1532 UserNotVerified, 1533 /// [`Backup::NotEligible`] was not sent back despite [`BackupReq::NotEligible`]. 1534 BackupEligible, 1535 /// [`Backup::NotEligible`] was sent back despite [`BackupReq::Eligible`]. 1536 BackupNotEligible, 1537 /// [`Backup::Eligible`] was not sent back despite [`BackupReq::EligibleNoteExists`]. 1538 BackupExists, 1539 /// [`Backup::Exists`] was not sent back despite [`BackupReq::Exists`]. 1540 BackupDoesNotExist, 1541 } 1542 impl<A: Display> Display for CeremonyErr<A> { 1543 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1544 match *self { 1545 Self::Timeout => f.write_str("ceremony timed out"), 1546 Self::AuthResp(ref err) => err.fmt(f), 1547 Self::OriginMismatch => { 1548 f.write_str("the origin sent from the client is not an allowed origin") 1549 } 1550 Self::CrossOrigin => { 1551 f.write_str("cross origin was from the client, but it is not allowed") 1552 } 1553 Self::TopOriginMismatch => { 1554 f.write_str("the top origin sent from the client is not an allowed top origin") 1555 } 1556 Self::ChallengeMismatch => f.write_str( 1557 "the challenge sent to the client does not match the challenge sent back", 1558 ), 1559 Self::RpIdHashMismatch => f.write_str( 1560 "the SHA-256 hash of the RP ID doesn't match the hash sent from the client", 1561 ), 1562 Self::UserNotVerified => f.write_str("user was not verified despite being required to"), 1563 Self::BackupEligible => f.write_str("credential is eligible to be backed up despite requiring that it not be"), 1564 Self::BackupNotEligible => f.write_str("credential is not eligible to be backed up despite requiring that it be"), 1565 Self::BackupExists => f.write_str("credential backup exists despite requiring that a backup not exist"), 1566 Self::BackupDoesNotExist => f.write_str("credential backup does not exist despite requiring that a backup exist"), 1567 } 1568 } 1569 } 1570 impl From<CeremonyErr<AttestationObjectErr>> for RegCeremonyErr { 1571 #[inline] 1572 fn from(value: CeremonyErr<AttestationObjectErr>) -> Self { 1573 match value { 1574 CeremonyErr::Timeout => Self::Timeout, 1575 CeremonyErr::AuthResp(err) => err.into(), 1576 CeremonyErr::OriginMismatch => Self::OriginMismatch, 1577 CeremonyErr::CrossOrigin => Self::CrossOrigin, 1578 CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch, 1579 CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch, 1580 CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch, 1581 CeremonyErr::UserNotVerified => Self::UserNotVerified, 1582 CeremonyErr::BackupEligible => Self::BackupEligible, 1583 CeremonyErr::BackupNotEligible => Self::BackupNotEligible, 1584 CeremonyErr::BackupExists => Self::BackupExists, 1585 CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist, 1586 } 1587 } 1588 } 1589 impl From<CeremonyErr<AuthAuthDataErr>> for AuthCeremonyErr { 1590 #[inline] 1591 fn from(value: CeremonyErr<AuthAuthDataErr>) -> Self { 1592 match value { 1593 CeremonyErr::Timeout => Self::Timeout, 1594 CeremonyErr::AuthResp(err) => err.into(), 1595 CeremonyErr::OriginMismatch => Self::OriginMismatch, 1596 CeremonyErr::CrossOrigin => Self::CrossOrigin, 1597 CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch, 1598 CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch, 1599 CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch, 1600 CeremonyErr::UserNotVerified => Self::UserNotVerified, 1601 CeremonyErr::BackupEligible => Self::BackupEligible, 1602 CeremonyErr::BackupNotEligible => Self::BackupNotEligible, 1603 CeremonyErr::BackupExists => Self::BackupExists, 1604 CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist, 1605 } 1606 } 1607 } 1608 /// [`AllAcceptedCredentialsOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions). 1609 /// 1610 /// This can be sent to _an already authenticated user_ to inform what credentials are currently registered. 1611 /// This can be useful when a user deletes credentials on the RP's side but does not do so on the authenticator. 1612 /// When the client forwards this response to the authenticator, it can remove all credentials that don't have 1613 /// a [`CredentialId`] in [`Self::all_accepted_credential_ids`]. 1614 #[derive(Debug)] 1615 pub struct AllAcceptedCredentialsOptions<'rp, 'user, const USER_LEN: usize> { 1616 /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-rpid). 1617 pub rp_id: &'rp RpId, 1618 /// [`userId`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-userid). 1619 pub user_id: &'user UserHandle<USER_LEN>, 1620 /// [`allAcceptedCredentialIds`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-allacceptedcredentialids). 1621 pub all_accepted_credential_ids: Vec<CredentialId<Vec<u8>>>, 1622 } 1623 /// [`CurrentUserDetailsOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions). 1624 /// 1625 /// This can be sent to _an already authenticated user_ to inform the user information. 1626 /// This can be useful when a user updates their user information on the RP's side but does not do so on the authenticator. 1627 /// When the client forwards this response to the authenticator, it can update the user info for the associated credential. 1628 #[derive(Debug)] 1629 pub struct CurrentUserDetailsOptions<'rp_id, 'name, 'display_name, 'id, const LEN: usize> { 1630 /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-rpid). 1631 pub rp_id: &'rp_id RpId, 1632 /// [`userId`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-userid), 1633 /// [`name`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-name), and 1634 /// [`displayName`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-displayname). 1635 pub user: PublicKeyCredentialUserEntity<'name, 'display_name, 'id, LEN>, 1636 } 1637 /// [`hmac-secret`](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#sctn-hmac-secret-extension) 1638 /// during authentication and 1639 /// [`hmac-secret-mc`](https://fidoalliance.org/specs/fido-v2.2-ps-20250228/fido-client-to-authenticator-protocol-v2.2-ps-20250228.html#sctn-hmac-secret-make-cred-extension) 1640 /// during registration. 1641 /// 1642 /// `REG` iff `hmac-secret-mc`. 1643 enum HmacSecretGet<const REG: bool> { 1644 /// No `hmac-secret` response. 1645 None, 1646 /// One encrypted `hmac-secret`. 1647 One, 1648 /// Two encrypted `hmac-secret`s. 1649 Two, 1650 } 1651 /// Error returned by [`HmacSecretGet::from_cbor`] 1652 enum HmacSecretGetErr { 1653 /// Error related to the length of the CBOR input. 1654 Len, 1655 /// Error related to the type of the CBOR key. 1656 Type, 1657 /// Error related to the value of the CBOR value. 1658 Value, 1659 } 1660 impl<const REG: bool> FromCbor<'_> for HmacSecretGet<REG> { 1661 type Err = HmacSecretGetErr; 1662 fn from_cbor(cbor: &[u8]) -> Result<CborSuccess<'_, Self>, Self::Err> { 1663 /// AES block size. 1664 const AES_BLOCK_SIZE: usize = 16; 1665 /// HMAC-SHA-256 output length. 1666 const HMAC_SHA_256_LEN: usize = 32; 1667 /// Length of two HMAC-SHA-256 outputs concatenated together. 1668 const TWO_HMAC_SHA_256_LEN: usize = HMAC_SHA_256_LEN << 1; 1669 // We need the smallest multiple of `AES_BLOCK_SIZE` that 1670 // is strictly greater than `HMAC_SHA_256_LEN`. 1671 /// AES-256 output length on a 32-byte input. 1672 #[expect( 1673 clippy::integer_division_remainder_used, 1674 reason = "doesn't need to be constant time" 1675 )] 1676 const ONE_SECRET_LEN: usize = 1677 HMAC_SHA_256_LEN + (AES_BLOCK_SIZE - (HMAC_SHA_256_LEN % AES_BLOCK_SIZE)); 1678 // We need the smallest multiple of `AES_BLOCK_SIZE` that 1679 // is strictly greater than `TWO_HMAC_SHA_256_LEN`. 1680 /// AES-256 output length on a 64-byte input. 1681 #[expect( 1682 clippy::integer_division_remainder_used, 1683 reason = "doesn't need to be constant time" 1684 )] 1685 const TWO_SECRET_LEN: usize = 1686 TWO_HMAC_SHA_256_LEN + (AES_BLOCK_SIZE - (TWO_HMAC_SHA_256_LEN % AES_BLOCK_SIZE)); 1687 /// `hmac-secret-mc`. 1688 /// 1689 /// This is the key iff `REG`. 1690 const KEY: [u8; 15] = [ 1691 cbor::TEXT_14, 1692 b'h', 1693 b'm', 1694 b'a', 1695 b'c', 1696 b'-', 1697 b's', 1698 b'e', 1699 b'c', 1700 b'r', 1701 b'e', 1702 b't', 1703 b'-', 1704 b'm', 1705 b'c', 1706 ]; 1707 /// Helper that unifies `HmacSecretGet`. 1708 enum CborVal<'a> { 1709 /// Extension does not exist with remaining payload 1710 Success, 1711 /// Extension exists with remaining payload. 1712 Continue(&'a [u8]), 1713 } 1714 if REG { 1715 cbor.split_at_checked(KEY.len()).map_or( 1716 Ok(CborVal::Success), 1717 |(key, key_rem)| { 1718 if key == KEY { 1719 Ok(CborVal::Continue(key_rem)) 1720 } else { 1721 Ok(CborVal::Success) 1722 } 1723 } 1724 ) 1725 } else { 1726 cbor.split_at_checked(cbor::HMAC_SECRET.len()).map_or( 1727 Ok(CborVal::Success), 1728 |(key, key_rem)| { 1729 if key == cbor::HMAC_SECRET { 1730 Ok(CborVal::Continue(key_rem)) 1731 } else { 1732 Ok(CborVal::Success) 1733 } 1734 } 1735 ) 1736 }.and_then(|cbor_val| { 1737 match cbor_val { 1738 CborVal::Success => Ok(CborSuccess { value: Self::None, remaining: cbor, }), 1739 CborVal::Continue(key_rem) => { 1740 key_rem 1741 .split_first() 1742 .ok_or(HmacSecretGetErr::Len) 1743 .and_then(|(bytes, bytes_rem)| { 1744 if *bytes == cbor::BYTES_INFO_24 { 1745 bytes_rem 1746 .split_first() 1747 .ok_or(HmacSecretGetErr::Len) 1748 .and_then(|(&len, len_rem)| { 1749 len_rem.split_at_checked(usize::from(len)).ok_or(HmacSecretGetErr::Len).and_then(|(_, remaining)| { 1750 match usize::from(len) { 1751 ONE_SECRET_LEN => { 1752 Ok(CborSuccess { 1753 value: Self::One, 1754 remaining, 1755 }) 1756 } 1757 TWO_SECRET_LEN => { 1758 Ok(CborSuccess { 1759 value: Self::Two, 1760 remaining, 1761 }) 1762 } 1763 _ => Err(HmacSecretGetErr::Value), 1764 } 1765 }) 1766 }) 1767 } else { 1768 Err(HmacSecretGetErr::Type) 1769 } 1770 }) 1771 } 1772 } 1773 }) 1774 } 1775 } 1776 #[cfg(test)] 1777 mod tests { 1778 use super::{CollectedClientDataErr, ClientDataJsonParser, LimitedVerificationParser}; 1779 #[test] 1780 fn parse_string() { 1781 assert!(LimitedVerificationParser::<true>::parse_string(br#"abc""#) 1782 .map_or(false, |tup| { tup.0 == "abc" && tup.1 == br#""# })); 1783 assert!(LimitedVerificationParser::<false>::parse_string(br#"abc"23"#) 1784 .map_or(false, |tup| { tup.0 == "abc" && tup.1 == br#"23"# })); 1785 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\"c"23"#) 1786 .map_or(false, |tup| { tup.0 == r#"ab"c"# && tup.1 == br#"23"# })); 1787 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\\c"23"#) 1788 .map_or(false, |tup| { tup.0 == r#"ab\c"# && tup.1 == br#"23"# })); 1789 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\u001fc"23"#) 1790 .map_or(false, |tup| { tup.0 == "ab\u{001f}c" && tup.1 == br#"23"# })); 1791 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\u000dc"23"#) 1792 .map_or(false, |tup| { tup.0 == "ab\u{000d}c" && tup.1 == br#"23"# })); 1793 assert!( 1794 LimitedVerificationParser::<true>::parse_string(b"\\\\\\\\\\\\a\\\\\\\\a\\\\\"").map_or(false, |tup| { 1795 tup.0 == "\\\\\\a\\\\a\\" && tup.1.is_empty() 1796 }) 1797 ); 1798 assert!( 1799 LimitedVerificationParser::<false>::parse_string(b"\\\\\\\\\\a\\\\\\\\a\\\\\"").map_or_else( 1800 |e| matches!(e, CollectedClientDataErr::InvalidEscapedString), 1801 |_| false 1802 ) 1803 ); 1804 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\u0020c"23"#).map_or_else( 1805 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1806 |_| false 1807 )); 1808 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\ac"23"#).map_or_else( 1809 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1810 |_| false 1811 )); 1812 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\""#).map_or_else( 1813 |err| matches!(err, CollectedClientDataErr::InvalidObject), 1814 |_| false 1815 )); 1816 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\u001Fc"23"#).map_or_else( 1817 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1818 |_| false 1819 )); 1820 assert!(LimitedVerificationParser::<true>::parse_string([0, b'"'].as_slice()).map_or_else( 1821 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1822 |_| false 1823 )); 1824 assert!(LimitedVerificationParser::<false>::parse_string([b'a', 255, b'"'].as_slice()) 1825 .map_or_else(|err| matches!(err, CollectedClientDataErr::Utf8(_)), |_| false)); 1826 assert!(LimitedVerificationParser::<true>::parse_string([b'a', b'"', 255].as_slice()).is_ok()); 1827 assert!( 1828 LimitedVerificationParser::<false>::parse_string(br#"""#).map_or(false, |tup| tup.0.is_empty() && tup.1.is_empty()) 1829 ); 1830 } 1831 #[test] 1832 fn c_data_json() { 1833 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && !val.cross_origin && val.top_origin.is_none())); 1834 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,{}}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && !val.cross_origin && val.top_origin.is_none())); 1835 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && val.cross_origin && val.top_origin.is_none())); 1836 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true,"topOrigin":"bob"}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && val.cross_origin && val.top_origin.map_or(false, |v| v == "bob"))); 1837 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true,"topOrigin":"bob",a}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && val.cross_origin && val.top_origin.map_or(false, |v| v == "bob"))); 1838 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true,"topOrigin":"bob"a}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidObject), |_| false)); 1839 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,"topOrigin":""}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::TopOriginWithoutCrossOrigin), |_| false)); 1840 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,"topOrigin":""}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1841 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0.is_empty() && !val.cross_origin && val.top_origin.is_none())); 1842 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Type), |_| false)); 1843 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create", "challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::ChallengeKey), |_| false)); 1844 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1845 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\\e.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://exampl\\e.com" && !val.cross_origin && val.top_origin.is_none())); 1846 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\"e.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://exampl\"e.com" && !val.cross_origin && val.top_origin.is_none())); 1847 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\u0013e.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://exampl\u{0013}e.com" && !val.cross_origin && val.top_origin.is_none())); 1848 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\3e.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1849 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\e.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1850 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\u0020.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1851 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\u000A.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1852 assert!(LimitedVerificationParser::<true>::parse([].as_slice()) 1853 .map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1854 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"abc","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidStart), |_| false)); 1855 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidObject), |_| false)); 1856 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false,"origin":"example.com"}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1857 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","topOrigin":"bob","crossOrigin":true}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::CrossOriginKey), |_| false)); 1858 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":"abc"}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::CrossOrigin), |_| false)); 1859 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true"a}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidObject), |_| false)); 1860 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true","topOrigin":"https://abc.com"a}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidObject), |_| false)); 1861 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && !val.cross_origin && val.top_origin.is_none())); 1862 assert!(LimitedVerificationParser::<false>::parse(b"{\"type\":\"webauthn.get\",\"challenge\":\"AAAAAAAAAAAAAAAAAAAAAA\",\"origin\":\"https://example.com\",\"crossOrigin\":false,\xff}".as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && !val.cross_origin && val.top_origin.is_none())); 1863 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && val.cross_origin && val.top_origin.is_none())); 1864 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true,"topOrigin":"bob"}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && val.cross_origin && val.top_origin.map_or(false, |v| v == "bob"))); 1865 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,"topOrigin":""}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::TopOriginWithoutCrossOrigin), |_| false)); 1866 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,"topOrigin":""}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1867 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0.is_empty() && !val.cross_origin && val.top_origin.is_none())); 1868 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Type), |_| false)); 1869 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get", "challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::ChallengeKey), |_| false)); 1870 assert!(LimitedVerificationParser::<false>::parse( 1871 br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false}"# 1872 .as_slice() 1873 ) 1874 .map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1875 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\\e.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://exampl\\e.com" && !val.cross_origin && val.top_origin.is_none())); 1876 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\"e.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://exampl\"e.com" && !val.cross_origin && val.top_origin.is_none())); 1877 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\u0013e.com","crossOrigin":false}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://exampl\u{0013}e.com" && !val.cross_origin && val.top_origin.is_none())); 1878 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\3e.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1879 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\e.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1880 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\u0020.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1881 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://exampl\u000A.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidEscapedString), |_| false)); 1882 assert!(LimitedVerificationParser::<false>::parse([].as_slice()) 1883 .map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1884 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"abc","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidStart), |_| false)); 1885 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidObject), |_| false)); 1886 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false,"origin":"example.com"}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1887 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","topOrigin":"bob","crossOrigin":true}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::CrossOriginKey), |_| false)); 1888 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":"abc"}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::CrossOrigin), |_| false)); 1889 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true"a}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::InvalidObject), |_| false)); 1890 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":true,"topOrigin":"https://example.com"}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::TopOriginSameAsOrigin), |_| false)); 1891 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,"foo":true}"#.as_slice()).map_or(false, |val| val.challenge.0 == 0 && val.origin.0 == "https://example.com" && !val.cross_origin && val.top_origin.is_none())); 1892 assert!(LimitedVerificationParser::<false>::parse(br#"{"type":"webauthn.get","challengE":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false,"foo":true}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::ChallengeKey), |_| false)); 1893 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create"challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossorigin":false,"foo":true}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::ChallengeKey), |_| false)); 1894 } 1895 #[test] 1896 fn c_data_challenge() { 1897 assert!(LimitedVerificationParser::<false>::get_sent_challenge([].as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1898 assert!(LimitedVerificationParser::<true>::get_sent_challenge([].as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1899 assert!(LimitedVerificationParser::<true>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBB").map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1900 assert!(LimitedVerificationParser::<false>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBB").map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1901 assert!(LimitedVerificationParser::<true>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".as_slice()).map_or(false, |c| c.0 == 0)); 1902 assert!(LimitedVerificationParser::<false>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".as_slice()).map_or(false, |c| c.0 == 0)); 1903 } 1904 }