synta-certificate 0.2.6

X.509 certificate structures for synta ASN.1 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
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! PKCS#11 token management via the `cryptoki` crate.
//!
//! Provides [`Pkcs11Manager`], which dynamically loads the system PKCS#11 module
//! (`p11-kit-proxy.so` by default, overridable via `PKCS11_MODULE_PATH` or the
//! `module-path` attribute in a PKCS#11 URI) and exposes the five management
//! operations required by FreeIPA's IPAThinCA:
//!
//! - [`TokenManager::list_slots`] — enumerate available token slots
//! - [`TokenManager::find_key`] — check whether a named key exists on a token
//! - [`TokenManager::list_keys`] — list all private keys on a token
//! - [`TokenManager::delete_key`] — destroy a private-key object from a token
//! - [`TokenManager::generate_key_pair_in_token`] — generate RSA/EC key pair on the token

// pkcs11-mgmt is only useful alongside a crypto backend that can load the generated key.
// If someone enables it standalone (without openssl or nss), fail fast at compile time.
#[cfg(not(any(feature = "openssl", feature = "nss")))]
compile_error!(
    "the `pkcs11-mgmt` feature requires at least one crypto backend; \
     enable the `openssl` or `nss` feature"
);

use std::env;

use cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11};
use cryptoki::error::{Error as CkError, RvError};
use cryptoki::mechanism::Mechanism;
use cryptoki::object::{
    Attribute, AttributeType, KeyType, MlDsaParameterSetType, MlKemParameterSetType, ObjectClass,
    ParameterSetType,
};
use cryptoki::session::UserType;
use cryptoki::types::{AuthPin, Ulong};

use synta::{ObjectIdentifier, ToDer};

use crate::crypto::token_manager::{Pkcs11KeyInfo, SlotInfo, TokenManager};
use crate::crypto::{BackendPrivateKey, KeySpec, PrivateKeyError};
use crate::pkcs11_uri::Pkcs11Uri;
use crate::{oids, oids::EC_CURVE_P256, oids::EC_CURVE_P384, oids::EC_CURVE_P521};

/// Well-known p11-kit-proxy paths probed by [`Pkcs11Manager::from_env`] when
/// `PKCS11_MODULE_PATH` is not set.  Covers Fedora/RHEL (`lib64`), Debian/Ubuntu
/// multiarch paths for the four most common architectures, and the generic
/// `/usr/lib/pkcs11` fallback.  Paths are probed in order; the first one that
/// exists on the current system is used.
const CANDIDATE_MODULE_PATHS: &[&str] = &[
    "/usr/lib64/pkcs11/p11-kit-proxy.so",
    "/usr/lib/x86_64-linux-gnu/pkcs11/p11-kit-proxy.so",
    "/usr/lib/aarch64-linux-gnu/pkcs11/p11-kit-proxy.so",
    "/usr/lib/powerpc64le-linux-gnu/pkcs11/p11-kit-proxy.so",
    "/usr/lib/s390x-linux-gnu/pkcs11/p11-kit-proxy.so",
    "/usr/lib/pkcs11/p11-kit-proxy.so",
];

fn key_err(msg: impl Into<String>) -> PrivateKeyError {
    PrivateKeyError(Box::new(std::io::Error::other(msg.into())))
}

fn from_cryptoki(e: CkError) -> PrivateKeyError {
    PrivateKeyError(Box::new(e))
}

/// A PKCS#11 token manager backed by the `cryptoki` crate.
///
/// Dynamically loads the PKCS#11 module and implements all five
/// [`TokenManager`] operations.  Both the NSS and OpenSSL backends share
/// this single implementation for token management; each backend retains its
/// own path for signing, verification, and other crypto operations.
///
/// # Thread safety
///
/// `Pkcs11Manager` is `Send + Sync`.  Each management call opens its own
/// session and closes it on return, so concurrent calls are safe.
pub struct Pkcs11Manager {
    pkcs11: Pkcs11,
}

