identity-kit 0.4.0

DID, key management and verifiable credential primitives
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
//! Key stores: private keys behind an opaque id, with signing as a remote operation.
//!
//! The module is shaped by remote signers, an HSM or a cloud KMS being the design target:
//!
//! - A key is named by an opaque [`KeyId`] (a label, a PKCS#11 object name, a cloud key ARN).
//! - Private material never leaves the backend. [`KeyStore::sign`] is `async`, and callers keep
//!   the public [`Jwk`] they get from [`KeyStore::public_jwk`] rather than asking for it on every
//!   use; [`KeySigner`] does exactly that and implements [`Signer`](crate::jose::Signer).
//! - Every key has one algorithm. A backend declares what it signs with, and whether it can
//!   generate and delete keys, in [`KeyStoreCapabilities`]; the declaration must be truthful and
//!   [`testsuite`] (feature `test-vectors`) checks it.
//! - Signatures are returned in their JWS form: 64 bytes for EdDSA, raw `r || s` for ECDSA.
//!
//! Three backends ship with the crate. [`InMemoryKeyStore`] (feature `in-memory`) and
//! [`SoftwareKeyStore`] (feature `software`), a private JWK set file, are for development and
//! tests: both sign EdDSA, ES256 and, with the `secp256k1` feature, ES256K, and neither signs
//! with RSA, which stays outside the software backends per
//! `docs/adr/0001-rsa-verification-only.md`. [`Pkcs11KeyStore`] (feature `pkcs11`) signs in a
//! PKCS#11 module, an HSM or a software token, with whatever the module offers, RSA included.
//! Vendor-specific backends live in their own crates and implement [`KeyStore`];
//! `docs/key-stores.md` is the contract they follow.
//!
//! # Cargo features
//!
//! - `in-memory`: [`InMemoryKeyStore`].
//! - `software` (default): [`SoftwareKeyStore`].
//! - `pkcs11`: [`Pkcs11KeyStore`].
//! - `test-vectors`: [`testsuite`].

use core::fmt;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::jose::{Jwk, JwsAlgorithm};

mod error;
#[cfg(feature = "in-memory")]
mod in_memory;
#[cfg(any(feature = "in-memory", feature = "software"))]
mod local;
#[cfg(feature = "pkcs11")]
mod pkcs11;
mod signer;
#[cfg(feature = "software")]
mod software;
#[cfg(feature = "test-vectors")]
#[cfg_attr(docsrs, doc(cfg(feature = "test-vectors")))]
pub mod testsuite;

pub use crate::jose::KeyType;
pub use error::KeyStoreError;
#[cfg(feature = "in-memory")]
#[cfg_attr(docsrs, doc(cfg(feature = "in-memory")))]
pub use in_memory::InMemoryKeyStore;
#[cfg(feature = "pkcs11")]
#[cfg_attr(docsrs, doc(cfg(feature = "pkcs11")))]
pub use pkcs11::{
    Pkcs11Error, Pkcs11KeyStore, Pkcs11KeyStoreOptions, Pkcs11Token, STAGING_LABEL_PREFIX,
};
pub use signer::KeySigner;
#[cfg(feature = "software")]
#[cfg_attr(docsrs, doc(cfg(feature = "software")))]
pub use software::{SoftwareKeyStore, SoftwareKeyStoreOptions};

/// The opaque id of a key in a [`KeyStore`].
///
/// What the string means is up to the backend: a label, a PKCS#11 object name, a cloud key ARN.
/// The crate never parses it. It serializes as a plain string.
///
/// # Examples
///
/// ```
/// use identity_kit::keys::KeyId;
///
/// let id = KeyId::new("signing-2026");
/// assert_eq!(id.as_str(), "signing-2026");
/// assert_eq!(id.to_string(), "signing-2026");
/// assert_eq!(serde_json::to_string(&id)?, "\"signing-2026\"");
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct KeyId(String);

impl KeyId {
    /// A key id from any string.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// The id as a string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for KeyId {
    fn from(id: &str) -> Self {
        Self::new(id)
    }
}

impl From<String> for KeyId {
    fn from(id: String) -> Self {
        Self(id)
    }
}

impl From<KeyId> for String {
    fn from(id: KeyId) -> Self {
        id.0
    }
}

