passkey-types 0.6.0

Rust type definitions for the webauthn and CTAP specifications
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
//! <https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#authenticatorMakeCredential>

use ciborium::cbor;
use serde::{Deserialize, Serialize};

use crate::{
    Bytes,
    ctap2::AuthenticatorData,
    utils::serde::{ignore_unknown_opt_vec, ignore_unknown_vec},
    webauthn,
};

#[cfg(doc)]
use {
    crate::webauthn::{
        CollectedClientData, PublicKeyCredentialCreationOptions, PublicKeyCredentialDescriptor,
    },
    ciborium::value::Value,
};

use super::extensions::{AuthenticatorPrfInputs, AuthenticatorPrfMakeOutputs, HmacGetSecretInput};

serde_workaround! {
    /// While similar in structure to [`PublicKeyCredentialCreationOptions`],
    /// it is not completely identical, namely the presence of the `options` key.
    #[derive(Debug, PartialEq)]
    pub struct Request {
        /// Hash of the ClientData contextual binding specified by host.
        #[serde(rename = 0x01)]
        pub client_data_hash: Bytes,

        /// This [`PublicKeyCredentialRpEntity`] data structure describes a Relying Party with which the
        /// new public key credential will be associated. It contains the Relying party identifier
        /// of type text string, (optionally) a human-friendly RP name of type text string,
        /// and (optionally) a URL of type text string, referencing a RP icon image. The RP name is
        /// to be used by the authenticator when displaying the credential to the user for selection
        /// and usage authorization. The RP name and URL are optional so that the RP can be more
        /// privacy friendly if it chooses to. For example, for authenticators with a display, RP
        /// may not want to display name/icon for single-factor scenarios.
        #[serde(rename = 0x02)]
        pub rp: PublicKeyCredentialRpEntity,

        /// This [`PublicKeyCredentialUserEntity`] data structure describes the user account to
        /// which the new public key credential will be associated at the RP. It contains an
        /// RP-specific user account identifier of type byte array, (optionally) a user name of type
        /// text string, (optionally) a user display name of type text string, and (optionally) a
        /// URL of type text string, referencing a user icon image (of a user avatar, for example).
        /// The authenticator associates the created public key credential with the account
        /// identifier, and MAY also associate any or all of the user name, user display name, and
        /// image data (pointed to by the URL, if any). The user name, display name, and URL are
        /// optional for privacy reasons for single-factor scenarios where only user presence is
        /// required. For example, in certain closed physical environments like factory floors, user
        /// presence only authenticators can satisfy RP’s productivity and security needs. In these
        /// environments, omitting user name, display name and URL makes the credential more privacy
        /// friendly. Although this information is not available without user verification, devices
        /// which support user verification but do not have it configured, can be tricked into
        /// releasing this information by configuring the user verification.
        #[serde(rename = 0x03)]
        pub user: webauthn::PublicKeyCredentialUserEntity,

        /// A sequence of CBOR maps consisting of pairs of PublicKeyCredentialType (a string) and
        /// cryptographic algorithm (a positive or negative integer), where algorithm identifiers
        /// are values that SHOULD be registered in the IANA COSE Algorithms registry
        /// [`passkey_crypto::iana::Algorithm`]. This sequence is ordered from most preferred (by the RP) to least
        /// preferred.
        #[serde(rename = 0x04, deserialize_with = ignore_unknown_vec)]
        pub pub_key_cred_params: Vec<webauthn::PublicKeyCredentialParameters>,

        /// A sequence of [`PublicKeyCredentialDescriptor`] structures, as specified in [`webauthn`].
        /// The authenticator returns an error if the authenticator already contains one of
        /// the credentials enumerated in this sequence. This allows RPs to limit the creation of
        /// multiple credentials for the same account on a single authenticator.
        #[serde(
            rename = 0x05;
            default,
            skip_serializing_if = Option::is_none,
            deserialize_with = ignore_unknown_opt_vec
        )]
        pub exclude_list: Option<Vec<webauthn::PublicKeyCredentialDescriptor>>,

        /// Parameters to influence authenticator operation, as specified in [`webauthn`].
        /// These parameters might be authenticator specific.
        #[serde(rename = 0x06; default, skip_serializing_if = Option::is_none)]
        pub extensions: Option<ExtensionInputs>,

        /// Parameters to influence authenticator operation, see [`Options`] for more details.
        #[serde(rename = 0x07; default)]
        pub options: Options,

        /// First 16 bytes of HMAC-SHA-256 of clientDataHash using pinToken which platform got from
        /// the authenticator: HMAC-SHA-256(pinToken, clientDataHash). (NOT YET SUPPORTED)
        #[serde(rename = 0x08; default, skip_serializing_if = Option::is_none)]
        pub pin_auth: Option<Bytes>,

        /// PIN protocol version chosen by the client
        ///
        /// if ever we hit more than 256 protocol versions, an enhacement request should be filed.
        #[serde(rename = 0x09; default, skip_serializing_if = Option::is_none)]
        pub pin_protocol: Option<u8>,
    }
}

