yubikit 1.0.0-beta.0

YubiKey management library
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
// Copyright 2026 Yubico AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! WebAuthn extension types and CBOR encoding/decoding.
//!
//! Each sub-module defines extension-specific input/output types with JSON
//! serialization. The aggregate [`RegistrationExtensionInputs`](crate::webauthn::extensions::RegistrationExtensionInputs) and
//! [`AuthenticationExtensionInputs`](crate::webauthn::extensions::AuthenticationExtensionInputs) structs are used in the WebAuthn
//! options, while the output types appear in ceremony responses.
//!
//! ## Extension Processing Architecture
//!
//! Extensions are pluggable via the [`Ctap2Extension`](crate::webauthn::extensions::Ctap2Extension) trait. Each extension
//! optionally produces a [`RegistrationProcessor`](crate::webauthn::extensions::RegistrationProcessor) or [`AuthenticationProcessor`](crate::webauthn::extensions::AuthenticationProcessor)
//! for a given ceremony, which handles building authenticator inputs and parsing
//! outputs.

use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use crate::cbor::{self, Value};
use crate::ctap2::{Info, Permissions, PinProtocol};

use super::types::{PublicKeyCredentialCreationOptions, PublicKeyCredentialRequestOptions};

/// Credential Blob extension (`credBlob`).
pub mod cred_blob;
/// Credential Properties extension (`credProps`).
pub mod cred_props;
/// Credential Protection extension (`credProtect`).
pub mod cred_protect;
/// Large Blob extension (`largeBlob`).
pub mod large_blob;
/// Minimum PIN Length extension (`minPinLength`).
pub mod min_pin_length;
/// Pseudo-Random Function extension (`prf` / `hmac-secret`).
pub mod prf;
/// Signing extension (`previewSign`) version 4.
pub mod sign;

// Re-export key types
/// Credential protection policy level.
pub use cred_protect::CredProtectPolicy;
/// Level of large blob support requested during registration.
pub use large_blob::LargeBlobSupport;
/// PRF evaluation inputs and derived results.
pub use prf::{PrfEval, PrfResults};

// ---------------------------------------------------------------------------
// Extension processing traits
// ---------------------------------------------------------------------------

/// Context provided to extension processors during input preparation.
///
/// Provides access to the PIN protocol and a way to obtain the ECDH shared
/// secret (needed by hmac-secret).
pub struct ExtensionContext {
    /// The negotiated PIN protocol, if any.
    pub pin_protocol: Option<PinProtocol>,
    /// The ECDH shared secret state, if obtained.
    pub(crate) hmac_secret_state: Option<prf::HmacSecretState>,
}

impl ExtensionContext {
    pub(crate) fn new(pin_protocol: Option<PinProtocol>) -> Self {
        Self {
            pin_protocol,
            hmac_secret_state: None,
        }
    }
}

/// Context provided to extension processors during output processing.
pub struct OutputContext<'a> {
    /// Whether the credential was created as a resident/discoverable key.
    pub rk: bool,
    /// The parsed extensions map from authenticator data, if present.
    pub auth_data_extensions: Option<&'a [(String, Value)]>,
    /// Unsigned extension outputs from the authenticator response.
    pub unsigned_extension_outputs: Option<&'a Value>,
    /// Whether the response contained a large_blob_key.
    pub has_large_blob_key: bool,
    /// The hmac-secret ECDH state, for decrypting PRF outputs.
    pub(crate) hmac_secret_state: Option<&'a prf::HmacSecretState>,
}

/// A WebAuthn extension definition. Stateless and reusable across requests.
///
/// Implementations check whether the extension is applicable and produce
/// per-request processors that handle the input/output lifecycle.
pub trait Ctap2Extension {
    /// Begin registration processing. Returns `None` if the extension is not
    /// applicable to this request (e.g. not requested in options, or not
    /// supported by the authenticator).
    fn make_credential(
        &self,
        info: &Info,
        options: &PublicKeyCredentialCreationOptions,
    ) -> Result<Option<Box<dyn RegistrationProcessor>>, String>;

    /// Begin authentication processing. Returns `None` if not applicable.
    fn get_assertion(
        &self,
        info: &Info,
        options: &PublicKeyCredentialRequestOptions,
    ) -> Result<Option<Box<dyn AuthenticationProcessor>>, String>;
}

