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
//! Types that are expected to be serialised in applications using [crate::Webauthn]

use serde::{Deserialize, Serialize};

use webauthn_rs_core::interface::{
    AttestationCaList, AuthenticationResult, AuthenticationState, RegistrationState,
};
use webauthn_rs_core::proto::{
    COSEAlgorithm, COSEKey, Credential, CredentialID, ParsedAttestation,
};

/// An in progress registration session for a [Passkey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
pub struct PasskeyRegistration {
    pub(crate) rs: RegistrationState,
}

/// An in progress authentication session for a [Passkey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
pub struct PasskeyAuthentication {
    pub(crate) ast: AuthenticationState,
}

/// A Passkey for a user. A passkey is a term that covers all possible authenticators that may exist.
/// These could be roaming credentials such as Apple's Account back passkeys, they could be a users
/// Yubikey, a Windows Hello TPM, or even a password manager softtoken.
///
/// Passkeys *may* opportunistically have some properties such as discoverability (residence). This
/// is not a guarantee since enforcing residence on devices like yubikeys that have limited storage
/// and no administration of resident keys may break the device.
///
/// These can be safely serialised and deserialised from a database for persistance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Passkey {
    pub(crate) cred: Credential,
}

impl Passkey {
    /// Retrieve a reference to this Pass Key's credential ID.
    pub fn cred_id(&self) -> &CredentialID {
        &self.cred.cred_id
    }

    /// Retrieve the type of cryptographic algorithm used by this key
    pub fn cred_algorithm(&self) -> &COSEAlgorithm {
        &self.cred.cred.type_
    }

    /// Retrieve a reference to this Passkey's credential public key.
    pub fn get_public_key(&self) -> &COSEKey {
        &self.cred.cred
    }

    /// Post authentication, update this credentials properties.
    ///
    /// To determine if this is required, you can inspect the result of
    /// `authentication_result.needs_update()`. Counter intuitively, most passkeys
    /// will never need their properties updated! This is because many passkeys lack an
    /// internal device activation counter (due to their synchronisation), and the
    /// backup-state flags are rarely if ever changed.
    ///
    /// If the credential_id does not match, None is returned.
    /// If the cred id matches and the credential is updated, Some(true) is returned.
    /// If the cred id matches, but the credential is not changed, Some(false) is returned.
    pub fn update_credential(&mut self, res: &AuthenticationResult) -> Option<bool> {
        if res.cred_id() == self.cred_id() {
            let mut changed = false;
            if res.counter() > self.cred.counter {
                self.cred.counter = res.counter();
                changed = true;
            }

            if res.backup_state() != self.cred.backup_state {
                self.cred.backup_state = res.backup_state();
                changed = true;
            }

            if res.backup_eligible() != self.cred.backup_eligible {
                // MUST be false -> true
                assert!(!self.cred.backup_eligible);
                assert!(res.backup_eligible());
                self.cred.backup_eligible = res.backup_eligible();
                changed = true;
            }

            Some(changed)
        } else {
            None
        }
    }
}

#[cfg(feature = "danger-credential-internals")]
impl From<Passkey> for Credential {
    fn from(pk: Passkey) -> Self {
        pk.cred
    }
}

#[cfg(feature = "danger-credential-internals")]
impl From<Credential> for Passkey {
    /// Convert a generic webauthn credential into a Passkey
    fn from(cred: Credential) -> Self {
        Passkey { cred }
    }
}

impl PartialEq for Passkey {
    fn eq(&self, other: &Self) -> bool {
        self.cred.cred_id == other.cred.cred_id
    }
}

// AttestedPasskey

/// An in progress registration session for a [AttestedPasskey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
#[cfg(feature = "preview-features")]
pub struct AttestedPasskeyRegistration {
    pub(crate) rs: RegistrationState,
    pub(crate) ca_list: AttestationCaList,
}

/// An in progress authentication session for a [AttestedPasskey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
#[cfg(feature = "preview-features")]
pub struct AttestedPasskeyAuthentication {
    pub(crate) ast: AuthenticationState,
}

/// An attested passkey for a user. This is a specialisation of [Passkey] as you can
/// limit the make and models of authenticators that a user may register. Additionally
/// these keys will always enforce userverification.
///
/// These can be safely serialised and deserialised from a database for use.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "preview-features")]
pub struct AttestedPasskey {
    pub(crate) cred: Credential,
}

#[cfg(feature = "preview-features")]
impl AttestedPasskey {
    /// Retrieve a reference to this AttestedPasskey Key's credential ID.
    pub fn cred_id(&self) -> &CredentialID {
        &self.cred.cred_id
    }

    /// Retrieve the type of cryptographic algorithm used by this key
    pub fn cred_algorithm(&self) -> &COSEAlgorithm {
        &self.cred.cred.type_
    }

