passkey-client 0.6.0

Webauthn client in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! # Passkey Client
//!
//! [![github]](https://github.com/1Password/passkey-rs/tree/main/passkey-client)
//! [![version]](https://crates.io/crates/passkey-client)
//! [![documentation]](https://docs.rs/passkey-client/)
//!
//! This crate defines a [`Client`] type along with a basic implementation of the [Webauthn]
//! specification. The [`Client`] uses an [`Authenticator`] to perform the actual cryptographic
//! operations, while the Client itself marshals data to and from the structs received from the Relying Party.
//!
//! This crate does not provide any code to perform networking requests to and from Relying Parties.
//!
//! [github]: https://img.shields.io/badge/GitHub-1Password%2Fpasskey--rs%2Fpasskey--client-informational?logo=github&style=flat
//! [version]: https://img.shields.io/crates/v/passkey-client?logo=rust&style=flat
//! [documentation]: https://img.shields.io/docsrs/passkey-client/latest?logo=docs.rs&style=flat
//! [Webauthn]: https://w3c.github.io/webauthn/
mod client_data;
pub use client_data::*;

use std::{borrow::Cow, fmt::Display, marker::PhantomData};

use passkey_authenticator::{Authenticator, CredentialStore, UserValidationMethod};
use passkey_crypto::{
    CryptoBackend, PublicKeyT, SecretKeyT, coset::Algorithm, hash::Sha256Backend, iana::EnumI64,
};
use passkey_types::{
    Bytes, Passkey, ctap2, encoding,
    webauthn::{
        self, AuthenticatorSelectionCriteria, ResidentKeyRequirement, UserVerificationRequirement,
    },
};
use serde::Serialize;
#[cfg(feature = "typeshare")]
use typeshare::typeshare;
use url::Url;

mod extensions;
mod rp_id_verifier;

#[cfg(all(feature = "linux", target_os = "linux"))]
pub mod linux;
#[cfg(all(feature = "windows", target_os = "windows"))]
pub mod windows;

pub use self::rp_id_verifier::{Fetcher, RelatedOriginResponse, RpIdVerifier};

#[cfg(feature = "android-asset-validation")]
pub use self::rp_id_verifier::android::{UnverifiedAssetLink, ValidationError, valid_fingerprint};

#[cfg(test)]
mod tests;

#[cfg_attr(feature = "typeshare", typeshare)]
#[derive(Debug, serde::Serialize, PartialEq, Eq)]
#[serde(tag = "type", content = "content")]
#[non_exhaustive]
/// Errors produced by Webauthn Operations.
pub enum WebauthnError {
    /// A credential ID can be a maximum of 1023 bytes.
    CredentialIdTooLong,
    /// The request origin was missing a proper domain part.
    OriginMissingDomain,
    /// The request origin is not a sub-domain of the RP ID.
    OriginRpMissmatch,
    /// The origin of the request does not use HTTPS.
    UnprotectedOrigin,
    /// Origin was set to localhost but allows_insecure_localhost was not set.
    InsecureLocalhostNotAllowed,
    /// No credential was found
    CredentialNotFound,
    /// The RP ID is invalid.
    InvalidRpId,
    /// Internal authenticator error whose value represents a `ctap2::StatusCode`
    AuthenticatorError(u8),
    /// The operation is not supported.
    NotSupportedError,
    /// The string did not match the expected pattern.
    SyntaxError,
    /// The input failed validation
    ValidationError {
        /// Context for the validation error
        context: &'static str,
    },
    /// The given RpId has possibly rolled out related origins
    RequiresRelatedOriginsSupport,
    /// An error when fetching remote resources
    FetcherError,
    /// A redirect that was not allowed occured
    RedirectError,
    /// Related Origins endpoint contains a number of labels exceeding the max limit
    ExceedsMaxLabelLimit,
    /// JSON serialization error
    SerializationError,
    /// The operation timed out
    TimeoutError,
}

const MAX_CREDENTIAL_ID_LENGTH: usize = 1023;

// Library sets tokio import as optional, timeouts rely on it
// Not sure if tokio should still be optional but guarding for now to avoid breaking changes
// https://www.w3.org/TR/webauthn-3/#recommended-range-and-default-for-a-webauthn-ceremony-timeout
#[cfg(feature = "tokio")]
const MIN_TIMEOUT: u32 = 300_000;
#[cfg(feature = "tokio")]
const MAX_TIMEOUT: u32 = 600_000;