/// Per-request registration extension processing.
///
/// Duplicate input identifiers, including those from other processors, are rejected.
pub trait RegistrationProcessor {
    /// Additional PIN/UV token permissions required by this extension.
    fn permissions(&self) -> Permissions {
        Permissions::new(0)
    }

    /// Prepare authenticator extension inputs as CBOR entries.
    ///
    /// May mutate the `ctx` to store state (e.g. hmac-secret shared secret).
    fn prepare_inputs(&self, ctx: &mut ExtensionContext) -> Result<Vec<(String, Value)>, String>;

    /// Parse outputs and write into the typed output struct.
    fn prepare_outputs(&self, ctx: &OutputContext<'_>, outputs: &mut RegistrationExtensionOutputs);
}

/// Per-request authentication extension processing.
///
/// Duplicate input identifiers, including those from other processors, are rejected.
pub trait AuthenticationProcessor {
    /// Additional PIN/UV token permissions required by this extension.
    fn permissions(&self) -> Permissions {
        Permissions::new(0)
    }

    /// Prepare authenticator extension inputs as CBOR entries.
    ///
    /// `selected_cred_id` is the credential ID selected during pre-flight
    /// filtering (needed for per-credential extension data like prf
    /// `eval_by_credential`).
    fn prepare_inputs(
        &self,
        selected_cred_id: Option<&[u8]>,
        ctx: &mut ExtensionContext,
    ) -> Result<Vec<(String, Value)>, String>;

    /// Parse outputs and write into the typed output struct.
    fn prepare_outputs(
        &self,
        ctx: &OutputContext<'_>,
        outputs: &mut AuthenticationExtensionOutputs,
    );
}

/// Returns the default list of WebAuthn extensions.
///
/// This includes all standard extensions supported by the library. The list
/// can be customized by replacing it with a subset or by appending additional
/// extensions.
pub fn default_extensions() -> Vec<Box<dyn Ctap2Extension>> {
    vec![
        Box::new(prf::HmacSecretExtension),
        Box::new(cred_protect::CredProtectExtension),
        Box::new(cred_blob::CredBlobExtension),
        Box::new(large_blob::LargeBlobExtension),
        Box::new(min_pin_length::MinPinLengthExtension),
        Box::new(cred_props::CredPropsExtension),
        Box::new(sign::PreviewSignExtension),
    ]
}

// ---------------------------------------------------------------------------
// Registration (makeCredential)
// ---------------------------------------------------------------------------

/// Extension inputs for a registration ceremony.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegistrationExtensionInputs {
    /// PRF extension input — enables hmac-secret and optionally evaluates salts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prf: Option<prf::RegistrationInput>,

    /// credProtect — uses flattened JSON fields (`credentialProtectionPolicy`,
    /// `enforceCredentialProtectionPolicy`).
    #[serde(default, skip_serializing_if = "Option::is_none", flatten)]
    pub cred_protect: Option<cred_protect::RegistrationInput>,

    /// credBlob — stores a small data blob with the credential.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cred_blob: Option<cred_blob::RegistrationInput>,

    /// largeBlob — requests a large blob key for the credential.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub large_blob: Option<large_blob::RegistrationInput>,

    /// credProps — client-side only, no CTAP2 extension is sent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cred_props: Option<bool>,

    /// minPinLength — requests the authenticator's minimum PIN length.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_pin_length: Option<bool>,

    /// previewSign — requests generation of a signing key pair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preview_sign: Option<sign::RegistrationInput>,
}

/// Extension outputs from a registration ceremony.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RegistrationExtensionOutputs {
    /// PRF extension output — whether hmac-secret is enabled and optional results.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prf: Option<prf::RegistrationOutput>,

    /// credProtect output — the effective credential protection policy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cred_protect: Option<cred_protect::RegistrationOutput>,

    /// credBlob output — whether the blob was successfully stored.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cred_blob: Option<cred_blob::RegistrationOutput>,

    /// largeBlob output — whether large blob storage is supported.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub large_blob: Option<large_blob::RegistrationOutput>,

    /// credProps output — credential properties (e.g. whether it is discoverable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cred_props: Option<cred_props::RegistrationOutput>,

    /// minPinLength output — the authenticator's minimum PIN length.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_pin_length: Option<min_pin_length::RegistrationOutput>,

    /// previewSign output — the generated signing key pair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preview_sign: Option<sign::RegistrationOutput>,
}

