rite-sdk 0.7.2

Backend traits and domain types for the Rite cryptographic key ceremony toolkit
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! Backend trait hierarchy for cryptographic hardware abstraction.
//!
//! ## Design philosophy
//!
//! Backends are **orthogonal to roles and participants**. They represent the
//! execution mechanism (how an action is implemented), not the human assignment
//! (who performs the action).
//!
//! The four layers of abstraction:
//! - **Step**: Unit of execution in the workflow
//! - **Role**: WHO performs the step (human/participant)
//! - **Action**: WHAT semantic operation happens
//! - **Backend**: HOW the action is implemented (software/hardware)
//!
//! ## Trait composition
//!
//! Backends implement only the traits they're capable of. There are no universal
//! requirements: traits are composable based on backend capabilities.
//!
//! Example trait support matrix:
//! - Software: `KeyStore + Sign + KeyTransport`
//! - `YubiKey` PIV: `KeyStore + Sign + Piv + Yubikey`
//! - PKCS#11 HSM: `KeyStore + Sign + KeyTransport + Pkcs11`
//! - Mock: All traits (for testing)

use std::collections::BTreeMap;

use zeroize::Zeroizing;

use crate::key_material::PublicKeyDer;
use crate::types::{
    Attestation, CertRef, DataKey, KeyAlgorithm, KeyId, KeyMetadata, KeyPolicy, KeyProtection,
    KeySecurityAttributes, KeySpec, PcrValue, PivDeviceInfo, PivSlot, PivSlotInfo, Pkcs11Mechanism,
    Pkcs11TokenInfo, SignAlgorithm, TpmInfo, WrapScheme, WrappedKey, YubikeySlotMetadata,
};