impl WebauthnError {
    /// Was the error a vendor error?
    pub fn is_vendor_error(&self) -> bool {
        matches!(self, WebauthnError::AuthenticatorError(ctap_error) if ctap2::VendorError::try_from(*ctap_error).is_ok())
    }
}

impl From<ctap2::StatusCode> for WebauthnError {
    fn from(value: ctap2::StatusCode) -> Self {
        match value {
            ctap2::StatusCode::Known(ctap2::Ctap2Error::NoCredentials) => {
                WebauthnError::CredentialNotFound
            }
            ctap2code => WebauthnError::AuthenticatorError(ctap2code.into()),
        }
    }
}

/// Build the `CollectedClientData`, JSON-serialize it, and derive the client-data
/// hash that will be signed by the authenticator. Shared by both `Client` and
/// `LinuxClient` because the client-data step of a WebAuthn ceremony is
/// authenticator-independent.
pub(crate) fn build_client_data<D, E, C>(
    client_data: &D,
    ty: webauthn::ClientDataType,
    challenge: &[u8],
    origin: &Origin<'_>,
    _crypto: PhantomData<C>,
) -> Result<(String, Vec<u8>), WebauthnError>
where
    D: ClientData<E>,
    E: Serialize + Clone,
    C: CryptoBackend,
{
    let collected_client_data = webauthn::CollectedClientData::<E> {
        ty,
        challenge: encoding::base64url(challenge),
        origin: origin.to_string(),
        cross_origin: None,
        extra_data: client_data.extra_client_data(),
        unknown_keys: Default::default(),
    };
    let client_data_json = serde_json::to_string(&collected_client_data)
        .map_err(|_| WebauthnError::SerializationError)?;
    let client_data_hash = client_data
        .client_data_hash()
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| C::Sha256::sha256(client_data_json.as_bytes()).to_vec());
    Ok((client_data_json, client_data_hash))
}

/// Resolve the WebAuthn resident-key requirement + authenticator capabilities
/// into the CTAP2 `rk` option.
pub(crate) fn map_rk(
    criteria: Option<&AuthenticatorSelectionCriteria>,
    auth_info: &ctap2::get_info::Response,
) -> bool {
    let supports_rk = auth_info.options.as_ref().is_some_and(|o| o.rk);

    match criteria.unwrap_or(&Default::default()) {
        // If pkOptions.authenticatorSelection.residentKey is present and set to required.
        AuthenticatorSelectionCriteria {
            resident_key: Some(ResidentKeyRequirement::Required),
            ..
        } => true,

        // If pkOptions.authenticatorSelection.residentKey is present and set to preferred,
        // require an rk only if the authenticator advertises support for it.
        AuthenticatorSelectionCriteria {
            resident_key: Some(ResidentKeyRequirement::Preferred),
            ..
        } => supports_rk,

        // If pkOptions.authenticatorSelection.residentKey is present and set to discouraged.
        AuthenticatorSelectionCriteria {
            resident_key: Some(ResidentKeyRequirement::Discouraged),
            ..
        } => false,

        // Fall back to the legacy `requireResidentKey` when `residentKey` is absent.
        AuthenticatorSelectionCriteria {
            resident_key: None,
            require_resident_key,
            ..
        } => *require_resident_key,
    }
}

/// Map [`UserVerificationRequirement`] to the CTAP2 `uv` option, deferring to
/// the client's preference for `Preferred`.
pub(crate) fn ctap_uv_option(
    requirement: UserVerificationRequirement,
    uv_when_preferred: bool,
) -> bool {
    match requirement {
        UserVerificationRequirement::Discouraged => false,
        UserVerificationRequirement::Required => true,
        UserVerificationRequirement::Preferred => uv_when_preferred,
    }
}

/// The origin of a WebAuthn request.
pub enum Origin<'a> {
    /// A Url, meant for a request in the web browser.
    Web(Cow<'a, Url>),
    /// An android digital asset fingerprint.
    /// Meant for a request coming from an android application.
    #[cfg(feature = "android-asset-validation")]
    Android(UnverifiedAssetLink<'a>),
}

impl From<Url> for Origin<'_> {
    fn from(value: Url) -> Self {
        Origin::Web(Cow::Owned(value))
    }
}

impl<'a> From<&'a Url> for Origin<'a> {
    fn from(value: &'a Url) -> Self {
        Origin::Web(Cow::Borrowed(value))
    }
}

