response.rs (97706B)
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 BASE64URL_NOPAD_ENC, 13 }; 14 use alloc::borrow::Cow; 15 use core::{ 16 borrow::Borrow, 17 cmp::Ordering, 18 convert::Infallible, 19 fmt::{self, Display, Formatter}, 20 hash::{Hash, Hasher}, 21 str, 22 }; 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 data_encoding::BASE64URL_NOPAD; 33 /// # #[cfg(not(feature = "serializable_server_state"))] 34 /// # use webauthn_rp::request::{FixedCapHashSet, InsertResult}; 35 /// # use webauthn_rp::{ 36 /// # request::{auth::{error::RequestOptionsErr, AuthenticationClientState, PublicKeyCredentialRequestOptions, AuthenticationVerificationOptions}, error::AsciiDomainErr, register::UserHandle, AsciiDomain, BackupReq, RpId}, 37 /// # response::{auth::{error::AuthCeremonyErr, Authentication}, error::CollectedClientDataErr, register::{AuthenticatorExtensionOutputStaticState, 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 /// # RequestOptions(RequestOptionsErr), 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<RequestOptionsErr> for E { 63 /// # fn from(value: RequestOptionsErr) -> Self { 64 /// # Self::RequestOptions(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 /// # #[cfg(not(feature = "serializable_server_state"))] 83 /// let mut ceremonies = FixedCapHashSet::new(128); 84 /// let rp_id = RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?); 85 /// let (server, client) = PublicKeyCredentialRequestOptions::passkey(&rp_id).start_ceremony()?; 86 /// # #[cfg(not(feature = "serializable_server_state"))] 87 /// assert!(matches!( 88 /// ceremonies.insert_or_replace_all_expired(server), 89 /// InsertResult::Success 90 /// )); 91 /// # #[cfg(feature = "serde")] 92 /// let authentication = serde_json::from_str::<Authentication>(get_authentication_json(client).as_str())?; 93 /// // `UserHandle` must exist since we sent an empty `AllowedCredentials`. 94 /// # #[cfg(feature = "serde")] 95 /// let user_handle = authentication.response().user_handle().ok_or(E::MissingUserHandle)?; 96 /// # #[cfg(feature = "serde")] 97 /// let (static_state, dynamic_state) = get_credential(authentication.raw_id(), user_handle).ok_or(E::UnknownCredential)?; 98 /// # #[cfg(all(feature = "custom", feature = "serde"))] 99 /// let mut cred = AuthenticatedCredential::new(authentication.raw_id(), user_handle, static_state, dynamic_state)?; 100 /// # #[cfg(all(not(feature = "serializable_server_state"), feature = "custom", feature = "serde"))] 101 /// if ceremonies.take(&authentication.challenge()?).ok_or(E::MissingCeremony)?.verify(&rp_id, &authentication, &mut cred, &AuthenticationVerificationOptions::<&str, &str>::default())? { 102 /// update_cred(authentication.raw_id(), cred.dynamic_state()); 103 /// } 104 /// /// Send `AuthenticationClientState` and receive `Authentication` JSON from client. 105 /// # #[cfg(feature = "serde")] 106 /// fn get_authentication_json(client: AuthenticationClientState<'_, '_>) -> String { 107 /// // ⋮ 108 /// # let client_data_json = BASE64URL_NOPAD.encode(serde_json::json!({ 109 /// # "type": "webauthn.get", 110 /// # "challenge": client.options().challenge, 111 /// # "origin": format!("https://{}", client.options().rp_id.as_ref()), 112 /// # "crossOrigin": false 113 /// # }).to_string().as_bytes()); 114 /// # serde_json::json!({ 115 /// # "id": "AAAAAAAAAAAAAAAAAAAAAA", 116 /// # "rawId": "AAAAAAAAAAAAAAAAAAAAAA", 117 /// # "response": { 118 /// # "clientDataJSON": client_data_json, 119 /// # "authenticatorData": "", 120 /// # "signature": "", 121 /// # "userHandle": "AA" 122 /// # }, 123 /// # "clientExtensionResults": {}, 124 /// # "type": "public-key" 125 /// # }).to_string() 126 /// } 127 /// /// Gets the `AuthenticatedCredential` parts associated with `id` and `user_handle` from the database. 128 /// fn get_credential(id: CredentialId<&[u8]>, user_handle: UserHandle<&[u8]>) -> Option<(StaticState<CompressedPubKey<[u8; 32], [u8; 32], [u8; 48], Vec<u8>>>, DynamicState)> { 129 /// // ⋮ 130 /// # Some((StaticState { credential_public_key: CompressedPubKey::Ed25519(Ed25519PubKey::from([0; 32])), extensions: AuthenticatorExtensionOutputStaticState { cred_protect: CredentialProtectionPolicy::UserVerificationRequired, hmac_secret: None, } }, DynamicState { user_verified: true, backup: Backup::NotEligible, sign_count: 1, authenticator_attachment: AuthenticatorAttachment::None })) 131 /// } 132 /// /// Updates the current `DynamicState` associated with `id` in the database to 133 /// /// `dyn_state`. 134 /// fn update_cred(id: CredentialId<&[u8]>, dyn_state: DynamicState) { 135 /// // ⋮ 136 /// } 137 /// # Ok::<_, E>(()) 138 /// ``` 139 pub mod auth; 140 /// Contains functionality to (de)serialize data to a data store. 141 #[cfg_attr(docsrs, doc(cfg(feature = "bin")))] 142 #[cfg(feature = "bin")] 143 pub mod bin; 144 /// Contains constants useful for 145 /// [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). 146 mod cbor; 147 /// Contains functionality that needs to be accessible when `bin` or `serde` are not enabled. 148 #[cfg_attr(docsrs, doc(cfg(feature = "custom")))] 149 #[cfg(feature = "custom")] 150 mod custom; 151 /// Contains error types. 152 pub mod error; 153 /// Contains functionality for completing the 154 /// [registration ceremony](https://www.w3.org/TR/webauthn-3/#registration-ceremony). 155 /// 156 /// # Examples 157 /// 158 /// ```no_run 159 /// # use data_encoding::BASE64URL_NOPAD; 160 /// # #[cfg(not(feature = "serializable_server_state"))] 161 /// # use webauthn_rp::request::{FixedCapHashSet, InsertResult}; 162 /// # use webauthn_rp::{ 163 /// # request::{register::{error::CreationOptionsErr, PublicKeyCredentialCreationOptions, PublicKeyCredentialUserEntity, RegistrationClientState, UserHandle, RegistrationVerificationOptions}, error::AsciiDomainErr, AsciiDomain, PublicKeyCredentialDescriptor, RpId}, 164 /// # response::{register::{error::RegCeremonyErr, Registration}, error::CollectedClientDataErr, CollectedClientData}, 165 /// # RegisteredCredential 166 /// # }; 167 /// # #[derive(Debug)] 168 /// # enum E { 169 /// # CollectedClientData(CollectedClientDataErr), 170 /// # RpId(AsciiDomainErr), 171 /// # CreationOptions(CreationOptionsErr), 172 /// # SerdeJson(serde_json::Error), 173 /// # MissingCeremony, 174 /// # RegCeremony(RegCeremonyErr), 175 /// # } 176 /// # impl From<AsciiDomainErr> for E { 177 /// # fn from(value: AsciiDomainErr) -> Self { 178 /// # Self::RpId(value) 179 /// # } 180 /// # } 181 /// # impl From<CollectedClientDataErr> for E { 182 /// # fn from(value: CollectedClientDataErr) -> Self { 183 /// # Self::CollectedClientData(value) 184 /// # } 185 /// # } 186 /// # impl From<CreationOptionsErr> for E { 187 /// # fn from(value: CreationOptionsErr) -> Self { 188 /// # Self::CreationOptions(value) 189 /// # } 190 /// # } 191 /// # impl From<serde_json::Error> for E { 192 /// # fn from(value: serde_json::Error) -> Self { 193 /// # Self::SerdeJson(value) 194 /// # } 195 /// # } 196 /// # impl From<RegCeremonyErr> for E { 197 /// # fn from(value: RegCeremonyErr) -> Self { 198 /// # Self::RegCeremony(value) 199 /// # } 200 /// # } 201 /// # #[cfg(not(feature = "serializable_server_state"))] 202 /// let mut ceremonies = FixedCapHashSet::new(128); 203 /// let rp_id = RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?); 204 /// let user_handle = get_user_handle(); 205 /// let handle = (&user_handle).into(); 206 /// let user = get_user_entity(handle); 207 /// let creds = get_registered_credentials(handle); 208 /// let (server, client) = PublicKeyCredentialCreationOptions::passkey(&rp_id, user, creds).start_ceremony()?; 209 /// # #[cfg(not(feature = "serializable_server_state"))] 210 /// assert!(matches!( 211 /// ceremonies.insert_or_replace_all_expired(server), 212 /// InsertResult::Success 213 /// )); 214 /// # #[cfg(feature = "serde_relaxed")] 215 /// let registration = serde_json::from_str::<Registration>(get_registration_json(client).as_str())?; 216 /// let ver_opts = RegistrationVerificationOptions::<&str, &str>::default(); 217 /// # #[cfg(all(not(feature = "serializable_server_state"), feature = "custom", feature = "serde_relaxed"))] 218 /// insert_cred(ceremonies.take(®istration.challenge()?).ok_or(E::MissingCeremony)?.verify(&rp_id, handle, ®istration, &ver_opts)?); 219 /// /// Extract `UserHandle` from session cookie if this is not the first credential registered. 220 /// fn get_user_handle() -> UserHandle<Vec<u8>> { 221 /// // ⋮ 222 /// # UserHandle::new() 223 /// } 224 /// /// Fetch `PublicKeyCredentialUserEntity` info associated with `user`. 225 /// /// 226 /// /// If this is the first time a credential is being registered, then `PublicKeyCredentialUserEntity` 227 /// /// will need to be constructed with `name` and `display_name` passed from the client and `UserHandle::new` 228 /// /// used for `id`. Once created, this info can be stored such that the entity information 229 /// /// does not need to be requested for subsequent registrations. 230 /// fn get_user_entity(user: UserHandle<&[u8]>) -> PublicKeyCredentialUserEntity<&[u8]> { 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<'_, '_, '_, '_>) -> String { 241 /// // ⋮ 242 /// # let client_data_json = BASE64URL_NOPAD.encode(serde_json::json!({ 243 /// # "type": "webauthn.create", 244 /// # "challenge": client.options().challenge, 245 /// # "origin": format!("https://{}", client.options().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<&[u8]>, 261 /// ) -> Vec<PublicKeyCredentialDescriptor<Vec<u8>>> { 262 /// // ⋮ 263 /// # Vec::new() 264 /// } 265 /// /// Inserts `RegisteredCredential::into_parts` into the database. 266 /// fn insert_cred(cred: RegisteredCredential<'_, '_>) { 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 fn from_slice<'b: 'a>(value: &'b [u8]) -> Result<Self, CredentialIdErr> { 523 if (CRED_ID_MIN_LEN..=CRED_ID_MAX_LEN).contains(&value.len()) { 524 Ok(Self(value)) 525 } else { 526 Err(CredentialIdErr) 527 } 528 } 529 } 530 impl<T: AsRef<[u8]>> AsRef<[u8]> for CredentialId<T> { 531 #[inline] 532 fn as_ref(&self) -> &[u8] { 533 self.0.as_ref() 534 } 535 } 536 impl<T: Borrow<[u8]>> Borrow<[u8]> for CredentialId<T> { 537 #[inline] 538 fn borrow(&self) -> &[u8] { 539 self.0.borrow() 540 } 541 } 542 impl<'a: 'b, 'b> From<&'a CredentialId<Vec<u8>>> for CredentialId<&'b Vec<u8>> { 543 #[inline] 544 fn from(value: &'a CredentialId<Vec<u8>>) -> Self { 545 Self(&value.0) 546 } 547 } 548 impl<'a: 'b, 'b> From<CredentialId<&'a Vec<u8>>> for CredentialId<&'b [u8]> { 549 #[inline] 550 fn from(value: CredentialId<&'a Vec<u8>>) -> Self { 551 Self(value.0.as_slice()) 552 } 553 } 554 impl<'a: 'b, 'b> From<&'a CredentialId<Vec<u8>>> for CredentialId<&'b [u8]> { 555 #[inline] 556 fn from(value: &'a CredentialId<Vec<u8>>) -> Self { 557 Self(value.0.as_slice()) 558 } 559 } 560 impl From<CredentialId<&[u8]>> for CredentialId<Vec<u8>> { 561 #[inline] 562 fn from(value: CredentialId<&[u8]>) -> Self { 563 Self(value.0.to_owned()) 564 } 565 } 566 impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<CredentialId<T>> for CredentialId<T2> { 567 #[inline] 568 fn eq(&self, other: &CredentialId<T>) -> bool { 569 self.0 == other.0 570 } 571 } 572 impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<CredentialId<T>> for &CredentialId<T2> { 573 #[inline] 574 fn eq(&self, other: &CredentialId<T>) -> bool { 575 **self == *other 576 } 577 } 578 impl<T: PartialEq<T2>, T2: PartialEq<T>> PartialEq<&CredentialId<T>> for CredentialId<T2> { 579 #[inline] 580 fn eq(&self, other: &&CredentialId<T>) -> bool { 581 *self == **other 582 } 583 } 584 impl<T: Eq> Eq for CredentialId<T> {} 585 impl<T: Hash> Hash for CredentialId<T> { 586 #[inline] 587 fn hash<H: Hasher>(&self, state: &mut H) { 588 self.0.hash(state); 589 } 590 } 591 // We define a separate type to ensure challenges sent to the client are always randomly generated; 592 // otherwise one could deserialize arbitrary data into a `Challenge`. 593 /// Copy of [`Challenge`] sent back from the client. 594 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 595 pub struct SentChallenge(pub u128); 596 impl PartialEq<&Self> for SentChallenge { 597 #[inline] 598 fn eq(&self, other: &&Self) -> bool { 599 *self == **other 600 } 601 } 602 impl PartialEq<SentChallenge> for &SentChallenge { 603 #[inline] 604 fn eq(&self, other: &SentChallenge) -> bool { 605 **self == *other 606 } 607 } 608 impl PartialOrd for SentChallenge { 609 #[inline] 610 fn partial_cmp(&self, other: &Self) -> Option<Ordering> { 611 Some(self.cmp(other)) 612 } 613 } 614 impl Ord for SentChallenge { 615 #[inline] 616 fn cmp(&self, other: &Self) -> Ordering { 617 self.0.cmp(&other.0) 618 } 619 } 620 impl Hash for SentChallenge { 621 #[inline] 622 fn hash<H: Hasher>(&self, state: &mut H) { 623 state.write_u128(self.0); 624 } 625 } 626 /// An [`origin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-origin) or 627 /// [`topOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-toporigin). 628 #[derive(Debug, Eq)] 629 pub struct Origin<'a>(pub Cow<'a, str>); 630 impl PartialEq<Origin<'_>> for Origin<'_> { 631 #[inline] 632 fn eq(&self, other: &Origin<'_>) -> bool { 633 self.0 == other.0 634 } 635 } 636 impl PartialEq<&Origin<'_>> for Origin<'_> { 637 #[inline] 638 fn eq(&self, other: &&Origin<'_>) -> bool { 639 *self == **other 640 } 641 } 642 impl PartialEq<Origin<'_>> for &Origin<'_> { 643 #[inline] 644 fn eq(&self, other: &Origin<'_>) -> bool { 645 **self == *other 646 } 647 } 648 impl PartialEq<str> for Origin<'_> { 649 #[inline] 650 fn eq(&self, other: &str) -> bool { 651 self.0.as_ref() == other 652 } 653 } 654 impl PartialEq<Origin<'_>> for str { 655 #[inline] 656 fn eq(&self, other: &Origin<'_>) -> bool { 657 *other == *self 658 } 659 } 660 impl PartialEq<&str> for Origin<'_> { 661 #[inline] 662 fn eq(&self, other: &&str) -> bool { 663 *self == **other 664 } 665 } 666 impl PartialEq<Origin<'_>> for &str { 667 #[inline] 668 fn eq(&self, other: &Origin<'_>) -> bool { 669 **self == *other 670 } 671 } 672 impl PartialEq<String> for Origin<'_> { 673 #[inline] 674 fn eq(&self, other: &String) -> bool { 675 self.0 == *other 676 } 677 } 678 impl PartialEq<Origin<'_>> for String { 679 #[inline] 680 fn eq(&self, other: &Origin<'_>) -> bool { 681 *other == *self 682 } 683 } 684 impl PartialEq<Url> for Origin<'_> { 685 #[inline] 686 fn eq(&self, other: &Url) -> bool { 687 self.0.as_ref() == other.as_ref() 688 } 689 } 690 impl PartialEq<Origin<'_>> for Url { 691 #[inline] 692 fn eq(&self, other: &Origin<'_>) -> bool { 693 *other == *self 694 } 695 } 696 impl PartialEq<&Url> for Origin<'_> { 697 #[inline] 698 fn eq(&self, other: &&Url) -> bool { 699 *self == **other 700 } 701 } 702 impl PartialEq<Origin<'_>> for &Url { 703 #[inline] 704 fn eq(&self, other: &Origin<'_>) -> bool { 705 **self == *other 706 } 707 } 708 /// [Authenticator data flags](https://www.w3.org/TR/webauthn-3/#authdata-flags). 709 #[derive(Clone, Copy, Debug)] 710 pub struct Flag { 711 /// [`UP` flag](https://www.w3.org/TR/webauthn-3/#authdata-flags-up). 712 /// 713 /// Note this is always `true` when part of [`auth::AuthenticatorData::flags`]. 714 pub user_present: bool, 715 /// [`UV` flag](https://www.w3.org/TR/webauthn-3/#concept-user-verified). 716 pub user_verified: bool, 717 /// [`BE`](https://www.w3.org/TR/webauthn-3/#backup-eligibility) and 718 /// [`BS`](https://www.w3.org/TR/webauthn-3/#backup-state) flags. 719 pub backup: Backup, 720 } 721 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 722 pub(super) trait AuthData<'a>: Sized { 723 /// Error returned by [`Self::user_is_not_present`]. 724 /// 725 /// This should be [`Infallible`] in the event user must not always be present. 726 type UpBitErr; 727 /// [`attestedCredentialData`](https://www.w3.org/TR/webauthn-3/#authdata-attestedcredentialdata). 728 type CredData; 729 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions). 730 type Ext: AuthExtOutput + Copy; 731 /// Errors iff the user must always be present. 732 fn user_is_not_present() -> Result<(), Self::UpBitErr>; 733 /// `true` iff `AT` bit (i.e., bit 6) in [`Self::flag_data`] can and must be set to 1. 734 fn contains_at_bit() -> bool; 735 /// Constructor. 736 fn new(rp_id_hash: &'a [u8], flags: Flag, sign_count: u32, attested_credential_data: Self::CredData, extensions: Self::Ext) -> Self; 737 /// [`rpIdHash`](https://www.w3.org/TR/webauthn-3/#authdata-rpidhash). 738 fn rp_hash(&self) -> &'a [u8]; 739 /// [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags). 740 fn flag(&self) -> Flag; 741 } 742 /// [`CollectedClientData`](https://www.w3.org/TR/webauthn-3/#dictdef-collectedclientdata). 743 #[derive(Debug)] 744 pub struct CollectedClientData<'a> { 745 /// [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-challenge). 746 pub challenge: SentChallenge, 747 /// [`origin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-origin). 748 pub origin: Origin<'a>, 749 /// [`crossOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-crossorigin). 750 pub cross_origin: bool, 751 /// [`topOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-toporigin). 752 /// 753 /// When `CollectedClientData` is constructed via [`Self::from_client_data_json`], this can only be 754 /// `Some` if [`Self::cross_origin`]; and if `Some`, it will be different than [`Self::origin`]. 755 pub top_origin: Option<Origin<'a>>, 756 } 757 impl<'a> CollectedClientData<'a> { 758 /// Parses `json` based on the 759 /// [limited verification algorithm](https://www.w3.org/TR/webauthn-3/#clientdatajson-verification). 760 /// 761 /// Additionally, [`topOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-toporigin) is only 762 /// allowed to exist if it has a different value than 763 /// [`origin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-origin) and 764 /// [`crossOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-crossorigin) is `true`. 765 /// 766 /// `REGISTRATION` iff [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type) must be 767 /// `"webauthn.create"`; otherwise it must be `"webauthn.get"`. 768 /// 769 /// # Errors 770 /// 771 /// Errors iff `json` cannot be parsed based on the aforementioned requirements. 772 /// 773 /// # Examples 774 /// 775 /// ``` 776 /// # use webauthn_rp::response::{error::CollectedClientDataErr, CollectedClientData}; 777 /// assert!(!CollectedClientData::from_client_data_json::<true>(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice())?.cross_origin); 778 /// assert!(!CollectedClientData::from_client_data_json::<false>(br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","origin":"https://example.com","crossOrigin":false}"#.as_slice())?.cross_origin); 779 /// # Ok::<_, CollectedClientDataErr>(()) 780 /// ``` 781 #[inline] 782 pub fn from_client_data_json<'b: 'a, const REGISTRATION: bool>(json: &'b [u8]) -> Result<Self, CollectedClientDataErr> { 783 LimitedVerificationParser::<REGISTRATION>::parse(json) 784 } 785 /// Parses `json` in a "relaxed" way. 786 /// 787 /// Unlike [`Self::from_client_data_json`] which requires `json` to be an output from the 788 /// [JSON-compatible serialization of client data](https://www.w3.org/TR/webauthn-3/#clientdatajson-serialization), 789 /// this parses `json` based entirely on the 790 /// [`CollectedClientData`](https://www.w3.org/TR/webauthn-3/#dictdef-collectedclientdata) Web IDL `dictionary`. 791 /// 792 /// L1 clients predate the JSON-compatible serialization of client data; additionally there are L2 and L3 793 /// clients that don't adhere to the JSON-compatible serialization of client data despite being required to. 794 /// These clients serialize `CollectedClientData` so that it's valid JSON and conforms to the Web IDL `dictionary` 795 /// and nothing more. Furthermore, when not relying on the 796 /// [limited verification algorithm](https://www.w3.org/TR/webauthn-3/#clientdatajson-verification), the spec 797 /// requires the data to be decoded in a way equivalent to 798 /// [UTF-8 decode](https://encoding.spec.whatwg.org/#utf-8-decode) which both interprets a leading zero 799 /// width no-breaking space (i.e., U+FEFF) as a byte-order mark (BOM) as well as replaces any sequences of 800 /// invalid UTF-8 code units with the replacement character (i.e., U+FFFD). That is precisely what this 801 /// function does. 802 /// 803 /// # Errors 804 /// 805 /// Errors iff any of the following is true: 806 /// * The payload is not valid JSON _after_ ignoring a leading U+FEFF and replacing any sequences of invalid 807 /// UTF-8 code units with U+FFFD. 808 /// * The JSON does not conform to the Web IDL `dictionary`. 809 /// * [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type) is not `"webauthn.create"` 810 /// or `"webauthn.get"` when `REGISTRATION` and `!REGISTRATION` respectively. 811 /// * [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-challenge) is not a 812 /// base64url-encoded [`Challenge`]. 813 /// * Existence of duplicate keys for the keys that are expected. 814 /// 815 /// # Examples 816 /// 817 /// ``` 818 /// # use webauthn_rp::response::{ser_relaxed::SerdeJsonErr, CollectedClientData}; 819 /// assert!(!CollectedClientData::from_client_data_json_relaxed::<true>(b"\xef\xbb\xbf{ 820 /// \"type\": \"webauthn.create\", 821 /// \"origin\": \"https://example.com\", 822 /// \"f\xffo\": 123, 823 /// \"topOrigin\": \"https://example.com\", 824 /// \"challenge\": \"AAAAAAAAAAAAAAAAAAAAAA\" 825 /// }")?.cross_origin); 826 /// # Ok::<_, SerdeJsonErr>(()) 827 /// ``` 828 #[cfg_attr(docsrs, doc(cfg(feature = "serde_relaxed")))] 829 #[cfg(feature = "serde_relaxed")] 830 #[inline] 831 pub fn from_client_data_json_relaxed<'b: 'a, const REGISTRATION: bool>(json: &'b [u8]) -> Result<Self, SerdeJsonErr> { 832 ser_relaxed::RelaxedClientDataJsonParser::<REGISTRATION>::parse(json) 833 } 834 } 835 /// Parser of 836 /// [`JSON-compatible serialization of client data`](https://www.w3.org/TR/webauthn-3/#collectedclientdata-json-compatible-serialization-of-client-data). 837 trait ClientDataJsonParser { 838 /// Error returned by [`Self::parse`]. 839 type Err; 840 /// Parses `json` into `CollectedClientData` based on the value of 841 /// [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type). 842 /// 843 /// # Errors 844 /// 845 /// Errors iff `json` cannot be parsed into a `CollectedClientData`. 846 fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err>; 847 /// Extracts [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-challenge) 848 /// from `json`. 849 /// 850 /// Note `json` should be minimally parsed such that only `challenge` is extracted; thus 851 /// `Ok` being returned does _not_ mean `json` is in fact valid. 852 fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err>; 853 } 854 /// [`ClientDataJsonParser`] based on the 855 /// [limited verification algorithm](https://www.w3.org/TR/webauthn-3/#clientdatajson-verification) 856 /// with the following additional requirements: 857 /// * Unknown keys are not allowed. 858 /// * The entire payload is parsed; thus the payload is guaranteed to be valid UTF-8 and JSON. 859 /// * [`CollectedClientData::top_origin`] can only be `Some` if 860 /// [`crossOrigin`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-crossorigin). 861 /// * If `CollectedClientData::top_origin` is `Some`, then it does not equal [`CollectedClientData::origin`]. 862 /// 863 /// `REGISTRATION` iff [`ClientDataJsonParser::parse`] requires 864 /// [`type`](https://www.w3.org/TR/webauthn-3/#dom-collectedclientdata-type) to be `"webauthn.create"`; 865 /// otherwise it must be `"webauthn.get"`. 866 struct LimitedVerificationParser<const REGISTRATION: bool>; 867 impl<const R: bool> LimitedVerificationParser<R> { 868 /// Parses `val` as a JSON string with possibly trailing data. `val` MUST NOT begin with an opening quote. Upon 869 /// encountering the first non-escaped quote, the parsed value is returned in addition to the remaining 870 /// portion of `val` _after_ the closing quote. The limited verification algorithm is adhered to; thus the 871 /// _only_ Unicode scalar values that are allowed (and must) be hex-escaped are U+0000 to U+001F inclusively. 872 /// Similarly only `b'\\'` and `b'"'` are allowed (and must) be escaped with `b'\\'`. 873 #[expect(clippy::arithmetic_side_effects, clippy::indexing_slicing, reason = "comments justify their correctness")] 874 fn parse_string(val: &[u8]) -> Result<(Cow<'_, str>, &'_ [u8]), CollectedClientDataErr> { 875 /// Tracks the state of the current Unicode scalar value that is being parsed. 876 enum State { 877 /// We are not parsing `'"'`, `'\\'`, or U+0000 to U+001F. 878 Normal, 879 /// We just encountered the escape character. 880 Escape, 881 /// We just encountered `b"\\u"`. 882 UnicodeEscape, 883 /// We just encountered `b"\\u0"`. 884 UnicodeHex1, 885 /// We just encountered `b"\\u00"`. 886 UnicodeHex2, 887 /// We just encountered `b"\\u000"` or `b"\\u001"`. The contained `u8` is `0` iff the former; otherwise 888 /// `0x10`. 889 UnicodeHex3(u8), 890 } 891 // We parse this as UTF-8 only at the end iff it is not empty. This contains all the potential Unicode scalar 892 // values after de-escaping. 893 let mut utf8 = Vec::new(); 894 // This tracks the start index of the next slice to add. We add slices iff we encounter the escape character or 895 // we return the parsed `Cow` (i.e., encounter an unescaped `b'"'`). 896 let mut cur_idx = 0; 897 // The state of the yet-to-be-parsed Unicode scalar value. 898 let mut state = State::Normal; 899 for (counter, &b) in val.iter().enumerate() { 900 match state { 901 State::Normal => { 902 match b { 903 b'"' => { 904 if utf8.is_empty() { 905 // `cur_idx` is 0 or 1. The latter is true iff `val` starts with a 906 // `b'\\'` or `b'"'` but contains no other escaped characters. 907 return str::from_utf8(&val[cur_idx..counter]) 908 .map_err(CollectedClientDataErr::Utf8) 909 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 910 .map(|v| (Cow::Borrowed(v), &val[counter + 1..])); 911 } 912 utf8.extend_from_slice(&val[cur_idx..counter]); 913 return String::from_utf8(utf8) 914 .map_err(CollectedClientDataErr::Utf8Owned) 915 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 916 .map(|v| (Cow::Owned(v), &val[counter + 1..])); 917 } 918 b'\\' => { 919 // Write the current slice of data. 920 utf8.extend_from_slice(&val[cur_idx..counter]); 921 state = State::Escape; 922 } 923 // ASCII is a subset of UTF-8 and this is a subset of ASCII. The code unit that is used for an 924 // ASCII Unicode scalar value _never_ appears in multi-code-unit Unicode scalar values; thus we 925 // error immediately. 926 ..=0x1f => return Err(CollectedClientDataErr::InvalidEscapedString), 927 _ => (), 928 } 929 } 930 State::Escape => { 931 match b { 932 b'"' | b'\\' => { 933 // We start the next slice here since we need to add it. 934 cur_idx = counter; 935 state = State::Normal; 936 } 937 b'u' => { 938 state = State::UnicodeEscape; 939 } 940 _ => { 941 return Err(CollectedClientDataErr::InvalidEscapedString); 942 } 943 } 944 } 945 State::UnicodeEscape => { 946 if b != b'0' { 947 return Err(CollectedClientDataErr::InvalidEscapedString); 948 } 949 state = State::UnicodeHex1; 950 } 951 State::UnicodeHex1 => { 952 if b != b'0' { 953 return Err(CollectedClientDataErr::InvalidEscapedString); 954 } 955 state = State::UnicodeHex2; 956 } 957 State::UnicodeHex2 => { 958 state = State::UnicodeHex3(match b { 959 b'0' => 0, 960 b'1' => 0x10, 961 _ => return Err(CollectedClientDataErr::InvalidEscapedString), 962 }); 963 } 964 State::UnicodeHex3(v) => { 965 match b { 966 // Only and all _lowercase_ hex is allowed. 967 b'0'..=b'9' | b'a'..=b'f' => { 968 // When `b < b'a'`, then `b >= b'0'`; and `b'a' > 87`; thus underflow cannot happen. 969 // Note `b'a' - 10 == 87`. 970 utf8.push(v | (b - if b < b'a' { b'0' } else { 87 })); 971 // `counter < val.len()`, so overflow cannot happen. 972 cur_idx = counter + 1; 973 state = State::Normal; 974 } 975 _ => return Err(CollectedClientDataErr::InvalidEscapedString), 976 } 977 } 978 } 979 } 980 // We never encountered an unescaped `b'"'`; thus we could not parse a string. 981 Err(CollectedClientDataErr::InvalidObject) 982 } 983 } 984 impl<const R: bool> ClientDataJsonParser for LimitedVerificationParser<R> { 985 type Err = CollectedClientDataErr; 986 #[expect(clippy::panic_in_result_fn, reason = "want to crash when there is a bug")] 987 #[expect(clippy::little_endian_bytes, reason = "Challenge::serialize and this need to be consistent across architectures")] 988 #[expect(clippy::too_many_lines, reason = "110 lines is fine")] 989 fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err> { 990 // `{"type":"webauthn.<create|get>","challenge":"<22 bytes>","origin":"<bytes>","crossOrigin":<true|false>[,"topOrigin":"<bytes>"][,<anything>]}`. 991 /// First portion of `value`. 992 const HEADER: &[u8; 18] = br#"{"type":"webauthn."#; 993 /// `get`. 994 const GET: &[u8; 3] = b"get"; 995 /// `create`. 996 const CREATE: &[u8; 6] = b"create"; 997 /// Value after type before the start of the base64url-encoded challenge. 998 const AFTER_TYPE: &[u8; 15] = br#"","challenge":""#; 999 /// Value after challenge before the start of the origin value. 1000 const AFTER_CHALLENGE: &[u8; 12] = br#"","origin":""#; 1001 /// Value after origin before the start of the crossOrigin value. 1002 const AFTER_ORIGIN: &[u8; 15] = br#","crossOrigin":"#; 1003 /// `true`. 1004 const TRUE: &[u8; 4] = b"true"; 1005 /// `false`. 1006 const FALSE: &[u8; 5] = b"false"; 1007 /// Value after crossOrigin before the start of the topOrigin value. 1008 const AFTER_CROSS: &[u8; 13] = br#""topOrigin":""#; 1009 json.split_last().ok_or(CollectedClientDataErr::Len).and_then(|(last, last_rem)| { 1010 if *last == b'}' { 1011 last_rem.split_at_checked(HEADER.len()).ok_or(CollectedClientDataErr::Len).and_then(|(header, header_rem)| { 1012 if header == HEADER { 1013 if R { 1014 header_rem.split_at_checked(CREATE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(create, create_rem)| { 1015 if create == CREATE { 1016 Ok(create_rem) 1017 } else { 1018 Err(CollectedClientDataErr::Type) 1019 } 1020 }) 1021 } else { 1022 header_rem.split_at_checked(GET.len()).ok_or(CollectedClientDataErr::Len).and_then(|(get, get_rem)| { 1023 if get == GET { 1024 Ok(get_rem) 1025 } else { 1026 Err(CollectedClientDataErr::Type) 1027 } 1028 }) 1029 }.and_then(|type_rem| { 1030 type_rem.split_at_checked(AFTER_TYPE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(chall_key, chall_key_rem)| { 1031 if chall_key == AFTER_TYPE { 1032 chall_key_rem.split_at_checked(Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|(base64_chall, base64_chall_rem)| { 1033 let mut chall = [0; 16]; 1034 BASE64URL_NOPAD_ENC.decode_mut(base64_chall, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).and_then(|chall_len| { 1035 assert_eq!(chall_len, 16, "there is a bug in BASE64URL_NOPAD::decode_mut"); 1036 base64_chall_rem.split_at_checked(AFTER_CHALLENGE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(origin_key, origin_key_rem)| { 1037 if origin_key == AFTER_CHALLENGE { 1038 Self::parse_string(origin_key_rem).and_then(|(origin, origin_rem)| { 1039 origin_rem.split_at_checked(AFTER_ORIGIN.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_key, cross_key_rem)| { 1040 if cross_key == AFTER_ORIGIN { 1041 // `FALSE.len() > TRUE.len()`, so we check for `FALSE` in `and_then`. 1042 cross_key_rem.split_at_checked(TRUE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_true, cross_true_rem)| { 1043 if cross_true == TRUE { 1044 Ok((true, cross_true_rem)) 1045 } else { 1046 cross_key_rem.split_at_checked(FALSE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_false, cross_false_rem)| { 1047 if cross_false == FALSE { 1048 Ok((false, cross_false_rem)) 1049 } else { 1050 Err(CollectedClientDataErr::CrossOrigin) 1051 } 1052 }) 1053 }.and_then(|(cross, cross_rem)| { 1054 cross_rem.split_first().map_or(Ok((cross, None)), |(comma, comma_rem)| { 1055 if *comma == b',' { 1056 comma_rem.split_at_checked(AFTER_CROSS.len()).map_or(Ok((cross, None)), |(top, top_rem)| { 1057 if top == AFTER_CROSS { 1058 if cross { 1059 Self::parse_string(top_rem).and_then(|(top_origin, top_origin_rem)| { 1060 top_origin_rem.first().map_or(Ok(()), |v| { 1061 if *v == b',' { 1062 Ok(()) 1063 } else { 1064 Err(CollectedClientDataErr::InvalidObject) 1065 } 1066 }).and_then(|()| { 1067 if origin == top_origin { 1068 Err(CollectedClientDataErr::TopOriginSameAsOrigin) 1069 } else { 1070 Ok((true, Some(Origin(top_origin)))) 1071 } 1072 }) 1073 }) 1074 } else { 1075 Err(CollectedClientDataErr::TopOriginWithoutCrossOrigin) 1076 } 1077 } else { 1078 Ok((cross, None)) 1079 } 1080 }) 1081 } else { 1082 Err(CollectedClientDataErr::InvalidObject) 1083 } 1084 }).map(|(cross_origin, top_origin)| CollectedClientData { challenge: SentChallenge(u128::from_le_bytes(chall)), origin: Origin(origin), cross_origin, top_origin, }) 1085 }) 1086 }) 1087 } else { 1088 Err(CollectedClientDataErr::CrossOriginKey) 1089 } 1090 }) 1091 }) 1092 } else { 1093 Err(CollectedClientDataErr::OriginKey) 1094 } 1095 }) 1096 }) 1097 }) 1098 } else { 1099 Err(CollectedClientDataErr::ChallengeKey) 1100 } 1101 }) 1102 }) 1103 } else { 1104 Err(CollectedClientDataErr::InvalidStart) 1105 } 1106 }) 1107 } else { 1108 Err(CollectedClientDataErr::InvalidObject) 1109 } 1110 }) 1111 } 1112 #[expect(clippy::panic_in_result_fn, reason = "want to crash when there is a bug")] 1113 #[expect(clippy::arithmetic_side_effects, reason = "comment justifies correctness")] 1114 #[expect(clippy::little_endian_bytes, reason = "Challenge::serialize and this need to be consistent across architectures")] 1115 fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err> { 1116 // Index 39. 1117 // `{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA"...`. 1118 // Index 36. 1119 // `{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA"...`. 1120 let idx = if R { 39 } else { 36 }; 1121 // This maxes at 39 + 22 = 61; thus overflow is not an issue. 1122 json.get(idx..idx + Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|chall_slice| { 1123 let mut chall = [0; 16]; 1124 BASE64URL_NOPAD_ENC.decode_mut(chall_slice, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).map(|len| { 1125 assert_eq!(len, 16, "there is a bug in BASE64URL_NOPAD::decode_mut"); 1126 SentChallenge(u128::from_le_bytes(chall)) 1127 }) 1128 }) 1129 } 1130 } 1131 /// Authenticator extension outputs; 1132 pub(super) trait AuthExtOutput { 1133 /// MUST return `true` iff there is no data. 1134 fn missing(self) -> bool; 1135 } 1136 /// Successful return type from [`FromCbor::from_cbor`]. 1137 struct CborSuccess<'a, T> { 1138 /// Value parsed from the slice. 1139 value: T, 1140 /// Remaining unprocessed data. 1141 remaining: &'a [u8], 1142 } 1143 /// Types that parse 1144 /// [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) 1145 /// data without necessarily consuming all the data. 1146 /// 1147 /// The purpose of this `trait` is to allow chains of types to progressively consume `cbor` by passing 1148 /// [`CborSuccess::remaining`] into the next `FromCbor` type. 1149 trait FromCbor<'a>: Sized { 1150 /// Error when conversion fails. 1151 type Err; 1152 /// Parses `cbor` into `Self`. 1153 /// 1154 /// # Errors 1155 /// 1156 /// Errors if `cbor` cannot be parsed into `Self:`. 1157 fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err>; 1158 } 1159 /// Error returned from [`A::from_cbor`] `where A: AuthData`. 1160 enum AuthenticatorDataErr<UpErr, CredData, AuthExt> { 1161 /// The `slice` had an invalid length. 1162 Len, 1163 /// [UP](https://www.w3.org/TR/webauthn-3/#authdata-flags-at) bit was 0. 1164 UserNotPresent(UpErr), 1165 /// Bit 1 in [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags) is not 0. 1166 FlagsBit1Not0, 1167 /// Bit 5 in [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags) is not 0. 1168 FlagsBit5Not0, 1169 /// [AT](https://www.w3.org/TR/webauthn-3/#authdata-flags-at) bit was 0 during registration or was 1 1170 /// during authentication. 1171 AttestedCredentialData, 1172 /// [BE](https://www.w3.org/TR/webauthn-3/#authdata-flags-be) and 1173 /// [BS](https://www.w3.org/TR/webauthn-3/#authdata-flags-bs) bits were 0 and 1 respectively. 1174 BackupWithoutEligibility, 1175 /// Error returned from [`AttestedCredentialData::from_cbor`]. 1176 AttestedCredential(CredData), 1177 /// Error returned from [`register::AuthenticatorExtensionOutput::from_cbor`] and 1178 /// [`auth::AuthenticatorExtensionOutput::from_cbor`]. 1179 AuthenticatorExtension(AuthExt), 1180 /// [ED](https://www.w3.org/TR/webauthn-3/#authdata-flags-ed) bit was 0, but 1181 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions) existed. 1182 NoExtensionBitWithData, 1183 /// [ED](https://www.w3.org/TR/webauthn-3/#authdata-flags-ed) bit was 1, but 1184 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions) did not exist. 1185 ExtensionBitWithoutData, 1186 /// There was trailing data that could not be deserialized. 1187 TrailingData, 1188 } 1189 impl<U, C: Display, A: Display> Display for AuthenticatorDataErr<U, C, A> { 1190 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1191 match *self { 1192 Self::Len => f.write_str("authenticator data had an invalid length"), 1193 Self::UserNotPresent(_) => f.write_str("user was not present"), 1194 Self::FlagsBit1Not0 => f.write_str("flags 1-bit was 1"), 1195 Self::FlagsBit5Not0 => f.write_str("flags 5-bit was 1"), 1196 Self::AttestedCredentialData => f.write_str("attested credential data was included during authentication or was not included during registration"), 1197 Self::BackupWithoutEligibility => { 1198 f.write_str("backup state bit was 1 despite backup eligibility being 0") 1199 } 1200 Self::AttestedCredential(ref err) => err.fmt(f), 1201 Self::AuthenticatorExtension(ref err) => err.fmt(f), 1202 Self::NoExtensionBitWithData => { 1203 f.write_str("extension bit was 0 despite extensions existing") 1204 } 1205 Self::ExtensionBitWithoutData => { 1206 f.write_str("extension bit was 1 despite no extensions existing") 1207 } 1208 Self::TrailingData => { 1209 f.write_str("slice had trailing data that could not be deserialized") 1210 } 1211 } 1212 } 1213 } 1214 impl From<AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>> for RegAuthDataErr { 1215 #[inline] 1216 fn from(value: AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>) -> Self { 1217 match value { 1218 AuthenticatorDataErr::Len => Self::Len, 1219 AuthenticatorDataErr::UserNotPresent(v) => match v {}, 1220 AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0, 1221 AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0, 1222 AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataNotIncluded, 1223 AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility, 1224 AuthenticatorDataErr::AttestedCredential(err) => Self::AttestedCredential(err), 1225 AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err), 1226 AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData, 1227 AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData, 1228 AuthenticatorDataErr::TrailingData => Self::TrailingData, 1229 } 1230 } 1231 } 1232 impl From<AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>> for AuthAuthDataErr { 1233 #[inline] 1234 fn from(value: AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>) -> Self { 1235 match value { 1236 AuthenticatorDataErr::Len => Self::Len, 1237 AuthenticatorDataErr::UserNotPresent(()) => Self::UserNotPresent, 1238 AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0, 1239 AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0, 1240 AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataIncluded, 1241 AuthenticatorDataErr::AttestedCredential(val) => match val {}, 1242 AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility, 1243 AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err), 1244 AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData, 1245 AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData, 1246 AuthenticatorDataErr::TrailingData => Self::TrailingData, 1247 } 1248 } 1249 } 1250 impl<'a, A> FromCbor<'a> for A 1251 where 1252 A: AuthData<'a>, 1253 A::CredData: FromCbor<'a>, 1254 A::Ext: FromCbor<'a>, 1255 { 1256 type Err = AuthenticatorDataErr<A::UpBitErr, <A::CredData as FromCbor<'a>>::Err, <A::Ext as FromCbor<'a>>::Err>; 1257 #[expect(clippy::big_endian_bytes, reason = "CBOR integers are in big-endian")] 1258 fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err> { 1259 /// Length of `signCount`. 1260 const SIGN_COUNT_LEN: usize = 4; 1261 /// `UP` bit (i.e., bit 0) set to 1. 1262 const UP: u8 = 0b0000_0001; 1263 /// `RFU1` bit (i.e., bit 1) set to 1. 1264 const RFU1: u8 = UP << 1; 1265 /// `UV` bit (i.e., bit 2) set to 1. 1266 const UV: u8 = RFU1 << 1; 1267 /// `BE` bit (i.e., bit 3) set to 1. 1268 const BE: u8 = UV << 1; 1269 /// `BS` bit (i.e., bit 4) set to 1. 1270 const BS: u8 = BE << 1; 1271 /// `RFU2` bit (i.e., bit 5) set to 1. 1272 const RFU2: u8 = BS << 1; 1273 /// `AT` bit (i.e., bit 6) set to 1. 1274 const AT: u8 = RFU2 << 1; 1275 /// `ED` bit (i.e., bit 7) set to 1. 1276 const ED: u8 = AT << 1; 1277 cbor.split_at_checked(Sha256::output_size()).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(rp_id_slice, rp_id_rem)| { 1278 rp_id_rem.split_first().ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(&flag, flag_rem)| { 1279 let user_present = flag & UP == UP; 1280 if user_present { 1281 Ok(()) 1282 } else { 1283 A::user_is_not_present().map_err(AuthenticatorDataErr::UserNotPresent) 1284 } 1285 .and_then(|()| { 1286 if flag & RFU1 == 0 { 1287 if flag & RFU2 == 0 { 1288 let at_bit = A::contains_at_bit(); 1289 if flag & AT == AT { 1290 if at_bit { 1291 Ok(()) 1292 } else { 1293 Err(AuthenticatorDataErr::AttestedCredentialData) 1294 } 1295 } else if at_bit { 1296 Err(AuthenticatorDataErr::AttestedCredentialData) 1297 } else { 1298 Ok(()) 1299 }.and_then(|()| { 1300 let bs = flag & BS == BS; 1301 if flag & BE == BE { 1302 if bs { 1303 Ok(Backup::Exists) 1304 } else { 1305 Ok(Backup::Eligible) 1306 } 1307 } else if bs { 1308 Err(AuthenticatorDataErr::BackupWithoutEligibility) 1309 } else { 1310 Ok(Backup::NotEligible) 1311 } 1312 .and_then(|backup| { 1313 flag_rem.split_at_checked(SIGN_COUNT_LEN).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(count_slice, count_rem)| { 1314 A::CredData::from_cbor(count_rem).map_err(AuthenticatorDataErr::AttestedCredential).and_then(|att_data| { 1315 A::Ext::from_cbor(att_data.remaining).map_err(AuthenticatorDataErr::AuthenticatorExtension).and_then(|ext| { 1316 if ext.remaining.is_empty() { 1317 let ed = flag & ED == ED; 1318 if ext.value.missing() { 1319 if ed { 1320 Err(AuthenticatorDataErr::ExtensionBitWithoutData) 1321 } else { 1322 Ok(()) 1323 } 1324 } else if ed { 1325 Ok(()) 1326 } else { 1327 Err(AuthenticatorDataErr::NoExtensionBitWithData) 1328 }.map(|()| { 1329 let mut sign_count = [0; SIGN_COUNT_LEN]; 1330 sign_count.copy_from_slice(count_slice); 1331 // `signCount` is in big-endian. 1332 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, } 1333 }) 1334 } else { 1335 Err(AuthenticatorDataErr::TrailingData) 1336 } 1337 }) 1338 }) 1339 }) 1340 }) 1341 }) 1342 } else { 1343 Err(AuthenticatorDataErr::FlagsBit5Not0) 1344 } 1345 } else { 1346 Err(AuthenticatorDataErr::FlagsBit1Not0) 1347 } 1348 }) 1349 }) 1350 }) 1351 } 1352 } 1353 /// Data returned by [`AuthDataContainer::from_data`]. 1354 pub(super) struct ParsedAuthData<'a, A> { 1355 /// The data the CBOR is parsed into. 1356 data: A, 1357 /// The raw authenticator data and 32-bytes of trailing data. 1358 auth_data_and_32_trailing_bytes: &'a [u8], 1359 } 1360 /// Error returned by [`AuthResponse::parse_data_and_verify_sig`]. 1361 pub(super) enum AuthRespErr<AuthDataErr> { 1362 /// Variant returned when parsing 1363 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1364 /// into [`CollectedClientData`] fails. 1365 CollectedClientData(CollectedClientDataErr), 1366 /// Variant returned when parsing 1367 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1368 /// in a "relaxed" way into [`CollectedClientData`] fails. 1369 #[cfg(feature = "serde_relaxed")] 1370 CollectedClientDataRelaxed(SerdeJsonErr), 1371 /// Variant returned when parsing [`AuthResponse::Auth`] fails. 1372 Auth(AuthDataErr), 1373 /// Variant when the [`CompressedPubKey`] or [`UncompressePubKey`] is not valid. 1374 PubKey(PubKeyErr), 1375 /// Variant returned when the signature, if one exists, associated with 1376 /// [`Self::AuthResponse`] is invalid. 1377 Signature, 1378 } 1379 impl<A: Display> Display for AuthRespErr<A> { 1380 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1381 match *self { 1382 Self::CollectedClientData(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"), 1383 #[cfg(feature = "serde_relaxed")] 1384 Self::CollectedClientDataRelaxed(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"), 1385 Self::Auth(ref err) => write!(f, "auth data could not be parsed: {err}"), 1386 Self::PubKey(err) => err.fmt(f), 1387 Self::Signature => f.write_str("the signature over the authenticator data and CollectedClientData could not be verified"), 1388 } 1389 } 1390 } 1391 impl From<AuthRespErr<AttestationObjectErr>> for RegCeremonyErr { 1392 #[inline] 1393 fn from(value: AuthRespErr<AttestationObjectErr>) -> Self { 1394 match value { 1395 AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err), 1396 #[cfg(feature = "serde_relaxed")] 1397 AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err), 1398 AuthRespErr::Auth(err) => Self::AttestationObject(err), 1399 AuthRespErr::PubKey(err) => Self::PubKey(err), 1400 AuthRespErr::Signature => Self::AttestationSignature, 1401 } 1402 } 1403 } 1404 impl From<AuthRespErr<AuthAuthDataErr>> for AuthCeremonyErr { 1405 #[inline] 1406 fn from(value: AuthRespErr<AuthAuthDataErr>) -> Self { 1407 match value { 1408 AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err), 1409 #[cfg(feature = "serde_relaxed")] 1410 AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err), 1411 AuthRespErr::Auth(err) => Self::AuthenticatorData(err), 1412 AuthRespErr::PubKey(err) => Self::PubKey(err), 1413 AuthRespErr::Signature => Self::AssertionSignature, 1414 } 1415 } 1416 } 1417 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data) 1418 /// container. 1419 /// 1420 /// Note [`Self::Auth`] may be `Self`. 1421 pub(super) trait AuthDataContainer<'a>: Sized { 1422 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1423 type Auth: AuthData<'a>; 1424 /// Error returned from [`Self::from_data`]. 1425 type Err; 1426 /// Converts `data` into [`ParsedAuthData`]. 1427 /// 1428 /// # Errors 1429 /// 1430 /// Errors iff `data` cannot be converted into `ParsedAuthData`. 1431 fn from_data(data: &'a [u8]) -> Result<ParsedAuthData<'a, Self>, Self::Err>; 1432 /// Returns the contained 1433 /// [authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1434 fn authenticator_data(&self) -> &Self::Auth; 1435 } 1436 /// [`AuthenticatorResponse`](https://www.w3.org/TR/webauthn-3/#authenticatorresponse). 1437 pub(super) trait AuthResponse { 1438 /// [Attestation object](https://www.w3.org/TR/webauthn-3/#attestation-object) or 1439 /// [authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1440 type Auth<'a>: AuthDataContainer<'a> where Self: 'a; 1441 /// Public key to use to verify the contained signature. 1442 type CredKey<'a>; 1443 /// Parses 1444 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1445 /// based on `RELAXED` and [`Self::Auth`] via [`AuthDataContainer::from_data`] in addition to 1446 /// verifying any possible signature over the concatenation of the raw 1447 /// [`AuthDataContainer::Auth`] and `clientDataJSON` using `key` or the contained 1448 /// public key if one exists. If `Self` contains a public key and should not be passed one, then it should set 1449 /// [`Self::CredKey`] to `()`. 1450 /// 1451 /// # Errors 1452 /// 1453 /// Errors iff parsing `clientDataJSON` errors, [`AuthDataContainer::from_data`] does, or the signature 1454 /// is invalid. 1455 /// 1456 /// # Panics 1457 /// 1458 /// `panic`s iff `relaxed` and `serde_relaxed` is not enabled. 1459 #[expect( 1460 clippy::type_complexity, 1461 reason = "type aliases with bounds are even more problematic at least until lazy_type_alias is stable" 1462 )] 1463 fn parse_data_and_verify_sig(&self, key: Self::CredKey<'_>, relaxed: bool) -> Result<(CollectedClientData<'_>, Self::Auth<'_>), AuthRespErr<<Self::Auth<'_> as AuthDataContainer<'_>>::Err>>; 1464 } 1465 /// Ceremony response (i.e., [`PublicKeyCredential`](https://www.w3.org/TR/webauthn-3/#publickeycredential)). 1466 pub(super) trait Response { 1467 /// [`AuthenticatorResponse`](https://www.w3.org/TR/webauthn-3/#authenticatorresponse). 1468 type Auth: AuthResponse; 1469 /// [`response`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredential-response). 1470 fn auth(&self) -> &Self::Auth; 1471 } 1472 /// Error returned from [`Ceremony::partial_validate`]. 1473 pub(super) enum CeremonyErr<AuthDataErr> { 1474 /// Timeout occurred. 1475 Timeout, 1476 /// Read [`AuthRespErr`] for information. 1477 AuthResp(AuthRespErr<AuthDataErr>), 1478 /// Origin did not validate. 1479 OriginMismatch, 1480 /// Cross origin was `true` but was not allowed to be. 1481 CrossOrigin, 1482 /// Top origin did not validate. 1483 TopOriginMismatch, 1484 /// Challenges don't match. 1485 ChallengeMismatch, 1486 /// `rpIdHash` does not match the SHA-256 hash of the [`RpId`]. 1487 RpIdHashMismatch, 1488 /// User was not verified despite being required to. 1489 UserNotVerified, 1490 /// [`Backup::NotEligible`] was not sent back despite [`BackupReq::NotEligible`]. 1491 BackupEligible, 1492 /// [`Backup::NotEligible`] was sent back despite [`BackupReq::Eligible`]. 1493 BackupNotEligible, 1494 /// [`Backup::Exists`] was not sent back despite [`BackupReq::Exists`]. 1495 BackupDoesNotExist, 1496 } 1497 impl<A: Display> Display for CeremonyErr<A> { 1498 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1499 match *self { 1500 Self::Timeout => f.write_str("ceremony timed out"), 1501 Self::AuthResp(ref err) => err.fmt(f), 1502 Self::OriginMismatch => { 1503 f.write_str("the origin sent from the client is not an allowed origin") 1504 } 1505 Self::CrossOrigin => { 1506 f.write_str("cross origin was from the client, but it is not allowed") 1507 } 1508 Self::TopOriginMismatch => { 1509 f.write_str("the top origin sent from the client is not an allowed top origin") 1510 } 1511 Self::ChallengeMismatch => f.write_str( 1512 "the challenge sent to the client does not match the challenge sent back", 1513 ), 1514 Self::RpIdHashMismatch => f.write_str( 1515 "the SHA-256 hash of the RP ID doesn't match the hash sent from the client", 1516 ), 1517 Self::UserNotVerified => f.write_str("user was not verified despite being required to"), 1518 Self::BackupEligible => f.write_str("credential is eligible to be backed up despite requiring that it not be"), 1519 Self::BackupNotEligible => f.write_str("credential is not eligible to be backed up despite requiring that it be"), 1520 Self::BackupDoesNotExist => f.write_str("credential backup does not exist despite requiring that a backup exist"), 1521 } 1522 } 1523 } 1524 impl From<CeremonyErr<AttestationObjectErr>> for RegCeremonyErr { 1525 #[inline] 1526 fn from(value: CeremonyErr<AttestationObjectErr>) -> Self { 1527 match value { 1528 CeremonyErr::Timeout => Self::Timeout, 1529 CeremonyErr::AuthResp(err) => err.into(), 1530 CeremonyErr::OriginMismatch => Self::OriginMismatch, 1531 CeremonyErr::CrossOrigin => Self::CrossOrigin, 1532 CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch, 1533 CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch, 1534 CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch, 1535 CeremonyErr::UserNotVerified => Self::UserNotVerified, 1536 CeremonyErr::BackupEligible => Self::BackupEligible, 1537 CeremonyErr::BackupNotEligible => Self::BackupNotEligible, 1538 CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist, 1539 } 1540 } 1541 } 1542 impl From<CeremonyErr<AuthAuthDataErr>> for AuthCeremonyErr { 1543 #[inline] 1544 fn from(value: CeremonyErr<AuthAuthDataErr>) -> Self { 1545 match value { 1546 CeremonyErr::Timeout => Self::Timeout, 1547 CeremonyErr::AuthResp(err) => err.into(), 1548 CeremonyErr::OriginMismatch => Self::OriginMismatch, 1549 CeremonyErr::CrossOrigin => Self::CrossOrigin, 1550 CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch, 1551 CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch, 1552 CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch, 1553 CeremonyErr::UserNotVerified => Self::UserNotVerified, 1554 CeremonyErr::BackupEligible => Self::BackupEligible, 1555 CeremonyErr::BackupNotEligible => Self::BackupNotEligible, 1556 CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist, 1557 } 1558 } 1559 } 1560 /// [`AllAcceptedCredentialsOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions). 1561 /// 1562 /// This can be sent to _an already authenticated user_ to inform what credentials are currently registered. 1563 /// This can be useful when a user deletes credentials on the RP's side but does not do so on the authenticator. 1564 /// When the client forwards this response to the authenticator, it can remove all credentials that don't have 1565 /// a [`CredentialId`] in [`Self::all_accepted_credential_ids`]. 1566 #[derive(Debug)] 1567 pub struct AllAcceptedCredentialsOptions<'rp, 'user> { 1568 /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-rpid). 1569 pub rp_id: &'rp RpId, 1570 /// [`userId`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-userid). 1571 pub user_id: UserHandle<&'user [u8]>, 1572 /// [`allAcceptedCredentialIds`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-allacceptedcredentialids). 1573 pub all_accepted_credential_ids: Vec<CredentialId<Vec<u8>>>, 1574 } 1575 /// [`CurrentUserDetailsOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions). 1576 /// 1577 /// This can be sent to _an already authenticated user_ to inform the user information. 1578 /// This can be useful when a user updates their user information on the RP's side but does not do so on the authenticator. 1579 /// When the client forwards this response to the authenticator, it can update the user info for the associated credential. 1580 #[derive(Debug)] 1581 pub struct CurrentUserDetailsOptions<'rp, 'user_name, 'user_display_name, 'user_handle> { 1582 /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-rpid). 1583 pub rp_id: &'rp RpId, 1584 /// [`userId`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-userid), 1585 /// [`name`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-name), and 1586 /// [`displayName`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-displayname). 1587 pub user: PublicKeyCredentialUserEntity<'user_name, 'user_display_name, &'user_handle [u8]>, 1588 } 1589 #[cfg(test)] 1590 mod tests { 1591 use super::{CollectedClientDataErr, ClientDataJsonParser, LimitedVerificationParser}; 1592 #[test] 1593 fn parse_string() { 1594 assert!(LimitedVerificationParser::<true>::parse_string(br#"abc""#) 1595 .map_or(false, |tup| { tup.0 == "abc" && tup.1 == br#""# })); 1596 assert!(LimitedVerificationParser::<false>::parse_string(br#"abc"23"#) 1597 .map_or(false, |tup| { tup.0 == "abc" && tup.1 == br#"23"# })); 1598 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\"c"23"#) 1599 .map_or(false, |tup| { tup.0 == r#"ab"c"# && tup.1 == br#"23"# })); 1600 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\\c"23"#) 1601 .map_or(false, |tup| { tup.0 == r#"ab\c"# && tup.1 == br#"23"# })); 1602 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\u001fc"23"#) 1603 .map_or(false, |tup| { tup.0 == "ab\u{001f}c" && tup.1 == br#"23"# })); 1604 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\u000dc"23"#) 1605 .map_or(false, |tup| { tup.0 == "ab\u{000d}c" && tup.1 == br#"23"# })); 1606 assert!( 1607 LimitedVerificationParser::<true>::parse_string(b"\\\\\\\\\\\\a\\\\\\\\a\\\\\"").map_or(false, |tup| { 1608 tup.0 == "\\\\\\a\\\\a\\" && tup.1.is_empty() 1609 }) 1610 ); 1611 assert!( 1612 LimitedVerificationParser::<false>::parse_string(b"\\\\\\\\\\a\\\\\\\\a\\\\\"").map_or_else( 1613 |e| matches!(e, CollectedClientDataErr::InvalidEscapedString), 1614 |_| false 1615 ) 1616 ); 1617 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\u0020c"23"#).map_or_else( 1618 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1619 |_| false 1620 )); 1621 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\ac"23"#).map_or_else( 1622 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1623 |_| false 1624 )); 1625 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\""#).map_or_else( 1626 |err| matches!(err, CollectedClientDataErr::InvalidObject), 1627 |_| false 1628 )); 1629 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\u001Fc"23"#).map_or_else( 1630 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1631 |_| false 1632 )); 1633 assert!(LimitedVerificationParser::<true>::parse_string([0, b'"'].as_slice()).map_or_else( 1634 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1635 |_| false 1636 )); 1637 assert!(LimitedVerificationParser::<false>::parse_string([b'a', 255, b'"'].as_slice()) 1638 .map_or_else(|err| matches!(err, CollectedClientDataErr::Utf8(_)), |_| false)); 1639 assert!(LimitedVerificationParser::<true>::parse_string([b'a', b'"', 255].as_slice()).is_ok()); 1640 assert!( 1641 LimitedVerificationParser::<false>::parse_string(br#"""#).map_or(false, |tup| tup.0.is_empty() && tup.1.is_empty()) 1642 ); 1643 } 1644 #[test] 1645 fn c_data_json() { 1646 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())); 1647 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())); 1648 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())); 1649 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"))); 1650 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"))); 1651 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)); 1652 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)); 1653 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)); 1654 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())); 1655 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)); 1656 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)); 1657 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1658 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())); 1659 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())); 1660 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())); 1661 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)); 1662 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)); 1663 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)); 1664 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)); 1665 assert!(LimitedVerificationParser::<true>::parse([].as_slice()) 1666 .map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1667 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)); 1668 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)); 1669 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)); 1670 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)); 1671 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)); 1672 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)); 1673 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)); 1674 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())); 1675 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())); 1676 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())); 1677 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"))); 1678 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)); 1679 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)); 1680 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())); 1681 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)); 1682 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)); 1683 assert!(LimitedVerificationParser::<false>::parse( 1684 br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false}"# 1685 .as_slice() 1686 ) 1687 .map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1688 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())); 1689 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())); 1690 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())); 1691 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)); 1692 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)); 1693 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)); 1694 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)); 1695 assert!(LimitedVerificationParser::<false>::parse([].as_slice()) 1696 .map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1697 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)); 1698 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)); 1699 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)); 1700 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)); 1701 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)); 1702 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)); 1703 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)); 1704 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())); 1705 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)); 1706 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)); 1707 } 1708 #[test] 1709 fn c_data_challenge() { 1710 assert!(LimitedVerificationParser::<false>::get_sent_challenge([].as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1711 assert!(LimitedVerificationParser::<true>::get_sent_challenge([].as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1712 assert!(LimitedVerificationParser::<true>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBB").map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1713 assert!(LimitedVerificationParser::<false>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBB").map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1714 assert!(LimitedVerificationParser::<true>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".as_slice()).map_or(false, |c| c.0 == 0)); 1715 assert!(LimitedVerificationParser::<false>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".as_slice()).map_or(false, |c| c.0 == 0)); 1716 } 1717 }