impl Pkcs11Manager {
    /// Load the PKCS#11 module at `module_path` and initialize it.
    ///
    /// `module_path` must be an absolute path to avoid ambiguous resolution.
    ///
    /// `CKR_CRYPTOKI_ALREADY_INITIALIZED` is treated as success rather than an
    /// error.  A PKCS#11 library may only be initialized once per process, but the
    /// OS dynamic linker reference-counts shared libraries, so a second
    /// `Pkcs11Manager` loading the same `.so` will attempt `C_Initialize` on an
    /// already-initialized library.  Accepting this return value allows multiple
    /// independent `Pkcs11Manager` instances to coexist safely in the same process.
    pub fn new(module_path: &str) -> Result<Self, PrivateKeyError> {
        if !std::path::Path::new(module_path).is_absolute() {
            return Err(key_err(format!(
                "PKCS#11 module path must be absolute: '{module_path}'"
            )));
        }
        let pkcs11 = Pkcs11::new(module_path).map_err(from_cryptoki)?;
        match pkcs11.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)) {
            Ok(()) => {}
            Err(CkError::Pkcs11(RvError::CryptokiAlreadyInitialized, _)) => {}
            Err(e) => return Err(from_cryptoki(e)),
        }
        Ok(Self { pkcs11 })
    }

    /// Resolve the module path from the URI, then fall back to `PKCS11_MODULE_PATH`
    /// env var, then probe well-known p11-kit-proxy paths.
    pub fn from_uri(uri: &Pkcs11Uri) -> Result<Self, PrivateKeyError> {
        if let Some(path) = uri.attrs.module_path.as_deref() {
            return Self::new(path);
        }
        Self::from_env()
    }

    /// Resolve the module path from `PKCS11_MODULE_PATH`, then probe well-known
    /// p11-kit-proxy paths for Fedora/RHEL, Debian/Ubuntu, and generic Linux.
    pub fn from_env() -> Result<Self, PrivateKeyError> {
        if let Ok(path) = env::var("PKCS11_MODULE_PATH") {
            return Self::new(&path);
        }
        for candidate in CANDIDATE_MODULE_PATHS {
            if std::path::Path::new(candidate).exists() {
                return Self::new(candidate);
            }
        }
        Err(key_err(format!(
            "no PKCS#11 module found; set PKCS11_MODULE_PATH or install p11-kit; tried: {}",
            CANDIDATE_MODULE_PATHS.join(", ")
        )))
    }
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn find_slot_by_token_name(
    pkcs11: &Pkcs11,
    token_name: &str,
) -> Result<cryptoki::slot::Slot, PrivateKeyError> {
    let slots = pkcs11
        .get_slots_with_initialized_token()
        .map_err(from_cryptoki)?;
    for slot in slots {
        let info = pkcs11.get_token_info(slot).map_err(from_cryptoki)?;
        if info.label().trim() == token_name.trim() {
            return Ok(slot);
        }
    }
    Err(key_err(format!("PKCS#11 token not found: '{token_name}'")))
}

fn login_if_needed(
    session: &cryptoki::session::Session,
    pin: Option<&str>,
) -> Result<(), PrivateKeyError> {
    if let Some(pin_str) = pin {
        match session.login(UserType::User, Some(&AuthPin::from(pin_str.to_owned()))) {
            Ok(()) => {}
            // Another session (or manager instance sharing the same .so) already logged in.
            Err(CkError::Pkcs11(RvError::UserAlreadyLoggedIn, _)) => {}
            Err(e) => return Err(from_cryptoki(e)),
        }
    }
    Ok(())
}

fn map_key_type(kt: KeyType) -> &'static str {
    // cryptoki's KeyType is a C-level constant newtype (CK_KEY_TYPE = CK_ULONG),
    // not a Rust enum, so exhaustive `match` is not available.
    if kt == KeyType::RSA {
        "RSA"
    } else if kt == KeyType::EC {
        "EC"
    } else if kt == KeyType::EC_EDWARDS {
        "Ed"
    } else if kt == KeyType::ML_DSA {
        "ML-DSA"
    } else if kt == KeyType::ML_KEM {
        "ML-KEM"
    } else {
        "Unknown"
    }
}