/// Implement the `as_*_mut` upcasting helpers on a backend struct.
///
/// Each `Backend` implementor must return `Some(self)` for every trait it
/// supports and `None` for those it does not. Without this macro that is four
/// lines of boilerplate per capability. The macro expands to those lines
/// automatically and allows attaching per-capability doc comments.
///
/// # Usage
///
/// ```
/// use rite_sdk::{
///     backend_capabilities, Backend, BackendError, KeyId, RandomBackend, SignAlgorithm,
///     SignBackend,
/// };
///
/// struct MyBackend {
///     name: String,
/// }
///
/// impl Backend for MyBackend {
///     fn name(&self) -> &str { &self.name }
///     fn provider(&self) -> &str { "software" }
///     fn fingerprint(&self) -> String { "sha256:...".to_string() }
///
///     backend_capabilities!(
///         /// Signs with software-held RSA and ECDSA keys.
///         as_sign_mut: SignBackend,
///         /// Draws ceremony randomness from the OS CSPRNG.
///         as_random_mut: RandomBackend,
///     );
/// }
///
/// impl SignBackend for MyBackend {
///     fn sign(&mut self, _key: &KeyId, _msg: &[u8], _alg: SignAlgorithm)
///         -> Result<Vec<u8>, BackendError> { Ok(Vec::new()) }
/// }
///
/// impl RandomBackend for MyBackend {
///     fn generate_random(&mut self, len: usize) -> Result<Vec<u8>, BackendError> {
///         Ok(vec![0u8; len])
///     }
/// }
/// ```
///
/// Capabilities not listed here are not overridden, so they inherit the trait's
/// default doc ("Not supported by this backend.") and return `None`.
///
/// The trait names passed to the macro must be in scope at the call site.
///
/// Note: `#[macro_export]` places this macro at the crate root
/// (`rite_sdk::backend_capabilities!`), not in the `backend` module.
/// This is standard Rust macro scoping.
#[macro_export]
macro_rules! backend_capabilities {
    ($($(#[$attr:meta])* $method:ident : $trait:ident),* $(,)?) => {
        $(
            $(#[$attr])*
            fn $method(&mut self) -> Option<&mut dyn $trait> {
                Some(self)
            }
        )*
    };
}

/// Core trait that all backends must implement.
///
/// Provides identity and fingerprinting for audit trails.
///
/// # Capability downcasting
///
/// Rust does not allow downcasting from `dyn Backend` to `dyn KeyStoreBackend`
/// (or any other subtrait) without explicit support. The `as_*_mut` methods
/// implement this pattern manually: a backend returns `Some(self)` for each
/// capability it supports, and `None` for those it does not.
///
/// Use the [`backend_capabilities!`] macro to generate these methods without
/// boilerplate.
pub trait Backend: Send + Sync {
    /// Backend name (unique identifier within a ceremony).
    fn name(&self) -> &str;

    /// Backend provider name (e.g., "software", "yubikey", "pkcs11").
    fn provider(&self) -> &str;

    /// Fingerprint for audit evidence.
    ///
    /// Format examples:
    /// - Software: `"software-backend=mybackend"`
    /// - `YubiKey`: `"yubikey-serial=12345678+firmware=5.7.1"`
    /// - PKCS#11: `"pkcs11-module=/usr/lib/softhsm2.so+slot=0"`
    fn fingerprint(&self) -> String;

    /// Not supported by this backend, always returns `None`.
    fn as_keystore_mut(&mut self) -> Option<&mut dyn KeyStoreBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_sign_mut(&mut self) -> Option<&mut dyn SignBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_verify_mut(&mut self) -> Option<&mut dyn VerifyBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_attest_mut(&mut self) -> Option<&mut dyn AttestationBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_piv_mut(&mut self) -> Option<&mut dyn PivBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_yubikey_mut(&mut self) -> Option<&mut dyn YubikeyBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_transport_mut(&mut self) -> Option<&mut dyn KeyTransportBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_certstore_mut(&mut self) -> Option<&mut dyn CertStoreBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_random_mut(&mut self) -> Option<&mut dyn RandomBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_pkcs11_mut(&mut self) -> Option<&mut dyn Pkcs11Backend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_pkcs11_admin_mut(&mut self) -> Option<&mut dyn Pkcs11AdminBackend> {
        None
    }

    /// Not supported by this backend, always returns `None`.
    fn as_tpm_mut(&mut self) -> Option<&mut dyn TpmBackend> {
        None
    }
}

/// Key generation and storage operations.
///
/// Backends implementing this trait can generate, import, and manage
/// cryptographic keys.
pub trait KeyStoreBackend: Backend {
    /// Generate a new key.
    ///
    /// The backend owns the key and returns metadata including an opaque
    /// `KeyId` reference. For hardware backends, the private key never leaves
    /// the device.
    fn generate_key(&mut self, spec: KeySpec) -> Result<KeyMetadata, BackendError>;

    /// Import an existing key from material the caller holds.
    ///
    /// `spec.algorithm` says how to read `key_bytes`, because nothing in the
    /// bytes distinguishes a 32-byte secret from any other 32 bytes: a symmetric
    /// algorithm takes the raw key, every other one takes a private key, as
    /// PKCS#8 DER or as PEM. The metadata that comes back carries a check value
    /// in the first case and a public key in the second, which is the identity
    /// each kind has.
    ///
    /// `passphrase` opens a private key that is encrypted, in any encoding the
    /// backend reads. Material that needs one and is given none is refused by
    /// name, and so is a passphrase given for material that is not encrypted:
    /// a passphrase the transcript says was used has to have been used.
    ///
    /// Only supported by backends that allow key import (software, some HSMs).
    /// Hardware security modules may reject it for security reasons, and a
    /// device that holds only one kind of key refuses the other by name.
    fn import_key(
        &mut self,
        spec: KeySpec,
        key_bytes: &[u8],
        passphrase: Option<&[u8]>,
    ) -> Result<KeyMetadata, BackendError>;

    /// Export the public key for `key_id`.
    fn export_public_key(&self, key_id: &KeyId) -> Result<PublicKeyDer, BackendError>;

    /// List all keys managed by this backend.
    fn list_keys(&self) -> Result<Vec<KeyMetadata>, BackendError>;

    /// Delete a key permanently.
    fn delete_key(&mut self, key_id: &KeyId) -> Result<(), BackendError>;
}

/// Signing operations.
pub trait SignBackend: Backend {
    /// Sign `message` with `key_id` using `algorithm`.
    ///
    /// Returns raw signature bytes (format depends on algorithm).
    fn sign(
        &mut self,
        key_id: &KeyId,
        message: &[u8],
        algorithm: SignAlgorithm,
    ) -> Result<Vec<u8>, BackendError>;
}

/// Signature verification operations.
///
/// Separate from [`SignBackend`] because the two need different things. Signing
/// needs a secret, so only the device holding it can do the work; verification
/// needs a public key, so anything can. A card that signs and never verifies
/// implements one trait, and a verification-only backend (a notary, an enclave)
/// implements the other without having to refuse `sign`.
///
/// Most ceremonies verify in software and name no backend. Naming one is for a
/// deployment that requires the check inside a validated boundary, or a
/// verifier that is not local.
pub trait VerifyBackend: Backend {
    /// Verify `signature` over `message` under `key`.
    ///
    /// Takes the key rather than a reference to one the backend holds, because
    /// the evidence a ceremony checks usually comes from outside it: a CSR from
    /// another party, a signature made on a card that is no longer present.
    /// There is no handle to name for those.
    ///
    /// `&mut self` because a verifier may need a session to work in. PKCS#11
    /// creates a public key object, verifies against it, and destroys it.
    fn verify_public_key(
        &mut self,
        key: &PublicKeyDer,
        message: &[u8],
        signature: &[u8],
        algorithm: SignAlgorithm,
    ) -> Result<bool, BackendError>;
}

/// Hardware attestation operations.
///
/// Backends that support attestation can cryptographically prove that a key
/// was generated on a specific hardware device.
pub trait AttestationBackend: Backend {
    /// Return a cryptographic proof that `key_id` was generated on this
    /// backend's hardware and has specific properties.
    fn attest_key(&self, key_id: &KeyId) -> Result<Attestation, BackendError>;
}

/// Certificate storage operations.
///
/// Backends implementing this trait can store, read, and delete X.509
/// certificates by reference. This is a unified interface for certificate
/// management across PIV (slot-based), PKCS#11 (label/ID-based), and
/// software backends.
pub trait CertStoreBackend: Backend {
    /// Store a DER-encoded X.509 certificate.
    fn store_cert(&mut self, cert_ref: &CertRef, cert_der: &[u8]) -> Result<(), BackendError>;

    /// Read a DER-encoded X.509 certificate.
    fn read_cert(&self, cert_ref: &CertRef) -> Result<Vec<u8>, BackendError>;

    /// Delete a certificate.
    fn delete_cert(&mut self, cert_ref: &CertRef) -> Result<(), BackendError>;
}

/// Hardware or software random number generation.
///
/// Backends implementing this trait can generate random bytes. For HSM
/// backends, this uses the device's internal RNG (e.g., PKCS#11 `C_GenerateRandom`).
pub trait RandomBackend: Backend {
    /// Generate `len` random bytes.
    fn generate_random(&mut self, len: usize) -> Result<Vec<u8>, BackendError>;
}

/// Key transport (wrapping) operations.
///
/// Every method returns a [`WrappedKey`] carrying the scheme it was asked for
/// and a [`WrapDescription`](crate::types::WrapDescription) of what it did, so
/// the caller records an observation rather than a request.
pub trait KeyTransportBackend: Backend {
    /// Wrap `key_id` using `wrapping_key_id` under `scheme`.
    fn wrap(
        &mut self,
        key_id: &KeyId,
        wrapping_key_id: &KeyId,
        scheme: WrapScheme,
    ) -> Result<WrappedKey, BackendError>;

    /// Unwrap `wrapped` using `unwrapping_key_id`, importing the result with
    /// `label` under `policy`.
    ///
    /// The policy is the receiving ceremony's, not the origin's: nothing
    /// travels with a wrapped key that says what it may do, so the step that
    /// imports it declares that, exactly as the step that generated it did.
    ///
    /// `expected` is that same declaration one level down, because nothing
    /// travels with a wrapped key saying what it *is* either. Recovered bytes
    /// are a private key or a bare secret depending on what was wrapped, and
    /// the two are told apart by what the receiving ceremony says it is
    /// restoring rather than by what the bytes happen to parse as. `None` is a
    /// ceremony that declared nothing, which an implementation may serve only
    /// where the recovered form is unambiguous. A declaration that disagrees
    /// with what came out is a failure, not something to reconcile.
    fn unwrap(
        &mut self,
        wrapped: &WrappedKey,
        unwrapping_key_id: &KeyId,
        label: &str,
        policy: KeyPolicy,
        expected: Option<KeyAlgorithm>,
    ) -> Result<KeyMetadata, BackendError>;

    /// Produce a fresh content-encryption key protected by `kek`.
    ///
    /// Two copies of one key come back: the plaintext, for the caller to
    /// encrypt content with and then drop, and a copy only `kek` opens, which
    /// the container carries to the recipient.
    ///
    /// Content does not appear here. No key-protection
    /// device Rite talks to is a cipher you hand a file to: a cloud KMS caps a
    /// direct encrypt at a few kilobytes, a TPM takes a kilobyte per call over
    /// a slow bus, and a smart card is slower still. Every one of them offers
    /// this operation instead, so a backend implements what it can actually do
    /// and the content pipeline stays in one place above it.
    ///
    /// `algorithm` must be a symmetric one, since a data key is a secret the
    /// caller encrypts with directly. It is the length request AWS KMS spells
    /// `KeySpec: AES_256 | AES_128`.
    ///
    /// The result carries a [`KeyProtection`] because the caller has to declare
    /// the key-encryption algorithm in the container it assembles, and only the
    /// backend knows which one it used.
    ///
    /// # Not yet a parameter
    ///
    /// An **encryption context**, which AWS calls `EncryptionContext` and Azure
    /// calls `aad`, binds a data key to the purpose it was issued for: the same
    /// value must be supplied to open it again, or the open fails. AWS
    /// recommends it on every call. It is absent here because supplying it would
    /// oblige the ceremony to store it somewhere a later run can read it back,
    /// and CMS has no slot for it that the tag covers except `authAttrs`, which
    /// is deferred. Adding it is the next widening this pair needs, and it wants
    /// the transcript question answered first.
    fn generate_data_key(
        &mut self,
        kek: &KeyId,
        algorithm: KeyAlgorithm,
    ) -> Result<DataKey, BackendError>;

    /// Recover a data key from the protected copy a container carries.
    ///
    /// The counterpart of [`generate_data_key`](Self::generate_data_key), and
    /// the half of the pair almost every backend implements: protecting a data
    /// key needs only a public key or a shared secret, while opening one always
    /// needs the device that holds the other half.
    ///
    /// `protection` says how `wrapped` was protected, taken from the container
    /// rather than assumed, because the bytes say nothing about themselves and
    /// the backend may implement several. An implementation that was not asked
    /// which one to use could only guess, and a wrong guess on key material is
    /// silent. A backend refuses a protection it does not implement rather than
    /// decrypting under an assumption.
    fn open_data_key(
        &mut self,
        kek: &KeyId,
        wrapped: &[u8],
        protection: KeyProtection,
    ) -> Result<Zeroizing<Vec<u8>>, BackendError>;

    /// Wrap `key_id` to an external recipient's public key.
    ///
    /// Default implementation returns `UnsupportedOperation`.
    fn wrap_to_public(
        &mut self,
        key_id: &KeyId,
        recipient_pub_key: &PublicKeyDer,
        scheme: WrapScheme,
    ) -> Result<WrappedKey, BackendError> {
        let _ = (key_id, recipient_pub_key, scheme);
        Err(BackendError::UnsupportedOperation(
            "wrap_to_public not supported".to_string(),
        ))
    }
}

/// PKCS#11 token operations.
///
/// Provides access to PKCS#11-specific functionality: token info, key
/// security attributes, mechanism enumeration, and session login/logout.
pub trait Pkcs11Backend: Backend {
    /// Get token information (label, manufacturer, serial, flags).
    fn token_info(&self) -> Result<Pkcs11TokenInfo, BackendError>;

    /// Read security attributes for `key_id` (`CKA_ALWAYS_SENSITIVE`, etc.).
    fn key_security_attributes(
        &self,
        key_id: &KeyId,
    ) -> Result<KeySecurityAttributes, BackendError>;

    /// List mechanisms supported by this token.
    fn supported_mechanisms(&self) -> Result<Vec<Pkcs11Mechanism>, BackendError>;

    /// Log in to the token with a PIN.
    fn login(&mut self, pin: &[u8]) -> Result<(), BackendError>;

    /// Log out of the token.
    fn logout(&mut self) -> Result<(), BackendError>;
}

/// PKCS#11 Security Officer (SO) role operations.
///
/// These operations require SO authentication and are typically performed
/// only during initial token setup.
pub trait Pkcs11AdminBackend: Backend {
    /// Initialize a token (`C_InitToken`).
    fn init_token(&mut self, so_pin: &[u8], label: &str) -> Result<(), BackendError>;

    /// Initialize the user PIN (`C_InitPIN`). Requires SO session.
    fn init_user_pin(&mut self, so_pin: &[u8], user_pin: &[u8]) -> Result<(), BackendError>;
}

/// TPM 2.0 operations.
///
/// Provides TPM-specific functionality: device info, PCR operations, and
/// quote generation.
pub trait TpmBackend: Backend {
    /// Get TPM information (version, manufacturer, firmware).
    fn tpm_info(&mut self) -> Result<TpmInfo, BackendError>;

    /// Read PCR (Platform Configuration Register) values for the given PCR indices.
    ///
    /// Returns a `BTreeMap` keyed by PCR index for deterministic ordering in transcripts.
    fn read_pcrs(&mut self, pcrs: &[u8]) -> Result<BTreeMap<u8, PcrValue>, BackendError>;

    /// Extend a PCR register with new data.
    fn extend_pcr(&mut self, pcr: u8, data: &[u8]) -> Result<(), BackendError>;

    /// Generate a TPM quote (signed attestation over PCR values).
    fn generate_quote(&mut self, pcrs: &[u8], nonce: &[u8]) -> Result<Attestation, BackendError>;
}

/// Personal Identity Verification (PIV) smart card operations.
///
/// Models the PIV card application interface defined by FIPS 201-3 and
/// NIST SP 800-73-5. Methods in this trait correspond to PIV card commands
/// and data model operations; their semantics are defined by the standard
/// and should not diverge.
///
/// Backends implementing `PivBackend` should also implement the generic traits
/// (`KeyStoreBackend`, `SignBackend`) for interoperability with non-PIV-aware actions.
///
/// # Standard references
/// - FIPS 201-3: Personal Identity Verification of Federal Employees and Contractors
/// - NIST SP 800-73-5 Part 1: PIV Card Application Data Model
/// - NIST SP 800-73-5 Part 2: PIV Card Application Card Command Interface
/// - NIST SP 800-78-5: Cryptographic Algorithms and Key Sizes for PIV
pub trait PivBackend: Backend {
    /// List populated PIV slots with metadata.
    ///
    /// Enumerates key references defined in SP 800-73-5 Part 1, Table 4b.
    fn list_slots(&self) -> Result<Vec<PivSlotInfo>, BackendError>;

    /// Verify the PIV Card Application PIN.
    ///
    /// Required before private key operations on slots with PIN access rules.
    /// The PIN is typically 6–8 digits (ASCII-encoded).
    /// [SP 800-73-5 Part 2, §3.3: VERIFY command]
    fn verify_pin(&mut self, pin: &[u8]) -> Result<(), BackendError>;

    /// Change the PIV Card Application PIN.
    ///
    /// [SP 800-73-5 Part 2, §3.4: CHANGE REFERENCE DATA command]
    fn change_pin(&mut self, current: &[u8], new: &[u8]) -> Result<(), BackendError>;

    /// Get remaining PIN retry count before lockout.
    fn pin_retries(&mut self) -> Result<u32, BackendError>;

    /// Reset a blocked PIN using the PUK (PIN Unblocking Key).
    ///
    /// [SP 800-73-5 Part 2, §3.4: RESET RETRY COUNTER command]
    fn unblock_pin(&mut self, puk: &[u8], new_pin: &[u8]) -> Result<(), BackendError>;

    /// Return device identity (serial, firmware version, form factor).
    ///
    /// Not all fields are available on every PIV card. Serial number
    /// retrieval is vendor-specific (not standardized by NIST SP 800-73).
    fn device_info(&self) -> Result<PivDeviceInfo, BackendError>;
}

/// `YubiKey`-specific extensions to the PIV interface.
///
/// Operations in this trait are Yubico vendor extensions that go beyond
/// the NIST SP 800-73 standard. They are specific to `YubiKey` hardware
/// and will not work with generic PIV smart cards.
///
/// # Vendor references
/// - Yubico PIV documentation: <https://developers.yubico.com/PIV/>
/// - `YubiKey` attestation: key reference F9 (Yubico-proprietary)
/// - Touch/PIN policy configuration: Yubico-proprietary extensions
///   to the GENERATE ASYMMETRIC KEY PAIR command
pub trait YubikeyBackend: PivBackend {
    /// Generate an attestation certificate for a key in `slot`.
    ///
    /// Proves the key was generated on-device (not imported).
    /// Uses `YubiKey`'s attestation key (slot F9) to sign a certificate
    /// over the public key in the target slot.
    /// This is a Yubico extension, not available on generic PIV cards.
    fn attest_slot(&self, slot: PivSlot) -> Result<Vec<u8>, BackendError>;

    /// Authenticate with the management key (3DES or AES).
    ///
    /// Required before administrative operations: key generation,
    /// certificate import, PIN/PUK retry configuration.
    fn authenticate_management(&mut self, mgm_key: &[u8]) -> Result<(), BackendError>;

    /// Change the management key.
    fn change_management_key(&mut self, current: &[u8], new: &[u8]) -> Result<(), BackendError>;

    /// Get `YubiKey`-specific metadata for `slot`.
    ///
    /// Returns touch policy, PIN policy, and key origin: information
    /// not available through standard PIV commands.
    fn slot_metadata(&self, slot: PivSlot) -> Result<YubikeySlotMetadata, BackendError>;

    /// Block PUK permanently (prevents PIN unblock forever).
    ///
    /// High-security operation: once blocked, a forgotten PIN requires
    /// full device reset (destroying all keys). Irreversible.
    fn block_puk(&mut self) -> Result<(), BackendError>;
}

/// Whether an error may be re-executed by retrying the step.
///
/// A `Transient` error means the world wasn't ready and the step's work did not
/// happen, so re-running it is meaningful (token reinserted, cable reseated). A
/// `Fatal` error means re-execution is either meaningless or unsafe: a procedural
/// result, a broken definition, or a terminal device state.
///
/// The classification lives on the error type, not in the ceremony definition: a
/// ceremony author must not be able to mark, say, a signature mismatch retriable.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Retriability {
    /// Environmental and recoverable; retrying the step may succeed.
    Transient,
    /// Not retriable; the run must stop or escalate.
    Fatal,
}

impl Retriability {
    /// Convenience predicate for callers that only need a yes/no answer.
    #[must_use]
    pub const fn is_retriable(self) -> bool {
        matches!(self, Retriability::Transient)
    }
}

/// Backend-specific errors.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BackendError {
    /// Authentication required (not logged in).
    #[error("Authentication required")]
    AuthRequired,

    /// PIN required to access backend.
    #[error("PIN required")]
    PinRequired,

    /// PIN verification failed (wrong PIN). Contains remaining retries if known.
    #[error("PIN verification failed ({0} retries remaining)")]
    PinFailed(u32),

    /// PIN is blocked (too many failed attempts).
    #[error("PIN blocked")]
    PinBlocked,

    /// User PIN not initialized (PKCS#11: `C_InitPIN` not yet called).
    #[error("User PIN not initialized")]
    UserPinNotInitialized,

    /// Management key authentication required.
    #[error("Management key authentication required")]
    ManagementKeyRequired,

    /// Key not found in backend storage.
    #[error("Key not found: {0}")]
    KeyNotFound(String),

    /// Object not found (PKCS#11: `find_objects` returned empty).
    #[error("Object not found: {0}")]
    ObjectNotFound(String),

    /// PIV slot is empty (no key or certificate).
    #[error("Slot empty: {0}")]
    SlotEmpty(String),

    /// Backend storage capacity exceeded.
    #[error("Capacity exceeded")]
    CapacityExceeded,

    /// Operation not permitted (key usage flags don't allow this).
    #[error("Operation not permitted: {0}")]
    OperationNotPermitted(String),

    /// Attribute is read-only (e.g., tried to set `CKA_ALWAYS_SENSITIVE`).
    #[error("Attribute is read-only: {0}")]
    AttributeReadOnly(String),

    /// Algorithm not supported by this backend.
    #[error("Unsupported algorithm: {0}")]
    UnsupportedAlgorithm(String),

    /// Operation not supported by this backend.
    #[error("Unsupported operation: {0}")]
    UnsupportedOperation(String),

    /// Token not present in slot.
    #[error("Token not present")]
    TokenNotPresent,

    /// Hardware failure (device disconnected, I/O error, etc.).
    #[error("Hardware failure: {0}")]
    HardwareFailure(String),

    /// Invalid key format or data.
    #[error("Invalid key format: {0}")]
    InvalidKeyFormat(String),

    /// Invalid data (malformed input, unexpected encoding, etc.).
    #[error("Invalid data: {0}")]
    InvalidData(String),

    /// Backend not found in registry.
    #[error("Backend not found: {0}")]
    NotFound(String),

    /// Configuration error (missing or invalid settings).
    #[error("Configuration error: {0}")]
    Configuration(String),

    /// Generic backend error.
    #[error("Backend error: {0}")]
    Other(String),
}

impl BackendError {
    /// Classify whether a step that failed with this error may be retried.
    ///
    /// The match is exhaustive with no wildcard arm on purpose: adding a new
    /// `BackendError` variant fails to compile until it is deliberately
    /// classified here.
    #[must_use]
    pub fn retriability(&self) -> Retriability {
        match self {
            // Environmental: the world wasn't ready, the work didn't happen.
            // The operator can fix the precondition (log in, enter a PIN,
            // insert the right token, initialize the device) and retry.
            BackendError::AuthRequired
            | BackendError::PinRequired
            | BackendError::PinFailed(_)
            | BackendError::ManagementKeyRequired
            | BackendError::UserPinNotInitialized
            | BackendError::KeyNotFound(_)
            | BackendError::ObjectNotFound(_)
            | BackendError::SlotEmpty(_)
            | BackendError::TokenNotPresent
            | BackendError::HardwareFailure(_)
            | BackendError::Configuration(_) => Retriability::Transient,

            // Fatal: re-execution is meaningless or unsafe. A terminal device
            // state (PIN budget exhausted, capacity full), a definition that
            // asks for something the backend cannot do, or malformed/unknown
            // input that retrying cannot resolve.
            BackendError::PinBlocked
            | BackendError::CapacityExceeded
            | BackendError::OperationNotPermitted(_)
            | BackendError::AttributeReadOnly(_)
            | BackendError::UnsupportedAlgorithm(_)
            | BackendError::UnsupportedOperation(_)
            | BackendError::InvalidKeyFormat(_)
            | BackendError::InvalidData(_)
            | BackendError::NotFound(_)
            | BackendError::Other(_) => Retriability::Fatal,
        }
    }
}

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

    #[test]
    fn retriability_is_retriable_predicate() {
        assert!(Retriability::Transient.is_retriable());
        assert!(!Retriability::Fatal.is_retriable());
    }

    #[test]
    fn environmental_errors_are_transient() {
        let transient = [
            BackendError::AuthRequired,
            BackendError::PinRequired,
            BackendError::PinFailed(2),
            BackendError::ManagementKeyRequired,
            BackendError::UserPinNotInitialized,
            BackendError::KeyNotFound("k".into()),
            BackendError::ObjectNotFound("o".into()),
            BackendError::SlotEmpty("9a".into()),
            BackendError::TokenNotPresent,
            BackendError::HardwareFailure("cable".into()),
            BackendError::Configuration("missing".into()),
        ];
        for err in transient {
            assert_eq!(
                err.retriability(),
                Retriability::Transient,
                "expected transient: {err:?}"
            );
        }
    }

    #[test]
    fn fatal_errors_are_not_retriable() {
        let fatal = [
            BackendError::PinBlocked,
            BackendError::CapacityExceeded,
            BackendError::OperationNotPermitted("usage".into()),
            BackendError::AttributeReadOnly("attr".into()),
            BackendError::UnsupportedAlgorithm("rsa1".into()),
            BackendError::UnsupportedOperation("wrap".into()),
            BackendError::InvalidKeyFormat("pem".into()),
            BackendError::InvalidData("bytes".into()),
            BackendError::NotFound("backend".into()),
            BackendError::Other("boom".into()),
        ];
        for err in fatal {
            assert_eq!(
                err.retriability(),
                Retriability::Fatal,
                "expected fatal: {err:?}"
            );
        }
    }

    #[test]
    fn pin_failed_retriable_but_pin_blocked_terminal() {
        // The hardware budget: a wrong PIN can be retried; an exhausted one cannot.
        assert!(BackendError::PinFailed(1).retriability().is_retriable());
        assert!(!BackendError::PinBlocked.retriability().is_retriable());
    }
}