impl AsRef<str> for KeyId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for KeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Display for KeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// What to generate: a key type, the one algorithm the key will sign with, and an optional
/// label.
///
/// The algorithm must fit the key type ([`KeySpec::validate`]); backends reject a spec that
/// does not. How a backend uses the label is its own business; the software backends use it as
/// the key id when set and the RFC 7638 thumbprint of the public key otherwise.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::{JwsAlgorithm, KeyType};
/// use identity_kit::keys::{KeySpec, KeyStoreError};
///
/// let spec = KeySpec::new(KeyType::P256, JwsAlgorithm::ES256).with_label("issuer");
/// assert!(spec.validate().is_ok());
///
/// let wrong = KeySpec::new(KeyType::P256, JwsAlgorithm::EdDSA);
/// assert!(matches!(wrong.validate(), Err(KeyStoreError::InvalidSpec { .. })));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct KeySpec {
    /// The kind of key.
    pub key_type: KeyType,
    /// The algorithm the key signs with.
    pub alg: JwsAlgorithm,
    /// A label for the backend: the key id for the software backends, a PKCS#11 label, a
    /// display name.
    pub label: Option<String>,
}

impl KeySpec {
    /// A spec without a label.
    pub fn new(key_type: KeyType, alg: JwsAlgorithm) -> Self {
        Self {
            key_type,
            alg,
            label: None,
        }
    }

    /// This spec with a label.
    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// Checks that the algorithm fits the key type.
    ///
    /// # Errors
    ///
    /// [`KeyStoreError::InvalidSpec`] when it does not: `EdDSA` needs an Ed25519 key, `ES256` a
    /// P-256 key, `ES256K` a secp256k1 key and `RS256` or `PS256` an RSA key. `ES384` fits no
    /// [`KeyType`] this crate has.
    pub fn validate(&self) -> Result<(), KeyStoreError> {
        if algorithm_fits(self.key_type, self.alg) {
            Ok(())
        } else {
            Err(KeyStoreError::InvalidSpec {
                key_type: self.key_type,
                alg: self.alg,
            })
        }
    }
}

/// Whether `alg` is an algorithm for keys of type `key_type`.
fn algorithm_fits(key_type: KeyType, alg: JwsAlgorithm) -> bool {
    match key_type {
        KeyType::Ed25519 => alg == JwsAlgorithm::EdDSA,
        KeyType::P256 => alg == JwsAlgorithm::ES256,
        KeyType::Secp256k1 => alg == JwsAlgorithm::ES256K,
        KeyType::Rsa2048 | KeyType::Rsa4096 => {
            matches!(alg, JwsAlgorithm::RS256 | JwsAlgorithm::PS256)
        }
    }
}

/// What a [`KeyStore`] can do.
///
/// A backend's declaration must be truthful: every algorithm listed signs, and `generate` and
/// `delete` succeed only when advertised. [`testsuite`] checks both directions.
///
/// # Examples
///
/// ```
/// use identity_kit::jose::JwsAlgorithm;
/// use identity_kit::keys::KeyStoreCapabilities;
///
/// let hsm = KeyStoreCapabilities::new([JwsAlgorithm::ES256, JwsAlgorithm::RS256]).remote();
/// assert!(hsm.supports(JwsAlgorithm::ES256));
/// assert!(!hsm.supports(JwsAlgorithm::EdDSA));
/// assert!(!hsm.can_generate && !hsm.can_delete && hsm.remote);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct KeyStoreCapabilities {
    /// Whether [`KeyStore::generate`] is implemented.
    pub can_generate: bool,
    /// Whether [`KeyStore::delete`] is implemented.
    pub can_delete: bool,
    /// Whether signing leaves the process (an HSM, a network service), so that callers should
    /// expect latency and transient failures.
    pub remote: bool,
    /// The algorithms the store signs with, without duplicates.
    pub algorithms: Vec<JwsAlgorithm>,
}

impl KeyStoreCapabilities {
    /// A local store that signs with `algorithms` and can neither generate nor delete.
    pub fn new(algorithms: impl IntoIterator<Item = JwsAlgorithm>) -> Self {
        let mut deduplicated: Vec<JwsAlgorithm> = Vec::new();
        for alg in algorithms {
            if !deduplicated.contains(&alg) {
                deduplicated.push(alg);
            }
        }
        Self {
            can_generate: false,
            can_delete: false,
            remote: false,
            algorithms: deduplicated,
        }
    }

    /// With [`can_generate`](Self::can_generate) set.
    #[must_use]
    pub fn with_generate(mut self) -> Self {
        self.can_generate = true;
        self
    }

    /// With [`can_delete`](Self::can_delete) set.
    #[must_use]
    pub fn with_delete(mut self) -> Self {
        self.can_delete = true;
        self
    }

    /// With [`remote`](Self::remote) set.
    #[must_use]
    pub fn remote(mut self) -> Self {
        self.remote = true;
        self
    }

    /// Whether the store signs with `alg`.
    pub fn supports(&self, alg: JwsAlgorithm) -> bool {
        self.algorithms.contains(&alg)
    }
}