/// Synthesise a `CKF_*` bitmask from the four `TokenInfo` boolean fields that
/// callers are most likely to inspect.
///
/// Bits captured (PKCS#11 v3.0 §4.9):
/// - `0x0000_0002` (`CKF_WRITE_PROTECTED`) — token is read-only
/// - `0x0000_0004` (`CKF_LOGIN_REQUIRED`) — user must call `C_Login` before accessing private objects
/// - `0x0000_0100` (`CKF_PROTECTED_AUTHENTICATION_PATH`) — PIN is entered via on-device keypad
/// - `0x0000_0400` (`CKF_TOKEN_INITIALIZED`) — token has been initialised with a SO PIN
///
/// All other bits are left as zero.
fn token_flags(info: &cryptoki::slot::TokenInfo) -> u64 {
    let mut flags: u64 = 0;
    if info.token_initialized() {
        flags |= 0x0000_0400;
    }
    if info.login_required() {
        flags |= 0x0000_0004;
    }
    if info.write_protected() {
        flags |= 0x0000_0002;
    }
    if info.protected_authentication_path() {
        flags |= 0x0000_0100;
    }
    flags
}

fn ml_dsa_param_set(name: &str) -> Option<ParameterSetType> {
    match name {
        "ML-DSA-44" => Some(MlDsaParameterSetType::ML_DSA_44.into()),
        "ML-DSA-65" => Some(MlDsaParameterSetType::ML_DSA_65.into()),
        "ML-DSA-87" => Some(MlDsaParameterSetType::ML_DSA_87.into()),
        _ => None,
    }
}

fn ml_kem_param_set(name: &str) -> Option<ParameterSetType> {
    match name {
        "ML-KEM-512" => Some(MlKemParameterSetType::ML_KEM_512.into()),
        "ML-KEM-768" => Some(MlKemParameterSetType::ML_KEM_768.into()),
        "ML-KEM-1024" => Some(MlKemParameterSetType::ML_KEM_1024.into()),
        _ => None,
    }
}

/// DER-encoded named-curve OID for PKCS#11 `CKA_EC_PARAMS`.
fn ec_oid_bytes(curve: &str) -> Option<Vec<u8>> {
    let components: &[u32] = match curve {
        "P-256" => EC_CURVE_P256,
        "P-384" => EC_CURVE_P384,
        "P-521" => EC_CURVE_P521,
        "Ed25519" | "1.3.101.112" => oids::ED25519,
        "Ed448" | "1.3.101.113" => oids::ED448,
        _ => return None,
    };
    ObjectIdentifier::new(components).ok()?.to_der().ok()
}

// ── TokenManager implementation ────────────────────────────────────────────────

impl TokenManager for Pkcs11Manager {
    fn list_slots(&self) -> Result<Vec<SlotInfo>, PrivateKeyError> {
        let slots = self
            .pkcs11
            .get_slots_with_initialized_token()
            .map_err(from_cryptoki)?;
        let mut result = Vec::with_capacity(slots.len());
        for slot in slots {
            let info = match self.pkcs11.get_token_info(slot) {
                Ok(i) => i,
                Err(e) => {
                    log::warn!(
                        "pkcs11: skipping slot {}: get_token_info failed: {e}",
                        slot.id()
                    );
                    continue;
                }
            };
            result.push(SlotInfo {
                slot_id: slot.id(),
                token_label: info.label().trim().to_owned(),
                manufacturer_id: info.manufacturer_id().trim().to_owned(),
                model: info.model().trim().to_owned(),
                serial_number: info.serial_number().trim().to_owned(),
                flags: token_flags(&info),
            });
        }
        Ok(result)
    }

    fn find_key(&self, uri: &Pkcs11Uri) -> Result<bool, PrivateKeyError> {
        let token_name = uri
            .attrs
            .token
            .as_deref()
            .ok_or_else(|| key_err("PKCS#11 URI must contain 'token=' for find_key"))?;
        let obj_label = uri
            .attrs
            .object
            .as_deref()
            .ok_or_else(|| key_err("PKCS#11 URI must contain 'object=' for find_key"))?;

        let slot = find_slot_by_token_name(&self.pkcs11, token_name)?;
        let session = self.pkcs11.open_ro_session(slot).map_err(from_cryptoki)?;
        login_if_needed(&session, uri.attrs.pin_value())?;

        let found = session
            .find_objects(&[
                Attribute::Class(ObjectClass::PRIVATE_KEY),
                Attribute::Label(obj_label.as_bytes().to_vec()),
            ])
            .map_err(from_cryptoki)?;

        Ok(!found.is_empty())
    }

