structured_webauthn/request.rs
1#[cfg(test)]
2mod tests;
3#[cfg(doc)]
4use super::{
5 hash::hash_set::MaxLenHashSet,
6 request::{
7 auth::{
8 AllowedCredential, AllowedCredentials, CredentialSpecificExtension,
9 DiscoverableAuthenticationServerState, DiscoverableCredentialRequestOptions,
10 NonDiscoverableAuthenticationServerState, NonDiscoverableCredentialRequestOptions,
11 PublicKeyCredentialRequestOptions,
12 },
13 register::{CredentialCreationOptions, RegistrationServerState},
14 },
15 response::{AuthenticatorAttachment, register::ClientExtensionsOutputs},
16};
17use crate::{
18 request::{
19 error::{
20 AsciiDomainErr, DomainOriginParseErr, PortParseErr, RpIdErr, SchemeParseErr, UrlErr,
21 },
22 register::{BackupReq, RegistrationVerificationOptions},
23 },
24 response::{
25 AuthData as _, AuthDataContainer, AuthResponse, AuthTransports, Backup, CeremonyErr,
26 CredentialId, Origin, Response, SentChallenge,
27 },
28};
29use core::{
30 borrow::Borrow,
31 cell::Cell,
32 fmt::{self, Display, Formatter},
33 num::NonZeroU32,
34 str::FromStr,
35};
36use rsa::sha2::{Digest as _, Sha256};
37#[cfg(any(doc, not(feature = "serializable_server_state")))]
38use std::time::Instant;
39#[cfg(feature = "serializable_server_state")]
40use std::time::SystemTime;
41use url::Url as Uri;
42/// Contains functionality for beginning the
43/// [authentication ceremony](https://www.w3.org/TR/webauthn-3/#authentication-ceremony).
44///
45/// # Examples
46///
47/// ```
48/// # use core::convert;
49/// # use structured_webauthn::{
50/// # hash::hash_set::{InsertRemoveExpired, MaxLenHashSet},
51/// # request::{
52/// # auth::{AllowedCredentials, DiscoverableCredentialRequestOptions, NonDiscoverableCredentialRequestOptions},
53/// # register::UserHandle64,
54/// # Credentials, PublicKeyCredentialDescriptor, RpId,
55/// # },
56/// # response::{AuthTransports, CredentialId, CRED_ID_MIN_LEN},
57/// # AggErr,
58/// # };
59/// const RP_ID: &RpId = &RpId::from_static_domain("example.com").unwrap();
60/// let mut ceremonies = MaxLenHashSet::new(128);
61/// let (server, client) = DiscoverableCredentialRequestOptions::passkey(RP_ID).start_ceremony()?;
62/// assert_eq!(ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success);
63/// # #[cfg(feature = "custom")]
64/// let mut ceremonies_2 = MaxLenHashSet::new(128);
65/// # #[cfg(feature = "serde")]
66/// assert!(serde_json::to_string(&client).is_ok());
67/// let user_handle = get_user_handle();
68/// # #[cfg(feature = "custom")]
69/// let creds = get_registered_credentials(&user_handle)?;
70/// # #[cfg(feature = "custom")]
71/// let (server_2, client_2) =
72/// NonDiscoverableCredentialRequestOptions::second_factor(RP_ID, creds).start_ceremony()?;
73/// # #[cfg(feature = "custom")]
74/// assert_eq!(ceremonies_2.insert_remove_all_expired(server_2), InsertRemoveExpired::Success);
75/// # #[cfg(all(feature = "custom", feature = "serde"))]
76/// assert!(serde_json::to_string(&client_2).is_ok());
77/// /// Extract `UserHandle` from session cookie.
78/// fn get_user_handle() -> UserHandle64 {
79/// // ⋮
80/// # UserHandle64::new()
81/// }
82/// # #[cfg(feature = "custom")]
83/// /// Fetch the `AllowedCredentials` associated with `user`.
84/// fn get_registered_credentials(user: &UserHandle64) -> Result<AllowedCredentials, AggErr> {
85/// // ⋮
86/// # let mut creds = AllowedCredentials::new();
87/// # creds.push(
88/// # PublicKeyCredentialDescriptor {
89/// # id: CredentialId::try_from(vec![0; CRED_ID_MIN_LEN].into_boxed_slice())?,
90/// # transports: AuthTransports::NONE,
91/// # }
92/// # .into(),
93/// # );
94/// # Ok(creds)
95/// }
96/// # Ok::<_, AggErr>(())
97/// ```
98pub mod auth;
99/// Contains error types.
100pub mod error;
101/// Contains functionality for beginning the
102/// [registration ceremony](https://www.w3.org/TR/webauthn-3/#registration-ceremony).
103///
104/// # Examples
105///
106/// ```
107/// # use core::convert;
108/// # use structured_webauthn::{
109/// # hash::hash_set::{InsertRemoveExpired, MaxLenHashSet},
110/// # request::{
111/// # register::{
112/// # CredentialCreationOptions, PublicKeyCredentialUserEntity, UserHandle, USER_HANDLE_MAX_LEN, UserHandle64,
113/// # },
114/// # PublicKeyCredentialDescriptor, RpId
115/// # },
116/// # response::{AuthTransports, CredentialId, CRED_ID_MIN_LEN},
117/// # AggErr,
118/// # };
119/// const RP_ID: &RpId = &RpId::from_static_domain("example.com").unwrap();
120/// # #[cfg(feature = "custom")]
121/// let mut ceremonies = MaxLenHashSet::new(128);
122/// # #[cfg(feature = "custom")]
123/// let user_handle = get_user_handle();
124/// # #[cfg(feature = "custom")]
125/// let user = get_user_entity(&user_handle)?;
126/// # #[cfg(feature = "custom")]
127/// let creds = get_registered_credentials(&user_handle)?;
128/// # #[cfg(feature = "custom")]
129/// let (server, client) = CredentialCreationOptions::passkey(RP_ID, user.clone(), creds)
130/// .start_ceremony()?;
131/// # #[cfg(feature = "custom")]
132/// assert_eq!(ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success);
133/// # #[cfg(all(feature = "serde", feature = "custom"))]
134/// assert!(serde_json::to_string(&client).is_ok());
135/// # #[cfg(feature = "custom")]
136/// let creds_2 = get_registered_credentials(&user_handle)?;
137/// # #[cfg(feature = "custom")]
138/// let (server_2, client_2) =
139/// CredentialCreationOptions::second_factor(RP_ID, user, creds_2).start_ceremony()?;
140/// # #[cfg(feature = "custom")]
141/// assert_eq!(ceremonies.insert_remove_all_expired(server_2), InsertRemoveExpired::Success);
142/// # #[cfg(all(feature = "serde", feature = "custom"))]
143/// assert!(serde_json::to_string(&client_2).is_ok());
144/// /// Extract `UserHandle` from session cookie or storage if this is not the first credential registered.
145/// # #[cfg(feature = "custom")]
146/// fn get_user_handle() -> UserHandle64 {
147/// // ⋮
148/// # [0; USER_HANDLE_MAX_LEN].into()
149/// }
150/// /// Fetch `PublicKeyCredentialUserEntity` info associated with `user`.
151/// ///
152/// /// If this is the first time a credential is being registered, then `PublicKeyCredentialUserEntity`
153/// /// will need to be constructed with `name` and `display_name` passed from the client and `UserHandle::new`
154/// /// used for `id`. Once created, this info can be stored such that the entity information
155/// /// does not need to be requested for subsequent registrations.
156/// # #[cfg(feature = "custom")]
157/// fn get_user_entity(user: &UserHandle64) -> Result<PublicKeyCredentialUserEntity<'_, '_, '_, USER_HANDLE_MAX_LEN>, AggErr> {
158/// // ⋮
159/// # Ok(PublicKeyCredentialUserEntity {
160/// # name: "foo",
161/// # id: user,
162/// # display_name: "",
163/// # })
164/// }
165/// /// Fetch the `PublicKeyCredentialDescriptor`s associated with `user`.
166/// ///
167/// /// This doesn't need to be called when this is the first credential registered for `user`; instead
168/// /// an empty `Vec` should be passed.
169/// fn get_registered_credentials(
170/// user: &UserHandle64,
171/// ) -> Result<Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>, AggErr> {
172/// // ⋮
173/// # Ok(Vec::new())
174/// }
175/// # Ok::<_, AggErr>(())
176/// ```
177pub mod register;
178/// Contains functionality to serialize data to a client.
179#[cfg(feature = "serde")]
180mod ser;
181/// Contains functionality to (de)serialize data needed for [`RegistrationServerState`],
182/// [`DiscoverableAuthenticationServerState`], and [`NonDiscoverableAuthenticationServerState`] to a data store.
183#[cfg(feature = "serializable_server_state")]
184pub(super) mod ser_server_state;
185// `Challenge` must _never_ be constructable directly or indirectly; thus its tuple field must always be private,
186// and it must never implement `trait`s (e.g., `Clone`) that would allow indirect creation. It must only ever
187// be constructed via `Self::new` or `Self::default`. In contrast downstream code must be able to construct
188// `SentChallenge` since it is used during ceremony validation; thus we must keep `Challenge` and `SentChallenge`
189// as separate types.
190/// [Cryptographic challenge](https://www.w3.org/TR/webauthn-3/#sctn-cryptographic-challenges).
191#[expect(
192 missing_copy_implementations,
193 reason = "want to enforce randomly-generated challenges"
194)]
195#[derive(Debug)]
196pub struct Challenge(u128);
197impl Challenge {
198 /// The number of bytes a `Challenge` takes to encode in base64url.
199 pub(super) const BASE64_LEN: usize = base64url_nopad::encode_len(16);
200 /// Generates a random `Challenge`.
201 ///
202 /// # Examples
203 ///
204 /// ```
205 /// # use structured_webauthn::request::Challenge;
206 /// // The probability of a `Challenge` being 0 (assuming a good entropy
207 /// // source) is 2^-128 ≈ 2.9 x 10^-39.
208 /// assert_ne!(Challenge::new().into_data(), 0);
209 /// ```
210 #[inline]
211 #[must_use]
212 pub fn new() -> Self {
213 Self(rand::random())
214 }
215 /// Returns the contained `u128` consuming `self`.
216 #[inline]
217 #[must_use]
218 pub const fn into_data(self) -> u128 {
219 self.0
220 }
221 /// Returns the contained `u128`.
222 #[inline]
223 #[must_use]
224 pub const fn as_data(&self) -> u128 {
225 self.0
226 }
227 /// Returns the contained `u128` as a little-endian `array` consuming `self`.
228 #[inline]
229 #[must_use]
230 pub const fn into_array(self) -> [u8; 16] {
231 self.as_array()
232 }
233 /// Returns the contained `u128` as a little-endian `array`.
234 #[expect(
235 clippy::little_endian_bytes,
236 reason = "Challenge and SentChallenge need to be compatible, and we need to ensure the data is sent and received in the same order"
237 )]
238 #[inline]
239 #[must_use]
240 pub const fn as_array(&self) -> [u8; 16] {
241 self.0.to_le_bytes()
242 }
243}
244impl Default for Challenge {
245 /// Same as [`Self::new`].
246 #[inline]
247 fn default() -> Self {
248 Self::new()
249 }
250}
251impl From<Challenge> for u128 {
252 #[inline]
253 fn from(value: Challenge) -> Self {
254 value.0
255 }
256}
257impl From<&Challenge> for u128 {
258 #[inline]
259 fn from(value: &Challenge) -> Self {
260 value.0
261 }
262}
263impl From<Challenge> for [u8; 16] {
264 #[inline]
265 fn from(value: Challenge) -> Self {
266 value.into_array()
267 }
268}
269impl From<&Challenge> for [u8; 16] {
270 #[inline]
271 fn from(value: &Challenge) -> Self {
272 value.as_array()
273 }
274}
275/// A [domain](https://url.spec.whatwg.org/#concept-domain) in representation format consisting of only and any
276/// ASCII.
277///
278/// The only ASCII character disallowed in a label is `'.'` since it is used exclusively as a separator. Every
279/// label must have length inclusively between 1 and 63, and the total length of the domain must be at most 253
280/// when a trailing `'.'` does not exist; otherwise the max length is 254. The root domain (i.e., `'.'`) is not
281/// allowed.
282///
283/// Note if the domain is a `&'static str`, then use [`AsciiDomainStatic`] instead.
284#[derive(Clone, Debug, Eq, PartialEq)]
285pub struct AsciiDomain(String);
286impl AsciiDomain {
287 /// Removes a trailing `'.'` if it exists.
288 ///
289 /// # Examples
290 ///
291 /// ```
292 /// # use structured_webauthn::request::{AsciiDomain, error::AsciiDomainErr};
293 /// let mut dom = AsciiDomain::try_from("example.com.".to_owned())?;
294 /// assert_eq!(dom.as_ref(), "example.com.");
295 /// dom.remove_trailing_dot();
296 /// assert_eq!(dom.as_ref(), "example.com");
297 /// dom.remove_trailing_dot();
298 /// assert_eq!(dom.as_ref(), "example.com");
299 /// # Ok::<_, AsciiDomainErr>(())
300 /// ```
301 #[expect(clippy::unreachable, reason = "want to crash when there is a bug")]
302 #[inline]
303 pub fn remove_trailing_dot(&mut self) {
304 if *self
305 .0
306 .as_bytes()
307 .last()
308 .unwrap_or_else(|| unreachable!("there is a bug in AsciiDomain::from_slice"))
309 == b'.'
310 {
311 _ = self.0.pop();
312 }
313 }
314}
315impl AsRef<str> for AsciiDomain {
316 #[inline]
317 fn as_ref(&self) -> &str {
318 self.0.as_str()
319 }
320}
321impl Borrow<str> for AsciiDomain {
322 #[inline]
323 fn borrow(&self) -> &str {
324 self.0.as_str()
325 }
326}
327impl From<AsciiDomain> for String {
328 #[inline]
329 fn from(value: AsciiDomain) -> Self {
330 value.0
331 }
332}
333impl PartialEq<&Self> for AsciiDomain {
334 #[inline]
335 fn eq(&self, other: &&Self) -> bool {
336 *self == **other
337 }
338}
339impl PartialEq<AsciiDomain> for &AsciiDomain {
340 #[inline]
341 fn eq(&self, other: &AsciiDomain) -> bool {
342 **self == *other
343 }
344}
345impl TryFrom<Vec<u8>> for AsciiDomain {
346 type Error = AsciiDomainErr;
347 /// Verifies `value` is an ASCII domain in representation format converting any uppercase ASCII into
348 /// lowercase.
349 ///
350 /// Note it is _strongly_ encouraged for `value` to only contain letters, numbers, hyphens, and underscores;
351 /// otherwise certain applications may consider it not a domain. If the original domain contains non-ASCII, then
352 /// one must encode it in Punycode _before_ calling this function. Domains that have a trailing `'.'` will be
353 /// considered differently than domains without it; thus one will likely want to trim it if it does exist
354 /// (e.g., [`AsciiDomain::remove_trailing_dot`]). Because this allows any ASCII, one may want to ensure `value`
355 /// is not an IP address.
356 ///
357 /// # Errors
358 ///
359 /// Errors iff `value` is not a valid ASCII domain.
360 ///
361 /// # Examples
362 ///
363 /// ```
364 /// # use structured_webauthn::request::{error::AsciiDomainErr, AsciiDomain};
365 /// // Root `'.'` is not removed if it exists.
366 /// assert_ne!("example.com", AsciiDomain::try_from(b"example.com.".to_vec())?.as_ref());
367 /// // Root domain (i.e., `'.'`) is not allowed.
368 /// assert!(AsciiDomain::try_from(vec![b'.']).is_err());
369 /// // Uppercase is transformed into lowercase.
370 /// assert_eq!("example.com", AsciiDomain::try_from(b"ExAmPle.CoM".to_vec())?.as_ref());
371 /// // The only ASCII character not allowed in a domain label is `'.'` as it is used exclusively to delimit
372 /// // labels.
373 /// assert_eq!("\x00", AsciiDomain::try_from(b"\x00".to_vec())?.as_ref());
374 /// // Empty labels are not allowed.
375 /// assert!(AsciiDomain::try_from(b"example..com".to_vec()).is_err());
376 /// // Labels cannot have length greater than 63.
377 /// let mut long_label = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned();
378 /// assert_eq!(long_label.len(), 64);
379 /// assert!(AsciiDomain::try_from(long_label.clone().into_bytes()).is_err());
380 /// long_label.pop();
381 /// assert_eq!(long_label, AsciiDomain::try_from(long_label.clone().into_bytes())?.as_ref());
382 /// // The maximum length of a domain is 254 if a trailing `'.'` exists; otherwise the max length is 253.
383 /// let mut long_domain = format!("{long_label}.{long_label}.{long_label}.{long_label}");
384 /// long_domain.pop();
385 /// long_domain.push('.');
386 /// assert_eq!(long_domain.len(), 255);
387 /// assert!(AsciiDomain::try_from(long_domain.clone().into_bytes()).is_err());
388 /// long_domain.pop();
389 /// long_domain.pop();
390 /// long_domain.push('.');
391 /// assert_eq!(long_domain.len(), 254);
392 /// assert_eq!(long_domain, AsciiDomain::try_from(long_domain.clone().into_bytes())?.as_ref());
393 /// long_domain.pop();
394 /// long_domain.push('a');
395 /// assert_eq!(long_domain.len(), 254);
396 /// assert!(AsciiDomain::try_from(long_domain.clone().into_bytes()).is_err());
397 /// long_domain.pop();
398 /// assert_eq!(long_domain.len(), 253);
399 /// assert_eq!(long_domain, AsciiDomain::try_from(long_domain.clone().into_bytes())?.as_ref());
400 /// // Only ASCII is allowed; thus if a domain needs to be Punycode-encoded, then it must be _before_ calling
401 /// // this function.
402 /// assert!(AsciiDomain::try_from("λ.com".to_owned().into_bytes()).is_err());
403 /// assert_eq!("xn--wxa.com", AsciiDomain::try_from(b"xn--wxa.com".to_vec())?.as_ref());
404 /// # Ok::<_, AsciiDomainErr>(())
405 /// ```
406 #[expect(unsafe_code, reason = "comment justifies correctness")]
407 #[expect(
408 clippy::arithmetic_side_effects,
409 reason = "comments justify correctness"
410 )]
411 #[inline]
412 fn try_from(mut value: Vec<u8>) -> Result<Self, Self::Error> {
413 /// Value to add to an uppercase ASCII `u8` to get the lowercase version.
414 const DIFF: u8 = b'a' - b'A';
415 let bytes = value.as_slice();
416 bytes
417 .as_ref()
418 .last()
419 .ok_or(AsciiDomainErr::Empty)
420 .and_then(|b| {
421 let len = bytes.len();
422 if *b == b'.' {
423 if len == 1 {
424 Err(AsciiDomainErr::RootDomain)
425 } else if len > 254 {
426 Err(AsciiDomainErr::Len)
427 } else {
428 Ok(())
429 }
430 } else if len > 253 {
431 Err(AsciiDomainErr::Len)
432 } else {
433 Ok(())
434 }
435 })
436 .and_then(|()| {
437 value
438 .iter_mut()
439 .try_fold(0u8, |mut label_len, byt| {
440 let b = *byt;
441 if b == b'.' {
442 if label_len == 0 {
443 Err(AsciiDomainErr::EmptyLabel)
444 } else {
445 Ok(0)
446 }
447 } else if label_len == 63 {
448 Err(AsciiDomainErr::LabelLen)
449 } else {
450 // We know `label_len` is less than 63, thus this won't overflow.
451 label_len += 1;
452 match b {
453 // Non-uppercase ASCII is allowed and doesn't need to be converted.
454 ..b'A' | b'['..=0x7F => Ok(label_len),
455 // Uppercase ASCII is allowed but needs to be transformed into lowercase.
456 b'A'..=b'Z' => {
457 // Lowercase ASCII is a contiguous block starting from `b'a'` as is uppercase
458 // ASCII which starts from `b'A'` with uppercase ASCII coming before; thus we
459 // simply need to shift by a fixed amount.
460 *byt += DIFF;
461 Ok(label_len)
462 }
463 // Non-ASCII is disallowed.
464 0x80.. => Err(AsciiDomainErr::NotAscii),
465 }
466 }
467 })
468 .map(|_| {
469 // SAFETY:
470 // We just verified `value` only contains ASCII; thus this is safe.
471 let utf8 = unsafe { String::from_utf8_unchecked(value) };
472 Self(utf8)
473 })
474 })
475 }
476}
477impl TryFrom<String> for AsciiDomain {
478 type Error = AsciiDomainErr;
479 /// Same as [`Self::try_from`] except `value` is a `String`.
480 #[inline]
481 fn try_from(value: String) -> Result<Self, Self::Error> {
482 Self::try_from(value.into_bytes())
483 }
484}
485/// Similar to [`AsciiDomain`] except the contained data is a `&'static str`.
486///
487/// Since [`Self::new`] and [`Option::unwrap`] are `const fn`s, one can define a global `const` or `static`
488/// variable that represents the RP ID.
489#[derive(Clone, Copy, Debug, Eq, PartialEq)]
490pub struct AsciiDomainStatic(&'static str);
491impl AsciiDomainStatic {
492 /// Returns the contained `str`.
493 #[inline]
494 #[must_use]
495 pub const fn as_str(self) -> &'static str {
496 self.0
497 }
498 /// Verifies `domain` is a valid lowercase ASCII domain returning `None` when not valid or when
499 /// uppercase ASCII exists.
500 ///
501 /// Read [`AsciiDomain`] for more information about what constitutes a valid domain.
502 ///
503 /// # Examples
504 ///
505 /// ```
506 /// # use structured_webauthn::request::{AsciiDomainStatic, RpId};
507 /// /// RP ID of our application.
508 /// const RP_IP: &RpId = &RpId::StaticDomain(AsciiDomainStatic::new("example.com").unwrap());
509 /// ```
510 #[expect(
511 clippy::arithmetic_side_effects,
512 reason = "comment justifies correctness"
513 )]
514 #[expect(
515 clippy::else_if_without_else,
516 reason = "part of if branch and else branch are the same"
517 )]
518 #[inline]
519 #[must_use]
520 pub const fn new(domain: &'static str) -> Option<Self> {
521 let mut utf8 = domain.as_bytes();
522 if let Some(lst) = utf8.last() {
523 let len = utf8.len();
524 if *lst == b'.' {
525 if len == 1 || len > 254 {
526 return None;
527 }
528 } else if len > 253 {
529 return None;
530 }
531 let mut label_len = 0;
532 while let [first, ref rest @ ..] = *utf8 {
533 if first == b'.' {
534 if label_len == 0 {
535 return None;
536 }
537 label_len = 0;
538 } else if label_len == 63 {
539 return None;
540 } else {
541 match first {
542 // Any non-uppercase ASCII is allowed.
543 // We know `label_len` is less than 63, so this won't overflow.
544 ..b'A' | b'['..=0x7F => label_len += 1,
545 // Uppercase ASCII and non-ASCII are disallowed.
546 b'A'..=b'Z' | 0x80.. => return None,
547 }
548 }
549 utf8 = rest;
550 }
551 Some(Self(domain))
552 } else {
553 None
554 }
555 }
556}
557impl AsRef<str> for AsciiDomainStatic {
558 #[inline]
559 fn as_ref(&self) -> &str {
560 self.as_str()
561 }
562}
563impl Borrow<str> for AsciiDomainStatic {
564 #[inline]
565 fn borrow(&self) -> &str {
566 self.as_str()
567 }
568}
569impl From<AsciiDomainStatic> for &'static str {
570 #[inline]
571 fn from(value: AsciiDomainStatic) -> Self {
572 value.0
573 }
574}
575impl From<AsciiDomainStatic> for String {
576 #[inline]
577 fn from(value: AsciiDomainStatic) -> Self {
578 value.0.to_owned()
579 }
580}
581impl From<AsciiDomainStatic> for AsciiDomain {
582 #[inline]
583 fn from(value: AsciiDomainStatic) -> Self {
584 Self(value.0.to_owned())
585 }
586}
587impl PartialEq<&Self> for AsciiDomainStatic {
588 #[inline]
589 fn eq(&self, other: &&Self) -> bool {
590 *self == **other
591 }
592}
593impl PartialEq<AsciiDomainStatic> for &AsciiDomainStatic {
594 #[inline]
595 fn eq(&self, other: &AsciiDomainStatic) -> bool {
596 **self == *other
597 }
598}
599/// The output of the [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer).
600#[derive(Clone, Debug, Eq, PartialEq)]
601pub struct Url(String);
602impl AsRef<str> for Url {
603 #[inline]
604 fn as_ref(&self) -> &str {
605 self.0.as_str()
606 }
607}
608impl Borrow<str> for Url {
609 #[inline]
610 fn borrow(&self) -> &str {
611 self.0.as_str()
612 }
613}
614impl From<Url> for String {
615 #[inline]
616 fn from(value: Url) -> Self {
617 value.0
618 }
619}
620impl PartialEq<&Self> for Url {
621 #[inline]
622 fn eq(&self, other: &&Self) -> bool {
623 *self == **other
624 }
625}
626impl PartialEq<Url> for &Url {
627 #[inline]
628 fn eq(&self, other: &Url) -> bool {
629 **self == *other
630 }
631}
632impl FromStr for Url {
633 type Err = UrlErr;
634 #[inline]
635 fn from_str(s: &str) -> Result<Self, Self::Err> {
636 let violation = Cell::new(false);
637 Uri::options()
638 .syntax_violation_callback(Some(&|_| {
639 violation.set(true);
640 }))
641 .parse(s)
642 .map_err(|_e| UrlErr)
643 .and_then(|url| {
644 if violation.into_inner() {
645 Err(UrlErr)
646 } else {
647 Ok(Self(url.into()))
648 }
649 })
650 }
651}
652/// [RP ID](https://w3c.github.io/webauthn/#rp-id).
653#[derive(Clone, Debug, Eq, PartialEq)]
654pub enum RpId {
655 /// An ASCII domain.
656 ///
657 /// Note web platforms MUST use this variant; and if possible, non-web platforms should too. Also despite
658 /// the spec currently requiring RP IDs to be
659 /// [valid domain strings](https://url.spec.whatwg.org/#valid-domain-string), this is unnecessarily strict
660 /// and will likely be relaxed in a [future version](https://github.com/w3c/webauthn/issues/2206); thus
661 /// any ASCII domain is allowed.
662 Domain(AsciiDomain),
663 /// Similar to [`Self::Domain`] except the ASCII domain is static.
664 ///
665 /// Since [`AsciiDomainStatic::new`] is a `const fn`, one can define a `const` or `static` global variable
666 /// the contains the RP ID.
667 StaticDomain(AsciiDomainStatic),
668 /// A URL.
669 Url(Url),
670}
671impl RpId {
672 /// Returns `Some` containing an [`AsciiDomainStatic`] iff [`AsciiDomainStatic::new`] does.
673 #[inline]
674 #[must_use]
675 pub const fn from_static_domain(domain: &'static str) -> Option<Self> {
676 if let Some(dom) = AsciiDomainStatic::new(domain) {
677 Some(Self::StaticDomain(dom))
678 } else {
679 None
680 }
681 }
682 /// Validates `hash` is the same as the SHA-256 hash of `self`.
683 fn validate_rp_id_hash<E>(&self, hash: &[u8]) -> Result<(), CeremonyErr<E>> {
684 if *hash == *Sha256::digest(self.as_ref()) {
685 Ok(())
686 } else {
687 Err(CeremonyErr::RpIdHashMismatch)
688 }
689 }
690}
691impl AsRef<str> for RpId {
692 #[inline]
693 fn as_ref(&self) -> &str {
694 match *self {
695 Self::Domain(ref dom) => dom.as_ref(),
696 Self::StaticDomain(dom) => dom.as_str(),
697 Self::Url(ref url) => url.as_ref(),
698 }
699 }
700}
701impl Borrow<str> for RpId {
702 #[inline]
703 fn borrow(&self) -> &str {
704 match *self {
705 Self::Domain(ref dom) => dom.borrow(),
706 Self::StaticDomain(dom) => dom.as_str(),
707 Self::Url(ref url) => url.borrow(),
708 }
709 }
710}
711impl From<RpId> for String {
712 #[inline]
713 fn from(value: RpId) -> Self {
714 match value {
715 RpId::Domain(dom) => dom.into(),
716 RpId::StaticDomain(dom) => dom.into(),
717 RpId::Url(url) => url.into(),
718 }
719 }
720}
721impl PartialEq<&Self> for RpId {
722 #[inline]
723 fn eq(&self, other: &&Self) -> bool {
724 *self == **other
725 }
726}
727impl PartialEq<RpId> for &RpId {
728 #[inline]
729 fn eq(&self, other: &RpId) -> bool {
730 **self == *other
731 }
732}
733impl From<AsciiDomain> for RpId {
734 #[inline]
735 fn from(value: AsciiDomain) -> Self {
736 Self::Domain(value)
737 }
738}
739impl From<AsciiDomainStatic> for RpId {
740 #[inline]
741 fn from(value: AsciiDomainStatic) -> Self {
742 Self::StaticDomain(value)
743 }
744}
745impl From<Url> for RpId {
746 #[inline]
747 fn from(value: Url) -> Self {
748 Self::Url(value)
749 }
750}
751impl TryFrom<String> for RpId {
752 type Error = RpIdErr;
753 /// Returns `Ok` iff `value` is a valid [`Url`] or [`AsciiDomain`].
754 ///
755 /// Note when `value` is a valid `Url` and `AsciiDomain`, it will be treated as a `Url`.
756 #[inline]
757 fn try_from(value: String) -> Result<Self, Self::Error> {
758 Url::from_str(value.as_str())
759 .map(Self::Url)
760 .or_else(|_err| {
761 AsciiDomain::try_from(value)
762 .map(Self::Domain)
763 .map_err(|_e| RpIdErr)
764 })
765 }
766}
767/// A URI scheme. This can be used to make
768/// [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin) more convenient.
769#[derive(Clone, Copy, Debug, Default)]
770pub enum Scheme<'a> {
771 /// A scheme must not exist when validating the origin.
772 None,
773 /// Any scheme, or no scheme at all, is allowed to exist when validating the origin.
774 Any,
775 /// The HTTPS scheme must exist when validating the origin.
776 #[default]
777 Https,
778 /// The SSH scheme must exist when validating the origin.
779 Ssh,
780 /// The contained `str` scheme must exist when validating the origin.
781 Other(&'a str),
782 /// [`Self::None`] or [`Self::Https`].
783 NoneHttps,
784 /// [`Self::None`] or [`Self::Ssh`].
785 NoneSsh,
786 /// [`Self::None`] or [`Self::Other`].
787 NoneOther(&'a str),
788}
789impl Scheme<'_> {
790 /// `self` is any `Scheme`; however `other` is assumed to only be a `Scheme` from a `DomainOrigin` returned
791 /// from `DomainOrigin::try_from`. The latter implies that `other` is only `Scheme::None`, `Scheme::Https`,
792 /// `Scheme::Ssh`, or `Scheme::Other`; furthermore when `Scheme::Other`, it won't contain a `str` that is
793 /// empty or equal to "https" or "ssh".
794 #[expect(clippy::unreachable, reason = "there is a bug, so we want to crash")]
795 fn is_equal_to_origin_scheme(self, other: Self) -> bool {
796 match self {
797 Self::None => matches!(other, Self::None),
798 Self::Any => true,
799 Self::Https => matches!(other, Self::Https),
800 Self::Ssh => matches!(other, Self::Ssh),
801 Self::Other(scheme) => match other {
802 Self::None => false,
803 // We want to crash and burn since there is a bug in code.
804 Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
805 unreachable!("there is a bug in DomainOrigin::try_from")
806 }
807 Self::Https => scheme == "https",
808 Self::Ssh => scheme == "ssh",
809 Self::Other(scheme_other) => scheme == scheme_other,
810 },
811 Self::NoneHttps => match other {
812 Self::None | Self::Https => true,
813 Self::Ssh | Self::Other(_) => false,
814 // We want to crash and burn since there is a bug in code.
815 Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
816 unreachable!("there is a bug in DomainOrigin::try_from")
817 }
818 },
819 Self::NoneSsh => match other {
820 Self::None | Self::Ssh => true,
821 // We want to crash and burn since there is a bug in code.
822 Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
823 unreachable!("there is a bug in DomainOrigin::try_from")
824 }
825 Self::Https | Self::Other(_) => false,
826 },
827 Self::NoneOther(scheme) => match other {
828 Self::None => true,
829 // We want to crash and burn since there is a bug in code.
830 Self::Any | Self::NoneHttps | Self::NoneSsh | Self::NoneOther(_) => {
831 unreachable!("there is a bug in DomainOrigin::try_from")
832 }
833 Self::Https => scheme == "https",
834 Self::Ssh => scheme == "ssh",
835 Self::Other(scheme_other) => scheme == scheme_other,
836 },
837 }
838 }
839}
840impl<'a: 'b, 'b> TryFrom<&'a str> for Scheme<'b> {
841 type Error = SchemeParseErr;
842 /// `"https"` and `"ssh"` get mapped to [`Self::Https`] and [`Self::Ssh`] respectively. All other
843 /// values get mapped to [`Self::Other`].
844 ///
845 /// # Errors
846 ///
847 /// Errors iff `s` is empty.
848 ///
849 /// # Examples
850 ///
851 /// ```
852 /// # use structured_webauthn::request::Scheme;
853 /// assert!(matches!(Scheme::try_from("https")?, Scheme::Https));
854 /// assert!(matches!(Scheme::try_from("https ")?, Scheme::Other(scheme) if scheme == "https "));
855 /// assert!(matches!(Scheme::try_from("ssh")?, Scheme::Ssh));
856 /// assert!(matches!(Scheme::try_from("Ssh")?, Scheme::Other(scheme) if scheme == "Ssh"));
857 /// // Even though one can construct an empty `Scheme` via `Scheme::Other` or `Scheme::NoneOther`,
858 /// // one cannot parse one.
859 /// assert!(Scheme::try_from("").is_err());
860 /// # Ok::<_, structured_webauthn::AggErr>(())
861 /// ```
862 #[inline]
863 fn try_from(value: &'a str) -> Result<Self, Self::Error> {
864 match value {
865 "" => Err(SchemeParseErr),
866 "https" => Ok(Self::Https),
867 "ssh" => Ok(Self::Ssh),
868 _ => Ok(Self::Other(value)),
869 }
870 }
871}
872/// A TCP/UDP port. This can be used to make
873/// [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin) more convenient.
874#[derive(Clone, Copy, Debug, Default)]
875pub enum Port {
876 /// A port must not exist when validating the origin.
877 #[default]
878 None,
879 /// Any port, or no port at all, is allowed to exist when validating the origin.
880 Any,
881 /// The contained `u16` port must exist when validating the origin.
882 Val(u16),
883 /// [`Self::None`] or [`Self::Val`].
884 NoneVal(u16),
885}
886impl Port {
887 /// `self` is any `Port`; however `other` is assumed to only be a `Port` from a `DomainOrigin` returned
888 /// from `DomainOrigin::try_from`. The latter implies that `other` is only `Port::None` or `Port::Val`.
889 #[expect(clippy::unreachable, reason = "there is a bug, so we want to crash")]
890 fn is_equal_to_origin_port(self, other: Self) -> bool {
891 match self {
892 Self::None => matches!(other, Self::None),
893 Self::Any => true,
894 Self::Val(port) => match other {
895 Self::None => false,
896 // There is a bug in code so we want to crash and burn.
897 Self::Any | Self::NoneVal(_) => {
898 unreachable!("there is a bug in DomainOrigin::try_from")
899 }
900 Self::Val(port_other) => port == port_other,
901 },
902 Self::NoneVal(port) => match other {
903 Self::None => true,
904 // There is a bug in code so we want to crash and burn.
905 Self::Any | Self::NoneVal(_) => {
906 unreachable!("there is a bug in DomainOrigin::try_from")
907 }
908 Self::Val(port_other) => port == port_other,
909 },
910 }
911 }
912}
913impl FromStr for Port {
914 type Err = PortParseErr;
915 /// Parses `s` as a 16-bit unsigned integer without leading 0s returning [`Self::Val`] with the contained
916 /// `u16`.
917 ///
918 /// # Errors
919 ///
920 /// Errors iff `s` is not a valid 16-bit unsigned integer in decimal notation without leading 0s.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// # use structured_webauthn::request::{error::PortParseErr, Port};
926 /// assert!(matches!("443".parse()?, Port::Val(443)));
927 /// // TCP/UDP ports have to be in canonical form:
928 /// assert!("022"
929 /// .parse::<Port>()
930 /// .map_or_else(|err| matches!(err, PortParseErr::NotCanonical), |_| false));
931 /// # Ok::<_, structured_webauthn::AggErr>(())
932 /// ```
933 #[inline]
934 fn from_str(s: &str) -> Result<Self, Self::Err> {
935 s.parse().map_err(PortParseErr::ParseInt).and_then(|port| {
936 if s.len()
937 == match port {
938 ..=9 => 1,
939 10..=99 => 2,
940 100..=999 => 3,
941 1_000..=9_999 => 4,
942 10_000.. => 5,
943 }
944 {
945 Ok(Self::Val(port))
946 } else {
947 Err(PortParseErr::NotCanonical)
948 }
949 })
950 }
951}
952/// A [`tuple origin`](https://html.spec.whatwg.org/multipage/browsers.html#concept-origin-tuple).
953///
954/// This can be used to make [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin)
955/// more convenient.
956#[derive(Clone, Copy, Debug)]
957pub struct DomainOrigin<'a, 'b> {
958 /// The scheme.
959 pub scheme: Scheme<'a>,
960 /// The host.
961 pub host: &'b str,
962 /// The TCP/UDP port.
963 pub port: Port,
964}
965impl<'b> DomainOrigin<'_, 'b> {
966 /// Returns a `DomainOrigin` with [`Self::scheme`] as [`Scheme::Https`], [`Self::host`] as `host`, and
967 /// [`Self::port`] as [`Port::None`].
968 ///
969 /// # Examples
970 ///
971 /// ```
972 /// # extern crate alloc;
973 /// # use alloc::borrow::Cow;
974 /// # use structured_webauthn::{request::DomainOrigin, response::Origin};
975 /// assert_eq!(
976 /// DomainOrigin::new("www.example.com"),
977 /// Origin(Cow::Borrowed("https://www.example.com"))
978 /// );
979 /// // `DomainOrigin::new` does not allow _any_ port to exist.
980 /// assert_ne!(
981 /// DomainOrigin::new("www.example.com"),
982 /// Origin(Cow::Borrowed("https://www.example.com:443"))
983 /// );
984 /// ```
985 #[must_use]
986 #[inline]
987 pub const fn new<'c: 'b>(host: &'c str) -> Self {
988 Self {
989 scheme: Scheme::Https,
990 host,
991 port: Port::None,
992 }
993 }
994 /// Returns a `DomainOrigin` with [`Self::scheme`] as [`Scheme::Https`], [`Self::host`] as `host`, and
995 /// [`Self::port`] as [`Port::Any`].
996 ///
997 /// # Examples
998 ///
999 /// ```
1000 /// # extern crate alloc;
1001 /// # use alloc::borrow::Cow;
1002 /// # use structured_webauthn::{request::DomainOrigin, response::Origin};
1003 /// // Any port is allowed to exist.
1004 /// assert_eq!(
1005 /// DomainOrigin::new_ignore_port("www.example.com"),
1006 /// Origin(Cow::Borrowed("https://www.example.com:1234"))
1007 /// );
1008 /// // A port doesn't have to exist at all either.
1009 /// assert_eq!(
1010 /// DomainOrigin::new_ignore_port("www.example.com"),
1011 /// Origin(Cow::Borrowed("https://www.example.com"))
1012 /// );
1013 /// ```
1014 #[must_use]
1015 #[inline]
1016 pub const fn new_ignore_port<'c: 'b>(host: &'c str) -> Self {
1017 Self {
1018 scheme: Scheme::Https,
1019 host,
1020 port: Port::Any,
1021 }
1022 }
1023}
1024impl PartialEq<Origin<'_>> for DomainOrigin<'_, '_> {
1025 /// Returns `true` iff [`DomainOrigin::scheme`], [`DomainOrigin::host`], and [`DomainOrigin::port`] are the
1026 /// same after calling [`DomainOrigin::try_from`] on `other.0.as_str()`.
1027 ///
1028 /// Note that [`Scheme`] and [`Port`] need not be the same variant. For example [`Scheme::Https`] and
1029 /// [`Scheme::Other`] containing `"https"` will be treated the same.
1030 #[inline]
1031 fn eq(&self, other: &Origin<'_>) -> bool {
1032 DomainOrigin::try_from(other.0.as_ref()).is_ok_and(|dom| {
1033 self.scheme.is_equal_to_origin_scheme(dom.scheme)
1034 && self.host == dom.host
1035 && self.port.is_equal_to_origin_port(dom.port)
1036 })
1037 }
1038}
1039impl PartialEq<Origin<'_>> for &DomainOrigin<'_, '_> {
1040 #[inline]
1041 fn eq(&self, other: &Origin<'_>) -> bool {
1042 **self == *other
1043 }
1044}
1045impl PartialEq<&Origin<'_>> for DomainOrigin<'_, '_> {
1046 #[inline]
1047 fn eq(&self, other: &&Origin<'_>) -> bool {
1048 *self == **other
1049 }
1050}
1051impl PartialEq<DomainOrigin<'_, '_>> for Origin<'_> {
1052 #[inline]
1053 fn eq(&self, other: &DomainOrigin<'_, '_>) -> bool {
1054 *other == *self
1055 }
1056}
1057impl PartialEq<DomainOrigin<'_, '_>> for &Origin<'_> {
1058 #[inline]
1059 fn eq(&self, other: &DomainOrigin<'_, '_>) -> bool {
1060 *other == **self
1061 }
1062}
1063impl PartialEq<&DomainOrigin<'_, '_>> for Origin<'_> {
1064 #[inline]
1065 fn eq(&self, other: &&DomainOrigin<'_, '_>) -> bool {
1066 **other == *self
1067 }
1068}
1069impl<'a: 'b + 'c, 'b, 'c> TryFrom<&'a str> for DomainOrigin<'b, 'c> {
1070 type Error = DomainOriginParseErr;
1071 /// `value` is parsed according to the following extended regex:
1072 ///
1073 /// `^([^:]*:\/\/)?[^:]*(:.*)?$`
1074 ///
1075 /// where the `[^:]*` of the first capturing group is parsed according to [`Scheme::try_from`], and
1076 /// the `.*` of the second capturing group is parsed according to [`Port::from_str`].
1077 ///
1078 /// # Errors
1079 ///
1080 /// Errors iff `Scheme::try_from` or `Port::from_str` fail when applicable.
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```
1085 /// # use structured_webauthn::request::{DomainOrigin, Port, Scheme};
1086 /// assert!(
1087 /// DomainOrigin::try_from("https://www.example.com:443").map_or(false, |dom| matches!(
1088 /// dom.scheme,
1089 /// Scheme::Https
1090 /// ) && dom.host
1091 /// == "www.example.com"
1092 /// && matches!(dom.port, Port::Val(port) if port == 443))
1093 /// );
1094 /// // Parsing is done in a case sensitive way.
1095 /// assert!(DomainOrigin::try_from("Https://www.EXample.com").map_or(
1096 /// false,
1097 /// |dom| matches!(dom.scheme, Scheme::Other(scheme) if scheme == "Https")
1098 /// && dom.host == "www.EXample.com"
1099 /// && matches!(dom.port, Port::None)
1100 /// ));
1101 /// ```
1102 #[inline]
1103 fn try_from(value: &'a str) -> Result<Self, Self::Error> {
1104 // Any string that contains `':'` is not a [valid domain](https://url.spec.whatwg.org/#valid-domain), and
1105 // and `"//"` never exists in a `Port`; thus if `"://"` exists, it's either invalid or delimits the scheme
1106 // from the rest of the origin.
1107 match value.split_once("://") {
1108 None => Ok((Scheme::None, value)),
1109 Some((poss_scheme, rem)) => Scheme::try_from(poss_scheme)
1110 .map_err(DomainOriginParseErr::Scheme)
1111 .map(|scheme| (scheme, rem)),
1112 }
1113 .and_then(|(scheme, rem)| {
1114 // `':'` never exists in a valid domain; thus if it exists, it's either invalid or
1115 // separates the domain from the port.
1116 rem.split_once(':')
1117 .map_or_else(
1118 || Ok((rem, Port::None)),
1119 |(rem2, poss_port)| {
1120 Port::from_str(poss_port)
1121 .map_err(DomainOriginParseErr::Port)
1122 .map(|port| (rem2, port))
1123 },
1124 )
1125 .map(|(host, port)| Self { scheme, host, port })
1126 })
1127 }
1128}
1129/// [`PublicKeyCredentialDescriptor`](https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialdescriptor)
1130/// associated with a registered credential.
1131#[derive(Clone, Debug)]
1132pub struct PublicKeyCredentialDescriptor<T> {
1133 /// [`id`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialdescriptor-id).
1134 pub id: CredentialId<T>,
1135 /// [`transports`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialdescriptor-transports).
1136 pub transports: AuthTransports,
1137}
1138/// [`UserVerificationRequirement`](https://www.w3.org/TR/webauthn-3/#enumdef-userverificationrequirement).
1139#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1140pub enum UserVerificationRequirement {
1141 /// [`required`](https://www.w3.org/TR/webauthn-3/#dom-userverificationrequirement-required).
1142 Required,
1143 /// [`discouraged`](https://www.w3.org/TR/webauthn-3/#dom-userverificationrequirement-discouraged).
1144 ///
1145 /// Note some authenticators always require user verification when registering a credential (e.g.,
1146 /// [CTAP 2.0](https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html)
1147 /// authenticators that have had a PIN enabled).
1148 Discouraged,
1149 /// [`preferred`](https://www.w3.org/TR/webauthn-3/#dom-userverificationrequirement-preferred).
1150 Preferred,
1151}
1152/// [`PublicKeyCredentialHint`](https://www.w3.org/TR/webauthn-3/#enumdef-publickeycredentialhint).
1153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1154pub enum PublicKeyCredentialHint {
1155 /// [`security-key`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialhint-security-key).
1156 SecurityKey,
1157 /// [`client-device`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialhint-client-device).
1158 ClientDevice,
1159 /// [`hybrid`](https://www.w3.org/TR/webauthn-3/#dom-publickeycredentialhint-hybrid).
1160 Hybrid,
1161}
1162impl PublicKeyCredentialHint {
1163 /// Returns `true` iff `self` is the same as `other`.
1164 const fn is_eq(self, other: Self) -> bool {
1165 match self {
1166 Self::SecurityKey => matches!(other, Self::SecurityKey),
1167 Self::ClientDevice => matches!(other, Self::ClientDevice),
1168 Self::Hybrid => matches!(other, Self::Hybrid),
1169 }
1170 }
1171}
1172/// Unique sequence of [`PublicKeyCredentialHint`].
1173#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1174pub struct Hints([Option<PublicKeyCredentialHint>; 3]);
1175impl Hints {
1176 /// Empty sequence of [`PublicKeyCredentialHint`]s.
1177 pub const EMPTY: Self = Self([None; 3]);
1178 /// Adds `hint` to `self` iff `self` doesn't already contain `hint`.
1179 ///
1180 /// # Examples
1181 ///
1182 /// ```
1183 /// # use structured_webauthn::request::{Hints, PublicKeyCredentialHint};
1184 /// assert_eq!(
1185 /// Hints::EMPTY
1186 /// .add(PublicKeyCredentialHint::SecurityKey)
1187 /// .first(),
1188 /// Some(PublicKeyCredentialHint::SecurityKey)
1189 /// );
1190 /// ```
1191 #[inline]
1192 #[must_use]
1193 pub const fn add(mut self, hint: PublicKeyCredentialHint) -> Self {
1194 let mut vals = self.0.as_mut_slice();
1195 while let [ref mut first, ref mut rem @ ..] = *vals {
1196 match *first {
1197 None => {
1198 *first = Some(hint);
1199 return self;
1200 }
1201 Some(h) => {
1202 if h.is_eq(hint) {
1203 return self;
1204 }
1205 }
1206 }
1207 vals = rem;
1208 }
1209 self
1210 }
1211 /// Returns the first `PublicKeyCredentialHint`.
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```
1216 /// # use structured_webauthn::request::Hints;
1217 /// assert!(Hints::EMPTY.first().is_none());
1218 /// ```
1219 #[inline]
1220 #[must_use]
1221 pub const fn first(self) -> Option<PublicKeyCredentialHint> {
1222 self.0[0]
1223 }
1224 /// Returns the second `PublicKeyCredentialHint`.
1225 ///
1226 /// # Examples
1227 ///
1228 /// ```
1229 /// # use structured_webauthn::request::Hints;
1230 /// assert!(Hints::EMPTY.second().is_none());
1231 /// ```
1232 #[inline]
1233 #[must_use]
1234 pub const fn second(self) -> Option<PublicKeyCredentialHint> {
1235 self.0[1]
1236 }
1237 /// Returns the third `PublicKeyCredentialHint`.
1238 ///
1239 /// # Examples
1240 ///
1241 /// ```
1242 /// # use structured_webauthn::request::Hints;
1243 /// assert!(Hints::EMPTY.third().is_none());
1244 /// ```
1245 #[inline]
1246 #[must_use]
1247 pub const fn third(self) -> Option<PublicKeyCredentialHint> {
1248 self.0[2]
1249 }
1250 /// Returns the number of [`PublicKeyCredentialHint`]s in `self`.
1251 ///
1252 /// # Examples
1253 ///
1254 /// ```
1255 /// # use structured_webauthn::request::Hints;
1256 /// assert_eq!(Hints::EMPTY.count(), 0);
1257 /// ```
1258 #[expect(
1259 clippy::arithmetic_side_effects,
1260 clippy::as_conversions,
1261 reason = "comment justifies correctness"
1262 )]
1263 #[inline]
1264 #[must_use]
1265 pub const fn count(self) -> u8 {
1266 // `bool as u8` is well-defined. This maxes at 3, so overflow isn't possible.
1267 self.first().is_some() as u8 + self.second().is_some() as u8 + self.third().is_some() as u8
1268 }
1269 /// Returns `true` iff `self` is empty.
1270 ///
1271 /// # Examples
1272 ///
1273 /// ```
1274 /// # use structured_webauthn::request::Hints;
1275 /// assert!(Hints::EMPTY.is_empty());
1276 /// ```
1277 #[inline]
1278 #[must_use]
1279 pub const fn is_empty(self) -> bool {
1280 self.count() == 0
1281 }
1282 /// Returns `true` iff `self` contains `hint`.
1283 ///
1284 /// # Examples
1285 ///
1286 /// ```
1287 /// # use structured_webauthn::request::{Hints, PublicKeyCredentialHint};
1288 /// assert!(!Hints::EMPTY.contains(PublicKeyCredentialHint::Hybrid));
1289 /// ```
1290 #[inline]
1291 #[must_use]
1292 pub const fn contains(self, hint: PublicKeyCredentialHint) -> bool {
1293 let mut vals = self.0.as_slice();
1294 while let [ref first, ref rem @ ..] = *vals {
1295 match *first {
1296 None => return false,
1297 Some(h) => {
1298 if h.is_eq(hint) {
1299 return true;
1300 }
1301 }
1302 }
1303 vals = rem;
1304 }
1305 false
1306 }
1307 /// Returns `true` iff `self` contains a `hint` that maps to [`AuthenticatorAttachment::CrossPlatform`].
1308 ///
1309 /// # Examples
1310 ///
1311 /// ```
1312 /// # use structured_webauthn::request::Hints;
1313 /// assert!(!Hints::EMPTY.contains_platform_hints());
1314 /// ```
1315 #[inline]
1316 #[must_use]
1317 pub const fn contains_cross_platform_hints(self) -> bool {
1318 let mut vals = self.0.as_slice();
1319 while let [ref first, ref rem @ ..] = *vals {
1320 match *first {
1321 None => return false,
1322 Some(h) => {
1323 if matches!(
1324 h,
1325 PublicKeyCredentialHint::SecurityKey | PublicKeyCredentialHint::Hybrid
1326 ) {
1327 return true;
1328 }
1329 }
1330 }
1331 vals = rem;
1332 }
1333 false
1334 }
1335 /// Returns `true` iff `self` contains a `hint` that maps to [`AuthenticatorAttachment::Platform`].
1336 ///
1337 /// # Examples
1338 ///
1339 /// ```
1340 /// # use structured_webauthn::request::Hints;
1341 /// assert!(!Hints::EMPTY.contains_platform_hints());
1342 /// ```
1343 #[inline]
1344 #[must_use]
1345 pub const fn contains_platform_hints(self) -> bool {
1346 let mut vals = self.0.as_slice();
1347 while let [ref first, ref rem @ ..] = *vals {
1348 match *first {
1349 None => return false,
1350 Some(h) => {
1351 if h.is_eq(PublicKeyCredentialHint::ClientDevice) {
1352 return true;
1353 }
1354 }
1355 }
1356 vals = rem;
1357 }
1358 false
1359 }
1360}
1361/// Controls if the response to a requested extension is required to be sent back.
1362///
1363/// Note when requiring an extension, the extension must not only be sent back but also
1364/// contain at least one expected field (e.g., [`ClientExtensionsOutputs::cred_props`] must be
1365/// `Some(CredentialPropertiesOutput { rk: Some(_) })`.
1366///
1367/// If one wants to additionally control the values of an extension, use [`ExtensionInfo`].
1368#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1369pub enum ExtensionReq {
1370 /// The response to a requested extension is required to be sent back.
1371 Require,
1372 /// The response to a requested extension is allowed, but not required, to be sent back.
1373 Allow,
1374}
1375/// Dictates how an extension should be processed.
1376///
1377/// If one wants to only control if the extension should be returned, use [`ExtensionReq`].
1378#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1379pub enum ExtensionInfo {
1380 /// Require the associated extension and enforce its value.
1381 RequireEnforceValue,
1382 /// Require the associated extension but don't enforce its value.
1383 RequireDontEnforceValue,
1384 /// Allow the associated extension to exist and enforce its value when it does exist.
1385 AllowEnforceValue,
1386 /// Allow the associated extension to exist but don't enforce its value.
1387 AllowDontEnforceValue,
1388}
1389impl Display for ExtensionInfo {
1390 #[inline]
1391 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1392 f.write_str(match *self {
1393 Self::RequireEnforceValue => "require the corresponding extension response and enforce its value",
1394 Self::RequireDontEnforceValue => "require the corresponding extension response but don't enforce its value",
1395 Self::AllowEnforceValue => "don't require the corresponding extension response; but if sent, enforce its value",
1396 Self::AllowDontEnforceValue => "don't require the corresponding extension response; and if sent, don't enforce its value",
1397 })
1398 }
1399}
1400/// [`CredentialMediationRequirement`](https://www.w3.org/TR/credential-management-1/#enumdef-credentialmediationrequirement).
1401///
1402/// Note [`silent`](https://www.w3.org/TR/credential-management-1/#dom-credentialmediationrequirement-silent)
1403/// is not supported for WebAuthn credentials, and
1404/// [`optional`](https://www.w3.org/TR/credential-management-1/#dom-credentialmediationrequirement-optional)
1405/// is just an alias for [`Self::Required`].
1406#[expect(clippy::doc_markdown, reason = "false positive")]
1407#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1408pub enum CredentialMediationRequirement {
1409 /// [`required`](https://www.w3.org/TR/credential-management-1/#dom-credentialmediationrequirement-required).
1410 ///
1411 /// This is the default mediation for ceremonies.
1412 #[default]
1413 Required,
1414 /// [`conditional`](https://www.w3.org/TR/credential-management-1/#dom-credentialmediationrequirement-conditional).
1415 ///
1416 /// Note that when registering a new credential with [`CredentialCreationOptions::mediation`] set to
1417 /// `Self::Conditional`, [`UserVerificationRequirement::Required`] MUST NOT be used unless user verification
1418 /// can be explicitly performed during the ceremony.
1419 Conditional,
1420}
1421/// A container of "credentials".
1422///
1423/// This is mainly a way to unify [`Vec`] of [`PublicKeyCredentialDescriptor`]
1424/// and [`AllowedCredentials`]. This can be useful in situations when one only
1425/// deals with [`AllowedCredential`]s with empty [`CredentialSpecificExtension`]s
1426/// essentially making them the same as [`PublicKeyCredentialDescriptor`]s.
1427///
1428/// # Examples
1429///
1430/// ```
1431/// # use structured_webauthn::{
1432/// # request::{
1433/// # auth::AllowedCredentials, register::UserHandle, Credentials, PublicKeyCredentialDescriptor,
1434/// # },
1435/// # response::{AuthTransports, CredentialId},
1436/// # };
1437/// /// Fetches all credentials under `user_handle` to be allowed during authentication for non-discoverable
1438/// /// requests.
1439/// # #[cfg(feature = "custom")]
1440/// fn get_allowed_credentials<const LEN: usize>(user_handle: &UserHandle<LEN>) -> AllowedCredentials {
1441/// get_credentials(user_handle)
1442/// }
1443/// /// Fetches all credentials under `user_handle` to be excluded during registration.
1444/// # #[cfg(feature = "custom")]
1445/// fn get_excluded_credentials<const LEN: usize>(
1446/// user_handle: &UserHandle<LEN>,
1447/// ) -> Vec<PublicKeyCredentialDescriptor<Box<[u8]>>> {
1448/// get_credentials(user_handle)
1449/// }
1450/// /// Used to fetch the excluded `PublicKeyCredentialDescriptor`s associated with `user_handle` during
1451/// /// registration as well as the `AllowedCredentials` containing `AllowedCredential`s with no credential-specific
1452/// /// extensions which is used for non-discoverable requests.
1453/// # #[cfg(feature = "custom")]
1454/// fn get_credentials<const LEN: usize, T>(user_handle: &UserHandle<LEN>) -> T
1455/// where
1456/// T: Credentials,
1457/// PublicKeyCredentialDescriptor<Box<[u8]>>: Into<T::Credential>,
1458/// {
1459/// let iter = get_cred_parts(user_handle);
1460/// let len = iter.size_hint().0;
1461/// iter.fold(T::with_capacity(len), |mut creds, parts| {
1462/// creds.push(
1463/// PublicKeyCredentialDescriptor {
1464/// id: parts.0,
1465/// transports: parts.1,
1466/// }
1467/// .into(),
1468/// );
1469/// creds
1470/// })
1471/// }
1472/// /// Fetches all `CredentialId`s and associated `AuthTransports` under `user_handle`
1473/// /// from the database.
1474/// # #[cfg(feature = "custom")]
1475/// fn get_cred_parts<const LEN: usize>(
1476/// user_handle: &UserHandle<LEN>,
1477/// ) -> impl Iterator<Item = (CredentialId<Box<[u8]>>, AuthTransports)> {
1478/// // ⋮
1479/// # [(
1480/// # CredentialId::try_from(vec![0; 16].into_boxed_slice()).unwrap(),
1481/// # AuthTransports::NONE,
1482/// # )]
1483/// # .into_iter()
1484/// }
1485/// ```
1486pub trait Credentials: Sized {
1487 /// The "credential"s that make up `Self`.
1488 type Credential;
1489 /// Returns `Self`.
1490 #[inline]
1491 #[must_use]
1492 fn new() -> Self {
1493 Self::with_capacity(0)
1494 }
1495 /// Returns `Self` with at least `capacity` allocated.
1496 fn with_capacity(capacity: usize) -> Self;
1497 /// Adds `cred` to `self`.
1498 ///
1499 /// Returns `true` iff `cred` was added.
1500 fn push(&mut self, cred: Self::Credential) -> bool;
1501 /// Returns the number of [`Self::Credential`]s in `Self`.
1502 fn len(&self) -> usize;
1503 /// Returns `true` iff [`Self::len`] is `0`.
1504 #[inline]
1505 fn is_empty(&self) -> bool {
1506 self.len() == 0
1507 }
1508}
1509impl<T> Credentials for Vec<T> {
1510 type Credential = T;
1511 #[inline]
1512 fn with_capacity(capacity: usize) -> Self {
1513 Self::with_capacity(capacity)
1514 }
1515 #[inline]
1516 fn push(&mut self, cred: Self::Credential) -> bool {
1517 self.push(cred);
1518 true
1519 }
1520 #[inline]
1521 fn len(&self) -> usize {
1522 self.len()
1523 }
1524}
1525/// Additional options that control how [`Ceremony::partial_validate`] works.
1526struct CeremonyOptions<'origins, 'top_origins, O, T> {
1527 /// Origins to use for [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin).
1528 ///
1529 /// When this is empty, the origin that will be used will be based on
1530 /// the [`RpId`] passed to [`RegistrationServerState::verify`]. If [`RpId::Domain`], then the [`DomainOrigin`] returned from
1531 /// passing [`AsciiDomain::as_ref`] to [`DomainOrigin::new`] will be used; otherwise the [`Url`] in
1532 /// [`RpId::Url`] will be used.
1533 allowed_origins: &'origins [O],
1534 /// [Top-level origins](https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-top-level-origin)
1535 /// to use for [origin validation](https://www.w3.org/TR/webauthn-3/#sctn-validating-origin).
1536 ///
1537 /// When this is `Some`, [`CollectedClientData::cross_origin`] is allowed to be `true`. When the contained
1538 /// `slice` is empty, [`CollectedClientData::top_origin`] must be `None`. When this is `None`,
1539 /// `CollectedClientData::cross_origin` must be `false` and `CollectedClientData::top_origin` must be `None`.
1540 allowed_top_origins: Option<&'top_origins [T]>,
1541 /// The required [`Backup`] state of the credential.
1542 backup_requirement: BackupReq,
1543 /// [`CollectedClientData::from_client_data_json_relaxed`] is used to extract [`CollectedClientData`] iff `true`.
1544 #[cfg(feature = "serde_relaxed")]
1545 client_data_json_relaxed: bool,
1546}
1547impl<'o, 't, O, T> From<&RegistrationVerificationOptions<'o, 't, O, T>>
1548 for CeremonyOptions<'o, 't, O, T>
1549{
1550 fn from(value: &RegistrationVerificationOptions<'o, 't, O, T>) -> Self {
1551 Self {
1552 allowed_origins: value.allowed_origins,
1553 allowed_top_origins: value.allowed_top_origins,
1554 backup_requirement: value.backup_requirement,
1555 #[cfg(feature = "serde_relaxed")]
1556 client_data_json_relaxed: value.client_data_json_relaxed,
1557 }
1558 }
1559}
1560/// Functionality common to both registration and authentication ceremonies.
1561///
1562/// Designed to be implemented on the _request_ side.
1563trait Ceremony<const USER_LEN: usize, const DISCOVERABLE: bool> {
1564 /// The type of response that is associated with the ceremony.
1565 type R: Response;
1566 /// Challenge.
1567 fn rand_challenge(&self) -> SentChallenge;
1568 /// `Instant` the ceremony was expires.
1569 #[cfg(not(feature = "serializable_server_state"))]
1570 fn expiry(&self) -> Instant;
1571 /// `Instant` the ceremony was expires.
1572 #[cfg(feature = "serializable_server_state")]
1573 fn expiry(&self) -> SystemTime;
1574 /// User verification requirement.
1575 fn user_verification(&self) -> UserVerificationRequirement;
1576 /// Performs validation of ceremony criteria common to both ceremony types.
1577 #[expect(
1578 clippy::type_complexity,
1579 reason = "type aliases with bounds are even more problematic at least until lazy_type_alias is stable"
1580 )]
1581 #[expect(clippy::too_many_lines, reason = "102 lines is fine")]
1582 fn partial_validate<'a, O: PartialEq<Origin<'a>>, T: PartialEq<Origin<'a>>>(
1583 &self,
1584 rp_id: &RpId,
1585 resp: &'a Self::R,
1586 key: <<Self::R as Response>::Auth as AuthResponse>::CredKey<'_>,
1587 options: &CeremonyOptions<'_, '_, O, T>,
1588 ) -> Result<
1589 <<Self::R as Response>::Auth as AuthResponse>::Auth<'a>,
1590 CeremonyErr<
1591 <<<Self::R as Response>::Auth as AuthResponse>::Auth<'a> as AuthDataContainer<'a>>::Err,
1592 >,
1593 > {
1594 // [Registration ceremony](https://www.w3.org/TR/webauthn-3/#sctn-registering-a-new-credential)
1595 // is handled by:
1596 //
1597 // 1. Calling code.
1598 // 2. Client code and the construction of `resp` (hopefully via [`Registration::deserialize`]).
1599 // 3. Client code and the construction of `resp` (hopefully via [`AuthenticatorAttestation::deserialize`]).
1600 // 4. Client code and the construction of `resp` (hopefully via [`ClientExtensionsOutputs::deserialize`]).
1601 // 5. Below via [`CollectedClientData::from_client_data_json_relaxed`].
1602 // 6. Below via [`CollectedClientData::from_client_data_json_relaxed`] or [`CollectedClientData::from_client_data_json_relaxed`].
1603 // 7. Below via [`CollectedClientData::from_client_data_json_relaxed`] or [`CollectedClientData::from_client_data_json_relaxed`].
1604 // 8. Below.
1605 // 9. Below.
1606 // 10. Below.
1607 // 11. Below.
1608 // 12. Below via [`AuthenticatorAttestation::new`].
1609 // 13. Below via [`AttestationObject::parse_data`].
1610 // 14. Below.
1611 // 15. [`RegistrationServerState::verify`].
1612 // 16. Below.
1613 // 17. Below via [`AuthenticatorData::from_cbor`].
1614 // 18. Below.
1615 // 19. Below.
1616 // 20. [`RegistrationServerState::verify`].
1617 // 21. Below via [`AttestationObject::parse_data`].
1618 // 22. Below via [`AttestationObject::parse_data`].
1619 // 23. N/A since only none and self attestations are supported.
1620 // 24. Always satisfied since only none and self attestations are supported (Item 3 is N/A).
1621 // 25. Below via [`AttestedCredentialData::from_cbor`].
1622 // 26. Calling code.
1623 // 27. [`RegistrationServerState::verify`].
1624 // 28. N/A since only none and self attestations are supported.
1625 // 29. [`RegistrationServerState::verify`].
1626 //
1627 //
1628 // [Authentication ceremony](https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion)
1629 // is handled by:
1630 //
1631 // 1. Calling code.
1632 // 2. Client code and the construction of `resp` (hopefully via [`Authentication::deserialize`]).
1633 // 3. Client code and the construction of `resp` (hopefully via [`AuthenticatorAssertion::deserialize`]).
1634 // 4. Client code and the construction of `resp` (hopefully via [`ClientExtensionsOutputs::deserialize`]).
1635 // 5. [`AuthenticationServerState::verify`].
1636 // 6. [`AuthenticationServerState::verify`].
1637 // 7. Informative only in that it defines variables.
1638 // 8. Below via [`CollectedClientData::from_client_data_json_relaxed`].
1639 // 9. Below via [`CollectedClientData::from_client_data_json_relaxed`] or [`CollectedClientData::from_client_data_json_relaxed`].
1640 // 10. Below via [`CollectedClientData::from_client_data_json_relaxed`] or [`CollectedClientData::from_client_data_json_relaxed`].
1641 // 11. Below.
1642 // 12. Below.
1643 // 13. Below.
1644 // 14. Below.
1645 // 15. Below.
1646 // 16. Below via [`AuthenticatorData::from_cbor`].
1647 // 17. Below.
1648 // 18. Below via [`AuthenticatorData::from_cbor`].
1649 // 19. Below.
1650 // 20. Below via [`AuthenticatorAssertion::new`].
1651 // 21. Below.
1652 // 22. [`AuthenticationServerState::verify`].
1653 // 23. [`AuthenticationServerState::verify`].
1654 // 24. [`AuthenticationServerState::verify`].
1655 // 25. [`AuthenticationServerState::verify`].
1656
1657 // Enforce timeout.
1658 #[cfg(not(feature = "serializable_server_state"))]
1659 let active = self.expiry() >= Instant::now();
1660 #[cfg(feature = "serializable_server_state")]
1661 let active = self.expiry() >= SystemTime::now();
1662 if active {
1663 #[cfg(feature = "serde_relaxed")]
1664 let relaxed = options.client_data_json_relaxed;
1665 #[cfg(not(feature = "serde_relaxed"))]
1666 let relaxed = false;
1667 resp.auth()
1668 // Steps 5–7, 12–13, 17, 21–22, and 25 of the registration ceremony.
1669 // Steps 8–10, 16, 18, and 20–21 of the authentication ceremony.
1670 .parse_data_and_verify_sig(key, relaxed)
1671 .map_err(CeremonyErr::AuthResp)
1672 .and_then(|(client_data_json, auth_response)| {
1673 if options.allowed_origins.is_empty() {
1674 if match *rp_id {
1675 RpId::Domain(ref dom) => {
1676 // Steps 9 and 12 of the registration and authentication ceremonies
1677 // respectively.
1678 DomainOrigin::new(dom.as_ref()) == client_data_json.origin
1679 }
1680 // Steps 9 and 12 of the registration and authentication ceremonies
1681 // respectively.
1682 RpId::Url(ref url) => url == client_data_json.origin,
1683 RpId::StaticDomain(dom) => {
1684 DomainOrigin::new(dom.0) == client_data_json.origin
1685 }
1686 } {
1687 Ok(())
1688 } else {
1689 Err(CeremonyErr::OriginMismatch)
1690 }
1691 } else {
1692 options
1693 .allowed_origins
1694 .iter()
1695 // Steps 9 and 12 of the registration and authentication ceremonies
1696 // respectively.
1697 .find(|o| **o == client_data_json.origin)
1698 .ok_or(CeremonyErr::OriginMismatch)
1699 .map(|_| ())
1700 }
1701 .and_then(|()| {
1702 // Steps 10–11 of the registration ceremony.
1703 // Steps 13–14 of the authentication ceremony.
1704 match options.allowed_top_origins {
1705 None => {
1706 if client_data_json.cross_origin {
1707 Err(CeremonyErr::CrossOrigin)
1708 } else if client_data_json.top_origin.is_some() {
1709 Err(CeremonyErr::TopOriginMismatch)
1710 } else {
1711 Ok(())
1712 }
1713 }
1714 Some(top_origins) => client_data_json.top_origin.map_or(Ok(()), |t| {
1715 top_origins
1716 .iter()
1717 .find(|top| **top == t)
1718 .ok_or(CeremonyErr::TopOriginMismatch)
1719 .map(|_| ())
1720 }),
1721 }
1722 .and_then(|()| {
1723 // Steps 8 and 11 of the registration and authentication ceremonies
1724 // respectively.
1725 if self.rand_challenge() == client_data_json.challenge {
1726 let auth_data = auth_response.authenticator_data();
1727 rp_id
1728 // Steps 14 and 15 of the registration and authentication ceremonies
1729 // respectively.
1730 .validate_rp_id_hash(auth_data.rp_hash())
1731 .and_then(|()| {
1732 let flag = auth_data.flag();
1733 // Steps 16 and 17 of the registration and authentication ceremonies
1734 // respectively.
1735 if flag.user_verified
1736 || !matches!(
1737 self.user_verification(),
1738 UserVerificationRequirement::Required
1739 )
1740 {
1741 // Steps 18–19 of the registration ceremony.
1742 // Step 19 of the authentication ceremony.
1743 match options.backup_requirement {
1744 BackupReq::None => Ok(()),
1745 BackupReq::NotEligible => {
1746 if matches!(flag.backup, Backup::NotEligible) {
1747 Ok(())
1748 } else {
1749 Err(CeremonyErr::BackupEligible)
1750 }
1751 }
1752 BackupReq::Eligible => {
1753 if matches!(flag.backup, Backup::NotEligible) {
1754 Err(CeremonyErr::BackupNotEligible)
1755 } else {
1756 Ok(())
1757 }
1758 }
1759 BackupReq::EligibleNotExists => {
1760 if matches!(flag.backup, Backup::Eligible) {
1761 Ok(())
1762 } else {
1763 Err(CeremonyErr::BackupExists)
1764 }
1765 }
1766 BackupReq::Exists => {
1767 if matches!(flag.backup, Backup::Exists) {
1768 Ok(())
1769 } else {
1770 Err(CeremonyErr::BackupDoesNotExist)
1771 }
1772 }
1773 }
1774 } else {
1775 Err(CeremonyErr::UserNotVerified)
1776 }
1777 })
1778 .map(|()| auth_response)
1779 } else {
1780 Err(CeremonyErr::ChallengeMismatch)
1781 }
1782 })
1783 })
1784 })
1785 } else {
1786 Err(CeremonyErr::Timeout)
1787 }
1788 }
1789}
1790/// "Ceremonies" stored on the server that expire after a certain duration.
1791///
1792/// Types like [`RegistrationServerState`] and [`DiscoverableAuthenticationServerState`] are based on [`Challenge`]s
1793/// that expire after a certain duration.
1794pub trait TimedCeremony {
1795 /// Returns the `Instant` the ceremony expires.
1796 ///
1797 /// Note when `serializable_server_state` is enabled, [`SystemTime`] is returned instead.
1798 #[cfg_attr(docsrs, doc(auto_cfg = false))]
1799 #[cfg(any(doc, not(feature = "serializable_server_state")))]
1800 fn expiration(&self) -> Instant;
1801 /// Returns the `SystemTime` the ceremony expires.
1802 #[cfg(all(not(doc), feature = "serializable_server_state"))]
1803 fn expiration(&self) -> SystemTime;
1804}
1805/// [`AuthenticationExtensionsPRFValues`](https://www.w3.org/TR/webauthn-3/#dictdef-authenticationextensionsprfvalues).
1806#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1807pub struct PrfInput<'first, 'second> {
1808 /// [`first`](https://www.w3.org/TR/webauthn-3/#dom-authenticationextensionsprfvalues-first).
1809 pub first: &'first [u8],
1810 /// [`second`](https://www.w3.org/TR/webauthn-3/#dom-authenticationextensionsprfvalues-second).
1811 pub second: Option<&'second [u8]>,
1812}
1813impl<'first, 'second> PrfInput<'first, 'second> {
1814 /// Returns a `PrfInput` with [`Self::first`] set to `first` and [`Self::second`] set to `None`.
1815 #[inline]
1816 #[must_use]
1817 pub const fn with_first<'a: 'first>(first: &'a [u8]) -> Self {
1818 Self {
1819 first,
1820 second: None,
1821 }
1822 }
1823 /// Same as [`Self::with_first`] except [`Self::second`] is set to `Some` containing `second`.
1824 #[inline]
1825 #[must_use]
1826 pub const fn with_two<'a: 'first, 'b: 'second>(first: &'a [u8], second: &'b [u8]) -> Self {
1827 Self {
1828 first,
1829 second: Some(second),
1830 }
1831 }
1832}
1833/// The number of milliseconds in 5 minutes.
1834///
1835/// This is the recommended default timeout duration for ceremonies
1836/// [in the spec](https://www.w3.org/TR/webauthn-3/#sctn-timeout-recommended-range).
1837pub const FIVE_MINUTES: NonZeroU32 = NonZeroU32::new(300_000).unwrap();