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