    fn list_keys(
        &self,
        token_name: &str,
        pin: Option<&str>,
    ) -> Result<Vec<Pkcs11KeyInfo>, PrivateKeyError> {
        let slot = find_slot_by_token_name(&self.pkcs11, token_name)?;
        let session = self.pkcs11.open_ro_session(slot).map_err(from_cryptoki)?;
        login_if_needed(&session, pin)?;

        let handles = session
            .find_objects(&[Attribute::Class(ObjectClass::PRIVATE_KEY)])
            .map_err(from_cryptoki)?;

        let mut keys = Vec::with_capacity(handles.len());
        for handle in handles {
            let attrs = match session.get_attributes(
                handle,
                &[
                    AttributeType::Label,
                    AttributeType::KeyType,
                    AttributeType::Id,
                    AttributeType::Modulus,
                ],
            ) {
                Ok(a) => a,
                Err(e) => {
                    log::warn!(
                        "pkcs11: skipping key object {:?}: get_attributes failed: {e}",
                        handle
                    );
                    continue;
                }
            };

            let mut label = String::new();
            let mut key_type_str: &'static str = "Unknown";
            let mut key_bits: u32 = 0;
            let mut id = Vec::new();

            for attr in &attrs {
                match attr {
                    Attribute::Label(bytes) => {
                        label = String::from_utf8_lossy(bytes).into_owned();
                    }
                    Attribute::KeyType(kt) => {
                        key_type_str = map_key_type(*kt);
                    }
                    Attribute::Id(bytes) => {
                        id = bytes.clone();
                    }
                    Attribute::Modulus(bytes) => {
                        // PKCS#11 uses unsigned big-endian; strip any leading zero bytes
                        // (some tokens add them defensively, inflating the count by 8 bits).
                        let significant = bytes.iter().skip_while(|&&b| b == 0).count();
                        key_bits = (significant * 8) as u32;
                    }
                    _ => {}
                }
            }

            keys.push(Pkcs11KeyInfo {
                label,
                id,
                key_type: key_type_str.to_owned(),
                key_bits,
            });
        }

        Ok(keys)
    }

    fn delete_key(&self, uri: &Pkcs11Uri) -> Result<(), PrivateKeyError> {
        let token_name = uri
            .attrs
            .token
            .as_deref()
            .ok_or_else(|| key_err("PKCS#11 URI must contain 'token=' for delete_key"))?;
        let obj_label = uri
            .attrs
            .object
            .as_deref()
            .ok_or_else(|| key_err("PKCS#11 URI must contain 'object=' for delete_key"))?;

        let slot = find_slot_by_token_name(&self.pkcs11, token_name)?;
        let session = self.pkcs11.open_rw_session(slot).map_err(from_cryptoki)?;
        login_if_needed(&session, uri.attrs.pin_value())?;

        let label_bytes = obj_label.as_bytes().to_vec();

        // Build the search template.  When the URI includes an `id=` component
        // we narrow the search by CKA_ID so duplicate-label ambiguity is resolved.
        let mut priv_template = vec![
            Attribute::Class(ObjectClass::PRIVATE_KEY),
            Attribute::Label(label_bytes.clone()),
        ];
        let mut pub_template = vec![
            Attribute::Class(ObjectClass::PUBLIC_KEY),
            Attribute::Label(label_bytes),
        ];
        if let Some(id) = &uri.attrs.id {
            priv_template.push(Attribute::Id(id.clone()));
            pub_template.push(Attribute::Id(id.clone()));
        }

        // Check for label ambiguity before destroying anything.  PKCS#11 labels
        // are not required to be unique; destroying all matches could silently
        // wipe unintended keys.  When there are multiple matches and no id= was
        // provided, refuse rather than delete arbitrarily.
        let priv_handles = session
            .find_objects(&priv_template)
            .map_err(from_cryptoki)?;
        if priv_handles.is_empty() {
            return Err(key_err(format!(
                "no private key with label '{obj_label}' found on token '{token_name}'"
            )));
        }
        if priv_handles.len() > 1 {
            return Err(key_err(format!(
                "{} private keys with label '{obj_label}' found on token '{token_name}'; \
                 add id= to the URI to select the specific key",
                priv_handles.len()
            )));
        }
        for handle in priv_handles {
            session.destroy_object(handle).map_err(from_cryptoki)?;
        }

        let pub_handles = session.find_objects(&pub_template).map_err(from_cryptoki)?;
        if pub_handles.len() > 1 {
            log::warn!(
                "pkcs11: {} public keys with label '{obj_label}' on token '{token_name}'; \
                 deleting all",
                pub_handles.len()
            );
        }
        for handle in pub_handles {
            session.destroy_object(handle).map_err(from_cryptoki)?;
        }

        Ok(())
    }