// ---------------------------------------------------------------------------
// Authentication (getAssertion)
// ---------------------------------------------------------------------------

/// Extension inputs for an authentication ceremony.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationExtensionInputs {
    /// PRF extension input — evaluates salts to derive symmetric secrets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prf: Option<prf::AuthenticationInput>,

    /// Whether to retrieve a previously stored credBlob.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub get_cred_blob: Option<bool>,

    /// largeBlob — reads or writes large blob data associated with a credential.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub large_blob: Option<large_blob::AuthenticationInput>,

    /// previewSign — requests signing with a signing key pair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preview_sign: Option<sign::AuthenticationInput>,
}

/// Extension outputs from an authentication ceremony.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthenticationExtensionOutputs {
    /// PRF extension output — derived symmetric secrets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prf: Option<prf::AuthenticationOutput>,

    /// credBlob output — the retrieved blob data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cred_blob: Option<cred_blob::AuthenticationOutput>,

    /// largeBlob output — blob data read or write status.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub large_blob: Option<large_blob::AuthenticationOutput>,

    /// previewSign output — the generated signature.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preview_sign: Option<sign::AuthenticationOutput>,
}

// ---------------------------------------------------------------------------
// Authenticator data extension parsing
// ---------------------------------------------------------------------------

/// Parse the extensions CBOR map from raw authenticator data.
///
/// Authenticator data layout:
/// `rpIdHash(32) + flags(1) + counter(4) + [attestedCredData] + [extensions]`
///
/// If the ED flag (0x80) is set, extensions are a CBOR map at the end of
/// the authenticator data, after any attested credential data.
pub(crate) fn parse_auth_data_extensions(auth_data: &[u8]) -> Option<Vec<(String, Value)>> {
    if auth_data.len() < 37 {
        return None;
    }

    let flags = auth_data[32];
    if flags & 0x80 == 0 {
        // ED flag not set
        return None;
    }

    // Skip past attested credential data if present (AT flag = 0x40)
    let mut offset = 37; // rpIdHash(32) + flags(1) + counter(4)
    if flags & 0x40 != 0 {
        // attestedCredData: aaguid(16) + credIdLen(2) + credId + credPubKey
        if auth_data.len() < offset + 18 {
            return None;
        }
        let cred_id_len = u16::from_be_bytes([auth_data[offset + 16], auth_data[offset + 17]]);
        offset += 18 + cred_id_len as usize;

        // Skip the credential public key (CBOR-encoded)
        let key_bytes = &auth_data[offset..];
        let key_len = cbor_item_length(key_bytes)?;
        offset += key_len;
    }

    if offset >= auth_data.len() {
        return None;
    }

    // Decode the extensions CBOR map
    let ext_bytes = &auth_data[offset..];
    let value = cbor::decode(ext_bytes).ok()?;

    let map = value.as_map()?;
    let mut result = Vec::new();
    for (k, v) in map {
        if let Some(key) = k.as_text() {
            result.push((key.to_string(), v.clone()));
        }
    }
    Some(result)
}

/// Determine the byte length of a CBOR item (for skipping over it).
fn cbor_item_length(data: &[u8]) -> Option<usize> {
    let (_value, remaining) = cbor::decode_from(data).ok()?;
    Some(data.len() - remaining.len())
}

// ---------------------------------------------------------------------------
// CBOR input builder
// ---------------------------------------------------------------------------

