Skip to main content

structured_webauthn/request/
auth.rs

1#[cfg(test)]
2mod tests;
3#[cfg(doc)]
4use super::{
5    super::response::{
6        CollectedClientData, Flag,
7        auth::AuthenticatorData,
8        register::{
9            AuthenticatorExtensionOutputStaticState, ClientExtensionsOutputsStaticState,
10            DynamicState, StaticState,
11        },
12    },
13    AsciiDomain, AsciiDomainStatic, DomainOrigin, Url,
14    register::{self, PublicKeyCredentialCreationOptions},
15};
16use super::{
17    super::{
18        AuthenticatedCredential,
19        response::{
20            AuthenticatorAttachment,
21            auth::{
22                Authentication, AuthenticatorExtensionOutput, DiscoverableAuthentication,
23                HmacSecret, NonDiscoverableAuthentication,
24                error::{AuthCeremonyErr, ExtensionErr, OneOrTwo},
25            },
26            register::{CompressedPubKey, CredentialProtectionPolicy},
27        },
28    },
29    Backup, BackupReq, Ceremony, CeremonyOptions, Challenge, CredentialId,
30    CredentialMediationRequirement, Credentials, ExtensionReq, FIVE_MINUTES, Hints, Origin,
31    PrfInput, PublicKeyCredentialDescriptor, RpId, SentChallenge, TimedCeremony,
32    UserVerificationRequirement,
33    auth::error::{
34        DiscoverableCredentialRequestOptionsErr, NonDiscoverableCredentialRequestOptionsErr,
35    },
36};
37use core::{
38    borrow::Borrow,
39    cmp::Ordering,
40    hash::{Hash, Hasher},
41    num::{NonZeroU32, NonZeroU64},
42    time::Duration,
43};
44#[cfg(any(doc, not(feature = "serializable_server_state")))]
45use std::time::Instant;
46#[cfg(any(doc, feature = "serializable_server_state"))]
47use std::time::SystemTime;
48/// Contains error types.
49pub mod error;
50/// Contains functionality to serialize data to a client.
51#[cfg(feature = "serde")]
52pub mod ser;
53/// Contains functionality to (de)serialize [`DiscoverableAuthenticationServerState`] and
54/// [`NonDiscoverableAuthenticationServerState`] to a data store.
55#[cfg(feature = "serializable_server_state")]
56pub mod ser_server_state;
57/// Controls how [signature counter](https://www.w3.org/TR/webauthn-3/#signature-counter) is enforced.
58///
59/// Note that if the previous signature counter is positive and the new counter is not strictly greater, then the
60/// authenticator is likely a clone (i.e., there are at least two copies of the private key).
61#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
62pub enum SignatureCounterEnforcement {
63    /// Fail the authentication ceremony if the counter is less than or equal to the previous value when the
64    /// previous value is positive.
65    #[default]
66    Fail,
67    /// When the counter is less than the previous value, don't fail and update the value.
68    ///
69    /// Note in the special case that the new signature counter is 0, [`DynamicState::sign_count`] _won't_
70    /// be updated since that would allow an attacker to permanently disable the counter.
71    Update,
72    /// When the counter is less than the previous value, don't fail but don't update the value.
73    Ignore,
74}
75impl SignatureCounterEnforcement {
76    /// Validates the signature counter based on `self`.
77    const fn validate(self, prev: u32, cur: u32) -> Result<u32, AuthCeremonyErr> {
78        if prev == 0 || cur > prev {
79            Ok(cur)
80        } else {
81            match self {
82                Self::Fail => Err(AuthCeremonyErr::SignatureCounter),
83                // When the new counter is `0`, we use the previous counter to avoid an attacker from
84                // being able to permanently disable it.
85                Self::Update => Ok(if cur == 0 { prev } else { cur }),
86                Self::Ignore => Ok(prev),
87            }
88        }
89    }
90}
91/// Owned version of [`PrfInput`].
92///
93/// When relying on [`NonDiscoverableCredentialRequestOptions`], it's recommended to use credential-specific PRF
94/// inputs that are continuously rolled over. One uses this type for such a thing.
95#[derive(Clone, Debug, Eq, PartialEq)]
96pub struct PrfInputOwned {
97    /// [`first`](https://www.w3.org/TR/webauthn-3/#dom-authenticationextensionsprfvalues-first).
98    pub first: Vec<u8>,
99    /// [`second`](https://www.w3.org/TR/webauthn-3/#dom-authenticationextensionsprfvalues-second).
100    pub second: Option<Vec<u8>>,
101    /// Note this is only applicable for authenticators that implement the
102    /// [`prf`](https://www.w3.org/TR/webauthn-3/#prf-extension) extension on top of the
103    /// [`hmac-secret`](https://fidoalliance.org/specs/fido-v2.2-ps-20250228/fido-client-to-authenticator-protocol-v2.2-ps-20250228.html#sctn-hmac-secret-extension)
104    /// extension since the data is encrypted and is part of the [`AuthenticatorData`].
105    pub ext_req: ExtensionReq,
106}
107/// The [defined extensions](https://www.w3.org/TR/webauthn-3/#sctn-defined-extensions) to send to the client.
108#[derive(Clone, Copy, Debug)]
109pub struct Extension<'prf_first, 'prf_second> {
110    /// [`prf`](https://www.w3.org/TR/webauthn-3/#prf-extension).
111    ///
112    /// If both [`CredentialSpecificExtension::prf`] and this are [`Some`], then `CredentialSpecificExtension::prf`
113    /// takes priority.
114    ///
115    /// Note `ExtensionReq` is only applicable for authenticators that implement the
116    /// [`prf`](https://www.w3.org/TR/webauthn-3/#prf-extension) extension on top of the
117    /// [`hmac-secret`](https://fidoalliance.org/specs/fido-v2.2-ps-20250228/fido-client-to-authenticator-protocol-v2.2-ps-20250228.html#sctn-hmac-secret-extension)
118    /// extension since the data is encrypted and is part of the [`AuthenticatorData`].
119    pub prf: Option<(PrfInput<'prf_first, 'prf_second>, ExtensionReq)>,
120}
121impl<'prf_first, 'prf_second> Extension<'prf_first, 'prf_second> {
122    /// Returns an `Extension` with [`Self::prf`] set to `None`.
123    #[inline]
124    #[must_use]
125    pub const fn none() -> Self {
126        Self { prf: None }
127    }
128    /// Returns an `Extension` with [`Self::prf`] set to `None`.
129    #[inline]
130    #[must_use]
131    pub const fn with_prf<'a: 'prf_first, 'b: 'prf_second>(
132        input: PrfInput<'a, 'b>,
133        req: ExtensionReq,
134    ) -> Self {
135        Self {
136            prf: Some((input, req)),
137        }
138    }
139}
140impl Default for Extension<'_, '_> {
141    /// Same as [`Self::none`].
142    #[inline]
143    fn default() -> Self {
144        Self::none()
145    }
146}
147/// The [defined extensions](https://www.w3.org/TR/webauthn-3/#sctn-defined-extensions) to send to the client that
148/// are credential-specific which among other things implies a non-discoverable request.
149#[derive(Clone, Debug, Default)]
150pub struct CredentialSpecificExtension {
151    /// [`prf`](https://www.w3.org/TR/webauthn-3/#prf-extension).
152    ///
153    /// If both [`Extension::prf`] and this are [`Some`], then this take priority.
154    pub prf: Option<PrfInputOwned>,
155}
156/// Registered credential used in
157/// [`allowCredentials`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-allowcredentials).
158#[derive(Clone, Debug)]
159pub struct AllowedCredential {
160    /// The registered credential.
161    pub credential: PublicKeyCredentialDescriptor<Box<[u8]>>,
162    /// Credential-specific extensions.
163    pub extension: CredentialSpecificExtension,
164}
165impl From<PublicKeyCredentialDescriptor<Box<[u8]>>> for AllowedCredential {
166    #[inline]
167    fn from(credential: PublicKeyCredentialDescriptor<Box<[u8]>>) -> Self {
168        Self {
169            credential,
170            extension: CredentialSpecificExtension::default(),
171        }
172    }
173}
174impl From<AllowedCredential> for PublicKeyCredentialDescriptor<Box<[u8]>> {
175    #[inline]
176    fn from(credential: AllowedCredential) -> Self {
177        credential.credential
178    }
179}
180/// Queue of unique [`AllowedCredential`]s.
181#[derive(Clone, Debug, Default)]
182pub struct AllowedCredentials {
183    /// Allowed credentials.
184    creds: Vec<AllowedCredential>,
185    /// Number of `AllowedCredential`s that have PRF inputs.
186    ///
187    /// Useful to help serialization.
188    prf_count: usize,
189}
190impl Credentials for AllowedCredentials {
191    type Credential = AllowedCredential;
192    /// # Examples
193    ///
194    /// ```
195    /// # use structured_webauthn::request::{auth::AllowedCredentials, Credentials};
196    /// assert!(AllowedCredentials::with_capacity(1).as_ref().is_empty());
197    /// ```
198    #[inline]
199    fn with_capacity(capacity: usize) -> Self {
200        Self {
201            creds: Vec::with_capacity(capacity),
202            prf_count: 0,
203        }
204    }
205    /// # Examples
206    ///
207    /// ```
208    /// # #[cfg(all(feature = "bin", feature = "custom"))]
209    /// # use structured_webauthn::{bin::Decode, response::bin::DecodeAuthTransportsErr};
210    /// # use structured_webauthn::{
211    /// #     request::{auth::AllowedCredentials, PublicKeyCredentialDescriptor, Credentials},
212    /// #     response::{AuthTransports, CredentialId},
213    /// # };
214    /// /// Retrieves the `AuthTransports` associated with the unique `cred_id`
215    /// /// from the database.
216    /// # #[cfg(all(feature = "bin", feature = "custom"))]
217    /// fn get_transports(cred_id: CredentialId<&[u8]>) -> Result<AuthTransports, DecodeAuthTransportsErr> {
218    ///     // ⋮
219    /// #     AuthTransports::decode(32)
220    /// }
221    /// let mut creds = AllowedCredentials::with_capacity(1);
222    /// assert!(creds.as_ref().is_empty());
223    /// // `CredentialId::try_from` only exists when `custom` is enabled; and even then, it is
224    /// // likely never needed since the `CredentialId` was originally sent from the client and is likely
225    /// // stored in a database which would be fetched by `UserHandle` or `Authentication::raw_id`.
226    /// # #[cfg(all(feature = "bin", feature = "custom"))]
227    /// let id = CredentialId::try_from(vec![0; 16].into_boxed_slice())?;
228    /// # #[cfg(all(feature = "bin", feature = "custom"))]
229    /// let transports = get_transports((&id).into())?;
230    /// # #[cfg(all(feature = "bin", feature = "custom"))]
231    /// assert!(creds.push(PublicKeyCredentialDescriptor { id, transports }.into()));
232    /// # #[cfg(all(feature = "bin", feature = "custom"))]
233    /// let id_copy = CredentialId::try_from(vec![0; 16].into_boxed_slice())?;
234    /// # #[cfg(all(feature = "bin", feature = "custom"))]
235    /// let transports_2 = AuthTransports::NONE;
236    /// // Duplicate `CredentialId`s don't get added.
237    /// # #[cfg(all(feature = "bin", feature = "custom"))]
238    /// assert!(!creds.push(
239    ///     PublicKeyCredentialDescriptor {
240    ///         id: id_copy,
241    ///         transports: transports_2
242    ///     }
243    ///     .into()
244    /// ));
245    /// # Ok::<_, structured_webauthn::AggErr>(())
246    /// ```
247    #[expect(
248        clippy::arithmetic_side_effects,
249        reason = "comment explains how overflow is not possible"
250    )]
251    #[inline]
252    fn push(&mut self, cred: Self::Credential) -> bool {
253        self.creds
254            .iter()
255            .try_fold((), |(), c| {
256                if c.credential.id == cred.credential.id {
257                    Err(())
258                } else {
259                    Ok(())
260                }
261            })
262            .is_ok_and(|()| {
263                // This can't overflow since `self.creds.push` would `panic` since
264                // `self.prf_count <= self.creds.len()`.
265                self.prf_count += usize::from(cred.extension.prf.is_some());
266                self.creds.push(cred);
267                true
268            })
269    }
270    #[inline]
271    fn len(&self) -> usize {
272        self.creds.len()
273    }
274}
275impl AsRef<[AllowedCredential]> for AllowedCredentials {
276    #[inline]
277    fn as_ref(&self) -> &[AllowedCredential] {
278        self.creds.as_slice()
279    }
280}
281impl From<&AllowedCredentials> for Box<[CredInfo]> {
282    #[inline]
283    fn from(value: &AllowedCredentials) -> Self {
284        let len = value.creds.len();
285        value
286            .creds
287            .iter()
288            .fold(Vec::with_capacity(len), |mut creds, cred| {
289                creds.push(CredInfo {
290                    id: cred.credential.id.clone(),
291                    ext: (&cred.extension).into(),
292                });
293                creds
294            })
295            .into_boxed_slice()
296    }
297}
298impl From<AllowedCredentials> for Vec<PublicKeyCredentialDescriptor<Box<[u8]>>> {
299    #[inline]
300    fn from(value: AllowedCredentials) -> Self {
301        let mut creds = Self::with_capacity(value.creds.len());
302        value.creds.into_iter().fold((), |(), cred| {
303            creds.push(cred.credential);
304        });
305        creds
306    }
307}
308impl From<Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>> for AllowedCredentials {
309    #[inline]
310    fn from(value: Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>) -> Self {
311        let mut creds = Self::with_capacity(value.len());
312        value.into_iter().fold((), |(), credential| {
313            _ = creds.push(AllowedCredential {
314                credential,
315                extension: CredentialSpecificExtension { prf: None },
316            });
317        });
318        creds
319    }
320}
321/// Helper that verifies the overlap of [`DiscoverableCredentialRequestOptions::start_ceremony`] and
322/// [`DiscoverableAuthenticationServerState::decode`].
323///
324/// Returns `true` iff the options are valid.
325const fn validate_discoverable_options_helper(
326    ext: ServerExtensionInfo,
327    uv: UserVerificationRequirement,
328) -> bool {
329    // If PRF is set, the user has to verify themselves.
330    matches!(ext.prf, ServerPrfInfo::None) || matches!(uv, UserVerificationRequirement::Required)
331}
332/// Helper that verifies the overlap of [`NonDiscoverableCredentialRequestOptions::start_ceremony`] and
333/// [`NonDiscoverableAuthenticationServerState::decode`].
334fn validate_non_discoverable_options_helper(
335    uv: UserVerificationRequirement,
336    creds: &[CredInfo],
337) -> Result<(), NonDiscoverableCredentialRequestOptionsErr> {
338    creds.iter().try_fold((), |(), cred| {
339        // If PRF is set, the user has to verify themselves.
340        if matches!(cred.ext.prf, ServerPrfInfo::None)
341            || matches!(uv, UserVerificationRequirement::Required)
342        {
343            Ok(())
344        } else {
345            Err(NonDiscoverableCredentialRequestOptionsErr::PrfWithoutUserVerification)
346        }
347    })
348}
349/// [`CredentialUiMode`](https://www.w3.org/TR/credential-management-1/#enumdef-credentialuimode)
350#[derive(Clone, Copy, Debug, Eq, PartialEq)]
351pub enum CredentialUiMode {
352    /// [`immediate`](https://www.w3.org/TR/credential-management-1/#dom-credentialuimode-immediate).
353    Immediate,
354}
355/// The [`CredentialRequestOptions`](https://www.w3.org/TR/credential-management-1/#dictdef-credentialrequestoptions)
356/// to send to the client when authenticating a discoverable credential.
357///
358/// Upon saving the [`DiscoverableAuthenticationServerState`] returned from [`Self::start_ceremony`], one MUST send
359/// [`DiscoverableAuthenticationClientState`] to the client ASAP. After receiving the newly created
360/// [`DiscoverableAuthentication`], it is validated using [`DiscoverableAuthenticationServerState::verify`].
361#[derive(Debug)]
362pub struct DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
363    /// [`mediation`](https://www.w3.org/TR/credential-management-1/#dom-credentialrequestoptions-mediation).
364    ///
365    /// Note if this is [`CredentialMediationRequirement::Conditional`], user agents are instructed to not
366    /// enforce any timeout; as result, one may want to set [`PublicKeyCredentialRequestOptions::timeout`] to
367    /// [`NonZeroU32::MAX`].
368    pub mediation: CredentialMediationRequirement,
369    /// [`uiMode`](https://www.w3.org/TR/credential-management-1/#dom-credentialrequestoptions-uimode).
370    pub ui_mode: Option<CredentialUiMode>,
371    /// `public-key` [credential type](https://www.w3.org/TR/credential-management-1/#sctn-cred-type-registry).
372    pub public_key: PublicKeyCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
373}
374impl<'rp_id, 'prf_first, 'prf_second>
375    DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>
376{
377    /// Creates a `DiscoverableCredentialRequestOptions` containing [`CredentialMediationRequirement::default`] and
378    /// [`PublicKeyCredentialRequestOptions::passkey`].
379    ///
380    /// # Examples
381    ///
382    /// ```
383    /// # use structured_webauthn::request::{auth::DiscoverableCredentialRequestOptions, AsciiDomain, RpId, UserVerificationRequirement};
384    /// assert!(matches!(
385    ///     DiscoverableCredentialRequestOptions::passkey(&RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?)).public_key.user_verification,
386    ///     UserVerificationRequirement::Required
387    /// ));
388    /// # Ok::<_, structured_webauthn::AggErr>(())
389    /// ```
390    #[inline]
391    #[must_use]
392    pub fn passkey<'a: 'rp_id>(rp_id: &'a RpId) -> Self {
393        Self {
394            mediation: CredentialMediationRequirement::default(),
395            ui_mode: None,
396            public_key: PublicKeyCredentialRequestOptions::passkey(rp_id),
397        }
398    }
399    /// Begins the [authentication ceremony](https://www.w3.org/TR/webauthn-3/#authentication-ceremony) consuming
400    /// `self`. Note that the expiration [`Instant`]/[`SystemTime`] is saved, so
401    /// `DiscoverableAuthenticationClientState` MUST be sent ASAP. In order to complete authentication, the returned
402    /// `DiscoverableAuthenticationServerState` MUST be saved so that it can later be used to verify the credential
403    /// assertion with [`DiscoverableAuthenticationServerState::verify`].
404    ///
405    /// # Errors
406    ///
407    /// Errors iff `self` contains incompatible configuration.
408    #[inline]
409    pub fn start_ceremony(
410        self,
411    ) -> Result<
412        (
413            DiscoverableAuthenticationServerState,
414            DiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>,
415        ),
416        DiscoverableCredentialRequestOptionsErr,
417    > {
418        let extensions = self.public_key.extensions.into();
419        if validate_discoverable_options_helper(extensions, self.public_key.user_verification) {
420            #[cfg(not(feature = "serializable_server_state"))]
421            let res = Instant::now();
422            #[cfg(feature = "serializable_server_state")]
423            let res = SystemTime::now();
424            res.checked_add(Duration::from_millis(
425                NonZeroU64::from(self.public_key.timeout).get(),
426            ))
427            .ok_or(DiscoverableCredentialRequestOptionsErr::InvalidTimeout)
428            .map(|expiration| {
429                (
430                    DiscoverableAuthenticationServerState(AuthenticationServerState {
431                        challenge: SentChallenge(self.public_key.challenge.0),
432                        user_verification: self.public_key.user_verification,
433                        extensions,
434                        expiration,
435                    }),
436                    DiscoverableAuthenticationClientState(self),
437                )
438            })
439        } else {
440            Err(DiscoverableCredentialRequestOptionsErr::PrfWithoutUserVerification)
441        }
442    }
443    /// Same as [`Self::start_ceremony`] except the raw challenge is returned instead of
444    /// [`DiscoverableAuthenticationClientState`].
445    ///
446    /// Note this is useful when one configures the authentication ceremony client-side and only needs the
447    /// server-generated challenge. It's of course essential that `self` is configured exactly the same as
448    /// how it is configured client-side. See
449    /// [`challengeURL`](https://github.com/w3c/webauthn/wiki/Explainer:-WebAuthn-challengeURL) for more
450    /// information.
451    ///
452    /// # Errors
453    ///
454    /// Read [`Self::start_ceremony`].
455    #[inline]
456    pub fn start_ceremony_challenge_only(
457        self,
458    ) -> Result<
459        (DiscoverableAuthenticationServerState, [u8; 16]),
460        DiscoverableCredentialRequestOptionsErr,
461    > {
462        self.start_ceremony()
463            .map(|(server, client)| (server, client.0.public_key.challenge.into_array()))
464    }
465}
466/// The [`CredentialRequestOptions`](https://www.w3.org/TR/credential-management-1/#dictdef-credentialrequestoptions)
467/// to send to the client when authenticating non-discoverable credentials.
468///
469/// Upon saving the [`NonDiscoverableAuthenticationServerState`] returned from [`Self::start_ceremony`], one MUST send
470/// [`NonDiscoverableAuthenticationClientState`] to the client ASAP. After receiving the newly created
471/// [`NonDiscoverableAuthentication`], it is validated using [`NonDiscoverableAuthenticationServerState::verify`].
472#[derive(Debug)]
473pub struct NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
474    /// [`mediation`](https://www.w3.org/TR/credential-management-1/#dom-credentialrequestoptions-mediation).
475    pub mediation: CredentialMediationRequirement,
476    /// [`PublicKeyCredentialRequestOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialrequestoptions).
477    pub options: PublicKeyCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
478    /// [`allowCredentials`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-allowcredentials).
479    pub allow_credentials: AllowedCredentials,
480}
481impl<'rp_id, 'prf_first, 'prf_second>
482    NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>
483{
484    /// Creates a `NonDiscoverableCredentialRequestOptions` containing
485    /// [`CredentialMediationRequirement::default`],
486    /// [`PublicKeyCredentialRequestOptions::second_factor`], and the passed [`AllowedCredentials`].
487    ///
488    /// # Examples
489    ///
490    /// ```
491    /// # #[cfg(all(feature = "bin", feature = "custom"))]
492    /// # use structured_webauthn::{bin::Decode, response::bin::DecodeAuthTransportsErr};
493    /// # use structured_webauthn::{
494    /// #     request::{
495    /// #         auth::{AllowedCredentials, NonDiscoverableCredentialRequestOptions},
496    /// #         AsciiDomain, RpId, PublicKeyCredentialDescriptor, Credentials
497    /// #     },
498    /// #     response::{AuthTransports, CredentialId},
499    /// # };
500    /// /// Retrieves the `AuthTransports` associated with the unique `cred_id`
501    /// /// from the database.
502    /// # #[cfg(all(feature = "bin", feature = "custom"))]
503    /// fn get_transports(cred_id: CredentialId<&[u8]>) -> Result<AuthTransports, DecodeAuthTransportsErr> {
504    ///     // ⋮
505    /// #     AuthTransports::decode(32)
506    /// }
507    /// let mut creds = AllowedCredentials::with_capacity(1);
508    /// assert!(creds.as_ref().is_empty());
509    /// // `CredentialId::try_from` only exists when `custom` is enabled; and even then, it is
510    /// // likely never needed since the `CredentialId` was originally sent from the client and is likely
511    /// // stored in a database which would be fetched by `UserHandle` or `Authentication::raw_id`.
512    /// # #[cfg(all(feature = "bin", feature = "custom"))]
513    /// let id = CredentialId::try_from(vec![0; 16].into_boxed_slice())?;
514    /// # #[cfg(all(feature = "bin", feature = "custom"))]
515    /// let transports = get_transports((&id).into())?;
516    /// # #[cfg(all(feature = "bin", feature = "custom"))]
517    /// assert!(creds.push(PublicKeyCredentialDescriptor { id, transports }.into()));
518    /// # #[cfg(all(feature = "bin", feature = "custom"))]
519    /// assert_eq!(
520    ///     NonDiscoverableCredentialRequestOptions::second_factor(&RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?), creds)
521    ///         .allow_credentials
522    ///         .len(),
523    ///     1
524    /// );
525    /// # Ok::<_, structured_webauthn::AggErr>(())
526    /// ```
527    #[inline]
528    #[must_use]
529    pub fn second_factor<'a: 'rp_id>(
530        rp_id: &'a RpId,
531        allow_credentials: AllowedCredentials,
532    ) -> Self {
533        Self {
534            mediation: CredentialMediationRequirement::default(),
535            options: PublicKeyCredentialRequestOptions::second_factor(rp_id),
536            allow_credentials,
537        }
538    }
539    /// Begins the [authentication ceremony](https://www.w3.org/TR/webauthn-3/#authentication-ceremony) consuming
540    /// `self`. Note that the expiration [`Instant`]/[`SystemTime`] is saved, so `NonDiscoverableAuthenticationClientState`
541    /// MUST be sent ASAP. In order to complete authentication, the returned `NonDiscoverableAuthenticationServerState`
542    /// MUST be saved so that it can later be used to verify the credential assertion with
543    /// [`NonDiscoverableAuthenticationServerState::verify`].
544    ///
545    /// # Errors
546    ///
547    /// Errors iff `self` contains incompatible configuration.
548    #[inline]
549    pub fn start_ceremony(
550        self,
551    ) -> Result<
552        (
553            NonDiscoverableAuthenticationServerState,
554            NonDiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>,
555        ),
556        NonDiscoverableCredentialRequestOptionsErr,
557    > {
558        if self.allow_credentials.is_empty() {
559            Err(NonDiscoverableCredentialRequestOptionsErr::EmptyAllowedCredentials)
560        } else if matches!(self.mediation, CredentialMediationRequirement::Conditional) {
561            Err(NonDiscoverableCredentialRequestOptionsErr::ConditionalMediationRequested)
562        } else {
563            let extensions = self.options.extensions.into();
564            if validate_discoverable_options_helper(extensions, self.options.user_verification) {
565                let allow_credentials = Box::from(&self.allow_credentials);
566                validate_non_discoverable_options_helper(
567                    self.options.user_verification,
568                    &allow_credentials,
569                )
570                .and_then(|()| {
571                    #[cfg(not(feature = "serializable_server_state"))]
572                    let res = Instant::now();
573                    #[cfg(feature = "serializable_server_state")]
574                    let res = SystemTime::now();
575                    res.checked_add(Duration::from_millis(
576                        NonZeroU64::from(self.options.timeout).get(),
577                    ))
578                    .ok_or(NonDiscoverableCredentialRequestOptionsErr::InvalidTimeout)
579                    .map(|expiration| {
580                        (
581                            NonDiscoverableAuthenticationServerState {
582                                state: AuthenticationServerState {
583                                    challenge: SentChallenge(self.options.challenge.0),
584                                    user_verification: self.options.user_verification,
585                                    extensions,
586                                    expiration,
587                                },
588                                allow_credentials,
589                            },
590                            NonDiscoverableAuthenticationClientState(self),
591                        )
592                    })
593                })
594            } else {
595                Err(NonDiscoverableCredentialRequestOptionsErr::PrfWithoutUserVerification)
596            }
597        }
598    }
599}
600/// The [`PublicKeyCredentialRequestOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialrequestoptions)
601/// to send to the client when authenticating a credential.
602///
603/// This does _not_ contain [`allowCredentials`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-allowcredentials).
604#[derive(Debug)]
605pub struct PublicKeyCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
606    /// [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-challenge).
607    pub challenge: Challenge,
608    /// [`timeout`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-timeout).
609    ///
610    /// Note we require a positive value despite the spec allowing an optional nonnegative value. This jives
611    /// with the fact that in-memory storage is required when `serializable_server_state` is not enabled
612    /// when authenticating credentials as no timeout would make out-of-memory (OOM) conditions more likely.
613    pub timeout: NonZeroU32,
614    /// [`rpId`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-rpid).
615    ///
616    /// This MUST be the same as the [`PublicKeyCredentialCreationOptions::rp_id`] used when the credential was registered.
617    pub rp_id: &'rp_id RpId,
618    /// [`userVerification`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-userverification).
619    pub user_verification: UserVerificationRequirement,
620    /// [`hints`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-hints).
621    pub hints: Hints,
622    /// [`extensions`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-extensions).
623    pub extensions: Extension<'prf_first, 'prf_second>,
624}
625impl<'rp_id> PublicKeyCredentialRequestOptions<'rp_id, '_, '_> {
626    /// Creates a `PublicKeyCredentialRequestOptions` with [`Self::user_verification`] set to
627    /// [`UserVerificationRequirement::Required`] and [`Self::timeout`] set to [`FIVE_MINUTES`].
628    ///
629    /// Note `rp_id` _must_ be the same as the [`PublicKeyCredentialCreationOptions::rp_id`] when the
630    /// credential was registered.
631    ///
632    /// # Examples
633    ///
634    /// ```
635    /// # use structured_webauthn::request::{auth::PublicKeyCredentialRequestOptions, AsciiDomain, RpId, UserVerificationRequirement};
636    /// assert!(matches!(
637    ///     PublicKeyCredentialRequestOptions::passkey(&RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?)).user_verification,
638    ///     UserVerificationRequirement::Required
639    /// ));
640    /// # Ok::<_, structured_webauthn::AggErr>(())
641    /// ```
642    #[inline]
643    #[must_use]
644    pub fn passkey<'a: 'rp_id>(rp_id: &'a RpId) -> Self {
645        Self {
646            challenge: Challenge::new(),
647            timeout: FIVE_MINUTES,
648            rp_id,
649            user_verification: UserVerificationRequirement::Required,
650            hints: Hints::EMPTY,
651            extensions: Extension::default(),
652        }
653    }
654    /// Creates a `PublicKeyCredentialRequestOptions` with [`Self::user_verification`] set to
655    /// [`UserVerificationRequirement::Discouraged`] and [`Self::timeout`] set to [`FIVE_MINUTES`].
656    ///
657    /// Note `rp_id` _must_ be the same as the [`PublicKeyCredentialCreationOptions::rp_id`] when the
658    /// credentials were registered.
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// # use structured_webauthn::request::{auth::PublicKeyCredentialRequestOptions, AsciiDomain, RpId, UserVerificationRequirement};
664    /// assert!(matches!(
665    ///     PublicKeyCredentialRequestOptions::second_factor(&RpId::Domain(AsciiDomain::try_from("example.com".to_owned())?)).user_verification,
666    ///     UserVerificationRequirement::Discouraged
667    /// ));
668    /// # Ok::<_, structured_webauthn::AggErr>(())
669    /// ```
670    #[inline]
671    #[must_use]
672    pub fn second_factor<'a: 'rp_id>(rp_id: &'a RpId) -> Self {
673        let mut opts = Self::passkey(rp_id);
674        opts.user_verification = UserVerificationRequirement::Discouraged;
675        opts
676    }
677}
678/// Container of a [`DiscoverableCredentialRequestOptions`] that has been used to start the authentication ceremony.
679/// This gets sent to the client ASAP.
680#[derive(Debug)]
681pub struct DiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>(
682    DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
683);
684impl<'rp_id, 'prf_first, 'prf_second>
685    DiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>
686{
687    /// Returns the `DiscoverableCredentialRequestOptions` that was used to start an authentication ceremony.
688    #[inline]
689    #[must_use]
690    pub const fn options(
691        &self,
692    ) -> &DiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
693        &self.0
694    }
695}
696/// Container of a [`NonDiscoverableCredentialRequestOptions`] that has been used to start the authentication
697/// ceremony. This gets sent to the client ASAP.
698#[derive(Debug)]
699pub struct NonDiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>(
700    NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second>,
701);
702impl<'rp_id, 'prf_first, 'prf_second>
703    NonDiscoverableAuthenticationClientState<'rp_id, 'prf_first, 'prf_second>
704{
705    /// Returns the `NonDiscoverableCredentialRequestOptions` that was used to start an authentication ceremony.
706    #[inline]
707    #[must_use]
708    pub const fn options(
709        &self,
710    ) -> &NonDiscoverableCredentialRequestOptions<'rp_id, 'prf_first, 'prf_second> {
711        &self.0
712    }
713}
714/// The possible combinations of an [`AuthenticatedCredential`]'s [`StaticState`]'s
715/// `extensions.hmac_secret` and `client_extension_results.prf`.
716///
717/// Note we ensure in `crate::verify_static_and_dynamic_state` that `hmac_secret` does not exist when
718/// `prf` does not exist, `hmac_secret` does not exist or is `false` when `prf` is `false`, or
719/// `hmac_secret` does not exist or is `true` when `prf` is `true`.
720#[derive(Clone, Copy)]
721enum CredPrf {
722    /// No `prf` or `hmac_secret`.
723    None,
724    /// `prf.enabled` is `false` but there is no `hmac_secret`.
725    FalseNoHmac,
726    /// `prf.enabled` and `hmac_secret` are `false`.
727    FalseFalseHmac,
728    /// `prf.enabled` is `true` but there is no `hmac_secret`.
729    TrueNoHmac,
730    /// `prf.enabled` and `hmac_secret` are `true`.
731    TrueTrueHmac,
732}
733/// `PrfInput` and `PrfInputOwned` without the actual data sent to reduce memory usage when storing
734/// [`DiscoverableAuthenticationServerState`] in an in-memory collection.
735#[derive(Clone, Copy, Debug)]
736enum ServerPrfInfo {
737    /// No `PrfInput`.
738    None,
739    /// `PrfInput::second` was `None`.
740    One(ExtensionReq),
741    /// `PrfInput::second` was `Some`.
742    Two(ExtensionReq),
743}
744impl ServerPrfInfo {
745    /// Validates `val` based on the passed arguments.
746    ///
747    /// It's not possible to request the PRF extension without sending `UserVerificationRequirement::Required`;
748    /// thus `user_verified` will always be `true` when sending PRF; otherwise ceremony validation will error.
749    /// However when we _don't_ send the PRF extension _and_ we don't error on an unsolicited response, it's
750    /// possible to receive an `HmacSecret` without the user having been verified; thus we only ensure
751    /// `user_verified` is true when we don't error on unsolicted responses _and_ we didn't send the PRF extension.
752    const fn validate(
753        self,
754        user_verified: bool,
755        cred_prf: CredPrf,
756        hmac: HmacSecret,
757        err_unsolicited: bool,
758    ) -> Result<(), ExtensionErr> {
759        match hmac {
760            HmacSecret::None => match self {
761                Self::None => Ok(()),
762                Self::One(req) | Self::Two(req) => {
763                    if matches!(req, ExtensionReq::Allow)
764                        || !matches!(cred_prf, CredPrf::TrueTrueHmac)
765                    {
766                        Ok(())
767                    } else {
768                        Err(ExtensionErr::MissingHmacSecret)
769                    }
770                }
771            },
772            HmacSecret::One => match self {
773                Self::None => {
774                    if err_unsolicited {
775                        Err(ExtensionErr::ForbiddenHmacSecret)
776                    } else if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
777                        if user_verified {
778                            Ok(())
779                        } else {
780                            Err(ExtensionErr::UserNotVerifiedHmacSecret)
781                        }
782                    } else {
783                        Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
784                    }
785                }
786                Self::One(_) => {
787                    if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
788                        Ok(())
789                    } else {
790                        Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
791                    }
792                }
793                Self::Two(_) => Err(ExtensionErr::InvalidHmacSecretValue(
794                    OneOrTwo::Two,
795                    OneOrTwo::One,
796                )),
797            },
798            HmacSecret::Two => match self {
799                Self::None => {
800                    if err_unsolicited {
801                        Err(ExtensionErr::ForbiddenHmacSecret)
802                    } else if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
803                        if user_verified {
804                            Ok(())
805                        } else {
806                            Err(ExtensionErr::UserNotVerifiedHmacSecret)
807                        }
808                    } else {
809                        Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
810                    }
811                }
812                Self::One(_) => Err(ExtensionErr::InvalidHmacSecretValue(
813                    OneOrTwo::One,
814                    OneOrTwo::Two,
815                )),
816                Self::Two(_) => {
817                    if matches!(cred_prf, CredPrf::None | CredPrf::TrueTrueHmac) {
818                        Ok(())
819                    } else {
820                        Err(ExtensionErr::HmacSecretForNonHmacSecretCredential)
821                    }
822                }
823            },
824        }
825    }
826}
827#[cfg(test)]
828impl PartialEq for ServerPrfInfo {
829    fn eq(&self, other: &Self) -> bool {
830        match *self {
831            Self::None => matches!(*other, Self::None),
832            Self::One(req) => matches!(*other, Self::One(req2) if req == req2),
833            Self::Two(req) => matches!(*other, Self::Two(req2) if req == req2),
834        }
835    }
836}
837impl From<Option<(PrfInput<'_, '_>, ExtensionReq)>> for ServerPrfInfo {
838    fn from(value: Option<(PrfInput<'_, '_>, ExtensionReq)>) -> Self {
839        value.map_or(Self::None, |val| {
840            val.0
841                .second
842                .map_or_else(|| Self::One(val.1), |_| Self::Two(val.1))
843        })
844    }
845}
846impl From<&PrfInputOwned> for ServerPrfInfo {
847    fn from(value: &PrfInputOwned) -> Self {
848        value
849            .second
850            .as_ref()
851            .map_or_else(|| Self::One(value.ext_req), |_| Self::Two(value.ext_req))
852    }
853}
854/// `Extension` without the actual data sent to reduce memory usage when storing [`AuthenticationServerState`]
855/// in an in-memory collection.
856#[derive(Clone, Copy, Debug)]
857struct ServerExtensionInfo {
858    /// `Extension::prf`.
859    prf: ServerPrfInfo,
860}
861impl From<Extension<'_, '_>> for ServerExtensionInfo {
862    fn from(value: Extension<'_, '_>) -> Self {
863        Self {
864            prf: value.prf.into(),
865        }
866    }
867}
868#[cfg(test)]
869impl PartialEq for ServerExtensionInfo {
870    fn eq(&self, other: &Self) -> bool {
871        self.prf == other.prf
872    }
873}
874/// `CredentialSpecificExtension` without the actual data sent to reduce memory usage when storing [`AuthenticationServerState`]
875/// in an in-memory collection.
876#[derive(Clone, Copy, Debug)]
877struct ServerCredSpecificExtensionInfo {
878    /// `CredentialSpecificExtension::prf`.
879    prf: ServerPrfInfo,
880}
881#[cfg(test)]
882impl PartialEq for ServerCredSpecificExtensionInfo {
883    fn eq(&self, other: &Self) -> bool {
884        self.prf == other.prf
885    }
886}
887impl From<&CredentialSpecificExtension> for ServerCredSpecificExtensionInfo {
888    fn from(value: &CredentialSpecificExtension) -> Self {
889        Self {
890            prf: value
891                .prf
892                .as_ref()
893                .map_or(ServerPrfInfo::None, ServerPrfInfo::from),
894        }
895    }
896}
897impl ServerExtensionInfo {
898    /// Validates the extensions.
899    ///
900    /// Note that this MUST only be called internally by `auth::validate_extensions`.
901    const fn validate_extensions(
902        self,
903        user_verified: bool,
904        auth_ext: AuthenticatorExtensionOutput,
905        error_unsolicited: bool,
906        cred_prf: CredPrf,
907    ) -> Result<(), ExtensionErr> {
908        ServerPrfInfo::validate(
909            self.prf,
910            user_verified,
911            cred_prf,
912            auth_ext.hmac_secret,
913            error_unsolicited,
914        )
915    }
916}
917/// Validates the extensions.
918fn validate_extensions(
919    ext: ServerExtensionInfo,
920    user_verified: bool,
921    cred_ext: Option<ServerCredSpecificExtensionInfo>,
922    auth_ext: AuthenticatorExtensionOutput,
923    error_unsolicited: bool,
924    cred_prf: CredPrf,
925) -> Result<(), ExtensionErr> {
926    cred_ext.map_or_else(
927        || {
928            // No credental-specific extensions, so we can simply focus on `ext`.
929            ext.validate_extensions(user_verified, auth_ext, error_unsolicited, cred_prf)
930        },
931        |c_ext| {
932            // Must carefully process each extension based on overlap and which gets priority over the other.
933            if matches!(c_ext.prf, ServerPrfInfo::None) {
934                ext.prf.validate(
935                    user_verified,
936                    cred_prf,
937                    auth_ext.hmac_secret,
938                    error_unsolicited,
939                )
940            } else {
941                c_ext.prf.validate(
942                    user_verified,
943                    cred_prf,
944                    auth_ext.hmac_secret,
945                    error_unsolicited,
946                )
947            }
948        },
949    )
950}
951/// [`AllowedCredential`] with less data to reduce memory usage when storing [`AuthenticationServerState`]
952/// in an in-memory collection.
953#[derive(Debug)]
954struct CredInfo {
955    /// The Credential ID.
956    id: CredentialId<Box<[u8]>>,
957    /// Any credential-specific extensions.
958    ext: ServerCredSpecificExtensionInfo,
959}
960#[cfg(test)]
961impl PartialEq for CredInfo {
962    fn eq(&self, other: &Self) -> bool {
963        self.id == other.id && self.ext == other.ext
964    }
965}
966/// Controls how to handle a change in [`DynamicState::authenticator_attachment`].
967///
968/// Note when `DynamicState::authenticator_attachment` is [`AuthenticatorAttachment::None`], then it will
969/// be updated regardless. Similarly when [`Authentication::authenticator_attachment`] is
970/// `AuthenticatorAttachment::None`, it will never update `DynamicState::authenticator_attachment`.
971#[derive(Clone, Copy, Debug, Eq, PartialEq)]
972pub enum AuthenticatorAttachmentEnforcement {
973    /// Fail the authentication ceremony if [`AuthenticatorAttachment`] is not the same.
974    ///
975    /// The contained `bool` represents if `AuthenticatorAttachment` must be sent.
976    Fail(bool),
977    /// Update [`DynamicState::authenticator_attachment`] to the sent [`AuthenticatorAttachment`].
978    ///
979    /// The contained `bool` represents if `AuthenticatorAttachment` must be sent.
980    Update(bool),
981    /// Do not update [`DynamicState::authenticator_attachment`] to the sent [`AuthenticatorAttachment`].
982    ///
983    /// The contained `bool` represents if `AuthenticatorAttachment` must be sent.
984    Ignore(bool),
985}
986impl AuthenticatorAttachmentEnforcement {
987    /// Validates `cur` based on `self` and `prev`.
988    const fn validate(
989        self,
990        prev: AuthenticatorAttachment,
991        cur: AuthenticatorAttachment,
992    ) -> Result<AuthenticatorAttachment, AuthCeremonyErr> {
993        match cur {
994            AuthenticatorAttachment::None => match self {
995                Self::Fail(require) | Self::Update(require) | Self::Ignore(require) => {
996                    if require {
997                        Err(AuthCeremonyErr::MissingAuthenticatorAttachment)
998                    } else {
999                        // We don't overwrite the previous one with [`AuthenticatorAttachment::None`].
1000                        Ok(prev)
1001                    }
1002                }
1003            },
1004            AuthenticatorAttachment::Platform => match self {
1005                Self::Fail(_) => {
1006                    if matches!(prev, AuthenticatorAttachment::CrossPlatform) {
1007                        Err(AuthCeremonyErr::AuthenticatorAttachmentMismatch)
1008                    } else {
1009                        // We don't fail when we previously had [`AuthenticatorAttachment::None`].
1010                        Ok(cur)
1011                    }
1012                }
1013                Self::Update(_) => Ok(cur),
1014                Self::Ignore(_) => {
1015                    if matches!(prev, AuthenticatorAttachment::None) {
1016                        // We overwrite the previous one when it is [`AuthenticatorAttachment::None`].
1017                        Ok(cur)
1018                    } else {
1019                        Ok(prev)
1020                    }
1021                }
1022            },
1023            AuthenticatorAttachment::CrossPlatform => match self {
1024                Self::Fail(_) => {
1025                    if matches!(prev, AuthenticatorAttachment::Platform) {
1026                        Err(AuthCeremonyErr::AuthenticatorAttachmentMismatch)
1027                    } else {
1028                        // We don't fail when we previously had [`AuthenticatorAttachment::None`].
1029                        Ok(cur)
1030                    }
1031                }
1032                Self::Update(_) => Ok(cur),
1033                Self::Ignore(_) => {
1034                    if matches!(prev, AuthenticatorAttachment::None) {
1035                        // We overwrite the previous one when it is [`AuthenticatorAttachment::None`].
1036                        Ok(cur)
1037                    } else {
1038                        Ok(prev)
1039                    }
1040                }
1041            },
1042        }
1043    }
1044}
1045impl Default for AuthenticatorAttachmentEnforcement {
1046    /// Returns [`Self::Ignore`] containing `false`.
1047    #[inline]
1048    fn default() -> Self {
1049        Self::Ignore(false)
1050    }
1051}
1052/// Backup state requirements for the credential.
1053///
1054/// Note the backup eligibility of a credential is not allowed to change. This is only used to allow one to
1055/// require the existence or lack of existence of a backup.
1056#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1057pub enum BackupStateReq {
1058    /// No requirements on the backup state.
1059    ///
1060    /// The backup eligibility of the credential must be the same as required by the spec, but the existence
1061    /// of a backup doesn't matter.
1062    #[default]
1063    None,
1064    /// Credential must be backed up.
1065    Exists,
1066    /// Credential must not be backed up.
1067    DoesntExist,
1068}
1069/// Additional verification options to perform in [`DiscoverableAuthenticationServerState::verify`] and
1070/// [`NonDiscoverableAuthenticationServerState::verify`].
1071#[derive(Clone, Copy, Debug)]
1072pub struct AuthenticationVerificationOptions<'origins, 'top_origins, O, T> {
1073    /// Origins to use for [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin).
1074    ///
1075    /// When this is empty, the origin that will be used will be based on the [`RpId`] passed to
1076    /// [`DiscoverableAuthenticationServerState::verify`] or [`NonDiscoverableAuthenticationServerState::verify`].
1077    /// If [`RpId::Domain`] or [`RpId::StaticDomain`], then the [`DomainOrigin`] returned from passing
1078    /// [`AsciiDomain::as_ref`] and [`AsciiDomainStatic::as_str`] to [`DomainOrigin::new`] respectively will be
1079    /// used; otherwise the [`Url`] in [`RpId::Url`] will be used.
1080    pub allowed_origins: &'origins [O],
1081    /// [Top-level origins](https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-top-level-origin)
1082    /// to use for [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin).
1083    ///
1084    /// When this is `Some`, [`CollectedClientData::cross_origin`] is allowed to be `true`. When the contained
1085    /// `slice` is empty, [`CollectedClientData::top_origin`] must be `None`. When this is `None`,
1086    /// `CollectedClientData::cross_origin` must be `false` and `CollectedClientData::top_origin` must be `None`.
1087    pub allowed_top_origins: Option<&'top_origins [T]>,
1088    /// The required [`Backup`] state of the credential.
1089    pub backup_state_requirement: BackupStateReq,
1090    /// Error when unsolicited extensions are sent back iff `true`.
1091    pub error_on_unsolicited_extensions: bool,
1092    /// Dictates what happens when [`Authentication::authenticator_attachment`] is not the same as
1093    /// [`DynamicState::authenticator_attachment`].
1094    pub auth_attachment_enforcement: AuthenticatorAttachmentEnforcement,
1095    /// [`DynamicState::user_verified`] will be set to `true` iff [`Flag::user_verified`] when `true`.
1096    pub update_uv: bool,
1097    /// Dictates what happens when [`AuthenticatorData::sign_count`] is not updated to a strictly greater value.
1098    pub sig_counter_enforcement: SignatureCounterEnforcement,
1099    /// [`CollectedClientData::from_client_data_json_relaxed`] is used to extract [`CollectedClientData`] iff `true`.
1100    #[cfg(feature = "serde_relaxed")]
1101    pub client_data_json_relaxed: bool,
1102}
1103impl<O, T> AuthenticationVerificationOptions<'_, '_, O, T> {
1104    /// Returns `Self` such that [`Self::allowed_origins`] is empty, [`Self::allowed_top_origins`] is `None`,
1105    /// [`Self::backup_state_requirement`] is [`BackupStateReq::None`], [`Self::error_on_unsolicited_extensions`] is
1106    /// `true`, [`Self::auth_attachment_enforcement`] is [`AuthenticatorAttachmentEnforcement::default`],
1107    /// [`Self::update_uv`] is `false`, [`Self::sig_counter_enforcement`] is
1108    /// [`SignatureCounterEnforcement::default`], and [`Self::client_data_json_relaxed`] is `true`.
1109    ///
1110    /// Note `O` and `T` should implement `PartialEq<Origin<'_>>` (e.g., `&str`).
1111    #[inline]
1112    #[must_use]
1113    pub const fn new() -> Self {
1114        Self {
1115            allowed_origins: [].as_slice(),
1116            allowed_top_origins: None,
1117            backup_state_requirement: BackupStateReq::None,
1118            error_on_unsolicited_extensions: true,
1119            auth_attachment_enforcement: AuthenticatorAttachmentEnforcement::Ignore(false),
1120            update_uv: false,
1121            sig_counter_enforcement: SignatureCounterEnforcement::Fail,
1122            #[cfg(feature = "serde_relaxed")]
1123            client_data_json_relaxed: true,
1124        }
1125    }
1126}
1127impl<O, T> Default for AuthenticationVerificationOptions<'_, '_, O, T> {
1128    /// Same as [`Self::new`].
1129    #[inline]
1130    fn default() -> Self {
1131        Self::new()
1132    }
1133}
1134// This is essentially the `DiscoverableCredentialRequestOptions` used to create it; however to reduce
1135// memory usage, we remove all unnecessary data making an instance of this 48 bytes in size
1136// `x86_64-unknown-linux-gnu` platforms.
1137//
1138/// State needed to be saved when beginning the authentication ceremony.
1139///
1140/// Saves the necessary information associated with the [`DiscoverableCredentialRequestOptions`] used to create it
1141/// via [`DiscoverableCredentialRequestOptions::start_ceremony`] so that authentication of a credential can be
1142/// performed with [`Self::verify`].
1143///
1144/// `DiscoverableAuthenticationServerState` implements [`Borrow`] of [`SentChallenge`]; thus to obtain the correct
1145/// `DiscoverableAuthenticationServerState` associated with a [`DiscoverableAuthentication`], one should use its
1146/// corresponding [`DiscoverableAuthentication::challenge`].
1147#[derive(Debug)]
1148pub struct DiscoverableAuthenticationServerState(AuthenticationServerState);
1149impl DiscoverableAuthenticationServerState {
1150    /// Verifies `response` is valid based on `self` consuming `self` and updating `cred`. Returns `true`
1151    /// iff `cred` was mutated.
1152    ///
1153    /// `rp_id` MUST be the same as the [`PublicKeyCredentialRequestOptions::rp_id`] used when starting the
1154    /// ceremony.
1155    ///
1156    /// It is _essential_ to save [`AuthenticatedCredential::dynamic_state`] overwriting the original value iff `Ok(true)`
1157    /// is returned.
1158    ///
1159    /// # Errors
1160    ///
1161    /// Errors iff `response` is not valid according to the
1162    /// [authentication ceremony](https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion) or violates any
1163    /// of the settings in `options`.
1164    #[inline]
1165    pub fn verify<
1166        'a,
1167        const USER_LEN: usize,
1168        O: PartialEq<Origin<'a>>,
1169        T: PartialEq<Origin<'a>>,
1170        MlDsa87Key: AsRef<[u8]>,
1171        MlDsa65Key: AsRef<[u8]>,
1172        MlDsa44Key: AsRef<[u8]>,
1173        EdKey: AsRef<[u8]>,
1174        P256Key: AsRef<[u8]>,
1175        P384Key: AsRef<[u8]>,
1176        RsaKey: AsRef<[u8]>,
1177    >(
1178        self,
1179        rp_id: &RpId,
1180        response: &'a DiscoverableAuthentication<USER_LEN>,
1181        cred: &mut AuthenticatedCredential<
1182            '_,
1183            '_,
1184            USER_LEN,
1185            CompressedPubKey<MlDsa87Key, MlDsa65Key, MlDsa44Key, EdKey, P256Key, P384Key, RsaKey>,
1186        >,
1187        options: &AuthenticationVerificationOptions<'_, '_, O, T>,
1188    ) -> Result<bool, AuthCeremonyErr> {
1189        // Step 6 item 2.
1190        if cred.user_id == response.response.user_handle() {
1191            // Step 6 item 2.
1192            if cred.id.as_ref() == response.raw_id.as_ref() {
1193                self.0.verify(rp_id, response, cred, options, None)
1194            } else {
1195                Err(AuthCeremonyErr::CredentialIdMismatch)
1196            }
1197        } else {
1198            Err(AuthCeremonyErr::UserHandleMismatch)
1199        }
1200    }
1201    #[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
1202    fn is_eq(&self, other: &Self) -> bool {
1203        self.0.is_eq(&other.0)
1204    }
1205}
1206// This is essentially the `NonDiscoverableCredentialRequestOptions` used to create it; however to reduce
1207// memory usage, we remove all unnecessary data making an instance of this as small as 64 bytes in size on
1208// `x86_64-unknown-linux-gnu` platforms. This does not include the size of each `CredInfo` which should exist
1209// elsewhere on the heap but obviously contributes memory overall.
1210/// State needed to be saved when beginning the authentication ceremony.
1211///
1212/// Saves the necessary information associated with the [`NonDiscoverableCredentialRequestOptions`] used to create
1213/// it via [`NonDiscoverableCredentialRequestOptions::start_ceremony`] so that authentication of a credential can be
1214/// performed with [`Self::verify`].
1215///
1216/// `NonDiscoverableAuthenticationServerState` implements [`Borrow`] of [`SentChallenge`]; thus to obtain the
1217/// correct `NonDiscoverableAuthenticationServerState` associated with a [`NonDiscoverableAuthentication`], one
1218/// should use its corresponding [`NonDiscoverableAuthentication::challenge`].
1219#[derive(Debug)]
1220pub struct NonDiscoverableAuthenticationServerState {
1221    /// Most server state.
1222    state: AuthenticationServerState,
1223    /// The set of credentials that are allowed.
1224    allow_credentials: Box<[CredInfo]>,
1225}
1226impl NonDiscoverableAuthenticationServerState {
1227    /// Verifies `response` is valid based on `self` consuming `self` and updating `cred`. Returns `true`
1228    /// iff `cred` was mutated.
1229    ///
1230    /// `rp_id` MUST be the same as the [`PublicKeyCredentialRequestOptions::rp_id`] used when starting the
1231    /// ceremony.
1232    ///
1233    /// It is _essential_ to save [`AuthenticatedCredential::dynamic_state`] overwriting the original value iff `Ok(true)`
1234    /// is returned.
1235    ///
1236    /// # Errors
1237    ///
1238    /// Errors iff `response` is not valid according to the
1239    /// [authentication ceremony](https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion) or violates any
1240    /// of the settings in `options`.
1241    #[inline]
1242    pub fn verify<
1243        'a,
1244        const USER_LEN: usize,
1245        O: PartialEq<Origin<'a>>,
1246        T: PartialEq<Origin<'a>>,
1247        MlDsa87Key: AsRef<[u8]>,
1248        MlDsa65Key: AsRef<[u8]>,
1249        MlDsa44Key: AsRef<[u8]>,
1250        EdKey: AsRef<[u8]>,
1251        P256Key: AsRef<[u8]>,
1252        P384Key: AsRef<[u8]>,
1253        RsaKey: AsRef<[u8]>,
1254    >(
1255        self,
1256        rp_id: &RpId,
1257        response: &'a NonDiscoverableAuthentication<USER_LEN>,
1258        cred: &mut AuthenticatedCredential<
1259            '_,
1260            '_,
1261            USER_LEN,
1262            CompressedPubKey<MlDsa87Key, MlDsa65Key, MlDsa44Key, EdKey, P256Key, P384Key, RsaKey>,
1263        >,
1264        options: &AuthenticationVerificationOptions<'_, '_, O, T>,
1265    ) -> Result<bool, AuthCeremonyErr> {
1266        response
1267            .response
1268            .user_handle()
1269            .as_ref()
1270            .map_or(Ok(()), |user| {
1271                // Step 6 item 1.
1272                if *user == cred.user_id() {
1273                    Ok(())
1274                } else {
1275                    Err(AuthCeremonyErr::UserHandleMismatch)
1276                }
1277            })
1278            .and_then(|()| {
1279                self.allow_credentials
1280                    .iter()
1281                    // Step 5.
1282                    .find(|c| c.id == response.raw_id)
1283                    .ok_or(AuthCeremonyErr::NoMatchingAllowedCredential)
1284                    .and_then(|c| {
1285                        // Step 6 item 1.
1286                        if c.id.as_ref() == cred.id.as_ref() {
1287                            self.state
1288                                .verify(rp_id, response, cred, options, Some(c.ext))
1289                        } else {
1290                            Err(AuthCeremonyErr::CredentialIdMismatch)
1291                        }
1292                    })
1293            })
1294    }
1295    #[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
1296    fn is_eq(&self, other: &Self) -> bool {
1297        self.state.is_eq(&other.state) && self.allow_credentials == other.allow_credentials
1298    }
1299}
1300// This is essentially the `PublicKeyCredentialRequestOptions` used to create it; however to reduce
1301// memory usage, we remove all unnecessary data making an instance of this 48 bytes in size on
1302// `x86_64-unknown-linux-gnu` platforms.
1303/// Shared state used by [`DiscoverableAuthenticationServerState`] and [`NonDiscoverableAuthenticationServerState`].
1304#[derive(Debug)]
1305struct AuthenticationServerState {
1306    // This is a `SentChallenge` since we need `AuthenticationServerState` to be fetchable after receiving the
1307    // response from the client. This response must obviously be constructable; thus its challenge is a
1308    // `SentChallenge`.
1309    //
1310    // This must never be mutated since we want to ensure it is actually a `Challenge` (which
1311    // can only be constructed via `Challenge::new`). This is guaranteed to be true iff
1312    // `serializable_server_state` is not enabled.
1313    /// [`challenge`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-challenge).
1314    challenge: SentChallenge,
1315    /// [`userVerification`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-userverification).
1316    user_verification: UserVerificationRequirement,
1317    /// [`extensions`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialrequestoptions-extensions).
1318    extensions: ServerExtensionInfo,
1319    /// `Instant` the ceremony expires.
1320    #[cfg(not(feature = "serializable_server_state"))]
1321    expiration: Instant,
1322    /// `SystemTime` the ceremony expires.
1323    #[cfg(feature = "serializable_server_state")]
1324    expiration: SystemTime,
1325}
1326impl AuthenticationServerState {
1327    /// Verifies `response` is valid based on `self` consuming `self` and updating `cred`. Returns `true`
1328    /// iff `cred` was mutated.
1329    ///
1330    /// `rp_id` MUST be the same as the [`PublicKeyCredentialRequestOptions::rp_id`] used when starting the
1331    /// ceremony.
1332    ///
1333    /// It is _essential_ to save [`AuthenticatedCredential::dynamic_state`] overwriting the original value iff `Ok(true)`
1334    /// is returned.
1335    ///
1336    /// # Errors
1337    ///
1338    /// Errors iff `response` is not valid according to the
1339    /// [authentication ceremony](https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion) or violates any
1340    /// of the settings in `options`.
1341    fn verify<
1342        'a,
1343        const USER_LEN: usize,
1344        const DISCOVERABLE: bool,
1345        O: PartialEq<Origin<'a>>,
1346        T: PartialEq<Origin<'a>>,
1347        MlDsa87Key: AsRef<[u8]>,
1348        MlDsa65Key: AsRef<[u8]>,
1349        MlDsa44Key: AsRef<[u8]>,
1350        EdKey: AsRef<[u8]>,
1351        P256Key: AsRef<[u8]>,
1352        P384Key: AsRef<[u8]>,
1353        RsaKey: AsRef<[u8]>,
1354    >(
1355        self,
1356        rp_id: &RpId,
1357        response: &'a Authentication<USER_LEN, DISCOVERABLE>,
1358        cred: &mut AuthenticatedCredential<
1359            '_,
1360            '_,
1361            USER_LEN,
1362            CompressedPubKey<MlDsa87Key, MlDsa65Key, MlDsa44Key, EdKey, P256Key, P384Key, RsaKey>,
1363        >,
1364        options: &AuthenticationVerificationOptions<'_, '_, O, T>,
1365        cred_ext: Option<ServerCredSpecificExtensionInfo>,
1366    ) -> Result<bool, AuthCeremonyErr> {
1367        // [Authentication ceremony](https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion)
1368        // is handled by:
1369        //
1370        // 1. Calling code.
1371        // 2. Client code and the construction of `resp` (hopefully via [`Authentication::deserialize`]).
1372        // 3. Client code and the construction of `resp` (hopefully via [`AuthenticatorAssertion::deserialize`]).
1373        // 4. Client code and the construction of `resp` (hopefully via [`ClientExtensionsOutputs::deserialize`]).
1374        // 5. [`NonDiscoverableAuthenticationServerState::verify`].
1375        // 6. [`DiscoverableAuthenticationServerState::verify`] and [`NonDiscoverableAuthenticationServerState::verify`].
1376        // 7. Informative only in that it defines variables.
1377        // 8. [`Self::partial_validate`].
1378        // 9. [`Self::partial_validate`].
1379        // 10. [`Self::partial_validate`].
1380        // 11. [`Self::partial_validate`].
1381        // 12. [`Self::partial_validate`].
1382        // 13. [`Self::partial_validate`].
1383        // 14. [`Self::partial_validate`].
1384        // 15. [`Self::partial_validate`].
1385        // 16. [`Self::partial_validate`].
1386        // 17. [`Self::partial_validate`].
1387        // 18. [`Self::partial_validate`].
1388        // 19. [`Self::partial_validate`].
1389        // 20. [`Self::partial_validate`].
1390        // 21. [`Self::partial_validate`].
1391        // 22. Below.
1392        // 23. Below.
1393        // 24. Below.
1394        // 25. Below.
1395
1396        // Steps 8–21.
1397        self.partial_validate(
1398            rp_id,
1399            response,
1400            (&cred.static_state.credential_public_key).into(),
1401            &CeremonyOptions {
1402                allowed_origins: options.allowed_origins,
1403                allowed_top_origins: options.allowed_top_origins,
1404                backup_requirement: if cred.dynamic_state.backup == Backup::NotEligible {
1405                    BackupReq::NotEligible
1406                } else {
1407                    match options.backup_state_requirement {
1408                        BackupStateReq::None => BackupReq::Eligible,
1409                        BackupStateReq::Exists => BackupReq::Exists,
1410                        BackupStateReq::DoesntExist => BackupReq::EligibleNotExists,
1411                    }
1412                },
1413                #[cfg(feature = "serde_relaxed")]
1414                client_data_json_relaxed: options.client_data_json_relaxed,
1415            },
1416        )
1417        .map_err(AuthCeremonyErr::from)
1418        .and_then(|auth_data| {
1419            options
1420                .auth_attachment_enforcement
1421                .validate(
1422                    cred.dynamic_state.authenticator_attachment,
1423                    response.authenticator_attachment,
1424                )
1425                .and_then(|auth_attachment| {
1426                    let flags = auth_data.flags();
1427                    // Step 23.
1428                    validate_extensions(
1429                        self.extensions,
1430                        flags.user_verified,
1431                        cred_ext,
1432                        auth_data.extensions(),
1433                        options.error_on_unsolicited_extensions,
1434                        cred.static_state.client_extension_results.prf.map_or(
1435                            CredPrf::None,
1436                            |prf| {
1437                                if prf.enabled {
1438                                    cred.static_state
1439                                        .extensions
1440                                        .hmac_secret
1441                                        .map_or(CredPrf::TrueNoHmac, |_| CredPrf::TrueTrueHmac)
1442                                } else {
1443                                    cred.static_state
1444                                        .extensions
1445                                        .hmac_secret
1446                                        .map_or(CredPrf::FalseNoHmac, |_| CredPrf::FalseFalseHmac)
1447                                }
1448                            },
1449                        ),
1450                    )
1451                    .map_err(AuthCeremonyErr::Extension)
1452                    .and_then(|()| {
1453                        // Step 22.
1454                        options
1455                            .sig_counter_enforcement
1456                            .validate(cred.dynamic_state.sign_count, auth_data.sign_count())
1457                            .and_then(|sig_counter| {
1458                                let prev_dyn_state = cred.dynamic_state;
1459                                // Step 24 item 2.
1460                                cred.dynamic_state.backup = flags.backup;
1461                                if options.update_uv && flags.user_verified {
1462                                    // Step 24 item 3.
1463                                    cred.dynamic_state.user_verified = true;
1464                                }
1465                                // Step 24 item 1.
1466                                cred.dynamic_state.sign_count = sig_counter;
1467                                cred.dynamic_state.authenticator_attachment = auth_attachment;
1468                                // Step 25.
1469                                if flags.user_verified {
1470                                    Ok(())
1471                                } else {
1472                                    match cred.static_state.extensions.cred_protect {
1473                                        CredentialProtectionPolicy::None | CredentialProtectionPolicy::UserVerificationOptional => Ok(()),
1474                                        CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIdList => {
1475                                            if DISCOVERABLE {
1476                                                Err(AuthCeremonyErr::DiscoverableCredProtectCredentialIdList)
1477                                            } else {
1478                                                Ok(())
1479                                            }
1480                                        }
1481                                        CredentialProtectionPolicy::UserVerificationRequired => {
1482                                            Err(AuthCeremonyErr::UserNotVerifiedCredProtectRequired)
1483                                        }
1484                                    }
1485                                }.inspect_err(|_| {
1486                                    cred.dynamic_state = prev_dyn_state;
1487                                }).map(|()| {
1488                                    prev_dyn_state != cred.dynamic_state
1489                                })
1490                            })
1491                    })
1492                })
1493        })
1494    }
1495    #[cfg(all(test, feature = "custom", feature = "serializable_server_state"))]
1496    fn is_eq(&self, other: &Self) -> bool {
1497        self.challenge == other.challenge
1498            && self.user_verification == other.user_verification
1499            && self.extensions == other.extensions
1500            && self.expiration == other.expiration
1501    }
1502}
1503impl TimedCeremony for AuthenticationServerState {
1504    #[cfg(any(doc, not(feature = "serializable_server_state")))]
1505    #[inline]
1506    fn expiration(&self) -> Instant {
1507        self.expiration
1508    }
1509    #[cfg(all(not(doc), feature = "serializable_server_state"))]
1510    #[inline]
1511    fn expiration(&self) -> SystemTime {
1512        self.expiration
1513    }
1514}
1515impl TimedCeremony for DiscoverableAuthenticationServerState {
1516    #[cfg(any(doc, not(feature = "serializable_server_state")))]
1517    #[inline]
1518    fn expiration(&self) -> Instant {
1519        self.0.expiration()
1520    }
1521    #[cfg(all(not(doc), feature = "serializable_server_state"))]
1522    #[inline]
1523    fn expiration(&self) -> SystemTime {
1524        self.0.expiration()
1525    }
1526}
1527impl TimedCeremony for NonDiscoverableAuthenticationServerState {
1528    #[cfg(any(doc, not(feature = "serializable_server_state")))]
1529    #[inline]
1530    fn expiration(&self) -> Instant {
1531        self.state.expiration()
1532    }
1533    #[cfg(all(not(doc), feature = "serializable_server_state"))]
1534    #[inline]
1535    fn expiration(&self) -> SystemTime {
1536        self.state.expiration()
1537    }
1538}
1539impl<const USER_LEN: usize, const DISCOVERABLE: bool> Ceremony<USER_LEN, DISCOVERABLE>
1540    for AuthenticationServerState
1541{
1542    type R = Authentication<USER_LEN, DISCOVERABLE>;
1543    fn rand_challenge(&self) -> SentChallenge {
1544        self.challenge
1545    }
1546    #[cfg(not(feature = "serializable_server_state"))]
1547    fn expiry(&self) -> Instant {
1548        self.expiration
1549    }
1550    #[cfg(feature = "serializable_server_state")]
1551    fn expiry(&self) -> SystemTime {
1552        self.expiration
1553    }
1554    fn user_verification(&self) -> UserVerificationRequirement {
1555        self.user_verification
1556    }
1557}
1558impl Borrow<SentChallenge> for AuthenticationServerState {
1559    #[inline]
1560    fn borrow(&self) -> &SentChallenge {
1561        &self.challenge
1562    }
1563}
1564impl PartialEq for AuthenticationServerState {
1565    #[inline]
1566    fn eq(&self, other: &Self) -> bool {
1567        self.challenge == other.challenge
1568    }
1569}
1570impl PartialEq<&Self> for AuthenticationServerState {
1571    #[inline]
1572    fn eq(&self, other: &&Self) -> bool {
1573        *self == **other
1574    }
1575}
1576impl PartialEq<AuthenticationServerState> for &AuthenticationServerState {
1577    #[inline]
1578    fn eq(&self, other: &AuthenticationServerState) -> bool {
1579        **self == *other
1580    }
1581}
1582impl Eq for AuthenticationServerState {}
1583impl Hash for AuthenticationServerState {
1584    #[inline]
1585    fn hash<H: Hasher>(&self, state: &mut H) {
1586        self.challenge.hash(state);
1587    }
1588}
1589impl PartialOrd for AuthenticationServerState {
1590    #[inline]
1591    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1592        Some(self.cmp(other))
1593    }
1594}
1595impl Ord for AuthenticationServerState {
1596    #[inline]
1597    fn cmp(&self, other: &Self) -> Ordering {
1598        self.challenge.cmp(&other.challenge)
1599    }
1600}
1601impl Borrow<SentChallenge> for DiscoverableAuthenticationServerState {
1602    #[inline]
1603    fn borrow(&self) -> &SentChallenge {
1604        self.0.borrow()
1605    }
1606}
1607impl PartialEq for DiscoverableAuthenticationServerState {
1608    #[inline]
1609    fn eq(&self, other: &Self) -> bool {
1610        self.0 == other.0
1611    }
1612}
1613impl PartialEq<&Self> for DiscoverableAuthenticationServerState {
1614    #[inline]
1615    fn eq(&self, other: &&Self) -> bool {
1616        self.0 == other.0
1617    }
1618}
1619impl PartialEq<DiscoverableAuthenticationServerState> for &DiscoverableAuthenticationServerState {
1620    #[inline]
1621    fn eq(&self, other: &DiscoverableAuthenticationServerState) -> bool {
1622        self.0 == other.0
1623    }
1624}
1625impl Eq for DiscoverableAuthenticationServerState {}
1626impl Hash for DiscoverableAuthenticationServerState {
1627    #[inline]
1628    fn hash<H: Hasher>(&self, state: &mut H) {
1629        self.0.hash(state);
1630    }
1631}
1632impl PartialOrd for DiscoverableAuthenticationServerState {
1633    #[inline]
1634    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1635        Some(self.cmp(other))
1636    }
1637}
1638impl Ord for DiscoverableAuthenticationServerState {
1639    #[inline]
1640    fn cmp(&self, other: &Self) -> Ordering {
1641        self.0.cmp(&other.0)
1642    }
1643}
1644impl Borrow<SentChallenge> for NonDiscoverableAuthenticationServerState {
1645    #[inline]
1646    fn borrow(&self) -> &SentChallenge {
1647        self.state.borrow()
1648    }
1649}
1650impl PartialEq for NonDiscoverableAuthenticationServerState {
1651    #[inline]
1652    fn eq(&self, other: &Self) -> bool {
1653        self.state == other.state
1654    }
1655}
1656impl PartialEq<&Self> for NonDiscoverableAuthenticationServerState {
1657    #[inline]
1658    fn eq(&self, other: &&Self) -> bool {
1659        self.state == other.state
1660    }
1661}
1662impl PartialEq<NonDiscoverableAuthenticationServerState>
1663    for &NonDiscoverableAuthenticationServerState
1664{
1665    #[inline]
1666    fn eq(&self, other: &NonDiscoverableAuthenticationServerState) -> bool {
1667        self.state == other.state
1668    }
1669}
1670impl Eq for NonDiscoverableAuthenticationServerState {}
1671impl Hash for NonDiscoverableAuthenticationServerState {
1672    #[inline]
1673    fn hash<H: Hasher>(&self, state: &mut H) {
1674        self.state.hash(state);
1675    }
1676}
1677impl PartialOrd for NonDiscoverableAuthenticationServerState {
1678    #[inline]
1679    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1680        Some(self.cmp(other))
1681    }
1682}
1683impl Ord for NonDiscoverableAuthenticationServerState {
1684    #[inline]
1685    fn cmp(&self, other: &Self) -> Ordering {
1686        self.state.cmp(&other.state)
1687    }
1688}