structured_webauthn/lib.rs
1//! [![github]](https://github.com/structured-world/structured-webauthn) [![crates-io]](https://crates.io/crates/structured-webauthn) [![docs-rs]](crate)
2//!
3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! `structured-webauthn` is a pure-Rust library for _server-side_
8//! [Web Authentication (WebAuthn)](https://www.w3.org/TR/webauthn-3/#sctn-rp-operations) Relying Party
9//! (RP) operations.
10//!
11//! The purpose of a server-side RP library is to be modular so that any client can be used with it as a backend
12//! _including_ native applications—WebAuthn technically only covers web applications; however it's relatively easy
13//! to adapt to native applications as well. It achieves this by not assuming how data is sent to/from the client;
14//! having said that, there are pre-defined serialization formats for "common" deployments which can be used when
15//! [`serde`](#serde) is enabled.
16//!
17//! It started from [`webauthn_rp`](https://git.philomathiclife.com/repos/webauthn_rp/) by Zack Newman;
18//! see `NOTICE` for the origin and its license.
19//!
20//! ## `structured-webauthn` in action
21//!
22//! ```
23//! use core::convert;
24//! use structured_webauthn::{
25//! AuthenticatedCredential64, DiscoverableAuthentication64, DiscoverableAuthenticationServerState,
26//! DiscoverableCredentialRequestOptions, CredentialCreationOptions64, RegisteredCredential64,
27//! Registration, RegistrationServerState64,
28//! hash::hash_set::{InsertRemoveExpired, MaxLenHashSet},
29//! request::{
30//! PublicKeyCredentialDescriptor, RpId,
31//! auth::AuthenticationVerificationOptions,
32//! register::{
33//! PublicKeyCredentialUserEntity64, RegistrationVerificationOptions,
34//! UserHandle64,
35//! },
36//! },
37//! response::{
38//! CredentialId,
39//! auth::error::AuthCeremonyErr,
40//! register::{CompressedPubKeyOwned, DynamicState, error::RegCeremonyErr},
41//! },
42//! };
43//! # #[cfg(feature = "serde")]
44//! use serde::de::{Deserialize, Deserializer};
45//! # #[cfg(feature = "serde_relaxed")]
46//! use serde_json::Error as JsonErr;
47//! /// The RP ID our application uses.
48//! const RP_ID: &RpId = &RpId::from_static_domain("example.com").unwrap();
49//! /// The registration verification options.
50//! const REG_OPTS: &RegistrationVerificationOptions::<'static, 'static, &'static str, &'static str> = &RegistrationVerificationOptions::new();
51//! /// The authentication verification options.
52//! const AUTH_OPTS: &AuthenticationVerificationOptions::<'static, 'static, &'static str, &'static str> = &AuthenticationVerificationOptions::new();
53//! /// Error we return in our application when a function fails.
54//! enum AppErr {
55//! /// WebAuthn registration ceremony failed.
56//! RegCeremony(RegCeremonyErr),
57//! /// WebAuthn authentication ceremony failed.
58//! AuthCeremony(AuthCeremonyErr),
59//! /// Unable to insert a WebAuthn ceremony.
60//! WebAuthnCeremonyCreation,
61//! /// WebAuthn ceremony does not exist; thus the ceremony could not be completed.
62//! MissingWebAuthnCeremony,
63//! /// General error related to JSON deserialization.
64//! # #[cfg(feature = "serde_relaxed")]
65//! Json(JsonErr),
66//! /// No account exists associated with a particular `UserHandle64`.
67//! NoAccount,
68//! /// No credential exists associated with a particular `CredentialId`.
69//! NoCredential,
70//! /// `CredentialId` exists but the associated `UserHandle64` does not match.
71//! CredentialUserIdMismatch,
72//! }
73//! # #[cfg(feature = "serde_relaxed")]
74//! impl From<JsonErr> for AppErr {
75//! fn from(value: JsonErr) -> Self {
76//! Self::Json(value)
77//! }
78//! }
79//! impl From<RegCeremonyErr> for AppErr {
80//! fn from(value: RegCeremonyErr) -> Self {
81//! Self::RegCeremony(value)
82//! }
83//! }
84//! impl From<AuthCeremonyErr> for AppErr {
85//! fn from(value: AuthCeremonyErr) -> Self {
86//! Self::AuthCeremony(value)
87//! }
88//! }
89//! /// First-time account creation.
90//! ///
91//! /// This gets sent from the user after an account is created on their side. The registration ceremony
92//! /// still has to be successfully completed for the account to be created server side. In the event of an error,
93//! /// the user should delete the created passkey since it won't be usable.
94//! struct AccountReg {
95//! registration: Registration,
96//! user_name: String,
97//! user_display_name: String,
98//! }
99//! # #[cfg(feature = "serde")]
100//! impl<'de> Deserialize<'de> for AccountReg {
101//! fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
102//! where
103//! D: Deserializer<'de>,
104//! {
105//! // ⋮
106//! # panic!("");
107//! }
108//! }
109//! /// Starts account creation.
110//! ///
111//! /// This only makes sense for greenfield deployments since account information (e.g., user name) would likely
112//! /// already exist otherwise. This is similar to credential creation except a random `UserHandle64` is generated and
113//! /// will be used for subsequent credential registrations.
114//! # #[cfg(feature = "serde_relaxed")]
115//! fn start_account_creation(
116//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
117//! ) -> Result<Vec<u8>, AppErr> {
118//! let user_id = UserHandle64::new();
119//! let (server, client) =
120//! CredentialCreationOptions64::passkey(
121//! RP_ID, PublicKeyCredentialUserEntity64 { id: &user_id, name: "", display_name: "", }, Vec::new()
122//! )
123//! .start_ceremony()
124//! .unwrap_or_else(|_e| {
125//! unreachable!("we don't manually mutate the options and we assume the server clock is functioning; thus this won't error")
126//! });
127//! if matches!(reg_ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success)
128//! {
129//! Ok(serde_json::to_vec(&client)
130//! .unwrap_or_else(|_e| unreachable!("bug in RegistrationClientState64::serialize")))
131//! } else {
132//! Err(AppErr::WebAuthnCeremonyCreation)
133//! }
134//! }
135//! /// Finishes account creation.
136//! ///
137//! /// Pending a successful registration ceremony, a new account associated with the randomly generated
138//! /// `UserHandle64` will be created with a corresponding passkey entry. This passkey will be used to
139//! /// log into the application.
140//! ///
141//! /// Note if this errors, then the user should be notified to delete the passkey created on their
142//! /// authenticator.
143//! # #[cfg(feature = "serde_relaxed")]
144//! fn finish_account_creation(
145//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
146//! client_data: &[u8],
147//! ) -> Result<(), AppErr> {
148//! let account = serde_json::from_slice::<AccountReg>(client_data)?;
149//! insert_account(
150//! &account,
151//! reg_ceremonies
152//! // `Registration::challenge_relaxed` is available iff `serde_relaxed` is enabled.
153//! .take(&account.registration.challenge_relaxed()?)
154//! .ok_or(AppErr::MissingWebAuthnCeremony)?
155//! .verify(
156//! RP_ID,
157//! &account.registration,
158//! REG_OPTS,
159//! )?,
160//! )
161//! }
162//! /// Starts passkey registration.
163//! ///
164//! /// This is used for _existing_ accounts where the user is already logged in and wants to register another
165//! /// passkey. This is similar to account creation except we already have the user entity info and we need to
166//! /// fetch the registered `PublicKeyCredentialDescriptor`s to avoid accidentally overwriting a passkey on
167//! /// the authenticator.
168//! # #[cfg(feature = "serde_relaxed")]
169//! fn start_cred_registration(
170//! user_id: &UserHandle64,
171//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
172//! ) -> Result<Vec<u8>, AppErr> {
173//! let (username, user_display_name, creds) = select_user_info(user_id)?.ok_or(AppErr::NoAccount)?;
174//! let (server, client) = CredentialCreationOptions64::passkey(RP_ID, PublicKeyCredentialUserEntity64 { name: &username, id: user_id, display_name: &user_display_name, }, creds)
175//! .start_ceremony()
176//! .unwrap_or_else(|_e| {
177//! unreachable!("we don't manually mutate the options and we assume the server clock is functioning; thus this won't error")
178//! });
179//! if matches!(reg_ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success)
180//! {
181//! Ok(serde_json::to_vec(&client)
182//! .unwrap_or_else(|_e| unreachable!("bug in RegistrationClientState64::serialize")))
183//! } else {
184//! Err(AppErr::WebAuthnCeremonyCreation)
185//! }
186//! }
187//! /// Finishes passkey registration.
188//! ///
189//! /// Pending a successful registration ceremony, a new credential associated with the `UserHandle64`
190//! /// will be created. This passkey can then be used to log into the application just like any other registered
191//! /// passkey.
192//! ///
193//! /// Note if this errors, then the user should be notified to delete the passkey created on their
194//! /// authenticator.
195//! # #[cfg(feature = "serde_relaxed")]
196//! fn finish_cred_registration(
197//! reg_ceremonies: &mut MaxLenHashSet<RegistrationServerState64>,
198//! client_data: &[u8],
199//! ) -> Result<(), AppErr> {
200//! // `Registration::from_json_custom` is available iff `serde_relaxed` is enabled.
201//! let registration = Registration::from_json_custom(client_data)?;
202//! insert_credential(
203//! reg_ceremonies
204//! // `Registration::challenge_relaxed` is available iff `serde_relaxed` is enabled.
205//! .take(®istration.challenge_relaxed()?)
206//! .ok_or(AppErr::MissingWebAuthnCeremony)?
207//! .verify(
208//! RP_ID,
209//! ®istration,
210//! REG_OPTS,
211//! )?,
212//! )
213//! }
214//! /// Starts the passkey authentication ceremony.
215//! # #[cfg(feature = "serde_relaxed")]
216//! fn start_auth(
217//! auth_ceremonies: &mut MaxLenHashSet<DiscoverableAuthenticationServerState>,
218//! ) -> Result<Vec<u8>, AppErr> {
219//! let (server, client) = DiscoverableCredentialRequestOptions::passkey(RP_ID)
220//! .start_ceremony()
221//! .unwrap_or_else(|_e| {
222//! unreachable!("we don't manually mutate the options and we assume the server clock is functioning; thus this won't error")
223//! });
224//! if matches!(auth_ceremonies.insert_remove_all_expired(server), InsertRemoveExpired::Success)
225//! {
226//! Ok(serde_json::to_vec(&client).unwrap_or_else(|_e| {
227//! unreachable!("bug in DiscoverableAuthenticationClientState::serialize")
228//! }))
229//! } else {
230//! Err(AppErr::WebAuthnCeremonyCreation)
231//! }
232//! }
233//! /// Finishes the passkey authentication ceremony.
234//! # #[cfg(feature = "serde_relaxed")]
235//! fn finish_auth(
236//! auth_ceremonies: &mut MaxLenHashSet<DiscoverableAuthenticationServerState>,
237//! client_data: &[u8],
238//! ) -> Result<(), AppErr> {
239//! // `DiscoverableAuthentication64::from_json_custom` is available iff `serde_relaxed` is enabled.
240//! let authentication =
241//! DiscoverableAuthentication64::from_json_custom(client_data)?;
242//! let mut cred = select_credential(
243//! authentication.raw_id(),
244//! authentication.response().user_handle(),
245//! )?
246//! .ok_or(AppErr::NoCredential)?;
247//! if auth_ceremonies
248//! // `DiscoverableAuthentication64::challenge_relaxed` is available iff `serde_relaxed` is enabled.
249//! .take(&authentication.challenge_relaxed()?)
250//! .ok_or(AppErr::MissingWebAuthnCeremony)?
251//! .verify(
252//! RP_ID,
253//! &authentication,
254//! &mut cred,
255//! AUTH_OPTS,
256//! )?
257//! {
258//! update_credential(cred.id(), cred.dynamic_state())
259//! } else {
260//! Ok(())
261//! }
262//! }
263//! /// Writes `account` and `cred` to storage.
264//! ///
265//! /// # Errors
266//! ///
267//! /// Errors iff writing `account` or `cred` errors, there already exists a credential using the same
268//! /// `CredentialId`, or there already exists an account using the same `UserHandle64`.
269//! fn insert_account(
270//! account: &AccountReg,
271//! cred: RegisteredCredential64<'_>,
272//! ) -> Result<(), AppErr> {
273//! // ⋮
274//! # Ok(())
275//! }
276//! /// Fetches the user info and registered credentials associated with `user_id`.
277//! ///
278//! /// # Errors
279//! ///
280//! /// Errors iff fetching the data errors.
281//! fn select_user_info(
282//! user_id: &UserHandle64,
283//! ) -> Result<
284//! Option<(
285//! String,
286//! String,
287//! Vec<PublicKeyCredentialDescriptor<Box<[u8]>>>,
288//! )>,
289//! AppErr,
290//! > {
291//! // ⋮
292//! # Ok(None)
293//! }
294//! /// Writes `cred` to storage.
295//! ///
296//! /// # Errors
297//! ///
298//! /// Errors iff writing `cred` errors, there already exists a credential using the same `CredentialId`,
299//! /// or there does not exist an account under the `UserHandle64`.
300//! fn insert_credential(
301//! cred: RegisteredCredential64<'_>,
302//! ) -> Result<(), AppErr> {
303//! // ⋮
304//! # Ok(())
305//! }
306//! /// Fetches the `AuthenticatedCredential` associated with `cred_id` ensuring `user_id` matches the
307//! /// `UserHandle64` associated with the account.
308//! ///
309//! /// # Errors
310//! ///
311//! /// Errors iff fetching the data errors or the `user_id` does not match the stored `UserHandle64`.
312//! fn select_credential<'cred, 'user>(
313//! cred_id: CredentialId<&'cred [u8]>,
314//! user_id: &'user UserHandle64,
315//! ) -> Result<
316//! Option<
317//! AuthenticatedCredential64<
318//! 'cred,
319//! 'user,
320//! CompressedPubKeyOwned,
321//! >,
322//! >,
323//! AppErr,
324//! > {
325//! // ⋮
326//! # Ok(None)
327//! }
328//! /// Overwrites the current `DynamicState` associated with `cred_id` with `dynamic_state`.
329//! ///
330//! /// # Errors
331//! ///
332//! /// Errors iff writing errors or `cred_id` does not exist.
333//! fn update_credential(
334//! cred_id: CredentialId<&[u8]>,
335//! dynamic_state: DynamicState,
336//! ) -> Result<(), AppErr> {
337//! // ⋮
338//! # Ok(())
339//! }
340//! ```
341//!
342//! ## Cargo "features"
343//!
344//! [`custom`](#custom) or both [`bin`](#bin) and [`serde`](#serde) must be enabled; otherwise a [`compile_error`]
345//! will occur.
346//!
347//! ### `bin`
348//!
349//! Enables binary (de)serialization via [`Encode`] and [`Decode`]. Since registered credentials will almost always
350//! have to be saved to persistent storage, _some_ form of (de)serialization is necessary. In the event `bin` is
351//! unsuitable or only partially suitable (e.g., human-readable output is desired), one will need to enable
352//! [`custom`](#custom) to allow construction of certain types (e.g., [`AuthenticatedCredential`]).
353//!
354//! If possible and desired, one may wish to save the data "directly" to avoid any potential temporary allocations.
355//! For example [`StaticState::encode`] will return a [`Vec`] containing thousands of bytes if the underlying
356//! public key is an ML-DSA key. This additional allocation and copy of data is obviously avoided if
357//! [`StaticState`] is stored as a [composite type](https://www.postgresql.org/docs/current/rowtypes.html) or its
358//! fields are stored in separate columns when written to a relational database (RDB).
359//!
360//! ### `custom`
361//!
362//! Exposes functions (e.g., [`AuthenticatedCredential::new`]) that allows one to construct instances of types that
363//! cannot be constructed when [`bin`](#bin) or [`serde`](#serde) is not enabled.
364//!
365//! ### `serde`
366//!
367//! This feature _strictly_ adheres to the JSON-motivated definitions. You _will_ encounter clients that send data
368//! that cannot be deserialized using this feature. For many [`serde_relaxed`](#serde_relaxed) should be used
369//! instead.
370//!
371//! Enables (de)serialization of data sent to/from the client via [`serde`](https://docs.rs/serde/latest/serde/)
372//! based on the JSON-motivated definitions (e.g.,
373//! [`RegistrationResponseJSON`](https://www.w3.org/TR/webauthn-3/#dictdef-registrationresponsejson)). Since
374//! data has to be sent to/from the client, _some_ form of (de)serialization is necessary. In the event `serde`
375//! is unsuitable or only partially suitable, one will need to enable [`custom`](#custom) to allow construction
376//! of certain types (e.g., [`Registration`]).
377//!
378//! Code is _strongly_ encouraged to rely on the [`Deserialize`] implementations as much as possible to reduce the
379//! chances of improperly deserializing the client data.
380//!
381//! Note that clients are free to send data in whatever form works best, so there is no requirement the
382//! JSON-motivated definitions are used even when JSON is sent. This is especially relevant since the JSON-motivated
383//! definitions were only added in [WebAuthn Level 3](https://www.w3.org/TR/webauthn-3/); thus many deployments only
384//! partially conform. Some specific deviations that may require partial customization of deserialization are the
385//! following:
386//!
387//! * [`ArrayBuffer`](https://webidl.spec.whatwg.org/#idl-ArrayBuffer)s encoded using something other than
388//! base64url.
389//! * `ArrayBuffer`s that are encoded multiple times (including the use of different encodings each time).
390//! * Missing fields (e.g.,
391//! [`transports`](https://www.w3.org/TR/webauthn-3/#dom-authenticatorattestationresponsejson-transports)).
392//! * Different field names (e.g., `extensions` instead of
393//! [`clientExtensionResults`](https://www.w3.org/TR/webauthn-3/#dom-registrationresponsejson-clientextensionresults)).
394//!
395//! ### `serde_relaxed`
396//!
397//! Automatically enables [`serde`](#serde) in addition to "relaxed" [`Deserialize`] implementations
398//! (e.g., [`RegistrationRelaxed`]). Roughly "relaxed" translates to unknown fields being ignored and only
399//! the fields necessary for construction of the type are required. Case still matters, duplicate fields are still
400//! forbidden, and interrelated data validation is still performed when applicable. This can be useful when one
401//! wants to accommodate non-conforming clients or clients that implement older versions of the spec.
402//!
403//! ### `serializable_server_state`
404//!
405//! Automatically enables [`bin`](#bin) in addition to [`Encode`] and [`Decode`] implementations for
406//! [`RegistrationServerState`], [`DiscoverableAuthenticationServerState`], and
407//! [`NonDiscoverableAuthenticationServerState`]. Less accurate [`SystemTime`] is used instead of [`Instant`] for
408//! timeout enforcement. This should be enabled if you don't desire to use in-memory collections to store the instances
409//! of those types.
410//!
411//! Note even when written to persistent storage, an application should still periodically remove expired ceremonies.
412//! If one is using a relational database (RDB); then one can achieve this by storing [`SentChallenge`],
413//! the `Vec` returned from [`Encode::encode`], and [`TimedCeremony::expiration`] and periodically remove all rows
414//! whose expiration exceeds the current date and time.
415//!
416//! ## Registration and authentication
417//!
418//! Both [registration](https://www.w3.org/TR/webauthn-3/#registration-ceremony) and
419//! [authentication](https://www.w3.org/TR/webauthn-3/#authentication-ceremony) ceremonies rely on "challenges", and
420//! these challenges are inherently temporary. For this reason the data associated with challenge completion can
421//! often be stored in memory without concern for out-of-memory (OOM) conditions. There are several benefits to
422//! storing such data in memory:
423//!
424//! * No data manipulation
425//! * By leveraging move semantics, the data sent to the client cannot be mutated once the ceremony begins.
426//! * Improved timeout enforcement
427//! * By ensuring the same machine that started the ceremony is also used to finish the ceremony, deviation of
428//! system clocks is not a concern. Additionally, allowing serialization requires the use of some form of
429//! cross-platform "timestamp" (e.g., [Unix time](https://en.wikipedia.org/wiki/Unix_time)) which differ in
430//! implementation (e.g., platforms implement leap seconds in different ways) and are often not monotonically
431//! increasing. If data resides in memory, a monotonic [`Instant`] can be used instead.
432//!
433//! It is for those reasons data like [`RegistrationServerState`] are not serializable by default and require the
434//! use of in-memory collections (e.g., [`MaxLenHashSet`]). To better ensure OOM is not a concern, RPs should set
435//! reasonable timeouts. Since ceremonies can only be completed by moving data (e.g.,
436//! [`RegistrationServerState::verify`]), ceremony completion is guaranteed to free up the memory used—
437//! `RegistrationServerState` instances are as small as 48 bytes on `x86_64-unknown-linux-gnu` platforms. To avoid
438//! issues related to incomplete ceremonies, RPs can periodically iterate the collection for expired ceremonies and
439//! remove such data. Other techniques can be employed as well to mitigate OOM, but they are application specific
440//! and out-of-scope. If this is undesirable, one can enable [`serializable_server_state`](#serializable_server_state)
441//! so that `RegistrationServerState`, [`DiscoverableAuthenticationServerState`], and
442//! [`NonDiscoverableAuthenticationServerState`] implement [`Encode`] and [`Decode`]. Another reason one may need to
443//! store this information persistently is for load-balancing purposes where the server that started the ceremony is
444//! not guaranteed to be the server that finishes the ceremony.
445//!
446//! ## Supported signature algorithms
447//!
448//! The only supported signature algorithms are the following:
449//!
450//! * ML-DSA-87 as defined in [NIST FIPS 204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf). This
451//! corresponds to [`CoseAlgorithmIdentifier::Mldsa87`].
452//! * ML-DSA-65 as defined in [NIST FIPS 204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf). This
453//! corresponds to [`CoseAlgorithmIdentifier::Mldsa65`].
454//! * ML-DSA-44 as defined in [NIST FIPS 204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf). This
455//! corresponds to [`CoseAlgorithmIdentifier::Mldsa44`].
456//! * Ed25519 as defined in [RFC 8032 § 5.1](https://www.rfc-editor.org/rfc/rfc8032#section-5.1). This corresponds
457//! to [`CoseAlgorithmIdentifier::Eddsa`].
458//! * ECDSA as defined in [SEC 1 Version 2.0 § 4.1](https://www.secg.org/sec1-v2.pdf#subsection.4.1) using SHA-256
459//! as the hash function and NIST P-256 as defined in
460//! [NIST SP 800-186 § 3.2.1.3](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-186.pdf#%5B%7B%22num%22%3A229%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C70%2C275%2C0%5D)
461//! for the underlying elliptic curve. This corresponds to [`CoseAlgorithmIdentifier::Es256`].
462//! * ECDSA as defined in SEC 1 Version 2.0 § 4.1 using SHA-384 as the hash function and NIST P-384 as defined in
463//! [NIST SP 800-186 § 3.2.1.4](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-186.pdf#%5B%7B%22num%22%3A232%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C70%2C264%2C0%5D)
464//! for the underlying elliptic curve. This corresponds to [`CoseAlgorithmIdentifier::Es384`].
465//! * RSASSA-PKCS1-v1_5 as defined in [RFC 8017 § 8.2](https://www.rfc-editor.org/rfc/rfc8017#section-8.2) using
466//! SHA-256 as the hash function. This corresponds to [`CoseAlgorithmIdentifier::Rs256`].
467//!
468//! ## Correctness of code
469//!
470//! This library more strictly adheres to the spec than many other similar libraries including but not limited to
471//! the following ways:
472//!
473//! * [CTAP2 canonical CBOR encoding form](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#ctap2-canonical-cbor-encoding-form).
474//! * `Deserialize` implementations requiring _exact_ conformance (e.g., not allowing unknown data).
475//! * More thorough interrelated data validation (e.g., all places a Credential ID exists must match).
476//! * Implement a lot of recommended (i.e., SHOULD) criteria.
477//!
478//! Unfortunately like almost all software, this library has not been formally verified; however great care is
479//! employed in the following ways:
480//!
481//! * Leverage move semantics to prevent mutation of data once in a static state.
482//! * Ensure a great many invariants via types.
483//! * Reduce code duplication.
484//! * Reduce variable mutation allowing for simpler algebraic reasoning.
485//! * `panic`-free code[^note] (i.e., define true/total functions).
486//! * Ensure arithmetic "side effects" don't occur (e.g., overflow).
487//! * Aggressive use of compiler and [Clippy](https://doc.rust-lang.org/stable/clippy/lints.html) lints.
488//! * Unit tests for common cases, edge cases, and error cases.
489//!
490//! ## Cryptographic libraries
491//!
492//! This library does not rely on _any_ sensitive data (e.g., private keys) as only signature verification is
493//! ever performed. This means that the only thing that matters with the libraries used is their algorithmic
494//! correctness and not other normally essential aspects like susceptibility to side-channel attacks. While I
495//! personally believe the libraries that are used are at least as "secure" as alternatives even when dealing with
496//! sensitive data, one only needs to audit the correctness of the libraries to be confident in their use. In fact
497//! [`curve25519_dalek`](https://docs.rs/curve25519-dalek/latest/curve25519_dalek/#backends) has been formally
498//! verified when the [`fiat`](https://github.com/mit-plv/fiat-crypto) backend is used making it _objectively_
499//! better than many other libraries whose correctness has not been proven. Two additional benefits of the library
500//! choices are simpler APIs making it more likely their use is correct and better cross-platform compatibility.
501//!
502//! [^note]: `panic`s related to memory allocations or stack overflow are possible since such issues are not
503//! formally guarded against.
504#![expect(
505 clippy::multiple_crate_versions,
506 reason = "RustCrypto hasn't updated rand yet"
507)]
508#![expect(
509 clippy::doc_paragraphs_missing_punctuation,
510 reason = "false positive for crate documentation having image links"
511)]
512#![cfg_attr(test, expect(dead_code_pub_in_binary, reason = "ignore for tests"))]
513#![cfg_attr(docsrs, feature(doc_cfg))]
514//#[cfg(not(any(feature = "custom", all(feature = "bin", feature = "serde"))))]
515//compile_error!("'custom' must be enabled or both 'bin' and 'serde' must be enabled");
516#[cfg(all(doc, feature = "serde"))]
517use crate::request::register::ser::{
518 PublicKeyCredentialCreationOptionsOwned, PublicKeyCredentialUserEntityOwned,
519};
520#[cfg(feature = "serde")]
521use crate::request::register::ser::{
522 PublicKeyCredentialCreationOptionsOwnedErr, PublicKeyCredentialUserEntityOwnedErr,
523};
524#[cfg(feature = "serializable_server_state")]
525use crate::request::{
526 auth::ser_server_state::{
527 DecodeDiscoverableAuthenticationServerStateErr,
528 DecodeNonDiscoverableAuthenticationServerStateErr,
529 EncodeNonDiscoverableAuthenticationServerStateErr,
530 },
531 register::ser_server_state::DecodeRegistrationServerStateErr,
532};
533#[cfg(any(feature = "bin", feature = "custom"))]
534use crate::response::error::CredentialIdErr;
535#[cfg(feature = "serde_relaxed")]
536use crate::response::ser_relaxed::SerdeJsonErr;
537#[cfg(feature = "bin")]
538use crate::response::{
539 bin::DecodeAuthTransportsErr,
540 register::bin::{DecodeDynamicStateErr, DecodeStaticStateErr},
541};
542#[cfg(doc)]
543use crate::{
544 hash::hash_set::MaxLenHashSet,
545 request::{
546 AsciiDomain, DomainOrigin, Port, PublicKeyCredentialDescriptor, RpId, Scheme,
547 TimedCeremony, Url,
548 auth::{AllowedCredential, AllowedCredentials, PublicKeyCredentialRequestOptions},
549 register::{
550 CoseAlgorithmIdentifier, PublicKeyCredentialCreationOptions,
551 PublicKeyCredentialUserEntity, UserHandle16, UserHandle64,
552 },
553 },
554 response::{
555 CollectedClientData, Flag, SentChallenge,
556 auth::{self, Authentication, DiscoverableAuthenticatorAssertion},
557 register::{
558 self, Aaguid, Attestation, AttestationObject, AttestedCredentialData,
559 AuthenticatorExtensionOutput, ClientExtensionsOutputs, CompressedPubKey,
560 CredentialPropertiesOutput,
561 },
562 },
563};
564use crate::{
565 request::{
566 auth::error::{
567 DiscoverableCredentialRequestOptionsErr, NonDiscoverableCredentialRequestOptionsErr,
568 },
569 error::{AsciiDomainErr, DomainOriginParseErr, PortParseErr, SchemeParseErr, UrlErr},
570 register::{
571 ResidentKeyRequirement, USER_HANDLE_MAX_LEN, UserHandle, error::CreationOptionsErr,
572 },
573 },
574 response::{
575 AuthTransports, CredentialId,
576 auth::error::{AuthCeremonyErr, AuthenticatorDataErr as AuthAuthDataErr},
577 error::CollectedClientDataErr,
578 register::{
579 CredentialProtectionPolicy, DynamicState, Metadata, StaticState, UncompressedPubKey,
580 error::{
581 AaguidErr, AttestationObjectErr, AuthenticatorDataErr as RegAuthDataErr,
582 RegCeremonyErr,
583 },
584 },
585 },
586};
587#[cfg(all(doc, feature = "bin"))]
588use bin::{Decode, Encode};
589#[cfg(doc)]
590use core::str::FromStr;
591use core::{
592 convert,
593 error::Error,
594 fmt::{self, Display, Formatter},
595 ops::Not,
596};
597#[cfg(all(doc, feature = "serde_relaxed"))]
598use response::register::ser_relaxed::RegistrationRelaxed;
599#[cfg(all(doc, feature = "serde"))]
600use serde::Deserialize;
601#[cfg(all(doc, feature = "serde_relaxed"))]
602use serde_json::de::{Deserializer, StreamDeserializer};
603#[cfg(feature = "serializable_server_state")]
604use std::time::SystemTimeError;
605#[cfg(doc)]
606use std::time::{Instant, SystemTime};
607/// Contains functionality to (de)serialize data to a data store.
608#[cfg(feature = "bin")]
609pub mod bin;
610/// Contains functionality for maximum-length hash maps and sets that allocate exactly once.
611pub mod hash;
612/// Functionality for starting ceremonies.
613///
614/// # What kind of credential should I create?
615///
616/// Without partitioning the possibilities _too_ much, the following are possible authentication flows:
617///
618/// | Label | Username | Password | Client-side credential | Authenticator-side user verification | Recommended |
619/// |-------|----------|----------|------------------------|--------------------------------------|:-----------:|
620/// | 1 | Yes | Yes | Required | Yes | ❌ |
621/// | 2 | Yes | Yes | Required | No | ❌ |
622/// | 3 | Yes | Yes | Optional | Yes | ❌ |
623/// | <a name="label4">4</a> | Yes | Yes | Optional | No | ✅ |
624/// | 5 | Yes | No | Required | Yes | ❌ |
625/// | 6 | Yes | No | Required | No | ❌ |
626/// | <a name="label7">7</a> | Yes | No | Optional | Yes | ❔ |
627/// | 8 | Yes | No | Optional | No | ❌ |
628/// | 9 | No | Yes | Required | Yes | ❌ |
629/// | 10 | No | Yes | Required | No | ❌ |
630/// | 11 | No | Yes | Optional | Yes | ❌ |
631/// | 12 | No | Yes | Optional | No | ❌ |
632/// | <a name="label13">13</a> | No | No | Required | Yes | ✅ |
633/// | 14 | No | No | Required | No | ❌ |
634/// | 15 | No | No | Optional | Yes | ❌ |
635/// | 16 | No | No | Optional | No | ❌ |
636///
637/// * All `Label`s with both `Password` and `Authenticator-side user verification` set to `Yes` are not recommended
638/// since the verification done on the authenticator is likely the same "factor" as a password; thus it does not
639/// add benefit but only serves as an annoyance to users.
640/// * All `Label`s with `Username` or `Password` set to `Yes` and `Client-side credential` set to `Required` are not
641/// recommended since you may preclude authenticators that are storage constrained (e.g., security keys).
642/// * All `Label`s with `Username` set to `No` and `Client-side credential` set to `Optional` are not possible since
643/// RPs would not have a way to identify the set of encrypted credentials to pass to the unknown user.
644/// * All `Label`s with `Password` and `Authenticator-side user verification` set to `No` are not recommended since
645/// those are single-factor authentication schemes; thus anyone possessing the credential without also passing
646/// some form of user verification (e.g., password) would authenticate.
647/// * [`Label 7`](#label7) is possible for RPs that are comfortable passing an encrypted credential to a potential user
648/// without having that user first pass another form of authentication. For many RPs passing such information even
649/// if encrypted is not desirable though.
650/// * [`Label 4`](#label4) is ideal as a single-factor flow incorporated within a wider multi-factor authentication (MFA)
651/// setup. The easiest way to register such a credential is with
652/// [`CredentialCreationOptions::second_factor`].
653/// * [`Label 13`](#label13) is ideal for passkey setups as it allows for pleasant UX where a user does not have to type a
654/// username nor password while still being secured with MFA with one of the factors being based on public-key
655/// cryptography which for many is the most secure form of single-factor authentication. The easiest way to register
656/// such a credential is with [`CredentialCreationOptions::passkey`].
657///
658/// Two other reasons one may prefer to construct client-side credentials is richer support for extensions (e.g.,
659/// [`largeBlobKey`](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#sctn-largeBlobKey-extension)
660/// for CTAP 2.2 authenticators) and the ability to use both discoverable and nondiscoverable requests. The former is not
661/// relevant for this library—at least currently—since the only extensions supported are applicable for both
662/// client-side and server-side credentials. The latter can be important especially if an RP wants the ability to
663/// seamlessly transition from a username and password scheme to a userless and passwordless one in the future.
664///
665/// Note the table is purely informative. While helper functions
666/// (e.g., [`CredentialCreationOptions::passkey`]) only exist for [`Label 4`](#label4) and
667/// [`Label 13`](#label13), one can create any credential since all fields in [`CredentialCreationOptions`]
668/// and [`PublicKeyCredentialRequestOptions`] are accessible.
669pub mod request;
670/// Functionality for completing ceremonies.
671///
672/// Read [`request`] for more information about what credentials one should create.
673pub mod response;
674#[doc(inline)]
675pub use crate::{
676 request::{
677 auth::{
678 DiscoverableAuthenticationClientState, DiscoverableAuthenticationServerState,
679 DiscoverableCredentialRequestOptions, NonDiscoverableAuthenticationClientState,
680 NonDiscoverableAuthenticationServerState, NonDiscoverableCredentialRequestOptions,
681 },
682 register::{
683 CredentialCreationOptions, CredentialCreationOptions16, CredentialCreationOptions64,
684 RegistrationClientState, RegistrationClientState16, RegistrationClientState64,
685 RegistrationServerState, RegistrationServerState16, RegistrationServerState64,
686 },
687 },
688 response::{
689 auth::{
690 DiscoverableAuthentication, DiscoverableAuthentication16, DiscoverableAuthentication64,
691 NonDiscoverableAuthentication, NonDiscoverableAuthentication16,
692 NonDiscoverableAuthentication64,
693 },
694 register::Registration,
695 },
696};
697/// Error returned in [`RegCeremonyErr::Credential`] and [`AuthenticatedCredential::new`].
698#[derive(Clone, Copy, Debug, Eq, PartialEq)]
699pub enum CredentialErr {
700 /// Variant when [`CredentialProtectionPolicy::UserVerificationRequired`], but
701 /// [`DynamicState::user_verified`] is `false`.
702 CredProtectUserVerificationRequiredWithoutUserVerified,
703 /// Variant when [`ClientExtensionsOutputs::prf`] is
704 /// `Some(AuthenticationExtensionsPRFOutputs { enabled: true })` and [`DynamicState::user_verified`] is `false`.
705 PrfWithoutUserVerified,
706 /// Variant when [`AuthenticatorExtensionOutput::hmac_secret`] is `Some(true)`, but
707 /// [`ClientExtensionsOutputs::prf`] is `Some(AuthenticationExtensionsPRFOutputs { enabled: false })`
708 /// or `AuthenticatorExtensionOutput::hmac_secret` is `Some`, but
709 /// `ClientExtensionsOutputs::prf` is `None`.
710 HmacSecretWithoutPrf,
711 /// Variant when [`ClientExtensionsOutputs::prf`] is
712 /// `Some(AuthenticationExtensionsPRFOutputs { enabled: true })`, but
713 /// [`AuthenticatorExtensionOutput::hmac_secret`] is `Some(false)`.
714 PrfWithoutHmacSecret,
715 /// Variant when [`ResidentKeyRequirement::Required`] was sent, but
716 /// [`CredentialPropertiesOutput::rk`] is `Some(false)`.
717 ResidentKeyRequiredServerCredentialCreated,
718}
719impl Display for CredentialErr {
720 #[inline]
721 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
722 f.write_str(match *self {
723 Self::CredProtectUserVerificationRequiredWithoutUserVerified => {
724 "credProtect requires user verification, but the user is not verified"
725 }
726 Self::PrfWithoutUserVerified => "prf is enabled, but the user is not verified",
727 Self::HmacSecretWithoutPrf => "hmac-secret was enabled but prf was not",
728 Self::PrfWithoutHmacSecret => "prf was enabled, but hmac-secret was not",
729 Self::ResidentKeyRequiredServerCredentialCreated => {
730 "server-side credential was created, but a client-side credential is required"
731 }
732 })
733 }
734}
735impl Error for CredentialErr {}
736/// Checks if the `static_state` and `dynamic_state` are valid.
737///
738/// # Errors
739///
740/// Errors iff `static_state` or `dynamc_state` are invalid.
741fn verify_static_and_dynamic_state<T>(
742 static_state: &StaticState<T>,
743 dynamic_state: DynamicState,
744) -> Result<(), CredentialErr> {
745 if dynamic_state.user_verified {
746 Ok(())
747 } else if matches!(
748 static_state.extensions.cred_protect,
749 CredentialProtectionPolicy::UserVerificationRequired
750 ) {
751 Err(CredentialErr::CredProtectUserVerificationRequiredWithoutUserVerified)
752 } else if static_state
753 .client_extension_results
754 .prf
755 .is_some_and(|prf| prf.enabled)
756 {
757 Err(CredentialErr::PrfWithoutUserVerified)
758 } else {
759 Ok(())
760 }
761 .and_then(|()| {
762 static_state.client_extension_results.prf.map_or_else(
763 || {
764 if static_state.extensions.hmac_secret.is_none() {
765 Ok(())
766 } else {
767 Err(CredentialErr::HmacSecretWithoutPrf)
768 }
769 },
770 |prf| {
771 if prf.enabled {
772 if static_state.extensions.hmac_secret.is_some_and(Not::not) {
773 Err(CredentialErr::PrfWithoutHmacSecret)
774 } else {
775 Ok(())
776 }
777 } else if static_state
778 .extensions
779 .hmac_secret
780 .is_some_and(convert::identity)
781 {
782 Err(CredentialErr::HmacSecretWithoutPrf)
783 } else {
784 Ok(())
785 }
786 },
787 )
788 })
789}
790/// Registered credential that needs to be saved server-side to perform future
791/// [authentication ceremonies](https://www.w3.org/TR/webauthn-3/#authentication-ceremony) with
792/// [`AuthenticatedCredential`].
793///
794/// When saving `RegisteredCredential` to persistent storage, one will almost always want to save the contained data
795/// separately. The reasons for this are the following:
796///
797/// * [`CredentialId`]
798/// * MUST be globally unique, and it will likely be easier to enforce such uniqueness when it's separate.
799/// * Fetching the [`AuthenticatedCredential`] by [`Authentication::raw_id`] when completing the
800/// authentication ceremony via [`DiscoverableAuthenticationServerState::verify`] or
801/// [`NonDiscoverableAuthenticationServerState::verify`] will likely be easier than alternatives.
802/// * [`AuthTransports`]
803/// * Fetching [`CredentialId`]s and associated `AuthTransports` by [`UserHandle`] will likely make credential
804/// registration easier since one should set [`PublicKeyCredentialCreationOptions::exclude_credentials`] to
805/// the [`PublicKeyCredentialDescriptor`]s belonging to a `UserHandle` in order to avoid accidentally
806/// overwriting an existing credential on the authenticator.
807/// * Fetching `CredentialId`s and associated `AuthTransports` by `UserHandle` will likely make starting
808/// authentication ceremonies easier for [`NonDiscoverableCredentialRequestOptions`].
809/// * [`UserHandle`]
810/// * Fetching the [`AuthenticatedCredential`] by [`DiscoverableAuthentication::raw_id`] must also coincide with
811/// verifying the associated `UserHandle` matches [`DiscoverableAuthenticatorAssertion::user_handle`].
812/// * Fetching [`CredentialId`]s and associated [`AuthTransports`] by `UserHandle` will likely make credential
813/// registration easier since one should set [`PublicKeyCredentialCreationOptions::exclude_credentials`] to
814/// the [`PublicKeyCredentialDescriptor`]s belonging to a `UserHandle` in order to avoid accidentally
815/// overwriting an existing credential on the authenticator.
816/// * Fetching `CredentialId`s and associated `AuthTransports` by `UserHandle` will likely make starting
817/// authentication ceremonies easier for [`NonDiscoverableCredentialRequestOptions`].
818/// * [`DynamicState`]
819/// * `DynamicState` is the only part that is ever updated after a successful authentication ceremony
820/// via [`DiscoverableAuthenticationServerState::verify`] or
821/// [`NonDiscoverableAuthenticationServerState::verify`]. It being separate allows for smaller and quicker
822/// updates.
823/// * [`Metadata`]
824/// * Informative data that is never used during authentication ceremonies; consequently, one may wish to
825/// not even save this information.
826/// * [`StaticState`]
827/// * All other data exists as part of `StaticState`.
828///
829/// It is for those reasons that `RegisteredCredential` does not implement [`Encode`] or [`Decode`]; instead its parts
830/// do.
831///
832/// Note that [`RpId`] and user information other than the `UserHandle` are not stored in `RegisteredCredential`.
833/// RPs that wish to store such information must do so on their own. Since user information is likely the same
834/// for a given `UserHandle` and `RpId` is likely static, it makes little sense to store such information
835/// automatically.
836///
837/// When registering a credential, [`AttestedCredentialData::aaguid`], [`AttestedCredentialData::credential_id`],
838/// and [`AttestedCredentialData::credential_public_key`] will be the sources for [`Metadata::aaguid`],
839/// [`Self::id`], and [`StaticState::credential_public_key`] respectively. The [`PublicKeyCredentialUserEntity::id`]
840/// associated with the [`CredentialCreationOptions`] used to create the `RegisteredCredential` via
841/// [`RegistrationServerState::verify`] will be the source for [`Self::user_id`].
842///
843/// The only way to create this is via `RegistrationServerState::verify`.
844#[derive(Debug)]
845pub struct RegisteredCredential<'reg, const USER_LEN: usize> {
846 /// The credential ID.
847 ///
848 /// For client-side credentials, this is a unique identifier; but for server-side
849 /// credentials, this _is_ the credential (i.e., the encrypted private key and necessary information).
850 id: CredentialId<&'reg [u8]>,
851 /// Hints for how the client might communicate with the authenticator containing the credential.
852 transports: AuthTransports,
853 /// The identifier for the user.
854 ///
855 /// Unlike [`Self::id`] which is globally unique for an RP, this is unique up to "user" (i.e.,
856 /// multiple [`CredentialId`]s will often exist for the same `UserHandle`).
857 user_id: UserHandle<USER_LEN>,
858 /// Immutable state returned during registration.
859 static_state: StaticState<UncompressedPubKey<'reg>>,
860 /// State that can change during authentication ceremonies.
861 dynamic_state: DynamicState,
862 /// Metadata.
863 metadata: Metadata<'reg>,
864}
865impl<'reg, const USER_LEN: usize> RegisteredCredential<'reg, USER_LEN> {
866 /// The credential ID.
867 ///
868 /// For client-side credentials, this is a unique identifier; but for server-side
869 /// credentials, this _is_ the credential (i.e., the encrypted private key and necessary information).
870 #[inline]
871 #[must_use]
872 pub const fn id(&self) -> CredentialId<&'reg [u8]> {
873 self.id
874 }
875 /// Hints for how the client might communicate with the authenticator containing the credential.
876 #[inline]
877 #[must_use]
878 pub const fn transports(&self) -> AuthTransports {
879 self.transports
880 }
881 /// The identifier for the user.
882 ///
883 /// Unlike [`Self::id`] which is globally unique for an RP, this is unique up to "user" (i.e.,
884 /// multiple [`CredentialId`]s will often exist for the same `UserHandle`).
885 #[inline]
886 #[must_use]
887 pub const fn user_id(&self) -> &UserHandle<USER_LEN> {
888 &self.user_id
889 }
890 /// Immutable state returned during registration.
891 #[inline]
892 #[must_use]
893 pub const fn static_state(&self) -> StaticState<UncompressedPubKey<'reg>> {
894 self.static_state
895 }
896 /// State that can change during authentication ceremonies.
897 #[inline]
898 #[must_use]
899 pub const fn dynamic_state(&self) -> DynamicState {
900 self.dynamic_state
901 }
902 /// Metadata.
903 #[inline]
904 #[must_use]
905 pub const fn metadata(&self) -> Metadata<'reg> {
906 self.metadata
907 }
908 /// Constructs a `RegisteredCredential` based on the passed arguments.
909 ///
910 /// # Errors
911 ///
912 /// Errors iff the passed arguments are invalid. Read [`CredentialErr`]
913 /// for more information.
914 #[inline]
915 fn new<'a: 'reg>(
916 id: CredentialId<&'a [u8]>,
917 transports: AuthTransports,
918 user_id: UserHandle<USER_LEN>,
919 static_state: StaticState<UncompressedPubKey<'a>>,
920 dynamic_state: DynamicState,
921 metadata: Metadata<'a>,
922 ) -> Result<Self, CredentialErr> {
923 verify_static_and_dynamic_state(&static_state, dynamic_state).and_then(|()| {
924 if !matches!(metadata.resident_key, ResidentKeyRequirement::Required)
925 || metadata
926 .client_extension_results
927 .cred_props
928 .as_ref()
929 .is_none_or(|props| props.rk.is_none_or(convert::identity))
930 {
931 Ok(Self {
932 id,
933 transports,
934 user_id,
935 static_state,
936 dynamic_state,
937 metadata,
938 })
939 } else {
940 Err(CredentialErr::ResidentKeyRequiredServerCredentialCreated)
941 }
942 })
943 }
944 /// Returns the contained data consuming `self`.
945 #[inline]
946 #[must_use]
947 pub const fn into_parts(
948 self,
949 ) -> (
950 CredentialId<&'reg [u8]>,
951 AuthTransports,
952 UserHandle<USER_LEN>,
953 StaticState<UncompressedPubKey<'reg>>,
954 DynamicState,
955 Metadata<'reg>,
956 ) {
957 (
958 self.id,
959 self.transports,
960 self.user_id,
961 self.static_state,
962 self.dynamic_state,
963 self.metadata,
964 )
965 }
966 /// Returns the contained data.
967 #[inline]
968 #[must_use]
969 pub const fn as_parts(
970 &self,
971 ) -> (
972 CredentialId<&'reg [u8]>,
973 AuthTransports,
974 &UserHandle<USER_LEN>,
975 StaticState<UncompressedPubKey<'reg>>,
976 DynamicState,
977 Metadata<'reg>,
978 ) {
979 (
980 self.id,
981 self.transports,
982 &self.user_id,
983 self.static_state,
984 self.dynamic_state,
985 self.metadata,
986 )
987 }
988}
989/// `RegisteredCredential` based on a [`UserHandle64`].
990pub type RegisteredCredential64<'reg> = RegisteredCredential<'reg, USER_HANDLE_MAX_LEN>;
991/// `RegisteredCredential` based on a [`UserHandle16`].
992pub type RegisteredCredential16<'reg> = RegisteredCredential<'reg, 16>;
993/// Credential used in authentication ceremonies.
994///
995/// Similar to [`RegisteredCredential`] except designed to only contain the necessary data to complete
996/// authentication ceremonies. In particular there is no [`AuthTransports`] or [`Metadata`],
997/// [`StaticState::credential_public_key`] is [`CompressedPubKey`] that can own or borrow its data, [`Self::id`] is
998/// based on the [`CredentialId`] passed to [`Self::new`] which itself must be from [`Authentication::raw_id`], and
999/// [`Self::user_id`] is based on the [`UserHandle`] passed to [`Self::new`] which itself must be the value in
1000/// persistent storage associated with the `CredentialId`.
1001///
1002/// When [`DiscoverableAuthentication`] is used, one can use [`DiscoverableAuthenticatorAssertion::user_handle`]
1003/// for `Self::user_id` so long as it matches the value in persistent storage.
1004///
1005/// Note `PublicKey` should be `CompressedPubKey` for this to be useful.
1006///
1007/// The only way to create this is via `Self::new`.
1008#[derive(Debug)]
1009pub struct AuthenticatedCredential<'cred, 'user, const USER_LEN: usize, PublicKey> {
1010 /// The credential ID.
1011 ///
1012 /// For client-side credentials, this is a unique identifier; but for server-side
1013 /// credentials, this _is_ the credential (i.e., the encrypted private key and necessary information).
1014 id: CredentialId<&'cred [u8]>,
1015 /// The identifier for the user.
1016 ///
1017 /// Unlike [`Self::id`] which is globally unique for an RP, this is unique up to "user" (i.e.,
1018 /// multiple [`CredentialId`]s will often exist for the same `UserHandle`).
1019 user_id: &'user UserHandle<USER_LEN>,
1020 /// Immutable state returned during registration.
1021 static_state: StaticState<PublicKey>,
1022 /// State that can change during authentication ceremonies.
1023 dynamic_state: DynamicState,
1024}
1025impl<'cred, 'user, const USER_LEN: usize, PublicKey>
1026 AuthenticatedCredential<'cred, 'user, USER_LEN, PublicKey>
1027{
1028 /// The credential ID.
1029 ///
1030 /// For client-side credentials, this is a unique identifier; but for server-side
1031 /// credentials, this _is_ the credential (i.e., the encrypted private key and necessary information).
1032 #[inline]
1033 #[must_use]
1034 pub const fn id(&self) -> CredentialId<&'cred [u8]> {
1035 self.id
1036 }
1037 /// The identifier for the user.
1038 ///
1039 /// Unlike [`Self::id`] which is globally unique for an RP, this is unique up to "user" (i.e.,
1040 /// multiple [`CredentialId`]s will often exist for the same `UserHandle`).
1041 #[inline]
1042 #[must_use]
1043 pub const fn user_id(&self) -> &'user UserHandle<USER_LEN> {
1044 self.user_id
1045 }
1046 /// Immutable state returned during registration.
1047 #[inline]
1048 #[must_use]
1049 pub const fn static_state(&self) -> &StaticState<PublicKey> {
1050 &self.static_state
1051 }
1052 /// State that can change during authentication ceremonies.
1053 #[inline]
1054 #[must_use]
1055 pub const fn dynamic_state(&self) -> DynamicState {
1056 self.dynamic_state
1057 }
1058 /// Constructs an `AuthenticatedCredential` based on the passed arguments.
1059 ///
1060 /// # Errors
1061 ///
1062 /// Errors iff the passed arguments are invalid. Read [`CredentialErr`]
1063 /// for more information.
1064 #[cfg(any(feature = "bin", feature = "custom"))]
1065 #[inline]
1066 pub fn new<'a: 'cred, 'b: 'user>(
1067 id: CredentialId<&'a [u8]>,
1068 user_id: &'b UserHandle<USER_LEN>,
1069 static_state: StaticState<PublicKey>,
1070 dynamic_state: DynamicState,
1071 ) -> Result<Self, CredentialErr> {
1072 verify_static_and_dynamic_state(&static_state, dynamic_state).map(|()| Self {
1073 id,
1074 user_id,
1075 static_state,
1076 dynamic_state,
1077 })
1078 }
1079 /// Returns the contained data consuming `self`.
1080 #[inline]
1081 #[must_use]
1082 pub fn into_parts(
1083 self,
1084 ) -> (
1085 CredentialId<&'cred [u8]>,
1086 &'user UserHandle<USER_LEN>,
1087 StaticState<PublicKey>,
1088 DynamicState,
1089 ) {
1090 (self.id, self.user_id, self.static_state, self.dynamic_state)
1091 }
1092 /// Returns the contained data.
1093 #[inline]
1094 #[must_use]
1095 pub const fn as_parts(
1096 &self,
1097 ) -> (
1098 CredentialId<&'cred [u8]>,
1099 &'user UserHandle<USER_LEN>,
1100 &StaticState<PublicKey>,
1101 DynamicState,
1102 ) {
1103 (
1104 self.id,
1105 self.user_id,
1106 self.static_state(),
1107 self.dynamic_state,
1108 )
1109 }
1110}
1111use response::register::{CompressedPubKeyBorrowed, CompressedPubKeyOwned};
1112/// `AuthenticatedCredential` based on a [`UserHandle64`].
1113pub type AuthenticatedCredential64<'cred, 'user, PublicKey> =
1114 AuthenticatedCredential<'cred, 'user, USER_HANDLE_MAX_LEN, PublicKey>;
1115/// `AuthenticatedCredential` based on a [`UserHandle16`].
1116pub type AuthenticatedCredential16<'cred, 'user, PublicKey> =
1117 AuthenticatedCredential<'cred, 'user, 16, PublicKey>;
1118/// `AuthenticatedCredential` that owns the key data.
1119pub type AuthenticatedCredentialOwned<'cred, 'user, const USER_LEN: usize> =
1120 AuthenticatedCredential<'cred, 'user, USER_LEN, CompressedPubKeyOwned>;
1121/// `AuthenticatedCredential` that borrows the key data.
1122pub type AuthenticatedCredentialBorrowed<'cred, 'user, 'key, const USER_LEN: usize> =
1123 AuthenticatedCredential<'cred, 'user, USER_LEN, CompressedPubKeyBorrowed<'key>>;
1124/// Convenience aggregate error that rolls up all errors into one.
1125#[derive(Debug)]
1126pub enum AggErr {
1127 /// Variant when [`AsciiDomain::try_from`] errors.
1128 AsciiDomain(AsciiDomainErr),
1129 /// Variant when [`Url::from_str`] errors.
1130 Url(UrlErr),
1131 /// Variant when [`Scheme::try_from`] errors.
1132 Scheme(SchemeParseErr),
1133 /// Variant when [`DomainOrigin::try_from`] errors.
1134 DomainOrigin(DomainOriginParseErr),
1135 /// Variant when [`Port::from_str`] errors.
1136 Port(PortParseErr),
1137 /// Variant when [`CredentialCreationOptions::start_ceremony`] errors.
1138 CreationOptions(CreationOptionsErr),
1139 /// Variant when [`DiscoverableCredentialRequestOptions::start_ceremony`] errors.
1140 DiscoverableCredentialRequestOptions(DiscoverableCredentialRequestOptionsErr),
1141 /// Variant when [`NonDiscoverableCredentialRequestOptions::start_ceremony`] errors.
1142 NonDiscoverableCredentialRequestOptions(NonDiscoverableCredentialRequestOptionsErr),
1143 /// Variant when [`RegistrationServerState::verify`] errors.
1144 RegCeremony(RegCeremonyErr),
1145 /// Variant when [`DiscoverableAuthenticationServerState::verify`] or.
1146 /// [`NonDiscoverableAuthenticationServerState::verify`] error.
1147 AuthCeremony(AuthCeremonyErr),
1148 /// Variant when [`AttestationObject::try_from`] errors.
1149 AttestationObject(AttestationObjectErr),
1150 /// Variant when [`register::AuthenticatorData::try_from`] errors.
1151 RegAuthenticatorData(RegAuthDataErr),
1152 /// Variant when [`auth::AuthenticatorData::try_from`] errors.
1153 AuthAuthenticatorData(AuthAuthDataErr),
1154 /// Variant when [`CollectedClientData::from_client_data_json`] errors.
1155 CollectedClientData(CollectedClientDataErr),
1156 /// Variant when [`CollectedClientData::from_client_data_json_relaxed`] errors or any of the [`Deserialize`]
1157 /// implementations error when relying on [`Deserializer`] or [`StreamDeserializer`].
1158 #[cfg(feature = "serde_relaxed")]
1159 SerdeJson(SerdeJsonErr),
1160 /// Variant when [`Aaguid::try_from`] errors.
1161 Aaguid(AaguidErr),
1162 /// Variant when [`AuthTransports::decode`] errors.
1163 #[cfg(feature = "bin")]
1164 DecodeAuthTransports(DecodeAuthTransportsErr),
1165 /// Variant when [`StaticState::decode`] errors.
1166 #[cfg(feature = "bin")]
1167 DecodeStaticState(DecodeStaticStateErr),
1168 /// Variant when [`DynamicState::decode`] errors.
1169 #[cfg(feature = "bin")]
1170 DecodeDynamicState(DecodeDynamicStateErr),
1171 /// Variant when [`RegistrationServerState::decode`] errors.
1172 #[cfg(feature = "serializable_server_state")]
1173 DecodeRegistrationServerState(DecodeRegistrationServerStateErr),
1174 /// Variant when [`DiscoverableAuthenticationServerState::decode`] errors.
1175 #[cfg(feature = "serializable_server_state")]
1176 DecodeDiscoverableAuthenticationServerState(DecodeDiscoverableAuthenticationServerStateErr),
1177 /// Variant when [`NonDiscoverableAuthenticationServerState::decode`] errors.
1178 #[cfg(feature = "serializable_server_state")]
1179 DecodeNonDiscoverableAuthenticationServerState(
1180 DecodeNonDiscoverableAuthenticationServerStateErr,
1181 ),
1182 /// Variant when [`RegistrationServerState::encode`] errors.
1183 #[cfg(feature = "serializable_server_state")]
1184 EncodeRegistrationServerState(SystemTimeError),
1185 /// Variant when [`DiscoverableAuthenticationServerState::encode`] errors.
1186 #[cfg(feature = "serializable_server_state")]
1187 EncodeDiscoverableAuthenticationServerState(SystemTimeError),
1188 /// Variant when [`NonDiscoverableAuthenticationServerState::encode`] errors.
1189 #[cfg(feature = "serializable_server_state")]
1190 EncodeNonDiscoverableAuthenticationServerState(
1191 EncodeNonDiscoverableAuthenticationServerStateErr,
1192 ),
1193 /// Variant when [`AuthenticatedCredential::new`] errors.
1194 #[cfg(any(feature = "bin", feature = "custom"))]
1195 Credential(CredentialErr),
1196 /// Variant when [`CredentialId::try_from`] or [`CredentialId::decode`] errors.
1197 #[cfg(any(feature = "bin", feature = "custom"))]
1198 CredentialId(CredentialIdErr),
1199 /// Variant when [`PublicKeyCredentialUserEntityOwned`] errors when converted into a
1200 /// [`PublicKeyCredentialUserEntity`].
1201 #[cfg(feature = "serde")]
1202 PublicKeyCredentialUserEntityOwned(PublicKeyCredentialUserEntityOwnedErr),
1203 /// Variant when [`PublicKeyCredentialCreationOptionsOwned`] errors when converted into a
1204 /// [`PublicKeyCredentialCreationOptions`].
1205 #[cfg(feature = "serde")]
1206 PublicKeyCredentialCreationOptionsOwned(PublicKeyCredentialCreationOptionsOwnedErr),
1207}
1208impl From<AsciiDomainErr> for AggErr {
1209 #[inline]
1210 fn from(value: AsciiDomainErr) -> Self {
1211 Self::AsciiDomain(value)
1212 }
1213}
1214impl From<UrlErr> for AggErr {
1215 #[inline]
1216 fn from(value: UrlErr) -> Self {
1217 Self::Url(value)
1218 }
1219}
1220impl From<SchemeParseErr> for AggErr {
1221 #[inline]
1222 fn from(value: SchemeParseErr) -> Self {
1223 Self::Scheme(value)
1224 }
1225}
1226impl From<DomainOriginParseErr> for AggErr {
1227 #[inline]
1228 fn from(value: DomainOriginParseErr) -> Self {
1229 Self::DomainOrigin(value)
1230 }
1231}
1232impl From<PortParseErr> for AggErr {
1233 #[inline]
1234 fn from(value: PortParseErr) -> Self {
1235 Self::Port(value)
1236 }
1237}
1238impl From<CreationOptionsErr> for AggErr {
1239 #[inline]
1240 fn from(value: CreationOptionsErr) -> Self {
1241 Self::CreationOptions(value)
1242 }
1243}
1244impl From<DiscoverableCredentialRequestOptionsErr> for AggErr {
1245 #[inline]
1246 fn from(value: DiscoverableCredentialRequestOptionsErr) -> Self {
1247 Self::DiscoverableCredentialRequestOptions(value)
1248 }
1249}
1250impl From<NonDiscoverableCredentialRequestOptionsErr> for AggErr {
1251 #[inline]
1252 fn from(value: NonDiscoverableCredentialRequestOptionsErr) -> Self {
1253 Self::NonDiscoverableCredentialRequestOptions(value)
1254 }
1255}
1256impl From<RegCeremonyErr> for AggErr {
1257 #[inline]
1258 fn from(value: RegCeremonyErr) -> Self {
1259 Self::RegCeremony(value)
1260 }
1261}
1262impl From<AuthCeremonyErr> for AggErr {
1263 #[inline]
1264 fn from(value: AuthCeremonyErr) -> Self {
1265 Self::AuthCeremony(value)
1266 }
1267}
1268impl From<AttestationObjectErr> for AggErr {
1269 #[inline]
1270 fn from(value: AttestationObjectErr) -> Self {
1271 Self::AttestationObject(value)
1272 }
1273}
1274impl From<RegAuthDataErr> for AggErr {
1275 #[inline]
1276 fn from(value: RegAuthDataErr) -> Self {
1277 Self::RegAuthenticatorData(value)
1278 }
1279}
1280impl From<AuthAuthDataErr> for AggErr {
1281 #[inline]
1282 fn from(value: AuthAuthDataErr) -> Self {
1283 Self::AuthAuthenticatorData(value)
1284 }
1285}
1286impl From<CollectedClientDataErr> for AggErr {
1287 #[inline]
1288 fn from(value: CollectedClientDataErr) -> Self {
1289 Self::CollectedClientData(value)
1290 }
1291}
1292#[cfg(feature = "serde_relaxed")]
1293impl From<SerdeJsonErr> for AggErr {
1294 #[inline]
1295 fn from(value: SerdeJsonErr) -> Self {
1296 Self::SerdeJson(value)
1297 }
1298}
1299impl From<AaguidErr> for AggErr {
1300 #[inline]
1301 fn from(value: AaguidErr) -> Self {
1302 Self::Aaguid(value)
1303 }
1304}
1305#[cfg(feature = "bin")]
1306impl From<DecodeAuthTransportsErr> for AggErr {
1307 #[inline]
1308 fn from(value: DecodeAuthTransportsErr) -> Self {
1309 Self::DecodeAuthTransports(value)
1310 }
1311}
1312#[cfg(feature = "bin")]
1313impl From<DecodeStaticStateErr> for AggErr {
1314 #[inline]
1315 fn from(value: DecodeStaticStateErr) -> Self {
1316 Self::DecodeStaticState(value)
1317 }
1318}
1319#[cfg(feature = "bin")]
1320impl From<DecodeDynamicStateErr> for AggErr {
1321 #[inline]
1322 fn from(value: DecodeDynamicStateErr) -> Self {
1323 Self::DecodeDynamicState(value)
1324 }
1325}
1326#[cfg(feature = "serializable_server_state")]
1327impl From<DecodeRegistrationServerStateErr> for AggErr {
1328 #[inline]
1329 fn from(value: DecodeRegistrationServerStateErr) -> Self {
1330 Self::DecodeRegistrationServerState(value)
1331 }
1332}
1333#[cfg(feature = "serializable_server_state")]
1334impl From<DecodeDiscoverableAuthenticationServerStateErr> for AggErr {
1335 #[inline]
1336 fn from(value: DecodeDiscoverableAuthenticationServerStateErr) -> Self {
1337 Self::DecodeDiscoverableAuthenticationServerState(value)
1338 }
1339}
1340#[cfg(feature = "serializable_server_state")]
1341impl From<DecodeNonDiscoverableAuthenticationServerStateErr> for AggErr {
1342 #[inline]
1343 fn from(value: DecodeNonDiscoverableAuthenticationServerStateErr) -> Self {
1344 Self::DecodeNonDiscoverableAuthenticationServerState(value)
1345 }
1346}
1347#[cfg(feature = "serializable_server_state")]
1348impl From<EncodeNonDiscoverableAuthenticationServerStateErr> for AggErr {
1349 #[inline]
1350 fn from(value: EncodeNonDiscoverableAuthenticationServerStateErr) -> Self {
1351 Self::EncodeNonDiscoverableAuthenticationServerState(value)
1352 }
1353}
1354#[cfg(any(feature = "bin", feature = "custom"))]
1355impl From<CredentialErr> for AggErr {
1356 #[inline]
1357 fn from(value: CredentialErr) -> Self {
1358 Self::Credential(value)
1359 }
1360}
1361#[cfg(any(feature = "bin", feature = "custom"))]
1362impl From<CredentialIdErr> for AggErr {
1363 #[inline]
1364 fn from(value: CredentialIdErr) -> Self {
1365 Self::CredentialId(value)
1366 }
1367}
1368#[cfg(feature = "serde")]
1369impl From<PublicKeyCredentialUserEntityOwnedErr> for AggErr {
1370 #[inline]
1371 fn from(value: PublicKeyCredentialUserEntityOwnedErr) -> Self {
1372 Self::PublicKeyCredentialUserEntityOwned(value)
1373 }
1374}
1375#[cfg(feature = "serde")]
1376impl From<PublicKeyCredentialCreationOptionsOwnedErr> for AggErr {
1377 #[inline]
1378 fn from(value: PublicKeyCredentialCreationOptionsOwnedErr) -> Self {
1379 Self::PublicKeyCredentialCreationOptionsOwned(value)
1380 }
1381}
1382impl Display for AggErr {
1383 #[inline]
1384 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1385 match *self {
1386 Self::AsciiDomain(err) => err.fmt(f),
1387 Self::Url(err) => err.fmt(f),
1388 Self::Scheme(err) => err.fmt(f),
1389 Self::DomainOrigin(ref err) => err.fmt(f),
1390 Self::Port(ref err) => err.fmt(f),
1391 Self::CreationOptions(err) => err.fmt(f),
1392 Self::DiscoverableCredentialRequestOptions(err) => err.fmt(f),
1393 Self::NonDiscoverableCredentialRequestOptions(err) => err.fmt(f),
1394 Self::RegCeremony(ref err) => err.fmt(f),
1395 Self::AuthCeremony(ref err) => err.fmt(f),
1396 Self::AttestationObject(err) => err.fmt(f),
1397 Self::RegAuthenticatorData(err) => err.fmt(f),
1398 Self::AuthAuthenticatorData(err) => err.fmt(f),
1399 Self::CollectedClientData(ref err) => err.fmt(f),
1400 #[cfg(feature = "serde_relaxed")]
1401 Self::SerdeJson(ref err) => err.fmt(f),
1402 Self::Aaguid(err) => err.fmt(f),
1403 #[cfg(feature = "bin")]
1404 Self::DecodeAuthTransports(err) => err.fmt(f),
1405 #[cfg(feature = "bin")]
1406 Self::DecodeStaticState(err) => err.fmt(f),
1407 #[cfg(feature = "bin")]
1408 Self::DecodeDynamicState(err) => err.fmt(f),
1409 #[cfg(feature = "serializable_server_state")]
1410 Self::DecodeRegistrationServerState(err) => err.fmt(f),
1411 #[cfg(feature = "serializable_server_state")]
1412 Self::DecodeDiscoverableAuthenticationServerState(err) => err.fmt(f),
1413 #[cfg(feature = "serializable_server_state")]
1414 Self::DecodeNonDiscoverableAuthenticationServerState(err) => err.fmt(f),
1415 #[cfg(feature = "serializable_server_state")]
1416 Self::EncodeRegistrationServerState(ref err) => err.fmt(f),
1417 #[cfg(feature = "serializable_server_state")]
1418 Self::EncodeDiscoverableAuthenticationServerState(ref err) => err.fmt(f),
1419 #[cfg(feature = "serializable_server_state")]
1420 Self::EncodeNonDiscoverableAuthenticationServerState(ref err) => err.fmt(f),
1421 #[cfg(any(feature = "bin", feature = "custom"))]
1422 Self::Credential(err) => err.fmt(f),
1423 #[cfg(any(feature = "bin", feature = "custom"))]
1424 Self::CredentialId(err) => err.fmt(f),
1425 #[cfg(feature = "serde")]
1426 Self::PublicKeyCredentialUserEntityOwned(err) => err.fmt(f),
1427 #[cfg(feature = "serde")]
1428 Self::PublicKeyCredentialCreationOptionsOwned(err) => err.fmt(f),
1429 }
1430 }
1431}
1432impl Error for AggErr {}