impl Display for Origin<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Origin::Web(url) => write!(f, "{}", url.as_str().trim_end_matches('/')),
            #[cfg(feature = "android-asset-validation")]
            Origin::Android(target_link) => {
                write!(
                    f,
                    "android:apk-key-hash:{}",
                    encoding::base64url(target_link.sha256_cert_fingerprint())
                )
            }
        }
    }
}

/// A `Client` represents a Webauthn client. Users of this struct should supply a
/// [`CredentialStore`], a [`UserValidationMethod`] and, optionally, an implementation of
/// [`public_suffix::EffectiveTLDProvider`].
///
/// The `tld_provider` is used to verify effective Top-Level Domains for request origins presented
/// to the client. Most applications can use the `new()` function, which creates a `Client` with a
/// default provider implementation. Use `new_with_custom_tld_provider()` to provide a custom
/// `EffectiveTLDProvider` if your application needs to interpret eTLDs differently from the Mozilla
/// Public Suffix List.
pub struct Client<S, U, C, P, F>
where
    S: CredentialStore + Sync,
    U: UserValidationMethod + Sync,
    C: CryptoBackend,
    P: public_suffix::EffectiveTLDProvider + Sync + 'static,
{
    authenticator: Authenticator<S, U, C>,
    rp_id_verifier: RpIdVerifier<P, F>,
    /// When the RP sends [`UserVerificationRequirement::Preferred`], whether to set CTAP `uv` to true.
    uv_when_preferred: bool,
    crypto: PhantomData<C>,
}

impl<S, U, C> Client<S, U, C, public_suffix::PublicSuffixList, ()>
where
    S: CredentialStore + Sync,
    U: UserValidationMethod + Sync,
    C: CryptoBackend + Sync,
    Passkey: TryFrom<<S as CredentialStore>::PasskeyItem>,
{
    /// Create a `Client` with a given `Authenticator` that uses the default
    /// TLD verifier provided by `[public_suffix]`.
    pub fn new(authenticator: Authenticator<S, U, C>) -> Self {
        Self {
            authenticator,
            rp_id_verifier: RpIdVerifier::new(public_suffix::DEFAULT_PROVIDER, None),
            uv_when_preferred: true,
            crypto: PhantomData,
        }
    }
}