/// This is a copy of [`webauthn::PublicKeyCredentialRpEntity`] but where the `id` is required
/// and the `name` is optional which is the inverse of what is defined in the [WebAuthn]. These are
/// the requirements of the [CTAP2] version of this struct.
///
/// [WebAuthn]: https://w3c.github.io/webauthn/#dictdef-publickeycredentialrpentity
/// [CTAP2]: https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#authenticatorMakeCredential
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublicKeyCredentialRpEntity {
    /// The domain of the relying party
    pub id: String,
    /// A human friendly name for the Relying Party
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// This is a copy of [`webauthn::PublicKeyCredentialUserEntity`] with differing optional fields.
///
/// Field names match the CTAP2 wire format (`displayName`, `icon`) rather than the WebAuthn JSON
/// names, so this type can be used to decode `authenticatorGetAssertion` responses where the
/// authenticator may legally omit anything beyond `id`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyCredentialUserEntity {
    /// The ID of the user
    pub id: Bytes,
    /// Optional user name
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Optional display name
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Optional URL pointing to a user icon.
    /// CTAP2 calls this field `icon`, not `iconUrl`.
    #[serde(default, skip_serializing_if = "Option::is_none", rename = "icon")]
    pub icon_url: Option<String>,
}

impl From<webauthn::PublicKeyCredentialUserEntity> for PublicKeyCredentialUserEntity {
    fn from(value: webauthn::PublicKeyCredentialUserEntity) -> Self {
        Self {
            id: value.id,
            name: Some(value.name),
            display_name: Some(value.display_name),
            icon_url: None,
        }
    }
}

impl TryFrom<PublicKeyCredentialUserEntity> for webauthn::PublicKeyCredentialUserEntity {
    type Error = &'static str;
    fn try_from(value: PublicKeyCredentialUserEntity) -> Result<Self, Self::Error> {
        match (value.name, value.display_name) {
            (Some(name), Some(display_name)) => Ok(Self {
                id: value.id,
                name,
                display_name,
            }),
            _ => Err(
                "PublicKeyCredentialUserEntity is missing one or more required fields: name, display_name",
            ),
        }
    }
}

/// In the case of a missing `rp_id` on [`webauthn::PublicKeyCredentialRpEntity`] use this to
/// construct a [`PublicKeyCredentialRpEntity`] using a effective domain.
#[non_exhaustive]
#[derive(Debug)]
pub struct MissingRpId {
    /// Human friendly name for the Relying Party, extracted from [`webauthn::PublicKeyCredentialRpEntity::name`].
    pub rp_name: String,
}

impl TryFrom<webauthn::PublicKeyCredentialRpEntity> for PublicKeyCredentialRpEntity {
    type Error = MissingRpId;
    /// Convert the webauthn version of the struct to the CTAP2 version with the effective domain if
    /// the id was not provided.
    fn try_from(value: webauthn::PublicKeyCredentialRpEntity) -> Result<Self, Self::Error> {
        if let Some(id) = value.id {
            Ok(Self {
                id,
                name: Some(value.name),
            })
        } else {
            Err(MissingRpId {
                rp_name: value.name,
            })
        }
    }
}