    fn generate_key_pair_in_token(
        &self,
        spec: &KeySpec,
        uri: &Pkcs11Uri,
        extractable: bool,
    ) -> Result<BackendPrivateKey, PrivateKeyError> {
        let token_name = uri
            .attrs
            .token
            .as_deref()
            .ok_or_else(|| key_err("PKCS#11 URI must contain 'token=' for key generation"))?;
        let obj_label = uri
            .attrs
            .object
            .as_deref()
            .ok_or_else(|| key_err("PKCS#11 URI must contain 'object=' for key generation"))?;

        let slot = find_slot_by_token_name(&self.pkcs11, token_name)?;
        let session = self.pkcs11.open_rw_session(slot).map_err(from_cryptoki)?;
        login_if_needed(&session, uri.attrs.pin_value())?;

        let label_bytes = obj_label.as_bytes().to_vec();

        match spec {
            KeySpec::Rsa(bits) => {
                if *bits < 2048 {
                    return Err(key_err(format!(
                        "RSA key size {bits} bits is below the 2048-bit minimum"
                    )));
                }
                let modulus_bits =
                    Ulong::try_from(*bits as usize).map_err(|e| key_err(e.to_string()))?;
                let pub_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Verify(true),
                    Attribute::ModulusBits(modulus_bits),
                    Attribute::PublicExponent(vec![0x01, 0x00, 0x01]),
                    Attribute::Label(label_bytes.clone()),
                ];
                let priv_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Private(true),
                    Attribute::Sensitive(true),
                    Attribute::Extractable(extractable),
                    Attribute::Sign(true),
                    Attribute::Label(label_bytes),
                ];
                session
                    .generate_key_pair(&Mechanism::RsaPkcsKeyPairGen, &pub_tmpl, &priv_tmpl)
                    .map_err(from_cryptoki)?;
            }
            KeySpec::Ec(curve) => {
                let ec_params = ec_oid_bytes(curve)
                    .ok_or_else(|| key_err(format!("unsupported EC curve: '{curve}'")))?;
                let pub_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Verify(true),
                    Attribute::EcParams(ec_params),
                    Attribute::Label(label_bytes.clone()),
                ];
                let priv_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Private(true),
                    Attribute::Sensitive(true),
                    Attribute::Extractable(extractable),
                    Attribute::Sign(true),
                    Attribute::Label(label_bytes),
                ];
                session
                    .generate_key_pair(&Mechanism::EccKeyPairGen, &pub_tmpl, &priv_tmpl)
                    .map_err(from_cryptoki)?;
            }
            KeySpec::Ed25519 | KeySpec::Ed448 => {
                let oid_name = if matches!(spec, KeySpec::Ed25519) {
                    "Ed25519"
                } else {
                    "Ed448"
                };
                let ec_params = ec_oid_bytes(oid_name)
                    .ok_or_else(|| key_err(format!("internal: {oid_name} OID unavailable")))?;
                let pub_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Verify(true),
                    Attribute::EcParams(ec_params),
                    Attribute::Label(label_bytes.clone()),
                ];
                let priv_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Private(true),
                    Attribute::Sensitive(true),
                    Attribute::Extractable(extractable),
                    Attribute::Sign(true),
                    Attribute::Label(label_bytes),
                ];
                session
                    .generate_key_pair(&Mechanism::EccEdwardsKeyPairGen, &pub_tmpl, &priv_tmpl)
                    .map_err(from_cryptoki)?;
            }
            KeySpec::MlDsa(ps) => {
                let param_set = ml_dsa_param_set(ps).ok_or_else(|| {
                    key_err(format!(
                        "unsupported ML-DSA parameter set '{ps}'; \
                         expected ML-DSA-44, ML-DSA-65, or ML-DSA-87"
                    ))
                })?;
                let pub_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Verify(true),
                    Attribute::ParameterSet(param_set),
                    Attribute::Label(label_bytes.clone()),
                ];
                let priv_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Private(true),
                    Attribute::Sensitive(true),
                    Attribute::Extractable(extractable),
                    Attribute::Sign(true),
                    Attribute::ParameterSet(param_set),
                    Attribute::Label(label_bytes),
                ];
                session
                    .generate_key_pair(&Mechanism::MlDsaKeyPairGen, &pub_tmpl, &priv_tmpl)
                    .map_err(from_cryptoki)?;
            }
            KeySpec::MlKem(ps) => {
                let param_set = ml_kem_param_set(ps).ok_or_else(|| {
                    key_err(format!(
                        "unsupported ML-KEM parameter set '{ps}'; \
                         expected ML-KEM-512, ML-KEM-768, or ML-KEM-1024"
                    ))
                })?;
                let pub_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Encrypt(true),
                    Attribute::Wrap(true),
                    Attribute::ParameterSet(param_set),
                    Attribute::Label(label_bytes.clone()),
                ];
                let priv_tmpl = vec![
                    Attribute::Token(true),
                    Attribute::Private(true),
                    Attribute::Sensitive(true),
                    Attribute::Extractable(extractable),
                    Attribute::Decrypt(true),
                    Attribute::Unwrap(true),
                    Attribute::ParameterSet(param_set),
                    Attribute::Label(label_bytes),
                ];
                session
                    .generate_key_pair(&Mechanism::MlKemKeyPairGen, &pub_tmpl, &priv_tmpl)
                    .map_err(from_cryptoki)?;
            }
            // KeySpec is #[non_exhaustive]; this arm handles future variants at runtime.
            #[allow(unreachable_patterns)]
            _ => {
                return Err(key_err(format!(
                    "key type {spec:?} is not supported for HSM key generation"
                )));
            }
        }

        // Close the generation session before asking the backend to load the key.
        // Some PKCS#11 modules (e.g. SoftHSM2) do not make newly generated objects
        // visible to searches until the generating session is closed.  Because both
        // key objects were created with CKA_TOKEN=true they persist on the token
        // after the session drops; the load-back call opens its own fresh session.
        drop(session);

        load_generated_key(uri)
    }
}