/// A backend holding private keys.
///
/// This is the crate's key extension point: a KMS, an HSM or a software store implements it,
/// and everything that signs takes a `&dyn KeyStore` (usually through [`KeySigner`]). The
/// contract, which [`testsuite`] checks, is:
///
/// - [`capabilities`](Self::capabilities) is truthful: every listed algorithm signs; `generate`
///   and `delete` return [`KeyStoreError::Unsupported`] unless advertised.
/// - [`public_jwk`](Self::public_jwk) returns a key without private parameters, with `alg` set
///   to the key's algorithm when the backend knows it.
/// - [`sign`](Self::sign) takes the raw signing input (the backend hashes) and returns the JWS
///   form of the signature: 64 bytes for EdDSA, raw `r || s` for ECDSA, the modulus-sized octet
///   string for RSA. A key signs only with its own algorithm; any other `alg` is
///   [`KeyStoreError::AlgorithmMismatch`].
/// - An unknown key is [`KeyStoreError::NotFound`] from every operation but
///   [`exists`](Self::exists), which returns `false`.
///
/// `generate` and `delete` have default implementations returning
/// [`KeyStoreError::Unsupported`], for backends whose keys are provisioned out of band.
#[async_trait::async_trait]
pub trait KeyStore: Send + Sync {
    /// What this store can do.
    fn capabilities(&self) -> KeyStoreCapabilities;

    /// The public key of `key`, without private parameters.
    ///
    /// # Errors
    ///
    /// [`KeyStoreError::NotFound`] when there is no such key.
    async fn public_jwk(&self, key: &KeyId) -> Result<Jwk, KeyStoreError>;

    /// Signs `data` with `key` under `alg`, returning the signature in its JWS form.
    ///
    /// # Errors
    ///
    /// [`KeyStoreError::NotFound`] when there is no such key and
    /// [`KeyStoreError::AlgorithmMismatch`] when `alg` is not the key's algorithm.
    async fn sign(
        &self,
        key: &KeyId,
        alg: JwsAlgorithm,
        data: &[u8],
    ) -> Result<Vec<u8>, KeyStoreError>;

    /// Whether `key` exists.
    ///
    /// # Errors
    ///
    /// Only when the backend cannot answer.
    async fn exists(&self, key: &KeyId) -> Result<bool, KeyStoreError>;

    /// Generates a key as `spec` describes and returns its id.
    ///
    /// # Errors
    ///
    /// [`KeyStoreError::Unsupported`] when the store does not generate keys (the default),
    /// [`KeyStoreError::InvalidSpec`] when the algorithm does not fit the key type,
    /// [`KeyStoreError::UnsupportedKeyType`] or [`KeyStoreError::UnsupportedAlgorithm`] when the
    /// store cannot make such a key, and [`KeyStoreError::AlreadyExists`] when the label names
    /// an existing key.
    async fn generate(&self, spec: KeySpec) -> Result<KeyId, KeyStoreError> {
        let _ = spec;
        Err(KeyStoreError::Unsupported("generate"))
    }

    /// Deletes `key`.
    ///
    /// # Errors
    ///
    /// [`KeyStoreError::Unsupported`] when the store does not delete keys (the default) and
    /// [`KeyStoreError::NotFound`] when there is no such key.
    async fn delete(&self, key: &KeyId) -> Result<(), KeyStoreError> {
        let _ = key;
        Err(KeyStoreError::Unsupported("delete"))
    }
}

// Implements `KeyStore` for `&T`, `Box<T>` and `Arc<T>` by forwarding every method to `T`.
// A method added to the trait is added here too: one with a default body would still compile
// if left out, and calls through these wrappers would then run the default, not `T`'s
// override. `clippy::missing_trait_methods` turns that omission into an error.
macro_rules! forward_key_store {
    ($($ty:ty),* $(,)?) => {
        $(
            #[async_trait::async_trait]
            #[deny(clippy::missing_trait_methods)]
            impl<T: KeyStore + ?Sized> KeyStore for $ty {
                fn capabilities(&self) -> KeyStoreCapabilities {
                    (**self).capabilities()
                }

                async fn public_jwk(&self, key: &KeyId) -> Result<Jwk, KeyStoreError> {
                    (**self).public_jwk(key).await
                }

                async fn sign(
                    &self,
                    key: &KeyId,
                    alg: JwsAlgorithm,
                    data: &[u8],
                ) -> Result<Vec<u8>, KeyStoreError> {
                    (**self).sign(key, alg, data).await
                }

                async fn exists(&self, key: &KeyId) -> Result<bool, KeyStoreError> {
                    (**self).exists(key).await
                }

                async fn generate(&self, spec: KeySpec) -> Result<KeyId, KeyStoreError> {
                    (**self).generate(spec).await
                }

                async fn delete(&self, key: &KeyId) -> Result<(), KeyStoreError> {
                    (**self).delete(key).await
                }
            }
        )*
    };
}

forward_key_store!(&T, Box<T>, Arc<T>);