Skip to main content

structured_webauthn/
response.rs

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