/// Load a key that was just generated on the token, using whichever crypto
/// backend is active, to produce a `BackendPrivateKey` with the SPKI populated.
fn load_generated_key(uri: &Pkcs11Uri) -> Result<BackendPrivateKey, PrivateKeyError> {
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::priv_load_from_pkcs11_uri(&uri.raw)
            .map_err(|e| PrivateKeyError(Box::new(e)))
    }

    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::priv_load_from_pkcs11_uri_nss(&uri.raw)
            .map_err(|e| PrivateKeyError(Box::new(e)))
    }

    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        let _ = uri;
        Err(key_err(
            "no crypto backend (openssl or nss) enabled; cannot load generated key",
        ))
    }
}

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

    fn find_test_module() -> Option<String> {
        if let Ok(p) = std::env::var("PKCS11_MODULE_PATH") {
            return Some(p);
        }
        for candidate in &[
            "/usr/lib64/pkcs11/libkryoptic_pkcs11.so",
            "/usr/lib/pkcs11/libkryoptic_pkcs11.so",
            "/usr/lib64/softhsm/libsofthsm2.so",
            "/usr/lib/softhsm/libsofthsm2.so",
            "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so",
        ] {
            if std::path::Path::new(candidate).exists() {
                return Some(candidate.to_string());
            }
        }
        None
    }

    #[test]
    fn list_slots_basic() {
        let Some(module) = find_test_module() else {
            eprintln!("no PKCS#11 module found — skipping");
            return;
        };
        let mgr = match Pkcs11Manager::new(&module) {
            Ok(m) => m,
            Err(e) => {
                // kryoptic returns CKR_TOKEN_NOT_PRESENT when no DB is configured
                eprintln!("PKCS#11 module unavailable ({e}) — skipping");
                return;
            }
        };
        let slots = mgr.list_slots().expect("list_slots");
        eprintln!("found {} slot(s)", slots.len());
        for s in &slots {
            assert!(!s.token_label.is_empty(), "token_label must not be empty");
            eprintln!(
                "  slot {}: {:?} / {:?}",
                s.slot_id, s.token_label, s.manufacturer_id
            );
        }
    }
}