### Handling File Metadata Operations with and_then Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/type.WebauthnResult.html Shows how to use `and_then` to chain operations that might fail, like getting file metadata and its modification time. This example includes error checking for file not found scenarios. ```Rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Example of Slice Iteration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Demonstrates iterating over a slice and checking the resulting ranges. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### Get URL Origin (Other Scheme) Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Url.html Demonstrates that URLs with non-standard schemes also have non-tuple origins. ```rust use url::{Host, Origin, Url}; let url = Url::parse("foo:bar")?; assert!(!url.origin().is_tuple()); ``` -------------------------------- ### Providing a Default Value with unwrap_or Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/type.WebauthnResult.html Shows how to get the `Ok` value or a provided default if the `Result` is `Err`. The default value is eagerly evaluated. ```Rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Iterating over a slice Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `iter()` to get an immutable iterator over the elements of a slice. The iterator yields elements from start to end. ```Rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### start_passkey_authentication Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the passkey authentication process for a user. It generates a challenge and returns state that must be persisted server-side for completing the authentication. ```APIDOC ## start_passkey_authentication ### Description Given a set of `Passkey`’s, begin an authentication of the user. This returns a `RequestChallengeResponse`, which should be serialised to json and sent to the user agent (e.g. a browser). The server must persist the PasskeyAuthentication state as it is paired to the `RequestChallengeResponse` and required to complete the authentication. ### Method Not specified (likely a method within a struct) ### Parameters - **creds** (`&[Passkey]`) - Required - A slice of `Passkey` objects associated with the user. ### Returns - **(RequestChallengeResponse, PasskeyAuthentication)** - A tuple containing the challenge response to be sent to the user agent and the server-side state for completing authentication. ### Errors - **WebauthnError** - Returned if there is an issue starting the authentication. ### Notes - WARNING ⚠️ YOU MUST STORE THE PasskeyAuthentication VALUE SERVER SIDE. Failure to do so _may_ open you to replay attacks which can significantly weaken the security of this system. - Finally you need to call `finish_passkey_authentication` to complete the authentication. ``` -------------------------------- ### Rust Binary Search Example Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Demonstrates using binary_search to find elements in a sorted slice. Shows successful lookups, failed lookups, and handling of multiple matches. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` -------------------------------- ### Get Element Index from Unaligned Reference Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Demonstrates that `element_offset` returns `None` when a reference does not point to the start of an element within the slice, such as when it points between elements. ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Mutably iterating over a slice Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `iter_mut()` to get a mutable iterator over the elements of a slice, allowing modification of each element. The iterator yields elements from start to end. ```Rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Rust Vec try_shrink_to_fit Example (Nightly) Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Shows the usage of the experimental `try_shrink_to_fit` method, which attempts to shrink a Vec's capacity as much as possible. It returns a `Result` to indicate potential allocator failures during the shrinking process. ```rust #![feature(vec_fallible_shrink)] let mut vec = Vec::with_capacity(10); vec.extend([1, 2, 3]); assert!(vec.capacity() >= 10); vec.try_shrink_to_fit().expect("why is the test harness failing to shrink to 12 bytes"); assert!(vec.capacity() >= 3); ``` -------------------------------- ### Get Element Index from Reference Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Finds the index of an element reference within its slice using pointer arithmetic. Returns `None` if the reference does not point to the start of an element. Does not compare elements. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### start_securitykey_authentication Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the authentication process for a user using a set of registered security keys. It generates a challenge and returns state that must be persisted server-side to complete the authentication later. ```APIDOC ## pub fn start_securitykey_authentication ### Description Given a set of SecurityKey, begin an authentication of the user. This returns a `RequestChallengeResponse`, which should be serialised to json and sent to the user agent (e.g. a browser). The server must persist the SecurityKeyAuthentication state as it is paired to the `RequestChallengeResponse` and required to complete the authentication. Finally you need to call `finish_securitykey_authentication` to complete the authentication. WARNING ⚠️ YOU MUST STORE THE SecurityKeyAuthentication VALUE SERVER SIDE. Failure to do so _may_ open you to replay attacks which can significantly weaken the security of this system. ### Returns Returns a `RequestChallengeResponse` and `SecurityKeyAuthentication` state. ``` -------------------------------- ### Start Security Key Registration with Authenticator Attachment Hint Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates security key registration, providing a hint that the authenticator is likely cross-platform (e.g., USB). The `SecurityKeyRegistration` object must be stored server-side to prevent replay attacks. ```rust let (ccr, skr) = webauthn .start_securitykey_registration( Uuid::new_v4(), "claire", "Claire", None, None, Some(AuthenticatorAttachment::CrossPlatform), ) .expect("Failed to start registration."); ``` -------------------------------- ### Get URL Path Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Url.html Retrieves the path component of a URL as a percent-encoded ASCII string. For non-base URLs, it's an arbitrary string; for others, it starts with '/' and includes path segments. ```Rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam") ``` -------------------------------- ### start_passkey_registration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration of a new passkey for a user. This method is designed to be phish-proof and supports various authenticator types like YubiKeys, TouchID, FaceID, and Windows Hello. ```APIDOC ## start_passkey_registration ### Description Initiate the registration of a new passkey for a user. A passkey is any cryptographic authenticator which internally verifies the user’s identity. As these are self contained multifactor authenticators, they are far stronger than a password or email-reset link. Due to how webauthn is designed these authentications are unable to be phished. Some examples of passkeys include Yubikeys, TouchID, FaceID, Windows Hello and others. The keys _may_ exist and ‘roam’ between multiple devices. For example, Apple allows Passkeys to sync between devices owned by the same Apple account. This can affect your risk model related to these credentials, but generally in most cases passkeys are better than passwords! You _should_ NOT pair this authentication with any other factor. A passkey will always enforce user-verification (MFA) removing the need for other factors. `user_unique_id` _may_ be stored in the authenticator. This may allow the credential to identify the user during certain client side work flows. `user_name` and `user_display_name` _may_ be stored in the authenticator. `user_name` is a friendly account name such as “claire@example.com”. `user_display_name` is the persons chosen way to be identified such as “Claire”. Both can change at _any_ time on the client side, and MUST NOT be used as primary keys. They _are not_ present in authentication, these are only present to allow client facing work flows to display human friendly identifiers. `exclude_credentials` ensures that a set of credentials may not participate in this registration. You _should_ provide the list of credentials that are already registered to this user’s account to prevent duplicate credential registrations. These credentials _can_ be from different authenticator classes since we only require the `CredentialID` ### Method POST (implied) ### Endpoint (Not specified) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed directly to the function) ### Function Signature `pub fn start_passkey_registration( &self, user_unique_id: Uuid, user_name: &str, user_display_name: &str, exclude_credentials: Option>, ) -> WebauthnResult<(CreationChallengeResponse, PasskeyRegistration)>` ### Parameters - **user_unique_id** (Uuid) - Required - A unique identifier for the user. - **user_name** (string) - Required - A friendly account name for the user. - **user_display_name** (string) - Required - The user's chosen display name. - **exclude_credentials** (Option>) - Optional - A list of credentials to exclude from this registration. ### Returns This function returns a `CreationChallengeResponse` which you must serialise to json and send to the user agent (e.g. a browser) for it to conduct the registration. You must persist on the server the `PasskeyRegistration` which contains the state of this registration attempt and is paired to the `CreationChallengeResponse`. Finally you need to call `finish_passkey_registration` to complete the registration. WARNING ⚠️ YOU MUST STORE THE PasskeyRegistration VALUE SERVER SIDE. Failure to do so _may_ open you to replay attacks which can significantly weaken the security of this system. ### Request Example ```rust // you must store this user's unique id with the account. Alternatelly you can // use an existed UUID source. let user_unique_id = Uuid::new_v4(); // Initiate a basic registration flow, allowing any cryptograhpic authenticator to proceed. let (ccr, skr) = webauthn .start_passkey_registration( user_unique_id, "claire", "Claire", None, // No other credentials are registered yet. ) .expect("Failed to start registration."); ``` ### Response #### Success Response - **CreationChallengeResponse** - Data to be sent to the user agent for registration. - **PasskeyRegistration** - State of the registration attempt to be stored server-side. ``` -------------------------------- ### Get Last Element of Slice Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `last()` to safely get an optional reference to the last element. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### start_securitykey_registration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration of a new security key for a user. This function generates a challenge and returns data necessary for the client-side to complete the registration process. It is crucial to store the returned `SecurityKeyRegistration` server-side to prevent replay attacks. ```APIDOC ## start_securitykey_registration ### Description Initiate the registration of a new security key for a user. A security key is any cryptographic authenticator acting as a single factor of authentication to supplement a password or some other authentication factor. ### Method `pub fn start_securitykey_registration(&self, user_unique_id: Uuid, user_name: &str, user_display_name: &str, exclude_credentials: Option>, attestation_ca_list: Option, ui_hint_authenticator_attachment: Option) -> WebauthnResult<(CreationChallengeResponse, SecurityKeyRegistration)>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **user_unique_id** (Uuid) - Required - A unique identifier for the user. This may be stored in the authenticator. - **user_name** (str) - Required - A friendly account name for the user (e.g., "claire@example.com"). May be stored in the authenticator but should not be used as a primary key. - **user_display_name** (str) - Required - The user's chosen display name (e.g., "Claire"). May be stored in the authenticator but should not be used as a primary key. - **exclude_credentials** (Option>) - Optional - A list of credential IDs to exclude from this registration, preventing duplicate registrations. - **attestation_ca_list** (Option) - Optional - A list of Root CA certificates of authenticator manufacturers to trust. Extensions are only trusted if this is provided. - **ui_hint_authenticator_attachment** (Option) - Optional - A hint about the expected authenticator attachment (e.g., `CrossPlatform`). ### Returns - **CreationChallengeResponse**: This must be serialized to JSON and sent to the user agent (e.g., a browser) to conduct the registration. - **SecurityKeyRegistration**: This value must be persisted on the server and contains the state of the registration attempt. It is paired to the `CreationChallengeResponse`. ### Request Example ```rust // you must store this user's unique id with the account. Alternatelly you can // use an existed UUID source. let user_unique_id = Uuid::new_v4(); // Initiate a basic registration flow, allowing any cryptograhpic authenticator to proceed. let (ccr, skr) = webauthn .start_securitykey_registration( user_unique_id, "claire", "Claire", None, None, None, ) .expect("Failed to start registration."); // Initiate a basic registration flow, hinting that the device is probably roaming (i.e. a usb), // but it could have any attachement in reality let (ccr, skr) = webauthn .start_securitykey_registration( Uuid::new_v4(), "claire", "Claire", None, None, Some(AuthenticatorAttachment::CrossPlatform), ) .expect("Failed to start registration."); // Only allow credentials from manufacturers that are trusted and part of the webauthn-rs // strict "high quality" list. use webauthn_rs_device_catalog::Data; let device_catalog = Data::strict(); let attestation_ca_list = (&device_catalog) .try_into() .expect("Failed to build attestation ca list"); let (ccr, skr) = webauthn .start_securitykey_registration( Uuid::new_v4(), "claire", "Claire", None, Some(attestation_ca_list), None, ) .expect("Failed to start registration."); ``` ### Response #### Success Response (200) - **CreationChallengeResponse**: Data to be sent to the client for registration. - **SecurityKeyRegistration**: Server-side state for the registration process. #### Response Example (See Request Example for illustrative Rust code demonstrating the return values) ### WARNING YOU MUST STORE THE `SecurityKeyRegistration` VALUE SERVER SIDE. Failure to do so may open you to replay attacks which can significantly weaken the security of this system. ``` -------------------------------- ### Start Attested Passkey Registration (Cross-Platform) Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration process for an attested passkey, allowing any attested cryptographic authenticator. It hints at preferring cross-platform authenticators like YubiKeys. The server must store the returned `AttestedPasskeyRegistration` state. ```rust use webauthn_rs_device_catalog::Data; // you must store this user's unique id with the account. Alternatively you can // use an existed UUID source. let user_unique_id = Uuid::new_v4(); // Create a device catalog reference that contains a list of known high quality authenticators let device_catalog = Data::all_known_devices(); let attestation_ca_list = (&device_catalog) .try_into() .expect("Failed to build attestation ca list"); // Initiate a basic registration flow, allowing any attested cryptograhpic authenticator to proceed. // Hint (but do not enforce) that we prefer this to be a token/key like a yubikey. // To enforce this you can validate the properties of the returned device aaguid. let (ccr, skr) = webauthn .start_attested_passkey_registration( user_unique_id, "claire", "Claire", None, attestation_ca_list, Some(AuthenticatorAttachment::CrossPlatform), ) .expect("Failed to start registration."); ``` -------------------------------- ### Get First Element of Slice Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `first()` to safely get an optional reference to the first element. Returns `None` if the slice is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Rust slice: fill_with example Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Fills a mutable slice by repeatedly calling a closure to generate values. This is useful when values need to be computed or are not easily clonable. ```rust let mut buf = vec![1; 10]; buf.fill_with(Default::default); assert_eq!(buf, vec![0; 10]); ``` -------------------------------- ### Get First Chunk of Slice Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `first_chunk::()` to get a reference to the first `N` elements as an array. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### WebauthnBuilder::build Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.WebauthnBuilder.html Completes the construction of the Webauthn instance. Returns an error if any configuration settings are invalid. ```APIDOC ## WebauthnBuilder::build ### Description Complete the construction of the Webauthn instance. If an invalid configuration setting is found, an Error will be returned. ### Method ``` pub fn build(self) -> WebauthnResult ``` ### Examples ```rust use webauthn_rs::prelude::*; let rp_id = "example.com"; let rp_origin = Url::parse("https://idm.example.com") .expect("Invalid URL"); let mut builder = WebauthnBuilder::new(rp_id, &rp_origin) .expect("Invalid configuration"); let webauthn = builder.build() .expect("Invalid configuration"); ``` ``` -------------------------------- ### start_attested_resident_key_registration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration of an attested resident key. This function is available only with the `resident-key-support` crate feature. ```APIDOC ## start_attested_resident_key_registration ### Description Initiates the registration of an attested resident key. Available on **crate features`resident-key-support`** only. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Not applicable (Rust function call) ### Endpoint Not applicable (Rust function call) ### Request Example None ### Response #### Success Response - **(CreationChallengeResponse, AttestedResidentKeyRegistration)** (tuple) - A tuple containing the creation challenge response and attested resident key registration state. #### Response Example None ``` -------------------------------- ### Get Element or Subslice by Index (Safe) Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `get` to safely access an element or subslice by index. Returns `Some` with a reference if the index is within bounds, otherwise `None`. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Get Mutable Reference to Last Element Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `last_mut()` to get an optional mutable reference to the last element. Allows in-place modification of the last element if it exists. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); let y: &mut [i32] = &mut []; assert_eq!(None, y.last_mut()); ``` -------------------------------- ### start_discoverable_authentication Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates a conditional UI authentication for discoverable credentials. This function requires no options as it relies on the client to discover the credential and user ID. Available only with the `conditional-ui` crate feature. ```APIDOC ## start_discoverable_authentication ### Description Initiates a conditional UI authentication for discoverable credentials. Since this relies on the client to “discover” what credential and user id to use, there are no options required to start this. Available on **crate features`conditional-ui`** only. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Not applicable (Rust function call) ### Endpoint Not applicable (Rust function call) ### Request Example None ### Response #### Success Response - **(RequestChallengeResponse, DiscoverableAuthentication)** (tuple) - A tuple containing the request challenge response and discoverable authentication state. #### Response Example None ``` -------------------------------- ### Start Attested Passkey Registration (Platform) Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration process for an attested passkey, enforcing the use of authenticators from trusted manufacturers in the "high quality" list. It hints at preferring platform authenticators like TouchID. The server must store the returned `AttestedPasskeyRegistration` state. ```rust // Only allow credentials from manufacturers that are trusted and part of the webauthn-rs // strict "high quality" list. // Hint (but do not enforce) that we prefer this to be a device like TouchID. // To enforce this you can validate the attestation ca used along with the returned device aaguid let device_catalog = Data::strict(); let attestation_ca_list = (&device_catalog) .try_into() .expect("Failed to build attestation ca list"); let (ccr, skr) = webauthn .start_attested_passkey_registration( Uuid::new_v4(), "claire", "Claire", None, attestation_ca_list, Some(AuthenticatorAttachment::Platform), ) .expect("Failed to start registration."); ``` -------------------------------- ### Get Mutable Reference to First Element Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `first_mut()` to get an optional mutable reference to the first element. Allows in-place modification of the first element if it exists. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); let y: &mut [i32] = &mut []; assert_eq!(None, y.first_mut()); ``` -------------------------------- ### Get Mutable First Chunk of Slice Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `first_chunk_mut::()` to get a mutable reference to the first `N` elements as an array. Returns `None` if the slice is shorter than `N`. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ``` -------------------------------- ### start_attested_resident_key_authentication Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the authentication for an attested resident key. This function is available only with the `resident-key-support` crate feature. ```APIDOC ## start_attested_resident_key_authentication ### Description Initiates the authentication for an attested resident key. Available on **crate features`resident-key-support`** only. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **creds** ( &[AttestedResidentKey]) - A slice of attested resident keys. ### Method Not applicable (Rust function call) ### Endpoint Not applicable (Rust function call) ### Request Example None ### Response #### Success Response - **(RequestChallengeResponse, AttestedResidentKeyAuthentication)** (tuple) - A tuple containing the request challenge response and attested resident key authentication state. #### Response Example None ``` -------------------------------- ### Split Off Slice Starting with Third Element Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `split_off` with a range starting from an index to remove and return the latter part of a slice. The original slice is modified to contain the elements before the specified range. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### Get Immutable Reference to Last N Elements Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `last_chunk` to get an immutable reference to the last N elements of a slice. Returns `None` if the slice is shorter than N. Handles N=0 by returning an empty slice. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### Build Webauthn Instance Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.WebauthnBuilder.html Completes the construction of the Webauthn instance using the configured builder. This method returns an error if any configuration settings are invalid. ```rust use webauthn_rs::prelude::*; let rp_id = "example.com"; let rp_origin = Url::parse("https://idm.example.com") .expect("Invalid URL"); let mut builder = WebauthnBuilder::new(rp_id, &rp_origin) .expect("Invalid configuration"); let webauthn = builder.build() .expect("Invalid configuration"); ``` -------------------------------- ### start_attested_passkey_authentication Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the authentication process for a user using their attested passkeys. It generates a challenge response to be sent to the user agent and a server-side state that must be persisted. This function requires a list of the user's `AttestedPasskey` objects. ```APIDOC ## `start_attested_passkey_authentication` ### Description Begins the authentication process for a user by generating a challenge response based on their attested passkeys. ### Method This is a library function call, not an HTTP endpoint. ### Parameters - `creds` (`&[AttestedPasskey]`): A slice of the user's attested passkey objects. ### Returns - `RequestChallengeResponse`: The challenge response to be sent to the user agent. - `AttestedPasskeyAuthentication`: The server-side state to be persisted. ### WARNING Persist the `AttestedPasskeyAuthentication` server-side to prevent replay attacks. ``` -------------------------------- ### strip_circumfix Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html This is a nightly-only experimental API. Returns a subslice with the prefix and suffix removed. If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the prefix and before the suffix, wrapped in `Some`. If the slice does not start with `prefix` or does not end with `suffix`, returns `None`. ```APIDOC ## strip_circumfix(&self, prefix: &P, suffix: &S) -> Option<&[T]> ### Description 🔬This is a nightly-only experimental API. (`strip_circumfix`) Returns a subslice with the prefix and suffix removed. If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the prefix and before the suffix, wrapped in `Some`. If the slice does not start with `prefix` or does not end with `suffix`, returns `None`. ### Parameters #### Path Parameters - **prefix** (P): The prefix to remove from the slice. - **suffix** (S): The suffix to remove from the slice. ### Response - **Some(&[T])**: If the slice starts with the prefix and ends with the suffix, returns the subslice between them. - **None**: If the slice does not start with the prefix or does not end with the suffix. ### Examples ```rust #![feature(strip_circumfix)] let v = &[10, 50, 40, 30]; assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..])); assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..])); assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..])); assert_eq!(v.strip_circumfix(&[50], &[30]), None); assert_eq!(v.strip_circumfix(&[10], &[40]), None); assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..])); assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..])); ``` ``` -------------------------------- ### start_attested_passkey_registration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration of a new attested passkey for a user. This function generates a challenge response and an attested passkey registration object, which are essential for the subsequent steps in the passkey registration process. It requires user identification details, optional excluded credentials, a list of trusted attestation CAs, and an optional UI hint for authenticator attachment. ```APIDOC ## start_attested_passkey_registration ### Description Initiate the registration of a new attested_passkey key for a user. A attested_passkey key is a cryptographic authenticator that is a self-contained multifactor authenticator. This means that the device (such as a yubikey) verifies the user is who they say they are via a PIN, biometric or other factor. Only if this verification passes, is the signature released and provided. As a result, the server _only_ requires this attested_passkey key to authenticate the user and assert their identity. Because of this reliance on the authenticator, attestation of the authenticator and its properties is strongly recommended. The primary difference to a passkey, is that these credentials must provide an attestation certificate which will be cryptographically validated to strictly enforce that only certain devices may be registered. This attestation requires that private key material is bound to a single hardware authenticator, and cannot be copied or moved out of it. At present, all widely deployed Hybrid authenticators (Apple iCloud Keychain and Google Passkeys in Google Password Manager) are synchronised authenticators which can roam between multiple devices, and so can never be attested. As of webauthn-rs v0.5.0, this creates a registration challenge with credential selection hints that only use ClientDevice or SecurityKey devices, so a user-agent supporting Webauthn L3 won’t offer to use Hybrid credentials. On user-agents not supporting Webauthn L3, and on older versions of webauthn-rs, user-agents would show a QR code and a user could attempt to register a Hybrid authenticator, but it would always fail at the end – which is a frustrating user experience! You _should_ recommend to the user to register multiple attested_passkey keys to their account on separate devices so that they have fall back authentication in the case of device failure or loss. You _should_ have a workflow that allows a user to register new devices without a need to register other factors. For example, allow a QR code that can be scanned from a phone, or a one-time link that can be copied to the device. You _must_ have a recovery workflow in case all devices are lost or destroyed. `user_unique_id` _may_ be stored in the authenticator. This may allow the credential to identify the user during certain client side work flows. `user_name` and `user_display_name` _may_ be stored in the authenticator. `user_name` is a friendly account name such as “claire@example.com”. `user_display_name` is the persons chosen way to be identified such as “Claire”. Both can change at _any_ time on the client side, and MUST NOT be used as primary keys. They _may not_ be present in authentication, these are only present to allow client work flows to display human friendly identifiers. `exclude_credentials` ensures that a set of credentials may not participate in this registration. You _should_ provide the list of credentials that are already registered to this user’s account to prevent duplicate credential registrations. `attestation_ca_list` contains a required list of Root CA certificates of authenticator manufacturers that you wish to trust. For example, if you want to only allow Yubikeys on your site, then you can provide the Yubico Root CA in this list, to validate that all registered devices are manufactured by Yubico. `ui_hint_authenticator_attachment` provides a UX/UI hint to the browser about the types of credentials that could be used in this registration. If set to `None` all authenticator attachement classes are valid. If set to Platform, only authenticators that are part of the device are used such as a TPM or TouchId. If set to Cross-Platform, only devices that are removable from the device can be used such as yubikeys. ### Method ```rust pub fn start_attested_passkey_registration( &self, user_unique_id: Uuid, user_name: &str, user_display_name: &str, exclude_credentials: Option>, attestation_ca_list: AttestationCaList, ui_hint_authenticator_attachment: Option, ) -> WebauthnResult<(CreationChallengeResponse, AttestedPasskeyRegistration)> ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **CreationChallengeResponse** (object) - The challenge response for creating a new credential. - **AttestedPasskeyRegistration** (object) - Information related to the attested passkey registration. #### Response Example None ### Error Handling - **WebauthnResult** (enum) - Indicates success or failure of the WebAuthn operation. ``` -------------------------------- ### Getting a Raw Pointer to Vec's Buffer Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Illustrates how to get a raw, immutable pointer to the vector's underlying buffer. This is an unsafe operation and requires careful handling to avoid undefined behavior, especially concerning aliasing and lifetimes. ```rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` ```rust unsafe { let mut v = vec![0, 1, 2]; let ptr1 = v.as_ptr(); let _ = ptr1.read(); let ptr2 = v.as_mut_ptr().offset(2); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1` // because it mutated a different element: let _ = ptr1.read(); } ``` -------------------------------- ### Split Off Slice Starting with Third Element Mutably Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Use `split_off_mut` with a range starting from an index to remove and return a mutable reference to the latter part of a mutable slice. The original mutable slice is modified to contain the elements before the specified range. ```rust let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd']; let mut tail = slice.split_off_mut(2..).unwrap(); assert_eq!(slice, &mut ['a', 'b']); assert_eq!(tail, &mut ['c', 'd']); ``` -------------------------------- ### Initialize WebauthnBuilder Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.WebauthnBuilder.html Initiates a new WebauthnBuilder with the relying party ID and origin. Ensure the rp_id is an effective domain of the rp_origin. ```rust use webauthn_rs::prelude::*; let rp_id = "example.com"; let rp_origin = Url::parse("https://idm.example.com") .expect("Invalid URL"); let mut builder = WebauthnBuilder::new(rp_id, &rp_origin) .expect("Invalid configuration"); ``` -------------------------------- ### start_attested_passkey_registration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration process for an attested passkey. It generates a challenge response that must be sent to the user agent. The returned `AttestedPasskeyRegistration` state must be persisted server-side to prevent replay attacks. This function allows for specifying preferred authenticator types and can be configured with different device catalogs for varying levels of trust. ```APIDOC ## `start_attested_passkey_registration` ### Description Initiates the registration of an attested passkey, generating a challenge response for the user agent and a server-side state that must be persisted. ### Method This is a library function call, not an HTTP endpoint. ### Parameters - `user_unique_id` (Uuid) - The unique identifier for the user. - `username` (string) - The username for the user. - `display_name` (string) - The display name for the user. - `icon_url` (Option) - An optional URL for the user's icon. - `attestation_ca_list` (Vec) - A list of trusted attestation Certificate Authorities. - `authenticator_attachment` (Option) - Preferred authenticator attachment type (e.g., Platform, CrossPlatform). ### Returns - `CreationChallengeResponse`: The challenge response to be sent to the user agent. - `AttestedPasskeyRegistration`: The server-side state to be persisted. ### Example ```rust // Example using a broad device catalog let user_unique_id = Uuid::new_v4(); let device_catalog = Data::all_known_devices(); let attestation_ca_list = (&device_catalog).try_into().expect("Failed to build attestation ca list"); let (ccr, skr) = webauthn.start_attested_passkey_registration( user_unique_id, "claire", "Claire", None, attestation_ca_list, Some(AuthenticatorAttachment::CrossPlatform), ).expect("Failed to start registration."); // Example using a strict device catalog let device_catalog = Data::strict(); let attestation_ca_list = (&device_catalog).try_into().expect("Failed to build attestation ca list"); let (ccr, skr) = webauthn.start_attested_passkey_registration( Uuid::new_v4(), "claire", "Claire", None, attestation_ca_list, Some(AuthenticatorAttachment::Platform), ).expect("Failed to start registration."); ``` ### WARNING Persist the `AttestedPasskeyRegistration` server-side to prevent replay attacks. ``` -------------------------------- ### impl Any for T Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.COSERSAKey.html Provides the `type_id` method to get the `TypeId` of the type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Parameters None ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Start Passkey Registration Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/struct.Webauthn.html Initiates the registration of a new passkey for a user. You must store the returned `PasskeyRegistration` value server-side to prevent replay attacks. This function allows any cryptographic authenticator to proceed. ```rust let user_unique_id = Uuid::new_v4(); // Initiate a basic registration flow, allowing any cryptograhpic authenticator to proceed. let (ccr, skr) = webauthn .start_passkey_registration( user_unique_id, "claire", "Claire", None, // No other credentials are registered yet. ) .expect("Failed to start registration."); ``` -------------------------------- ### strip_prefix Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Base64UrlSafeData.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## strip_prefix

(&self, prefix: &P) -> Option<&[T]> ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Parameters #### Path Parameters - **prefix** (P): The prefix to remove from the slice. ### Response - **Some(&[T])**: If the slice starts with the prefix, returns the subslice after the prefix. - **None**: If the slice does not start with the prefix. ### Examples ```rust let v = &[10, 40, 30]; assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..])); assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..])); assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..])); assert_eq!(v.strip_prefix(&[50]), None); assert_eq!(v.strip_prefix(&[10, 50]), None); let prefix : &str = "he"; assert_eq!(b"hello".strip_prefix(prefix.as_bytes()), Some(b"llo".as_ref())); ``` ``` -------------------------------- ### Configure URL Parsing Options Source: https://docs.rs/webauthn-rs/latest/webauthn_rs/prelude/struct.Url.html Obtain default `ParseOptions` to customize URL parsing behavior. This example demonstrates setting a base URL for relative URL parsing. ```rust use url::Url; let options = Url::options(); let api = Url::parse("https://api.example.com")?; let base_url = options.base_url(Some(&api)); let version_url = base_url.parse("version.json")?; assert_eq!(version_url.as_str(), "https://api.example.com/version.json"); ```