/// The options that control how an authenticator will behave during authenticatorMakeCredential.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Options {
    /// Specifies whether this credential is to be discoverable or not.
    #[serde(default)]
    pub rk: bool,
    /// Instructs the authenticator to require a gesture that verifies the user to complete the request. Examples of such gestures are fingerprint scan or a PIN.
    /// This is marked with `skip_serializing` because CTAP 2.0 does not specify a `up` field in
    /// `Options`, while CTAP 2.1 allows the `up` field to be present but requires that its value
    /// be set to true if it is present.
    #[serde(default = "default_true", skip_serializing_if = "is_false")]
    pub up: bool,
    /// User Verification:
    ///
    /// If the "uv" option is absent, let the "uv" option be treated as being present with the value false.
    #[serde(default)]
    pub uv: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            rk: false,
            up: true,
            uv: false,
        }
    }
}

const fn default_true() -> bool {
    true
}

const fn is_false(e: &bool) -> bool {
    !*e
}

/// All supported Authenticator extensions inputs during credential creation
#[derive(Debug, Serialize, Deserialize, Default, PartialEq)]
pub struct ExtensionInputs {
    /// A boolean value to indicate that this extension is requested by the Relying Party
    ///
    /// <https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#sctn-hmac-secret-extension>
    #[serde(
        rename = "hmac-secret",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hmac_secret: Option<bool>,

    /// The input salts for fetching and deriving a symmetric secret during registration.
    ///
    /// TODO: link to the hmac-secret-mc extension in the spec once it's published.
    #[serde(
        rename = "hmac-secret-mc",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hmac_secret_mc: Option<HmacGetSecretInput>,

    /// The direct input from a on-system client for the prf extension.
    ///
    /// The output from a request using the `prf` extension will not be signed
    /// and will be un-encrypted.
    /// This input should already be hashed by the client.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prf: Option<AuthenticatorPrfInputs>,
}

impl ExtensionInputs {
    /// Validates that there is at least one extension field that is `Some`.
    /// If all fields are `None` then this returns `None` as well.
    pub fn zip_contents(self) -> Option<Self> {
        let Self {
            hmac_secret,
            hmac_secret_mc,
            prf,
        } = &self;

        let has_hmac_secret = hmac_secret.is_some();
        let has_hmac_secret_mc = hmac_secret_mc.is_some();
        let has_prf = prf.is_some();

        (has_hmac_secret || has_hmac_secret_mc || has_prf).then_some(self)
    }
}

serde_workaround! {
    /// Upon successful creation of a credential, the authenticator returns an attestation object.
    #[derive(Debug)]
    pub struct Response {
        /// The attestation statement format identifier
        #[serde(rename = 0x01)]
        pub fmt: String,

        /// The authenticator data object
        #[serde(rename = 0x02)]
        pub auth_data: AuthenticatorData,

        /// The attestation statement, whose format is identified by the "fmt" object member.
        /// The client treats it as an opaque object.
        //
        // TODO: Change to a flattened enum when `content, type` serde enums can use numbers as
        // the keys
        #[serde(rename = 0x03)]
        pub att_stmt: ciborium::value::Value,

        /// Indicates whether an enterprise attestation was returned for this credential.
        /// If `ep_att` is absent or present and set to false, then an enterprise attestation was not returned.
        /// If `ep_att` is present and set to true, then an enterprise attestation was returned.
        ///
        /// Enterprise attestation is currently unsupported by this library.
        #[serde(rename = 0x04; default, skip_serializing_if = Option::is_none)]
        pub ep_att: Option<bool>,

        /// Contains the `largeBlobKey` for the credential, if requested with the `largeBlobKey` extension.
        ///
        /// The `largeBlobKey` extension is currently unsupported by this library.
        #[serde(rename = 0x05; default, skip_serializing_if = Option::is_none)]
        pub large_blob_key: Option<Bytes>,

        /// A map, keyed by extension identifiers, to unsigned outputs of extensions, if any.
        /// Authenticators SHOULD omit this field if no processed extensions define unsigned outputs.
        /// Clients MUST treat an empty map the same as an omitted field.
        #[serde(rename = 0x06; default, skip_serializing_if = Option::is_none)]
        pub unsigned_extension_outputs: Option<UnsignedExtensionOutputs>,
    }
}

