response.rs (99793B)
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 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(unsafe_code, reason = "comment justifies its correctness")] 874 #[expect(clippy::arithmetic_side_effects, clippy::indexing_slicing, reason = "comments justify their correctness")] 875 fn parse_string(val: &[u8]) -> Result<(Cow<'_, str>, &'_ [u8]), CollectedClientDataErr> { 876 /// Tracks the state of the current Unicode scalar value that is being parsed. 877 enum State { 878 /// We are not parsing `'"'`, `'\\'`, or U+0000 to U+001F. 879 Normal, 880 /// We just encountered the escape character. 881 Escape, 882 /// We just encountered `b"\\u"`. 883 UnicodeEscape, 884 /// We just encountered `b"\\u0"`. 885 UnicodeHex1, 886 /// We just encountered `b"\\u00"`. 887 UnicodeHex2, 888 /// We just encountered `b"\\u000"` or `b"\\u001"`. The contained `u8` is `0` iff the former; otherwise 889 /// `0x10`. 890 UnicodeHex3(u8), 891 } 892 // We parse this as UTF-8 only at the end iff it is not empty. This contains all the potential Unicode scalar 893 // values after de-escaping. 894 let mut utf8 = Vec::new(); 895 // We check for all `u8`s already; thus we might as well check if we encounter a non-ASCII `u8`. 896 // If we don't, then we can rely on `str::from_utf8_unchecked`. 897 let mut all_ascii = true; 898 // This tracks the start index of the next slice to add. We add slices iff we encounter the escape character or 899 // we return the parsed `Cow` (i.e., encounter an unescaped `b'"'`). 900 let mut cur_idx = 0; 901 // The state of the yet-to-be-parsed Unicode scalar value. 902 let mut state = State::Normal; 903 for (counter, &b) in val.iter().enumerate() { 904 match state { 905 State::Normal => { 906 match b { 907 b'"' => { 908 if utf8.is_empty() { 909 if all_ascii { 910 // `cur_idx` is 0 or 1. The latter is true iff `val` starts with a 911 // `b'\\'` or `b'"'` but contains no other escaped characters. 912 let s = &val[cur_idx..counter]; 913 // SAFETY: 914 // `all_ascii` is `false` iff we encountered any `u8` that was not 915 // an ASCII `u8`; thus we know `s` is valid ASCII which in turn means 916 // it's valid UTF-8. 917 let v = unsafe { str::from_utf8_unchecked(s) }; 918 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 919 return Ok((Cow::Borrowed(v), &val[counter + 1..])); 920 } 921 // `cur_idx` is 0 or 1. The latter is true iff `val` starts with a 922 // `b'\\'` or `b'"'` but contains no other escaped characters. 923 return str::from_utf8(&val[cur_idx..counter]) 924 .map_err(CollectedClientDataErr::Utf8) 925 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 926 .map(|v| (Cow::Borrowed(v), &val[counter + 1..])); 927 } 928 // `val.len() > counter && counter >= cur_idx`, so indexing is fine and overflow 929 // cannot happen. 930 utf8.extend_from_slice(&val[cur_idx..counter]); 931 if all_ascii { 932 // SAFETY: 933 // `all_ascii` is `false` iff we encountered any `u8` that was not 934 // an ASCII `u8`; thus we know `utf8` is valid ASCII which in turn means 935 // it's valid UTF-8. 936 let v = unsafe { String::from_utf8_unchecked(utf8) }; 937 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 938 return Ok((Cow::Owned(v), &val[counter + 1..])); 939 } 940 return String::from_utf8(utf8) 941 .map_err(CollectedClientDataErr::Utf8Owned) 942 // `val.len() > counter`, so indexing is fine and overflow cannot happen. 943 .map(|v| (Cow::Owned(v), &val[counter + 1..])); 944 } 945 b'\\' => { 946 // Write the current slice of data. 947 utf8.extend_from_slice(&val[cur_idx..counter]); 948 state = State::Escape; 949 } 950 // ASCII is a subset of UTF-8 and this is a subset of ASCII. The code unit that is used for an 951 // ASCII Unicode scalar value _never_ appears in multi-code-unit Unicode scalar values; thus we 952 // error immediately. 953 ..=0x1f => return Err(CollectedClientDataErr::InvalidEscapedString), 954 128.. => all_ascii = false, 955 _ => (), 956 } 957 } 958 State::Escape => { 959 match b { 960 b'"' | b'\\' => { 961 // We start the next slice here since we need to add it. 962 cur_idx = counter; 963 state = State::Normal; 964 } 965 b'u' => { 966 state = State::UnicodeEscape; 967 } 968 _ => { 969 return Err(CollectedClientDataErr::InvalidEscapedString); 970 } 971 } 972 } 973 State::UnicodeEscape => { 974 if b != b'0' { 975 return Err(CollectedClientDataErr::InvalidEscapedString); 976 } 977 state = State::UnicodeHex1; 978 } 979 State::UnicodeHex1 => { 980 if b != b'0' { 981 return Err(CollectedClientDataErr::InvalidEscapedString); 982 } 983 state = State::UnicodeHex2; 984 } 985 State::UnicodeHex2 => { 986 state = State::UnicodeHex3(match b { 987 b'0' => 0, 988 b'1' => 0x10, 989 _ => return Err(CollectedClientDataErr::InvalidEscapedString), 990 }); 991 } 992 State::UnicodeHex3(v) => { 993 match b { 994 // Only and all _lowercase_ hex is allowed. 995 b'0'..=b'9' | b'a'..=b'f' => { 996 // When `b < b'a'`, then `b >= b'0'`; and `b'a' > 87`; thus underflow cannot happen. 997 // Note `b'a' - 10 == 87`. 998 utf8.push(v | (b - if b < b'a' { b'0' } else { 87 })); 999 // `counter < val.len()`, so overflow cannot happen. 1000 cur_idx = counter + 1; 1001 state = State::Normal; 1002 } 1003 _ => return Err(CollectedClientDataErr::InvalidEscapedString), 1004 } 1005 } 1006 } 1007 } 1008 // We never encountered an unescaped `b'"'`; thus we could not parse a string. 1009 Err(CollectedClientDataErr::InvalidObject) 1010 } 1011 } 1012 impl<const R: bool> ClientDataJsonParser for LimitedVerificationParser<R> { 1013 type Err = CollectedClientDataErr; 1014 #[expect(clippy::panic_in_result_fn, reason = "want to crash when there is a bug")] 1015 #[expect(clippy::little_endian_bytes, reason = "Challenge::serialize and this need to be consistent across architectures")] 1016 #[expect(clippy::too_many_lines, reason = "110 lines is fine")] 1017 fn parse(json: &[u8]) -> Result<CollectedClientData<'_>, Self::Err> { 1018 // `{"type":"webauthn.<create|get>","challenge":"<22 bytes>","origin":"<bytes>","crossOrigin":<true|false>[,"topOrigin":"<bytes>"][,<anything>]}`. 1019 /// First portion of `value`. 1020 const HEADER: &[u8; 18] = br#"{"type":"webauthn."#; 1021 /// `get`. 1022 const GET: &[u8; 3] = b"get"; 1023 /// `create`. 1024 const CREATE: &[u8; 6] = b"create"; 1025 /// Value after type before the start of the base64url-encoded challenge. 1026 const AFTER_TYPE: &[u8; 15] = br#"","challenge":""#; 1027 /// Value after challenge before the start of the origin value. 1028 const AFTER_CHALLENGE: &[u8; 12] = br#"","origin":""#; 1029 /// Value after origin before the start of the crossOrigin value. 1030 const AFTER_ORIGIN: &[u8; 15] = br#","crossOrigin":"#; 1031 /// `true`. 1032 const TRUE: &[u8; 4] = b"true"; 1033 /// `false`. 1034 const FALSE: &[u8; 5] = b"false"; 1035 /// Value after crossOrigin before the start of the topOrigin value. 1036 const AFTER_CROSS: &[u8; 13] = br#""topOrigin":""#; 1037 json.split_last().ok_or(CollectedClientDataErr::Len).and_then(|(last, last_rem)| { 1038 if *last == b'}' { 1039 last_rem.split_at_checked(HEADER.len()).ok_or(CollectedClientDataErr::Len).and_then(|(header, header_rem)| { 1040 if header == HEADER { 1041 if R { 1042 header_rem.split_at_checked(CREATE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(create, create_rem)| { 1043 if create == CREATE { 1044 Ok(create_rem) 1045 } else { 1046 Err(CollectedClientDataErr::Type) 1047 } 1048 }) 1049 } else { 1050 header_rem.split_at_checked(GET.len()).ok_or(CollectedClientDataErr::Len).and_then(|(get, get_rem)| { 1051 if get == GET { 1052 Ok(get_rem) 1053 } else { 1054 Err(CollectedClientDataErr::Type) 1055 } 1056 }) 1057 }.and_then(|type_rem| { 1058 type_rem.split_at_checked(AFTER_TYPE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(chall_key, chall_key_rem)| { 1059 if chall_key == AFTER_TYPE { 1060 chall_key_rem.split_at_checked(Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|(base64_chall, base64_chall_rem)| { 1061 let mut chall = [0; 16]; 1062 BASE64URL_NOPAD.decode_mut(base64_chall, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).and_then(|chall_len| { 1063 assert_eq!(chall_len, 16, "there is a bug in BASE64URL_NOPAD::decode_mut"); 1064 base64_chall_rem.split_at_checked(AFTER_CHALLENGE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(origin_key, origin_key_rem)| { 1065 if origin_key == AFTER_CHALLENGE { 1066 Self::parse_string(origin_key_rem).and_then(|(origin, origin_rem)| { 1067 origin_rem.split_at_checked(AFTER_ORIGIN.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_key, cross_key_rem)| { 1068 if cross_key == AFTER_ORIGIN { 1069 // `FALSE.len() > TRUE.len()`, so we check for `FALSE` in `and_then`. 1070 cross_key_rem.split_at_checked(TRUE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_true, cross_true_rem)| { 1071 if cross_true == TRUE { 1072 Ok((true, cross_true_rem)) 1073 } else { 1074 cross_key_rem.split_at_checked(FALSE.len()).ok_or(CollectedClientDataErr::Len).and_then(|(cross_false, cross_false_rem)| { 1075 if cross_false == FALSE { 1076 Ok((false, cross_false_rem)) 1077 } else { 1078 Err(CollectedClientDataErr::CrossOrigin) 1079 } 1080 }) 1081 }.and_then(|(cross, cross_rem)| { 1082 cross_rem.split_first().map_or(Ok((cross, None)), |(comma, comma_rem)| { 1083 if *comma == b',' { 1084 comma_rem.split_at_checked(AFTER_CROSS.len()).map_or(Ok((cross, None)), |(top, top_rem)| { 1085 if top == AFTER_CROSS { 1086 if cross { 1087 Self::parse_string(top_rem).and_then(|(top_origin, top_origin_rem)| { 1088 top_origin_rem.first().map_or(Ok(()), |v| { 1089 if *v == b',' { 1090 Ok(()) 1091 } else { 1092 Err(CollectedClientDataErr::InvalidObject) 1093 } 1094 }).and_then(|()| { 1095 if origin == top_origin { 1096 Err(CollectedClientDataErr::TopOriginSameAsOrigin) 1097 } else { 1098 Ok((true, Some(Origin(top_origin)))) 1099 } 1100 }) 1101 }) 1102 } else { 1103 Err(CollectedClientDataErr::TopOriginWithoutCrossOrigin) 1104 } 1105 } else { 1106 Ok((cross, None)) 1107 } 1108 }) 1109 } else { 1110 Err(CollectedClientDataErr::InvalidObject) 1111 } 1112 }).map(|(cross_origin, top_origin)| CollectedClientData { challenge: SentChallenge(u128::from_le_bytes(chall)), origin: Origin(origin), cross_origin, top_origin, }) 1113 }) 1114 }) 1115 } else { 1116 Err(CollectedClientDataErr::CrossOriginKey) 1117 } 1118 }) 1119 }) 1120 } else { 1121 Err(CollectedClientDataErr::OriginKey) 1122 } 1123 }) 1124 }) 1125 }) 1126 } else { 1127 Err(CollectedClientDataErr::ChallengeKey) 1128 } 1129 }) 1130 }) 1131 } else { 1132 Err(CollectedClientDataErr::InvalidStart) 1133 } 1134 }) 1135 } else { 1136 Err(CollectedClientDataErr::InvalidObject) 1137 } 1138 }) 1139 } 1140 #[expect(clippy::panic_in_result_fn, reason = "want to crash when there is a bug")] 1141 #[expect(clippy::arithmetic_side_effects, reason = "comment justifies correctness")] 1142 #[expect(clippy::little_endian_bytes, reason = "Challenge::serialize and this need to be consistent across architectures")] 1143 fn get_sent_challenge(json: &[u8]) -> Result<SentChallenge, Self::Err> { 1144 // Index 39. 1145 // `{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA"...`. 1146 // Index 36. 1147 // `{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA"...`. 1148 let idx = if R { 39 } else { 36 }; 1149 // This maxes at 39 + 22 = 61; thus overflow is not an issue. 1150 json.get(idx..idx + Challenge::BASE64_LEN).ok_or(CollectedClientDataErr::Len).and_then(|chall_slice| { 1151 let mut chall = [0; 16]; 1152 BASE64URL_NOPAD.decode_mut(chall_slice, chall.as_mut_slice()).map_err(|_e| CollectedClientDataErr::Challenge).map(|len| { 1153 assert_eq!(len, 16, "there is a bug in BASE64URL_NOPAD::decode_mut"); 1154 SentChallenge(u128::from_le_bytes(chall)) 1155 }) 1156 }) 1157 } 1158 } 1159 /// Authenticator extension outputs; 1160 pub(super) trait AuthExtOutput { 1161 /// MUST return `true` iff there is no data. 1162 fn missing(self) -> bool; 1163 } 1164 /// Successful return type from [`FromCbor::from_cbor`]. 1165 struct CborSuccess<'a, T> { 1166 /// Value parsed from the slice. 1167 value: T, 1168 /// Remaining unprocessed data. 1169 remaining: &'a [u8], 1170 } 1171 /// Types that parse 1172 /// [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) 1173 /// data without necessarily consuming all the data. 1174 /// 1175 /// The purpose of this `trait` is to allow chains of types to progressively consume `cbor` by passing 1176 /// [`CborSuccess::remaining`] into the next `FromCbor` type. 1177 trait FromCbor<'a>: Sized { 1178 /// Error when conversion fails. 1179 type Err; 1180 /// Parses `cbor` into `Self`. 1181 /// 1182 /// # Errors 1183 /// 1184 /// Errors if `cbor` cannot be parsed into `Self:`. 1185 fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err>; 1186 } 1187 /// Error returned from [`A::from_cbor`] `where A: AuthData`. 1188 enum AuthenticatorDataErr<UpErr, CredData, AuthExt> { 1189 /// The `slice` had an invalid length. 1190 Len, 1191 /// [UP](https://www.w3.org/TR/webauthn-3/#authdata-flags-at) bit was 0. 1192 UserNotPresent(UpErr), 1193 /// Bit 1 in [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags) is not 0. 1194 FlagsBit1Not0, 1195 /// Bit 5 in [`flags`](https://www.w3.org/TR/webauthn-3/#authdata-flags) is not 0. 1196 FlagsBit5Not0, 1197 /// [AT](https://www.w3.org/TR/webauthn-3/#authdata-flags-at) bit was 0 during registration or was 1 1198 /// during authentication. 1199 AttestedCredentialData, 1200 /// [BE](https://www.w3.org/TR/webauthn-3/#authdata-flags-be) and 1201 /// [BS](https://www.w3.org/TR/webauthn-3/#authdata-flags-bs) bits were 0 and 1 respectively. 1202 BackupWithoutEligibility, 1203 /// Error returned from [`AttestedCredentialData::from_cbor`]. 1204 AttestedCredential(CredData), 1205 /// Error returned from [`register::AuthenticatorExtensionOutput::from_cbor`] and 1206 /// [`auth::AuthenticatorExtensionOutput::from_cbor`]. 1207 AuthenticatorExtension(AuthExt), 1208 /// [ED](https://www.w3.org/TR/webauthn-3/#authdata-flags-ed) bit was 0, but 1209 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions) existed. 1210 NoExtensionBitWithData, 1211 /// [ED](https://www.w3.org/TR/webauthn-3/#authdata-flags-ed) bit was 1, but 1212 /// [`extensions`](https://www.w3.org/TR/webauthn-3/#authdata-extensions) did not exist. 1213 ExtensionBitWithoutData, 1214 /// There was trailing data that could not be deserialized. 1215 TrailingData, 1216 } 1217 impl<U, C: Display, A: Display> Display for AuthenticatorDataErr<U, C, A> { 1218 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1219 match *self { 1220 Self::Len => f.write_str("authenticator data had an invalid length"), 1221 Self::UserNotPresent(_) => f.write_str("user was not present"), 1222 Self::FlagsBit1Not0 => f.write_str("flags 1-bit was 1"), 1223 Self::FlagsBit5Not0 => f.write_str("flags 5-bit was 1"), 1224 Self::AttestedCredentialData => f.write_str("attested credential data was included during authentication or was not included during registration"), 1225 Self::BackupWithoutEligibility => { 1226 f.write_str("backup state bit was 1 despite backup eligibility being 0") 1227 } 1228 Self::AttestedCredential(ref err) => err.fmt(f), 1229 Self::AuthenticatorExtension(ref err) => err.fmt(f), 1230 Self::NoExtensionBitWithData => { 1231 f.write_str("extension bit was 0 despite extensions existing") 1232 } 1233 Self::ExtensionBitWithoutData => { 1234 f.write_str("extension bit was 1 despite no extensions existing") 1235 } 1236 Self::TrailingData => { 1237 f.write_str("slice had trailing data that could not be deserialized") 1238 } 1239 } 1240 } 1241 } 1242 impl From<AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>> for RegAuthDataErr { 1243 #[inline] 1244 fn from(value: AuthenticatorDataErr<Infallible, AttestedCredentialDataErr, RegAuthExtErr>) -> Self { 1245 match value { 1246 AuthenticatorDataErr::Len => Self::Len, 1247 AuthenticatorDataErr::UserNotPresent(v) => match v {}, 1248 AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0, 1249 AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0, 1250 AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataNotIncluded, 1251 AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility, 1252 AuthenticatorDataErr::AttestedCredential(err) => Self::AttestedCredential(err), 1253 AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err), 1254 AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData, 1255 AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData, 1256 AuthenticatorDataErr::TrailingData => Self::TrailingData, 1257 } 1258 } 1259 } 1260 impl From<AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>> for AuthAuthDataErr { 1261 #[inline] 1262 fn from(value: AuthenticatorDataErr<(), Infallible, AuthAuthExtErr>) -> Self { 1263 match value { 1264 AuthenticatorDataErr::Len => Self::Len, 1265 AuthenticatorDataErr::UserNotPresent(()) => Self::UserNotPresent, 1266 AuthenticatorDataErr::FlagsBit1Not0 => Self::FlagsBit1Not0, 1267 AuthenticatorDataErr::FlagsBit5Not0 => Self::FlagsBit5Not0, 1268 AuthenticatorDataErr::AttestedCredentialData => Self::AttestedCredentialDataIncluded, 1269 AuthenticatorDataErr::AttestedCredential(val) => match val {}, 1270 AuthenticatorDataErr::BackupWithoutEligibility => Self::BackupWithoutEligibility, 1271 AuthenticatorDataErr::AuthenticatorExtension(err) => Self::AuthenticatorExtension(err), 1272 AuthenticatorDataErr::NoExtensionBitWithData => Self::NoExtensionBitWithData, 1273 AuthenticatorDataErr::ExtensionBitWithoutData => Self::ExtensionBitWithoutData, 1274 AuthenticatorDataErr::TrailingData => Self::TrailingData, 1275 } 1276 } 1277 } 1278 impl<'a, A> FromCbor<'a> for A 1279 where 1280 A: AuthData<'a>, 1281 A::CredData: FromCbor<'a>, 1282 A::Ext: FromCbor<'a>, 1283 { 1284 type Err = AuthenticatorDataErr<A::UpBitErr, <A::CredData as FromCbor<'a>>::Err, <A::Ext as FromCbor<'a>>::Err>; 1285 #[expect(clippy::big_endian_bytes, reason = "CBOR integers are in big-endian")] 1286 fn from_cbor(cbor: &'a [u8]) -> Result<CborSuccess<'a, Self>, Self::Err> { 1287 /// Length of `signCount`. 1288 const SIGN_COUNT_LEN: usize = 4; 1289 /// `UP` bit (i.e., bit 0) set to 1. 1290 const UP: u8 = 0b0000_0001; 1291 /// `RFU1` bit (i.e., bit 1) set to 1. 1292 const RFU1: u8 = UP << 1; 1293 /// `UV` bit (i.e., bit 2) set to 1. 1294 const UV: u8 = RFU1 << 1; 1295 /// `BE` bit (i.e., bit 3) set to 1. 1296 const BE: u8 = UV << 1; 1297 /// `BS` bit (i.e., bit 4) set to 1. 1298 const BS: u8 = BE << 1; 1299 /// `RFU2` bit (i.e., bit 5) set to 1. 1300 const RFU2: u8 = BS << 1; 1301 /// `AT` bit (i.e., bit 6) set to 1. 1302 const AT: u8 = RFU2 << 1; 1303 /// `ED` bit (i.e., bit 7) set to 1. 1304 const ED: u8 = AT << 1; 1305 cbor.split_at_checked(Sha256::output_size()).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(rp_id_slice, rp_id_rem)| { 1306 rp_id_rem.split_first().ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(&flag, flag_rem)| { 1307 let user_present = flag & UP == UP; 1308 if user_present { 1309 Ok(()) 1310 } else { 1311 A::user_is_not_present().map_err(AuthenticatorDataErr::UserNotPresent) 1312 } 1313 .and_then(|()| { 1314 if flag & RFU1 == 0 { 1315 if flag & RFU2 == 0 { 1316 let at_bit = A::contains_at_bit(); 1317 if flag & AT == AT { 1318 if at_bit { 1319 Ok(()) 1320 } else { 1321 Err(AuthenticatorDataErr::AttestedCredentialData) 1322 } 1323 } else if at_bit { 1324 Err(AuthenticatorDataErr::AttestedCredentialData) 1325 } else { 1326 Ok(()) 1327 }.and_then(|()| { 1328 let bs = flag & BS == BS; 1329 if flag & BE == BE { 1330 if bs { 1331 Ok(Backup::Exists) 1332 } else { 1333 Ok(Backup::Eligible) 1334 } 1335 } else if bs { 1336 Err(AuthenticatorDataErr::BackupWithoutEligibility) 1337 } else { 1338 Ok(Backup::NotEligible) 1339 } 1340 .and_then(|backup| { 1341 flag_rem.split_at_checked(SIGN_COUNT_LEN).ok_or_else(|| AuthenticatorDataErr::Len).and_then(|(count_slice, count_rem)| { 1342 A::CredData::from_cbor(count_rem).map_err(AuthenticatorDataErr::AttestedCredential).and_then(|att_data| { 1343 A::Ext::from_cbor(att_data.remaining).map_err(AuthenticatorDataErr::AuthenticatorExtension).and_then(|ext| { 1344 if ext.remaining.is_empty() { 1345 let ed = flag & ED == ED; 1346 if ext.value.missing() { 1347 if ed { 1348 Err(AuthenticatorDataErr::ExtensionBitWithoutData) 1349 } else { 1350 Ok(()) 1351 } 1352 } else if ed { 1353 Ok(()) 1354 } else { 1355 Err(AuthenticatorDataErr::NoExtensionBitWithData) 1356 }.map(|()| { 1357 let mut sign_count = [0; SIGN_COUNT_LEN]; 1358 sign_count.copy_from_slice(count_slice); 1359 // `signCount` is in big-endian. 1360 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, } 1361 }) 1362 } else { 1363 Err(AuthenticatorDataErr::TrailingData) 1364 } 1365 }) 1366 }) 1367 }) 1368 }) 1369 }) 1370 } else { 1371 Err(AuthenticatorDataErr::FlagsBit5Not0) 1372 } 1373 } else { 1374 Err(AuthenticatorDataErr::FlagsBit1Not0) 1375 } 1376 }) 1377 }) 1378 }) 1379 } 1380 } 1381 /// Data returned by [`AuthDataContainer::from_data`]. 1382 pub(super) struct ParsedAuthData<'a, A> { 1383 /// The data the CBOR is parsed into. 1384 data: A, 1385 /// The raw authenticator data and 32-bytes of trailing data. 1386 auth_data_and_32_trailing_bytes: &'a [u8], 1387 } 1388 /// Error returned by [`AuthResponse::parse_data_and_verify_sig`]. 1389 pub(super) enum AuthRespErr<AuthDataErr> { 1390 /// Variant returned when parsing 1391 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1392 /// into [`CollectedClientData`] fails. 1393 CollectedClientData(CollectedClientDataErr), 1394 /// Variant returned when parsing 1395 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1396 /// in a "relaxed" way into [`CollectedClientData`] fails. 1397 #[cfg(feature = "serde_relaxed")] 1398 CollectedClientDataRelaxed(SerdeJsonErr), 1399 /// Variant returned when parsing [`AuthResponse::Auth`] fails. 1400 Auth(AuthDataErr), 1401 /// Variant when the [`CompressedPubKey`] or [`UncompressePubKey`] is not valid. 1402 PubKey(PubKeyErr), 1403 /// Variant returned when the signature, if one exists, associated with 1404 /// [`Self::AuthResponse`] is invalid. 1405 Signature, 1406 } 1407 impl<A: Display> Display for AuthRespErr<A> { 1408 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1409 match *self { 1410 Self::CollectedClientData(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"), 1411 #[cfg(feature = "serde_relaxed")] 1412 Self::CollectedClientDataRelaxed(ref err) => write!(f, "CollectedClientData could not be parsed: {err}"), 1413 Self::Auth(ref err) => write!(f, "auth data could not be parsed: {err}"), 1414 Self::PubKey(err) => err.fmt(f), 1415 Self::Signature => f.write_str("the signature over the authenticator data and CollectedClientData could not be verified"), 1416 } 1417 } 1418 } 1419 impl From<AuthRespErr<AttestationObjectErr>> for RegCeremonyErr { 1420 #[inline] 1421 fn from(value: AuthRespErr<AttestationObjectErr>) -> Self { 1422 match value { 1423 AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err), 1424 #[cfg(feature = "serde_relaxed")] 1425 AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err), 1426 AuthRespErr::Auth(err) => Self::AttestationObject(err), 1427 AuthRespErr::PubKey(err) => Self::PubKey(err), 1428 AuthRespErr::Signature => Self::AttestationSignature, 1429 } 1430 } 1431 } 1432 impl From<AuthRespErr<AuthAuthDataErr>> for AuthCeremonyErr { 1433 #[inline] 1434 fn from(value: AuthRespErr<AuthAuthDataErr>) -> Self { 1435 match value { 1436 AuthRespErr::CollectedClientData(err) => Self::CollectedClientData(err), 1437 #[cfg(feature = "serde_relaxed")] 1438 AuthRespErr::CollectedClientDataRelaxed(err) => Self::CollectedClientDataRelaxed(err), 1439 AuthRespErr::Auth(err) => Self::AuthenticatorData(err), 1440 AuthRespErr::PubKey(err) => Self::PubKey(err), 1441 AuthRespErr::Signature => Self::AssertionSignature, 1442 } 1443 } 1444 } 1445 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data) 1446 /// container. 1447 /// 1448 /// Note [`Self::Auth`] may be `Self`. 1449 pub(super) trait AuthDataContainer<'a>: Sized { 1450 /// [Authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1451 type Auth: AuthData<'a>; 1452 /// Error returned from [`Self::from_data`]. 1453 type Err; 1454 /// Converts `data` into [`ParsedAuthData`]. 1455 /// 1456 /// # Errors 1457 /// 1458 /// Errors iff `data` cannot be converted into `ParsedAuthData`. 1459 fn from_data(data: &'a [u8]) -> Result<ParsedAuthData<'a, Self>, Self::Err>; 1460 /// Returns the contained 1461 /// [authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1462 fn authenticator_data(&self) -> &Self::Auth; 1463 } 1464 /// [`AuthenticatorResponse`](https://www.w3.org/TR/webauthn-3/#authenticatorresponse). 1465 pub(super) trait AuthResponse { 1466 /// [Attestation object](https://www.w3.org/TR/webauthn-3/#attestation-object) or 1467 /// [authenticator data](https://www.w3.org/TR/webauthn-3/#authenticator-data). 1468 type Auth<'a>: AuthDataContainer<'a> where Self: 'a; 1469 /// Public key to use to verify the contained signature. 1470 type CredKey<'a>; 1471 /// Parses 1472 /// [`clientDataJSON`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorresponse-clientdatajson) 1473 /// based on `RELAXED` and [`Self::Auth`] via [`AuthDataContainer::from_data`] in addition to 1474 /// verifying any possible signature over the concatenation of the raw 1475 /// [`AuthDataContainer::Auth`] and `clientDataJSON` using `key` or the contained 1476 /// public key if one exists. If `Self` contains a public key and should not be passed one, then it should set 1477 /// [`Self::CredKey`] to `()`. 1478 /// 1479 /// # Errors 1480 /// 1481 /// Errors iff parsing `clientDataJSON` errors, [`AuthDataContainer::from_data`] does, or the signature 1482 /// is invalid. 1483 /// 1484 /// # Panics 1485 /// 1486 /// `panic`s iff `relaxed` and `serde_relaxed` is not enabled. 1487 #[expect( 1488 clippy::type_complexity, 1489 reason = "type aliases with bounds are even more problematic at least until lazy_type_alias is stable" 1490 )] 1491 fn parse_data_and_verify_sig(&self, key: Self::CredKey<'_>, relaxed: bool) -> Result<(CollectedClientData<'_>, Self::Auth<'_>), AuthRespErr<<Self::Auth<'_> as AuthDataContainer<'_>>::Err>>; 1492 } 1493 /// Ceremony response (i.e., [`PublicKeyCredential`](https://www.w3.org/TR/webauthn-3/#publickeycredential)). 1494 pub(super) trait Response { 1495 /// [`AuthenticatorResponse`](https://www.w3.org/TR/webauthn-3/#authenticatorresponse). 1496 type Auth: AuthResponse; 1497 /// [`response`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredential-response). 1498 fn auth(&self) -> &Self::Auth; 1499 } 1500 /// Error returned from [`Ceremony::partial_validate`]. 1501 pub(super) enum CeremonyErr<AuthDataErr> { 1502 /// Timeout occurred. 1503 Timeout, 1504 /// Read [`AuthRespErr`] for information. 1505 AuthResp(AuthRespErr<AuthDataErr>), 1506 /// Origin did not validate. 1507 OriginMismatch, 1508 /// Cross origin was `true` but was not allowed to be. 1509 CrossOrigin, 1510 /// Top origin did not validate. 1511 TopOriginMismatch, 1512 /// Challenges don't match. 1513 ChallengeMismatch, 1514 /// `rpIdHash` does not match the SHA-256 hash of the [`RpId`]. 1515 RpIdHashMismatch, 1516 /// User was not verified despite being required to. 1517 UserNotVerified, 1518 /// [`Backup::NotEligible`] was not sent back despite [`BackupReq::NotEligible`]. 1519 BackupEligible, 1520 /// [`Backup::NotEligible`] was sent back despite [`BackupReq::Eligible`]. 1521 BackupNotEligible, 1522 /// [`Backup::Exists`] was not sent back despite [`BackupReq::Exists`]. 1523 BackupDoesNotExist, 1524 } 1525 impl<A: Display> Display for CeremonyErr<A> { 1526 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 1527 match *self { 1528 Self::Timeout => f.write_str("ceremony timed out"), 1529 Self::AuthResp(ref err) => err.fmt(f), 1530 Self::OriginMismatch => { 1531 f.write_str("the origin sent from the client is not an allowed origin") 1532 } 1533 Self::CrossOrigin => { 1534 f.write_str("cross origin was from the client, but it is not allowed") 1535 } 1536 Self::TopOriginMismatch => { 1537 f.write_str("the top origin sent from the client is not an allowed top origin") 1538 } 1539 Self::ChallengeMismatch => f.write_str( 1540 "the challenge sent to the client does not match the challenge sent back", 1541 ), 1542 Self::RpIdHashMismatch => f.write_str( 1543 "the SHA-256 hash of the RP ID doesn't match the hash sent from the client", 1544 ), 1545 Self::UserNotVerified => f.write_str("user was not verified despite being required to"), 1546 Self::BackupEligible => f.write_str("credential is eligible to be backed up despite requiring that it not be"), 1547 Self::BackupNotEligible => f.write_str("credential is not eligible to be backed up despite requiring that it be"), 1548 Self::BackupDoesNotExist => f.write_str("credential backup does not exist despite requiring that a backup exist"), 1549 } 1550 } 1551 } 1552 impl From<CeremonyErr<AttestationObjectErr>> for RegCeremonyErr { 1553 #[inline] 1554 fn from(value: CeremonyErr<AttestationObjectErr>) -> Self { 1555 match value { 1556 CeremonyErr::Timeout => Self::Timeout, 1557 CeremonyErr::AuthResp(err) => err.into(), 1558 CeremonyErr::OriginMismatch => Self::OriginMismatch, 1559 CeremonyErr::CrossOrigin => Self::CrossOrigin, 1560 CeremonyErr::TopOriginMismatch => Self::TopOriginMismatch, 1561 CeremonyErr::ChallengeMismatch => Self::ChallengeMismatch, 1562 CeremonyErr::RpIdHashMismatch => Self::RpIdHashMismatch, 1563 CeremonyErr::UserNotVerified => Self::UserNotVerified, 1564 CeremonyErr::BackupEligible => Self::BackupEligible, 1565 CeremonyErr::BackupNotEligible => Self::BackupNotEligible, 1566 CeremonyErr::BackupDoesNotExist => Self::BackupDoesNotExist, 1567 } 1568 } 1569 } 1570 impl From<CeremonyErr<AuthAuthDataErr>> for AuthCeremonyErr { 1571 #[inline] 1572 fn from(value: CeremonyErr<AuthAuthDataErr>) -> 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::BackupDoesNotExist => Self::BackupDoesNotExist, 1585 } 1586 } 1587 } 1588 /// [`AllAcceptedCredentialsOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions). 1589 /// 1590 /// This can be sent to _an already authenticated user_ to inform what credentials are currently registered. 1591 /// This can be useful when a user deletes credentials on the RP's side but does not do so on the authenticator. 1592 /// When the client forwards this response to the authenticator, it can remove all credentials that don't have 1593 /// a [`CredentialId`] in [`Self::all_accepted_credential_ids`]. 1594 #[derive(Debug)] 1595 pub struct AllAcceptedCredentialsOptions<'rp, 'user> { 1596 /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-rpid). 1597 pub rp_id: &'rp RpId, 1598 /// [`userId`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-userid). 1599 pub user_id: UserHandle<&'user [u8]>, 1600 /// [`allAcceptedCredentialIds`](https://www.w3.org/TR/webauthn-3/#dictdef-allacceptedcredentialsoptions-allacceptedcredentialids). 1601 pub all_accepted_credential_ids: Vec<CredentialId<Vec<u8>>>, 1602 } 1603 /// [`CurrentUserDetailsOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions). 1604 /// 1605 /// This can be sent to _an already authenticated user_ to inform the user information. 1606 /// This can be useful when a user updates their user information on the RP's side but does not do so on the authenticator. 1607 /// When the client forwards this response to the authenticator, it can update the user info for the associated credential. 1608 #[derive(Debug)] 1609 pub struct CurrentUserDetailsOptions<'rp, 'user_name, 'user_display_name, 'user_handle> { 1610 /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-rpid). 1611 pub rp_id: &'rp RpId, 1612 /// [`userId`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-userid), 1613 /// [`name`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-name), and 1614 /// [`displayName`](https://www.w3.org/TR/webauthn-3/#dictdef-currentuserdetailsoptions-displayname). 1615 pub user: PublicKeyCredentialUserEntity<'user_name, 'user_display_name, &'user_handle [u8]>, 1616 } 1617 #[cfg(test)] 1618 mod tests { 1619 use super::{CollectedClientDataErr, ClientDataJsonParser, LimitedVerificationParser}; 1620 #[test] 1621 fn parse_string() { 1622 assert!(LimitedVerificationParser::<true>::parse_string(br#"abc""#) 1623 .map_or(false, |tup| { tup.0 == "abc" && tup.1 == br#""# })); 1624 assert!(LimitedVerificationParser::<false>::parse_string(br#"abc"23"#) 1625 .map_or(false, |tup| { tup.0 == "abc" && tup.1 == br#"23"# })); 1626 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\"c"23"#) 1627 .map_or(false, |tup| { tup.0 == r#"ab"c"# && tup.1 == br#"23"# })); 1628 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\\c"23"#) 1629 .map_or(false, |tup| { tup.0 == r#"ab\c"# && tup.1 == br#"23"# })); 1630 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\u001fc"23"#) 1631 .map_or(false, |tup| { tup.0 == "ab\u{001f}c" && tup.1 == br#"23"# })); 1632 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\u000dc"23"#) 1633 .map_or(false, |tup| { tup.0 == "ab\u{000d}c" && tup.1 == br#"23"# })); 1634 assert!( 1635 LimitedVerificationParser::<true>::parse_string(b"\\\\\\\\\\\\a\\\\\\\\a\\\\\"").map_or(false, |tup| { 1636 tup.0 == "\\\\\\a\\\\a\\" && tup.1.is_empty() 1637 }) 1638 ); 1639 assert!( 1640 LimitedVerificationParser::<false>::parse_string(b"\\\\\\\\\\a\\\\\\\\a\\\\\"").map_or_else( 1641 |e| matches!(e, CollectedClientDataErr::InvalidEscapedString), 1642 |_| false 1643 ) 1644 ); 1645 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\u0020c"23"#).map_or_else( 1646 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1647 |_| false 1648 )); 1649 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\ac"23"#).map_or_else( 1650 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1651 |_| false 1652 )); 1653 assert!(LimitedVerificationParser::<true>::parse_string(br#"ab\""#).map_or_else( 1654 |err| matches!(err, CollectedClientDataErr::InvalidObject), 1655 |_| false 1656 )); 1657 assert!(LimitedVerificationParser::<false>::parse_string(br#"ab\u001Fc"23"#).map_or_else( 1658 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1659 |_| false 1660 )); 1661 assert!(LimitedVerificationParser::<true>::parse_string([0, b'"'].as_slice()).map_or_else( 1662 |err| matches!(err, CollectedClientDataErr::InvalidEscapedString), 1663 |_| false 1664 )); 1665 assert!(LimitedVerificationParser::<false>::parse_string([b'a', 255, b'"'].as_slice()) 1666 .map_or_else(|err| matches!(err, CollectedClientDataErr::Utf8(_)), |_| false)); 1667 assert!(LimitedVerificationParser::<true>::parse_string([b'a', b'"', 255].as_slice()).is_ok()); 1668 assert!( 1669 LimitedVerificationParser::<false>::parse_string(br#"""#).map_or(false, |tup| tup.0.is_empty() && tup.1.is_empty()) 1670 ); 1671 } 1672 #[test] 1673 fn c_data_json() { 1674 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())); 1675 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())); 1676 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())); 1677 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"))); 1678 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"))); 1679 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)); 1680 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)); 1681 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)); 1682 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())); 1683 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)); 1684 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)); 1685 assert!(LimitedVerificationParser::<true>::parse(br#"{"type":"webauthn.create","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false}"#.as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1686 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())); 1687 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())); 1688 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())); 1689 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)); 1690 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)); 1691 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)); 1692 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)); 1693 assert!(LimitedVerificationParser::<true>::parse([].as_slice()) 1694 .map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1695 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)); 1696 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)); 1697 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)); 1698 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)); 1699 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)); 1700 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)); 1701 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)); 1702 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())); 1703 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())); 1704 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())); 1705 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"))); 1706 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)); 1707 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)); 1708 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())); 1709 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)); 1710 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)); 1711 assert!(LimitedVerificationParser::<false>::parse( 1712 br#"{"type":"webauthn.get","challenge":"AAAAAAAAAAAAAAAAAAAAAA","crossOrigin":false}"# 1713 .as_slice() 1714 ) 1715 .map_or_else(|e| matches!(e, CollectedClientDataErr::OriginKey), |_| false)); 1716 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())); 1717 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())); 1718 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())); 1719 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)); 1720 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)); 1721 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)); 1722 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)); 1723 assert!(LimitedVerificationParser::<false>::parse([].as_slice()) 1724 .map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1725 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)); 1726 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)); 1727 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)); 1728 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)); 1729 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)); 1730 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)); 1731 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)); 1732 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())); 1733 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)); 1734 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)); 1735 } 1736 #[test] 1737 fn c_data_challenge() { 1738 assert!(LimitedVerificationParser::<false>::get_sent_challenge([].as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1739 assert!(LimitedVerificationParser::<true>::get_sent_challenge([].as_slice()).map_or_else(|e| matches!(e, CollectedClientDataErr::Len), |_| false)); 1740 assert!(LimitedVerificationParser::<true>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBB").map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1741 assert!(LimitedVerificationParser::<false>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBB").map_or_else(|e| matches!(e, CollectedClientDataErr::Challenge), |_| false)); 1742 assert!(LimitedVerificationParser::<true>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".as_slice()).map_or(false, |c| c.0 == 0)); 1743 assert!(LimitedVerificationParser::<false>::get_sent_challenge(b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".as_slice()).map_or(false, |c| c.0 == 0)); 1744 } 1745 }