    /// Retrieve a reference to the attestation used during this [`Credential`]'s
    /// registration. This can tell you information about the manufacterer and
    /// what type of credential it is.
    pub fn attestation(&self) -> &ParsedAttestation {
        &self.cred.attestation
    }

    /// Post authentication, update this credentials properties.
    ///
    /// To determine if this is required, you can inspect the result of
    /// `authentication_result.needs_update()`. Generally this will always
    /// be true as this class of key will maintain an activation counter which
    /// allows (limited) protection against device cloning.
    ///
    /// If the credential_id does not match, None is returned. If the cred id matches
    /// and the credential is updated, Some(true) is returned. If the cred id
    /// matches, but the credential is not changed, Some(false) is returned.
    pub fn update_credential(&mut self, res: &AuthenticationResult) -> Option<bool> {
        if res.cred_id() == self.cred_id() {
            let mut changed = false;
            if res.counter() > self.cred.counter {
                self.cred.counter = res.counter();
                changed = true;
            }

            if res.backup_state() != self.cred.backup_state {
                self.cred.backup_state = res.backup_state();
                changed = true;
            }

            Some(changed)
        } else {
            None
        }
    }
}

#[cfg(feature = "preview-features")]
impl PartialEq for AttestedPasskey {
    fn eq(&self, other: &Self) -> bool {
        self.cred.cred_id == other.cred.cred_id
    }
}

#[cfg(all(feature = "danger-credential-internals", feature = "preview-features"))]
impl From<AttestedPasskey> for Credential {
    fn from(pk: AttestedPasskey) -> Self {
        pk.cred
    }
}

#[cfg(all(feature = "danger-credential-internals", feature = "preview-features"))]
impl From<Credential> for AttestedPasskey {
    /// Convert a generic webauthn credential into a Passkey
    fn from(cred: Credential) -> Self {
        AttestedPasskey { cred }
    }
}

/// An in progress registration session for a [SecurityKey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
pub struct SecurityKeyRegistration {
    pub(crate) rs: RegistrationState,
    pub(crate) ca_list: Option<AttestationCaList>,
}

/// An in progress authentication session for a [SecurityKey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
pub struct SecurityKeyAuthentication {
    pub(crate) ast: AuthenticationState,
}

/// A Security Key for a user. These are the legacy "second factor" method of security tokens.
///
/// You should avoid this type in favour of [Passkey] or [AttestedPasskey]
///
/// These can be safely serialised and deserialised from a database for use.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityKey {
    pub(crate) cred: Credential,
}

impl SecurityKey {
    /// Retrieve a reference to this Security Key's credential ID.
    pub fn cred_id(&self) -> &CredentialID {
        &self.cred.cred_id
    }

    /// Retrieve the type of cryptographic algorithm used by this key
    pub fn cred_algorithm(&self) -> &COSEAlgorithm {
        &self.cred.cred.type_
    }

    /// Retrieve a reference to the attestation used during this [`Credential`]'s
    /// registration. This can tell you information about the manufacterer and
    /// what type of credential it is.
    pub fn attestation(&self) -> &ParsedAttestation {
        &self.cred.attestation
    }

    /// Post authentication, update this credentials properties.
    ///
    /// To determine if this is required, you can inspect the result of
    /// `authentication_result.needs_update()`. Generally this will always
    /// be true as this class of key will maintain an activation counter which
    /// allows (limited) protection against device cloning.
    ///
    /// If the credential_id does not match, None is returned. If the cred id matches
    /// and the credential is updated, Some(true) is returned. If the cred id
    /// matches, but the credential is not changed, Some(false) is returned.
    pub fn update_credential(&mut self, res: &AuthenticationResult) -> Option<bool> {
        if res.cred_id() == self.cred_id() {
            let mut changed = false;
            if res.counter() > self.cred.counter {
                self.cred.counter = res.counter();
                changed = true;
            }

            if res.backup_state() != self.cred.backup_state {
                self.cred.backup_state = res.backup_state();
                changed = true;
            }

            Some(changed)
        } else {
            None
        }
    }
}

impl PartialEq for SecurityKey {
    fn eq(&self, other: &Self) -> bool {
        self.cred.cred_id == other.cred.cred_id
    }
}

#[cfg(feature = "danger-credential-internals")]
impl From<SecurityKey> for Credential {
    fn from(sk: SecurityKey) -> Self {
        sk.cred
    }
}

#[cfg(feature = "danger-credential-internals")]
impl From<Credential> for SecurityKey {
    /// Convert a generic webauthn credential into a security key
    fn from(cred: Credential) -> Self {
        SecurityKey { cred }
    }
}

/// An in progress registration session for a [AttestedResidentKey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
#[cfg(feature = "resident-key-support")]
pub struct AttestedResidentKeyRegistration {
    pub(crate) rs: RegistrationState,
    pub(crate) ca_list: AttestationCaList,
}