impl<S, U, C, P, F> Client<S, U, C, P, F>
where
    S: CredentialStore + Sync,
    U: UserValidationMethod<PasskeyItem = <S as CredentialStore>::PasskeyItem> + Sync,
    C: CryptoBackend,
    P: public_suffix::EffectiveTLDProvider + Sync + 'static,
    F: Fetcher + Sync,
{
    /// Create a `Client` with a given `Authenticator` and a custom TLD provider
    /// that implements `[public_suffix::EffectiveTLDProvider]`.
    pub fn new_with_custom_tld_provider(
        authenticator: Authenticator<S, U, C>,
        custom_provider: P,
        fetcher: Option<F>,
    ) -> Self {
        Self {
            authenticator,
            rp_id_verifier: RpIdVerifier::new(custom_provider, fetcher),
            uv_when_preferred: true,
            crypto: PhantomData,
        }
    }

    /// Allows the internal [RpIdVerifier] to pass through localhost requests.
    pub fn allows_insecure_localhost(mut self, is_allowed: bool) -> Self {
        self.rp_id_verifier = self.rp_id_verifier.allows_insecure_localhost(is_allowed);
        self
    }

    /// Read access to the Client's `Authenticator`.
    pub fn authenticator(&self) -> &Authenticator<S, U, C> {
        &self.authenticator
    }

    /// Write access to the Client's `Authenticator`.
    pub fn authenticator_mut(&mut self) -> &mut Authenticator<S, U, C> {
        &mut self.authenticator
    }

    /// Set the client's preferred user verification setting.
    /// This setting is used when the RP requirement is [`UserVerificationRequirement::Preferred`] to determine if uv should be set to true.
    pub fn user_verification_when_preferred(mut self, enabled: bool) -> Self {
        self.uv_when_preferred = enabled;
        self
    }

    /// Register a webauthn `request` from the given `origin`.
    ///
    /// Returns either a [`webauthn::CreatedPublicKeyCredential`] on success or some [`WebauthnError`]
    pub async fn register<D: ClientData<E>, E: Serialize + Clone>(
        &mut self,
        origin: impl Into<Origin<'_>>,
        request: webauthn::CredentialCreationOptions,
        client_data: D,
    ) -> Result<webauthn::CreatedPublicKeyCredential, WebauthnError> {
        let origin = origin.into();

        // extract inner value of request as there is nothing else of value directly in CredentialCreationOptions
        let request = request.public_key;
        let auth_info = self.authenticator.get_info().await;

        let pub_key_cred_params = if request.pub_key_cred_params.is_empty() {
            webauthn::PublicKeyCredentialParameters::default_algorithms()
        } else {
            request.pub_key_cred_params
        };

        // Build the timeout for the request, clamping to a reasonable range if the RP provided one,
        // or using our defaults if not.
        #[cfg(feature = "tokio")]
        let timeout = std::time::Duration::from_millis(
            request
                .timeout
                .map(|t| t.clamp(MIN_TIMEOUT, MAX_TIMEOUT))
                .unwrap_or(MIN_TIMEOUT)
                .into(),
        ); // Treat MIN_TIMEOUT as default as per webauthn-3 spec

        let rp_id = self
            .rp_id_verifier
            .assert_domain(&origin, request.rp.id.as_deref())
            .await?;

        let (client_data_json, client_data_json_hash) = build_client_data(
            &client_data,
            webauthn::ClientDataType::Create,
            &request.challenge,
            &origin,
            PhantomData::<C>,
        )?;

        let extension_request = request.extensions.and_then(|e| e.zip_contents());

        let ctap_extensions = self.registration_extension_ctap2_input(
            extension_request.as_ref(),
            auth_info.extensions.as_deref().unwrap_or_default(),
        )?;

        let rk = map_rk(request.authenticator_selection.as_ref(), &auth_info);
        let uv_requirement = request
            .authenticator_selection
            .as_ref()
            .map(|s| s.user_verification)
            .unwrap_or_default();
        let uv = ctap_uv_option(uv_requirement, self.uv_when_preferred);

        let make_credential_request = ctap2::make_credential::Request {
            client_data_hash: client_data_json_hash.into(),
            rp: ctap2::make_credential::PublicKeyCredentialRpEntity {
                id: rp_id.to_owned(),
                name: Some(request.rp.name),
            },
            user: request.user,
            pub_key_cred_params,
            exclude_list: request.exclude_credentials,
            extensions: ctap_extensions,
            options: ctap2::make_credential::Options { rk, up: true, uv },
            pin_auth: None,
            pin_protocol: None,
        };

        #[cfg(feature = "tokio")]
        let ctap2_response = tokio::time::timeout(
            timeout,
            self.authenticator.make_credential(make_credential_request),
        )
        .await
        .map_err(|_| WebauthnError::TimeoutError)?
        .map_err(|sc| WebauthnError::AuthenticatorError(sc.into()))?;

        #[cfg(not(feature = "tokio"))]
        let ctap2_response = self
            .authenticator
            .make_credential(make_credential_request)
            .await
            .map_err(|sc| WebauthnError::AuthenticatorError(sc.into()))?;

        // SAFETY: this unwrap is safe because the ctap2_response was just created in make_credential()
        // above, which currently sets auth_data.attested_credential_data unconditionally.
        // If this fails, it's a programmer error in that the postconditions of make_credential will
        // have changed.
        let credential_id = ctap2_response
            .auth_data
            .attested_credential_data
            .as_ref()
            .unwrap();

        // Validate returned credential ID length to comply with new credential registration ceremony spec
        // https://w3c.github.io/webauthn/#sctn-registering-a-new-credential
        if credential_id.credential_id().len() > MAX_CREDENTIAL_ID_LENGTH {
            return Err(WebauthnError::CredentialIdTooLong);
        }

        let alg = match credential_id.key.alg.as_ref().unwrap() {
            Algorithm::PrivateUse(val) => *val,
            Algorithm::Assigned(alg) => alg.to_i64(),
            Algorithm::Text(_) => {
                unreachable!()
            }
        };
        let public_key = Some(
            <<C as CryptoBackend>::SecretKey as SecretKeyT>::PublicKey::der_from_cose_key(
                &credential_id.key,
            )
            .map(Bytes::from)
            .map_err(|e| WebauthnError::AuthenticatorError(ctap2::Ctap2Error::from(e).into()))?,
        );

        let attestation_object = ctap2_response.as_webauthn_bytes();
        let store_info = self.authenticator.store().get_info().await;
        let client_extension_results = self.registration_extension_outputs(
            extension_request.as_ref(),
            store_info,
            rk,
            ctap2_response.unsigned_extension_outputs,
        );

        let response = webauthn::CreatedPublicKeyCredential {
            id: encoding::base64url(credential_id.credential_id()),
            raw_id: credential_id.credential_id().to_vec().into(),
            ty: webauthn::PublicKeyCredentialType::PublicKey,
            response: webauthn::AuthenticatorAttestationResponse {
                client_data_json: Vec::from(client_data_json).into(),
                authenticator_data: ctap2_response.auth_data.to_vec().into(),
                public_key,
                public_key_algorithm: alg,
                attestation_object,
                transports: auth_info.transports,
            },
            authenticator_attachment: Some(self.authenticator().attachment_type()),
            client_extension_results,
        };

        Ok(response)
    }

    /// Authenticate a Webauthn request.
    ///
    /// Returns either an [`webauthn::AuthenticatedPublicKeyCredential`] on success or some [`WebauthnError`].
    pub async fn authenticate<D: ClientData<E>, E: Serialize + Clone>(
        &mut self,
        origin: impl Into<Origin<'_>>,
        request: webauthn::CredentialRequestOptions,
        client_data: D,
    ) -> Result<webauthn::AuthenticatedPublicKeyCredential, WebauthnError> {
        let origin = origin.into();

        // extract inner value of request as there is nothing else of value directly in CredentialRequestOptions
        let request = request.public_key;
        let auth_info = self.authenticator().get_info().await;

        #[cfg(feature = "tokio")]
        let timeout = std::time::Duration::from_millis(
            request
                .timeout
                .map(|t| t.clamp(MIN_TIMEOUT, MAX_TIMEOUT))
                .unwrap_or(MIN_TIMEOUT)
                .into(),
        ); // Treat MIN_TIMEOUT as default as per webauthn-3 spec

        let rp_id = self
            .rp_id_verifier
            .assert_domain(&origin, request.rp_id.as_deref())
            .await?;

        let (client_data_json, client_data_json_hash) = build_client_data(
            &client_data,
            webauthn::ClientDataType::Get,
            &request.challenge,
            &origin,
            PhantomData::<C>,
        )?;

        let ctap_extensions = self.auth_extension_ctap2_input(
            &request,
            auth_info.extensions.unwrap_or_default().as_slice(),
        )?;
        let uv = ctap_uv_option(request.user_verification, self.uv_when_preferred);

        let get_assertion_request = ctap2::get_assertion::Request {
            rp_id: rp_id.to_owned(),
            client_data_hash: client_data_json_hash.into(),
            allow_list: request.allow_credentials,
            extensions: ctap_extensions,
            options: ctap2::get_assertion::Options { up: true, uv },
            pin_auth: None,
            pin_protocol: None,
        };

        #[cfg(feature = "tokio")]
        let ctap2_response = tokio::time::timeout(
            timeout,
            self.authenticator.get_assertion(get_assertion_request),
        )
        .await
        .map_err(|_| WebauthnError::TimeoutError)?
        .map_err(Into::<WebauthnError>::into)?;

        #[cfg(not(feature = "tokio"))]
        let ctap2_response = self
            .authenticator
            .get_assertion(get_assertion_request)
            .await
            .map_err(Into::<WebauthnError>::into)?;

        let client_extension_results =
            self.auth_extension_outputs(ctap2_response.unsigned_extension_outputs);

        // SAFETY: This unwrap is safe because ctap2_response was created immedately
        // above and the postcondition of that function is that response.credential
        // will yield a credential. If none was found, we will have already returned
        // a WebauthnError::CredentialNotFound error from map_err in that line.
        let credential_id_bytes = ctap2_response.credential.unwrap().id;
        Ok(webauthn::AuthenticatedPublicKeyCredential {
            id: encoding::base64url(&credential_id_bytes),
            raw_id: credential_id_bytes.to_vec().into(),
            ty: webauthn::PublicKeyCredentialType::PublicKey,
            response: webauthn::AuthenticatorAssertionResponse {
                client_data_json: Vec::from(client_data_json).into(),
                authenticator_data: ctap2_response.auth_data.to_vec().into(),
                signature: ctap2_response.signature,
                user_handle: ctap2_response.user.map(|user| user.id),
                attestation_object: None,
            },
            authenticator_attachment: Some(self.authenticator().attachment_type()),
            client_extension_results,
        })
    }
}