/// Build the CTAP2 extensions map, rejecting duplicate input identifiers.
pub(crate) fn build_extensions_cbor(
    entries: Vec<(String, Value)>,
) -> Result<Option<Value>, String> {
    if entries.is_empty() {
        return Ok(None);
    }
    let mut names = BTreeSet::new();
    for (name, _) in &entries {
        if !names.insert(name) {
            return Err(format!("Duplicate extension input: {name}"));
        }
    }
    let map: Vec<(Value, Value)> = entries
        .into_iter()
        .map(|(k, v)| (Value::Text(k), v))
        .collect();
    Ok(Some(Value::Map(map)))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_registration_inputs_json_empty() {
        let inputs = RegistrationExtensionInputs::default();
        let json = serde_json::to_string(&inputs).unwrap();
        assert_eq!(json, "{}");
    }

    #[test]
    fn test_registration_inputs_json_cred_protect() {
        let json = r#"{"credentialProtectionPolicy":"userVerificationRequired","enforceCredentialProtectionPolicy":true}"#;
        let inputs: RegistrationExtensionInputs = serde_json::from_str(json).unwrap();
        let cp = inputs.cred_protect.unwrap();
        assert_eq!(cp.policy, CredProtectPolicy::UserVerificationRequired);
        assert!(cp.enforce);
    }

    #[test]
    fn test_authentication_inputs_json() {
        let json = r#"{"getCredBlob":true}"#;
        let inputs: AuthenticationExtensionInputs = serde_json::from_str(json).unwrap();
        assert_eq!(inputs.get_cred_blob, Some(true));
    }

    #[test]
    fn test_build_extensions_cbor() {
        let entries = vec![
            ("credProtect".into(), Value::Int(3)),
            ("minPinLength".into(), Value::Bool(true)),
        ];
        let cbor = build_extensions_cbor(entries).unwrap().unwrap();
        let map = cbor.as_map().unwrap();
        assert_eq!(map.len(), 2);
    }

    #[test]
    fn test_build_extensions_cbor_empty() {
        assert!(build_extensions_cbor(vec![]).unwrap().is_none());
    }

    #[test]
    fn test_build_extensions_cbor_rejects_duplicates() {
        for policies in [[3, 1], [1, 3], [3, 3]] {
            let entries = policies
                .into_iter()
                .map(|policy| ("credProtect".into(), Value::Int(policy)))
                .collect();
            assert_eq!(
                build_extensions_cbor(entries).unwrap_err(),
                "Duplicate extension input: credProtect"
            );
        }
    }

    #[test]
    fn test_parse_auth_data_no_extensions() {
        // Minimal auth_data: 37 bytes, no ED flag
        let mut auth_data = vec![0u8; 37];
        auth_data[32] = 0x01; // UP only
        assert!(parse_auth_data_extensions(&auth_data).is_none());
    }

    #[test]
    fn test_parse_auth_data_with_extensions() {
        // Build auth_data with ED flag and a simple extension map
        let mut auth_data = vec![0u8; 37];
        auth_data[32] = 0x80; // ED flag only (no AT)

        // Append CBOR map: {"credProtect": 3}
        let ext_map = Value::Map(vec![(Value::Text("credProtect".into()), Value::Int(3))]);
        auth_data.extend_from_slice(&cbor::encode(&ext_map));

        let exts = parse_auth_data_extensions(&auth_data).unwrap();
        assert_eq!(exts.len(), 1);
        assert_eq!(exts[0].0, "credProtect");
        assert_eq!(exts[0].1.as_int(), Some(3));
    }

    #[test]
    fn test_parse_auth_data_with_at_and_ed() {
        // Build auth_data with both AT and ED flags
        let mut auth_data = vec![0u8; 37];
        auth_data[32] = 0xC0; // AT + ED

        // Attested credential data: aaguid(16) + credIdLen(2) + credId(4)
        auth_data.extend_from_slice(&[0u8; 16]); // aaguid
        auth_data.extend_from_slice(&[0x00, 0x04]); // credIdLen = 4
        auth_data.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]); // credId

        // Minimal COSE key (CBOR map)
        let cose_key = Value::Map(vec![
            (Value::Int(1), Value::Int(2)),  // kty: EC2
            (Value::Int(-1), Value::Int(1)), // crv: P-256
        ]);
        auth_data.extend_from_slice(&cbor::encode(&cose_key));

        // Extension map
        let ext_map = Value::Map(vec![(Value::Text("minPinLength".into()), Value::Int(8))]);
        auth_data.extend_from_slice(&cbor::encode(&ext_map));

        let exts = parse_auth_data_extensions(&auth_data).unwrap();
        assert_eq!(exts.len(), 1);
        assert_eq!(exts[0].0, "minPinLength");
        assert_eq!(exts[0].1.as_int(), Some(8));
    }

    #[test]
    fn test_outputs_default_empty() {
        let out = RegistrationExtensionOutputs::default();
        let json = serde_json::to_string(&out).unwrap();
        assert_eq!(json, "{}");
    }
}