impl Response {
    // Note: Technically the authenticator response should be a CBOR object, but we add this method instead
    // for backwards compatibility with previous versions of this library.
    // [WebAuthn]: Return the attestation object as a CBOR map with the following syntax, filled in with variables initialized by this algorithm

    /// Convert response into a CBOR-encoded WebAuthn attestation object.
    ///
    /// Note: This uses the WebAuthn string labels for fields rather than the CTAP2 integer labels.
    pub fn as_webauthn_bytes(&self) -> Bytes {
        let mut attestation_object = Vec::with_capacity(128);
        // SAFETY: The Results here are from serializing all the internals of `cbor!` into `ciborium::Value`
        // then serializing said value to bytes. The unwraps here are safe because it would otherwise be
        // programmer error.
        // TODO: Create strong attestation type definitions, part of CTAP2
        let attestation_object_value = cbor!({
               // TODO: Follow preference and/or implement AnonCA https://w3c.github.io/webauthn/#anonymization-ca
               "fmt" => "none",
                "attStmt" => {},
                // Explicitly define these fields as bytes since specialization is still fairly far
               "authData" => ciborium::value::Value::Bytes(self.auth_data.to_vec()),
        })
        .unwrap();
        ciborium::ser::into_writer(&attestation_object_value, &mut attestation_object).unwrap();
        attestation_object.into()
    }
}

/// All supported Authenticator extensions outputs during credential creation
///
/// This is to be serialized to [`Value`] in [`AuthenticatorData::extensions`]
#[derive(Debug, Serialize, Deserialize)]
pub struct SignedExtensionOutputs {
    /// A boolean value to indicate that this extension was successfully processed by the extension
    ///
    /// <https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-errata-20220621.html#sctn-hmac-secret-extension>
    #[serde(
        rename = "hmac-secret",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hmac_secret: Option<bool>,

    /// Outputs the symmetric secrets after successfull processing. The output MUST be encrypted.
    ///
    /// TODO: link to the hmac-secret-mc extension in the spec once it's published.
    #[serde(
        rename = "hmac-secret-mc",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub hmac_secret_mc: Option<Bytes>,
}

impl SignedExtensionOutputs {
    /// Validates that there is at least one extension field that is `Some`.
    /// If all fields are `None` then this returns `None` as well.
    pub fn zip_contents(self) -> Option<Self> {
        let Self {
            hmac_secret,
            hmac_secret_mc,
        } = &self;
        let has_hmac_secret = hmac_secret.is_some();
        let has_hmac_secret_mc = hmac_secret_mc.is_some();

        (has_hmac_secret || has_hmac_secret_mc).then_some(self)
    }
}

/// A map, keyed by extension identifiers, to unsigned outputs of extensions, if any.
/// Authenticators SHOULD omit this field if no processed extensions define unsigned outputs.
/// Clients MUST treat an empty map the same as an omitted field.
#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct UnsignedExtensionOutputs {
    /// This output is supported in the Webauthn specification and will be used when the authenticator
    /// and the client are in memory or communicating through an internal channel.
    ///
    /// If you are using transports where this needs to pass through a wire, use hmac-secret instead.
    pub prf: Option<AuthenticatorPrfMakeOutputs>,
}

impl UnsignedExtensionOutputs {
    /// Validates that there is at least one extension field that is `Some`.
    /// If all fields are `None` then this returns `None` as well.
    pub fn zip_contents(self) -> Option<Self> {
        let Self { prf } = &self;

        prf.is_some().then_some(self)
    }
}

#[cfg(test)]
mod tests;