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