/// An in progress authentication session for a [AttestedResidentKey].
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
#[cfg(feature = "resident-key-support")]
pub struct AttestedResidentKeyAuthentication {
    pub(crate) ast: AuthenticationState,
}

/// An attested resident key belonging to a user. These are a specialisation of [AttestedPasskey] where
/// the devices in use can be attested. In addition this type enforces keys to be resident on the
/// authenticator.
///
/// Since most authenticators have very limited key residence support, this should only be used in
/// tightly controlled enterprise environments where you have strict access over the makes and models
/// of keys in use.
///
/// Key residence is *not* a security property. The general reason for the usage of key residence is
/// to allow the device to identify the user in addition to authenticating them.
///
/// These can be safely serialised and deserialised from a database for use.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "resident-key-support")]
pub struct AttestedResidentKey {
    pub(crate) cred: Credential,
}

#[cfg(feature = "resident-key-support")]
impl AttestedResidentKey {
    /// Retrieve a reference to this Resident Key's credential ID.
    pub fn cred_id(&self) -> &CredentialID {
        &self.cred.cred_id
    }

    /// Retrieve the type of cryptographic algorithm used by this key
    pub fn cred_algorithm(&self) -> &COSEAlgorithm {
        &self.cred.cred.type_
    }

    /// Retrieve a reference to the attestation used during this [`Credential`]'s
    /// registration. This can tell you information about the manufacterer and
    /// what type of credential it is.
    pub fn attestation(&self) -> &ParsedAttestation {
        &self.cred.attestation
    }

    /// Post authentication, update this credentials properties.
    ///
    /// To determine if this is required, you can inspect the result of
    /// `authentication_result.needs_update()`. Generally this will always
    /// be true as this class of key will maintain an activation counter which
    /// allows (limited) protection against device cloning.
    ///
    /// If the credential_id does not match, None is returned. If the cred id matches
    /// and the credential is updated, Some(true) is returned. If the cred id
    /// matches, but the credential is not changed, Some(false) is returned.
    pub fn update_credential(&mut self, res: &AuthenticationResult) -> Option<bool> {
        if res.cred_id() == self.cred_id() {
            let mut changed = false;
            if res.counter() > self.cred.counter {
                self.cred.counter = res.counter();
                changed = true;
            }

            if res.backup_state() != self.cred.backup_state {
                self.cred.backup_state = res.backup_state();
                changed = true;
            }

            Some(changed)
        } else {
            None
        }
    }
}

#[cfg(feature = "resident-key-support")]
impl PartialEq for AttestedResidentKey {
    fn eq(&self, other: &Self) -> bool {
        self.cred.cred_id == other.cred.cred_id
    }
}

#[cfg(all(
    feature = "danger-credential-internals",
    feature = "resident-key-support"
))]
impl From<AttestedResidentKey> for Credential {
    fn from(dk: AttestedResidentKey) -> Self {
        dk.cred
    }
}

#[cfg(all(
    feature = "danger-credential-internals",
    feature = "resident-key-support"
))]
impl From<Credential> for AttestedResidentKey {
    /// Convert a generic webauthn credential into a security key
    fn from(cred: Credential) -> Self {
        AttestedResidentKey { cred }
    }
}

/// An in progress authentication session for a [DiscoverableKey]. [Passkey] and [AttestedResidentKey]
/// can be used with these workflows.
///
/// WARNING ⚠️  YOU MUST STORE THIS VALUE SERVER SIDE.
///
/// Failure to do so *may* open you to replay attacks which can significantly weaken the
/// security of this system.
///
/// In some cases you *may* wish to serialise this value. For details on how to achieve this
/// see the [crate#allow-serialising-registration-and-authentication-state] level documentation.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "danger-allow-state-serialisation",
    derive(Serialize, Deserialize)
)]
#[cfg(feature = "preview-features")]
pub struct DiscoverableAuthentication {
    pub(crate) ast: AuthenticationState,
}

/// A key that can be used in discoverable workflows. Within this library [Passkey]s may be
/// discoverable on an opportunistic bases, and [AttestedResidentKey]s will always be discoverable.
///
/// Generally this is used as part of conditional ui which allows autofill of discovered
/// credentials in username fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg(feature = "preview-features")]
pub struct DiscoverableKey {
    pub(crate) cred: Credential,
}

#[cfg(feature = "preview-features")]
impl From<&AttestedResidentKey> for DiscoverableKey {
    fn from(k: &AttestedResidentKey) -> Self {
        DiscoverableKey {
            cred: k.cred.clone(),
        }
    }
}

#[cfg(feature = "preview-features")]
impl From<&Passkey> for DiscoverableKey {
    fn from(k: &Passkey) -> Self {
        DiscoverableKey {
            cred: k.cred.clone(),
        }
    }
}