1
//! Code for managing multiple [`Keystore`](crate::Keystore)s.
2
//!
3
//! See the [`KeyMgr`] docs for more details.
4

            
5
use crate::raw::RawEntryId;
6
use crate::{
7
    ArtiPath, BoxedKeystore, KeyPath, KeyPathError, KeyPathInfo, KeyPathInfoExtractor,
8
    KeyPathPattern, KeySpecifier, KeystoreCorruptionError, KeystoreEntryResult, KeystoreId,
9
    KeystoreSelector, Result,
10
};
11

            
12
use itertools::Itertools;
13
use std::iter;
14
use std::result::Result as StdResult;
15
use tor_error::{bad_api_usage, internal, into_bad_api_usage};
16
use tor_key_forge::{
17
    ItemType, Keygen, KeygenRng, KeystoreItemType, ToEncodableCert, ToEncodableKey,
18
};
19

            
20
#[cfg(feature = "experimental-api")]
21
use crate::KeyCertificateSpecifier;
22

            
23
/// A key manager that acts as a frontend to a primary [`Keystore`](crate::Keystore) and
24
/// any number of secondary [`Keystore`](crate::Keystore)s.
25
///
26
/// Note: [`KeyMgr`] is a low-level utility and does not implement caching (the key stores are
27
/// accessed for every read/write).
28
///
29
/// The `KeyMgr` accessors - currently just [`get()`](KeyMgr::get) -
30
/// search the configured key stores in order: first the primary key store,
31
/// and then the secondary stores, in order.
32
///
33
///
34
/// ## Concurrent key store access
35
///
36
/// The key stores will allow concurrent modification by different processes. In
37
/// order to implement this safely without locking, the key store operations (get,
38
/// insert, remove) will need to be atomic.
39
///
40
/// **Note**: [`KeyMgr::generate`] and [`KeyMgr::get_or_generate`] should **not** be used
41
/// concurrently with any other `KeyMgr` operation that mutates the same key
42
/// (i.e. a key with the same `ArtiPath`), because
43
/// their outcome depends on whether the selected key store
44
/// [`contains`][crate::Keystore::contains]
45
/// the specified key (and thus suffers from a TOCTOU race).
46
#[derive(derive_builder::Builder)]
47
#[builder(pattern = "owned", build_fn(private, name = "build_unvalidated"))]
48
pub struct KeyMgr {
49
    /// The primary key store.
50
    primary_store: BoxedKeystore,
51
    /// The secondary key stores.
52
    #[builder(default, setter(custom))]
53
    secondary_stores: Vec<BoxedKeystore>,
54
    /// The key info extractors.
55
    ///
56
    /// These are initialized internally by [`KeyMgrBuilder::build`], using the values collected
57
    /// using `inventory`.
58
    #[builder(default, setter(skip))]
59
    key_info_extractors: Vec<&'static dyn KeyPathInfoExtractor>,
60
}
61

            
62
/// A keystore entry descriptor.
63
///
64
/// This identifies a key entry from a specific keystore.
65
/// The key entry can be retrieved, using [`KeyMgr::get_entry`],
66
/// or removed, using [`KeyMgr::remove_entry`].
67
///
68
/// Returned from [`KeyMgr::list_matching`].
69
#[derive(Clone, Debug, PartialEq, amplify::Getters)]
70
pub struct KeystoreEntry<'a> {
71
    /// The [`KeyPath`] of the key.
72
    key_path: KeyPath,
73
    /// The [`KeystoreItemType`] of the key.
74
    key_type: KeystoreItemType,
75
    /// The [`KeystoreId`] of the keystore where the key was found.
76
    #[getter(as_copy)]
77
    keystore_id: &'a KeystoreId,
78
    /// The [`RawEntryId`] of the key, an identifier used in
79
    /// `arti raw` operations.
80
    #[cfg_attr(not(feature = "onion-service-cli-extra"), getter(skip))]
81
    raw_id: RawEntryId,
82
}
83

            
84
impl<'a> KeystoreEntry<'a> {
85
    /// Create a new `KeystoreEntry`
86
54760
    #[cfg_attr(feature = "experimental-api", visibility::make(pub))]
87
54760
    pub(crate) fn new(
88
54760
        key_path: KeyPath,
89
54760
        key_type: KeystoreItemType,
90
54760
        keystore_id: &'a KeystoreId,
91
54760
        raw_id: RawEntryId,
92
54760
    ) -> Self {
93
54760
        Self {
94
54760
            key_path,
95
54760
            key_type,
96
54760
            keystore_id,
97
54760
            raw_id,
98
54760
        }
99
54760
    }
100
}
101

            
102
impl KeyMgrBuilder {
103
    /// Construct a [`KeyMgr`] from this builder.
104
3386
    pub fn build(self) -> StdResult<KeyMgr, KeyMgrBuilderError> {
105
        use itertools::Itertools as _;
106

            
107
3386
        let mut keymgr = self.build_unvalidated()?;
108

            
109
4321
        if !keymgr.all_stores().map(|s| s.id()).all_unique() {
110
            return Err(KeyMgrBuilderError::ValidationError(
111
                "the keystore IDs are not pairwise unique".into(),
112
            ));
113
3386
        }
114

            
115
3386
        keymgr.key_info_extractors = inventory::iter::<&'static dyn KeyPathInfoExtractor>
116
3386
            .into_iter()
117
3386
            .copied()
118
3386
            .collect();
119

            
120
3386
        Ok(keymgr)
121
3386
    }
122
}
123

            
124
// TODO: auto-generate using define_list_builder_accessors/define_list_builder_helper
125
// when that becomes possible.
126
//
127
// See https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1760#note_2969841
128
impl KeyMgrBuilder {
129
    /// Access the being-built list of secondary stores (resolving default)
130
    ///
131
    /// If the field has not yet been set or accessed, the default list will be
132
    /// constructed and a mutable reference to the now-defaulted list of builders
133
    /// will be returned.
134
820
    pub fn secondary_stores(&mut self) -> &mut Vec<BoxedKeystore> {
135
820
        self.secondary_stores.get_or_insert(Default::default())
136
820
    }
137

            
138
    /// Set the whole list (overriding the default)
139
    pub fn set_secondary_stores(mut self, list: Vec<BoxedKeystore>) -> Self {
140
        self.secondary_stores = Some(list);
141
        self
142
    }
143

            
144
    /// Inspect the being-built list (with default unresolved)
145
    ///
146
    /// If the list has not yet been set, or accessed, `&None` is returned.
147
    pub fn opt_secondary_stores(&self) -> &Option<Vec<BoxedKeystore>> {
148
        &self.secondary_stores
149
    }
150

            
151
    /// Mutably access the being-built list (with default unresolved)
152
    ///
153
    /// If the list has not yet been set, or accessed, `&mut None` is returned.
154
    pub fn opt_secondary_stores_mut(&mut self) -> &mut Option<Vec<BoxedKeystore>> {
155
        &mut self.secondary_stores
156
    }
157
}
158

            
159
inventory::collect!(&'static dyn crate::KeyPathInfoExtractor);
160

            
161
impl KeyMgr {
162
    /// Read a key from one of the key stores, and try to deserialize it as `K::Key`.
163
    ///
164
    /// The key returned is retrieved from the first key store that contains an entry for the given
165
    /// specifier.
166
    ///
167
    /// Returns `Ok(None)` if none of the key stores have the requested key.
168
2040
    pub fn get<K: ToEncodableKey>(&self, key_spec: &dyn KeySpecifier) -> Result<Option<K>> {
169
2040
        self.get_from_store(key_spec, &K::Key::item_type(), self.all_stores())
170
2040
    }
171

            
172
    /// Retrieve the specified keystore entry, and try to deserialize it as `K::Key`.
173
    ///
174
    /// The key returned is retrieved from the key store specified in the [`KeystoreEntry`].
175
    ///
176
    /// Returns `Ok(None)` if the key store does not contain the requested entry.
177
    ///
178
    /// Returns an error if the specified `key_type` does not match `K::Key::item_type()`.
179
68
    pub fn get_entry<K: ToEncodableKey>(&self, entry: &KeystoreEntry) -> Result<Option<K>> {
180
68
        let selector = entry.keystore_id().into();
181
68
        let store = self.select_keystore(&selector)?;
182
68
        self.get_from_store(entry.key_path(), entry.key_type(), [store].into_iter())
183
68
    }
184

            
185
    /// Retrieve the specified keystore certificate entry and the corresponding
186
    /// subject and signing keys, deserializing the subject key as `K::Key`,
187
    /// the cert as `C::Cert`, and the signing key as `C::SigningKey`.
188
    ///
189
    /// The `S` type parameter is the [`KeyCertificateSpecifier`] of the certificate.
190
    ///
191
    /// The key returned is retrieved from the key store specified in the [`KeystoreEntry`].
192
    ///
193
    /// Returns `Ok(None)` if the key store does not contain the requested entry.
194
    ///
195
    /// Returns an error if the item type of the [`KeystoreEntry`] does not match `C::item_type()`,
196
    /// or if the certificate is not valid according to [`ToEncodableCert::validate`],
197
    /// or if the [`ArtiPath`] of the entry cannot be converted to a certificate specifier
198
    /// of type `S`.
199
    #[cfg(feature = "experimental-api")]
200
22
    pub fn get_cert_entry<
201
22
        S: KeyCertificateSpecifier + for<'a> TryFrom<&'a KeyPath, Error = KeyPathError>,
202
22
        K: ToEncodableKey,
203
22
        C: ToEncodableCert<K>,
204
22
    >(
205
22
        &self,
206
22
        entry: &KeystoreEntry,
207
22
        signing_key_spec: &dyn KeySpecifier,
208
22
    ) -> Result<Option<C>> {
209
22
        let selector = entry.keystore_id().into();
210
22
        let store = self.select_keystore(&selector)?;
211
22
        let cert_spec = S::try_from(entry.key_path())
212
22
            .map_err(into_bad_api_usage!("wrong cert specifier for entry?!"))?;
213
22
        let subject_key_spec = cert_spec.subject_key_specifier();
214

            
215
22
        self.get_cert_from_store(
216
22
            entry.key_path(),
217
22
            entry.key_type(),
218
22
            signing_key_spec,
219
22
            subject_key_spec,
220
22
            [store].into_iter(),
221
        )
222
22
    }
223

            
224
    /// Read the key identified by `key_spec`.
225
    ///
226
    /// The key returned is retrieved from the first key store that contains an entry for the given
227
    /// specifier.
228
    ///
229
    /// If the requested key does not exist in any of the key stores, this generates a new key of
230
    /// type `K` from the key created using using `K::Key`'s [`Keygen`] implementation, and inserts
231
    /// it into the specified keystore, returning the newly inserted value.
232
    ///
233
    /// This is a convenience wrapper around [`get()`](KeyMgr::get) and
234
    /// [`generate()`](KeyMgr::generate).
235
236
    pub fn get_or_generate<K>(
236
236
        &self,
237
236
        key_spec: &dyn KeySpecifier,
238
236
        selector: KeystoreSelector,
239
236
        rng: &mut dyn KeygenRng,
240
236
    ) -> Result<K>
241
236
    where
242
236
        K: ToEncodableKey,
243
236
        K::Key: Keygen,
244
    {
245
236
        match self.get(key_spec)? {
246
162
            Some(k) => Ok(k),
247
74
            None => self.generate(key_spec, selector, rng, false),
248
        }
249
236
    }
250

            
251
    /// Read a key from one of the key stores specified, and try to deserialize it as `K::Key`.
252
    ///
253
    /// Returns `Ok(None)` if none of the key stores have the requested key.
254
    ///
255
    /// Returns an error if the specified keystore does not exist.
256
    // TODO: The function takes `&KeystoreId`, but it would be better to accept a
257
    // `KeystoreSelector`.
258
    // This way, the caller can pass `KeystoreSelector::Primary` directly without
259
    // needing to know the specific `KeystoreId` of the primary keystore.
260
    #[cfg(feature = "onion-service-cli-extra")]
261
76
    pub fn get_from<K: ToEncodableKey>(
262
76
        &self,
263
76
        key_spec: &dyn KeySpecifier,
264
76
        keystore_id: &KeystoreId,
265
76
    ) -> Result<Option<K>> {
266
76
        let store = std::iter::once(self.find_keystore(keystore_id)?);
267
76
        self.get_from_store(key_spec, &K::Key::item_type(), store)
268
76
    }
269

            
270
    /// Validates the integrity of a [`KeystoreEntry`].
271
    ///
272
    /// This retrieves the key corresponding to the provided [`KeystoreEntry`],
273
    /// and checks if its contents are valid (i.e. that the key can be parsed).
274
    /// The [`KeyPath`] of the entry is further validated using [`describe`](KeyMgr::describe).
275
    ///
276
    /// Returns `Ok(())` if the specified keystore entry is valid, and `Err` otherwise.
277
    ///
278
    /// NOTE: If the specified entry does not exist, this will only validate its [`KeyPath`].
279
    #[cfg(feature = "onion-service-cli-extra")]
280
    pub fn validate_entry_integrity(&self, entry: &KeystoreEntry) -> Result<()> {
281
        let selector = entry.keystore_id().into();
282
        let store = self.select_keystore(&selector)?;
283
        // Ignore the parsed key, only checking if it parses correctly
284
        let _ = store.get(entry.key_path(), entry.key_type())?;
285

            
286
        let path = entry.key_path();
287
        // Ignore the result, just checking if the path is recognized
288
        let _ = self
289
            .describe(path)
290
            .ok_or_else(|| KeystoreCorruptionError::Unrecognized(path.clone()))?;
291

            
292
        Ok(())
293
    }
294

            
295
    /// Generate a new key of type `K`, and insert it into the key store specified by `selector`.
296
    ///
297
    /// If the key already exists in the specified key store, the `overwrite` flag is used to
298
    /// decide whether to overwrite it with a newly generated key.
299
    ///
300
    /// On success, this function returns the newly generated key.
301
    ///
302
    /// Returns [`Error::KeyAlreadyExists`](crate::Error::KeyAlreadyExists)
303
    /// if the key already exists in the specified key store and `overwrite` is `false`.
304
    ///
305
    /// **IMPORTANT**: using this function concurrently with any other `KeyMgr` operation that
306
    /// mutates the key store state is **not** recommended, as it can yield surprising results! The
307
    /// outcome of [`KeyMgr::generate`] depends on whether the selected key store
308
    /// [`contains`][crate::Keystore::contains] the specified key, and thus suffers from a TOCTOU race.
309
    //
310
    // TODO (#1119): can we make this less racy without a lock? Perhaps we should say we'll always
311
    // overwrite any existing keys.
312
    //
313
    // TODO: consider replacing the overwrite boolean with a GenerateOptions type
314
    // (sort of like std::fs::OpenOptions)
315
394
    pub fn generate<K>(
316
394
        &self,
317
394
        key_spec: &dyn KeySpecifier,
318
394
        selector: KeystoreSelector,
319
394
        rng: &mut dyn KeygenRng,
320
394
        overwrite: bool,
321
394
    ) -> Result<K>
322
394
    where
323
394
        K: ToEncodableKey,
324
394
        K::Key: Keygen,
325
    {
326
394
        let store = self.select_keystore(&selector)?;
327

            
328
394
        if overwrite || !store.contains(key_spec, &K::Key::item_type())? {
329
392
            let key = K::Key::generate(rng)?;
330
392
            store.insert(&key, key_spec)?;
331

            
332
392
            Ok(K::from_encodable_key(key))
333
        } else {
334
2
            Err(crate::Error::KeyAlreadyExists)
335
        }
336
394
    }
337

            
338
    /// Insert `key` into the [`Keystore`](crate::Keystore) specified by `selector`.
339
    ///
340
    /// If the key already exists in the specified key store, the `overwrite` flag is used to
341
    /// decide whether to overwrite it with the provided key.
342
    ///
343
    /// If this key is not already in the keystore, `None` is returned.
344
    ///
345
    /// If this key already exists in the keystore, its value is updated
346
    /// and the old value is returned.
347
    ///
348
    /// Returns an error if the selected keystore is not the primary keystore or one of the
349
    /// configured secondary stores.
350
302
    pub fn insert<K: ToEncodableKey>(
351
302
        &self,
352
302
        key: K,
353
302
        key_spec: &dyn KeySpecifier,
354
302
        selector: KeystoreSelector,
355
302
        overwrite: bool,
356
302
    ) -> Result<Option<K>> {
357
302
        let key = key.to_encodable_key();
358
302
        let store = self.select_keystore(&selector)?;
359
302
        let key_type = K::Key::item_type();
360
302
        let old_key: Option<K> = self.get_from_store(key_spec, &key_type, [store].into_iter())?;
361

            
362
302
        if old_key.is_some() && !overwrite {
363
2
            Err(crate::Error::KeyAlreadyExists)
364
        } else {
365
300
            let () = store.insert(&key, key_spec)?;
366
300
            Ok(old_key)
367
        }
368
302
    }
369

            
370
    /// Remove the key identified by `key_spec` from the [`Keystore`](crate::Keystore)
371
    /// specified by `selector`.
372
    ///
373
    /// Returns an error if the selected keystore is not the primary keystore or one of the
374
    /// configured secondary stores.
375
    ///
376
    /// Returns the value of the removed key,
377
    /// or `Ok(None)` if the key does not exist in the requested keystore.
378
    ///
379
    /// Returns `Err` if an error occurred while trying to remove the key.
380
44
    pub fn remove<K: ToEncodableKey>(
381
44
        &self,
382
44
        key_spec: &dyn KeySpecifier,
383
44
        selector: KeystoreSelector,
384
44
    ) -> Result<Option<K>> {
385
44
        let store = self.select_keystore(&selector)?;
386
42
        let key_type = K::Key::item_type();
387
42
        let old_key: Option<K> = self.get_from_store(key_spec, &key_type, [store].into_iter())?;
388

            
389
42
        store.remove(key_spec, &key_type)?;
390

            
391
42
        Ok(old_key)
392
44
    }
393

            
394
    /// Remove the specified keystore entry.
395
    ///
396
    /// Like [`KeyMgr::remove`], except this function does not return the value of the removed key.
397
    ///
398
    /// A return value of `Ok(None)` indicates the key was not found in the specified key store,
399
    /// whereas `Ok(Some(())` means the key was successfully removed.
400
    //
401
    // TODO: We should be consistent and return the removed key.
402
    //
403
    // This probably will involve changing the return type of Keystore::remove
404
    // to Result<Option<ErasedKey>>.
405
1724
    pub fn remove_entry(&self, entry: &KeystoreEntry) -> Result<Option<()>> {
406
1724
        let selector = entry.keystore_id().into();
407
1724
        let store = self.select_keystore(&selector)?;
408

            
409
1724
        store.remove(entry.key_path(), entry.key_type())
410
1724
    }
411

            
412
    /// Remove the specified keystore entry.
413
    ///
414
    /// Similar to [`KeyMgr::remove_entry`], except this method accepts both recognized and
415
    /// unrecognized entries, identified by a raw id (in the form of a `&str`) and a
416
    /// [`KeystoreId`].
417
    ///
418
    /// Returns an error if the entry could not be removed, or if the entry doesn't exist.
419
    #[cfg(feature = "onion-service-cli-extra")]
420
4
    pub fn remove_unchecked(&self, raw_id: &str, keystore_id: &KeystoreId) -> Result<()> {
421
4
        let selector = KeystoreSelector::from(keystore_id);
422
4
        let store = self.select_keystore(&selector)?;
423
4
        let raw_id = store.raw_entry_id(raw_id)?;
424
4
        let store = self.select_keystore(&selector)?;
425
4
        store.remove_unchecked(&raw_id)
426
4
    }
427

            
428
    /// Return the keystore entry descriptors of the keys matching the specified [`KeyPathPattern`].
429
    ///
430
    /// NOTE: This searches for matching keys in _all_ keystores.
431
    ///
432
    /// NOTE: This function only returns the *recognized* entries that match the provided pattern.
433
    /// The unrecognized entries (i.e. those that do not have a valid [`KeyPath`]) will be filtered out,
434
    /// even if they match the specified pattern.
435
12328
    pub fn list_matching(&self, pat: &KeyPathPattern) -> Result<Vec<KeystoreEntry>> {
436
12328
        self.all_stores()
437
12884
            .map(|store| -> Result<Vec<_>> {
438
12572
                Ok(store
439
12572
                    .list()?
440
12572
                    .into_iter()
441
54342
                    .filter_map(|entry| entry.ok())
442
53860
                    .filter(|entry| entry.key_path().matches(pat))
443
12572
                    .collect::<Vec<_>>())
444
12572
            })
445
12328
            .flatten_ok()
446
12328
            .collect::<Result<Vec<_>>>()
447
12328
    }
448

            
449
    /// List keys and certificates of the specified keystore.
450
    #[cfg(feature = "onion-service-cli-extra")]
451
404
    pub fn list_by_id(&self, id: &KeystoreId) -> Result<Vec<KeystoreEntryResult<KeystoreEntry>>> {
452
404
        self.find_keystore(id)?.list()
453
404
    }
454

            
455
    /// List keys and certificates of all the keystores.
456
    #[cfg(feature = "onion-service-cli-extra")]
457
122
    pub fn list(&self) -> Result<Vec<KeystoreEntryResult<KeystoreEntry>>> {
458
122
        self.all_stores()
459
210
            .map(|store| -> Result<Vec<_>> { store.list() })
460
122
            .flatten_ok()
461
122
            .collect::<Result<Vec<_>>>()
462
122
    }
463

            
464
    /// List all the configured keystore.
465
    #[cfg(feature = "onion-service-cli-extra")]
466
122
    pub fn list_keystores(&self) -> Vec<KeystoreId> {
467
122
        self.all_stores()
468
170
            .map(|store| store.id().to_owned())
469
122
            .collect()
470
122
    }
471

            
472
    /// Describe the specified key.
473
    ///
474
    /// Returns `None` if none of the registered
475
    /// [`KeyPathInfoExtractor`]s is able to parse the specified [`KeyPath`].
476
    ///
477
    /// This function uses the [`KeyPathInfoExtractor`]s registered using
478
    /// [`register_key_info_extractor`](crate::register_key_info_extractor),
479
    /// or by [`DefaultKeySpecifier`](crate::derive_deftly_template_KeySpecifier).
480
800
    pub fn describe(&self, path: &KeyPath) -> Option<KeyPathInfo> {
481
3000
        for info_extractor in &self.key_info_extractors {
482
3000
            if let Ok(info) = info_extractor.describe(path) {
483
720
                return Some(info);
484
2280
            }
485
        }
486

            
487
80
        None
488
800
    }
489

            
490
    /// Attempt to retrieve a key from one of the specified `stores`.
491
    ///
492
    /// Returns the `<K as ToEncodableKey>::Key` representation of the key.
493
    ///
494
    /// See [`KeyMgr::get`] for more details.
495
3449
    fn get_from_store_raw<'a, K: ItemType>(
496
3449
        &self,
497
3449
        key_spec: &dyn KeySpecifier,
498
3449
        key_type: &KeystoreItemType,
499
3449
        stores: impl Iterator<Item = &'a BoxedKeystore>,
500
3449
    ) -> Result<Option<K>> {
501
3449
        let static_key_type = K::item_type();
502
3449
        if key_type != &static_key_type {
503
            return Err(internal!(
504
                "key type {:?} does not match the key type {:?} of requested key K::Key",
505
                key_type,
506
                static_key_type
507
            )
508
            .into());
509
3449
        }
510

            
511
3613
        for store in stores {
512
3613
            let key = match store.get(key_spec, &K::item_type()) {
513
                Ok(None) => {
514
                    // The key doesn't exist in this store, so we check the next one...
515
1366
                    continue;
516
                }
517
2247
                Ok(Some(k)) => k,
518
                Err(e) => {
519
                    // Note: we immediately return if one of the keystores is inaccessible.
520
                    return Err(e);
521
                }
522
            };
523

            
524
            // Found it! Now try to downcast it to the right type (this should _not_ fail)...
525
2247
            let key: K = key
526
2247
                .downcast::<K>()
527
2247
                .map(|k| *k)
528
2247
                .map_err(|_| internal!("failed to downcast key to requested type"))?;
529

            
530
2247
            return Ok(Some(key));
531
        }
532

            
533
1202
        Ok(None)
534
3449
    }
535

            
536
    /// Attempt to retrieve a certificate from one of the specified `stores`.
537
    #[cfg(feature = "experimental-api")]
538
22
    fn get_cert_from_store<'a, K: ToEncodableKey, C: ToEncodableCert<K>>(
539
22
        &self,
540
22
        cert_spec: &dyn KeySpecifier,
541
22
        cert_type: &KeystoreItemType,
542
22
        signing_cert_spec: &dyn KeySpecifier,
543
22
        subject_cert_spec: &dyn KeySpecifier,
544
22
        stores: impl Iterator<Item = &'a BoxedKeystore>,
545
22
    ) -> Result<Option<C>> {
546
22
        let Some(cert) = self.get_from_store_raw::<C::ParsedCert>(cert_spec, cert_type, stores)?
547
        else {
548
            return Ok(None);
549
        };
550

            
551
        // Get the subject key...
552
22
        let Some(subject) =
553
22
            self.get_from_store::<K>(subject_cert_spec, &K::Key::item_type(), self.all_stores())?
554
        else {
555
            return Ok(None);
556
        };
557
22
        let signed_with = self.get_cert_signing_key::<K, C>(signing_cert_spec)?;
558
22
        let cert = C::validate(cert, &subject, &signed_with)?;
559

            
560
20
        Ok(Some(cert))
561
22
    }
562

            
563
    /// Attempt to retrieve a key from one of the specified `stores`.
564
    ///
565
    /// See [`KeyMgr::get`] for more details.
566
3146
    fn get_from_store<'a, K: ToEncodableKey>(
567
3146
        &self,
568
3146
        key_spec: &dyn KeySpecifier,
569
3146
        key_type: &KeystoreItemType,
570
3146
        stores: impl Iterator<Item = &'a BoxedKeystore> + Clone,
571
3146
    ) -> Result<Option<K>> {
572
3146
        let Some(key) = self.get_from_store_raw::<K::Key>(key_spec, key_type, stores.clone())?
573
        else {
574
            // If the key_spec is the specifier for the public part of a keypair,
575
            // try getting the pair and extracting the public portion from it.
576
1049
            let Some(key_pair_spec) = key_spec.keypair_specifier() else {
577
711
                return Ok(None);
578
            };
579

            
580
338
            let key_type = <K::KeyPair as ToEncodableKey>::Key::item_type();
581
338
            return Ok(self
582
338
                .get_from_store::<K::KeyPair>(&*key_pair_spec, &key_type, stores)?
583
338
                .map(|k| k.into()));
584
        };
585

            
586
2097
        Ok(Some(K::from_encodable_key(key)))
587
3146
    }
588

            
589
    /// Read the specified key and certificate from one of the key stores,
590
    /// deserializing the subject key as `K::Key`, the cert as `C::Cert`,
591
    /// and the signing key as `C::SigningKey`.
592
    ///
593
    /// Returns `Ok(None)` if none of the key stores have the requested key.
594
    ///
595
    // Note: the behavior of this function is a bit inconsistent with
596
    // get_or_generate_key_and_cert: here, if the cert is absent but
597
    // its subject key is not, we return Ok(None).
598
    // In get_or_generate_key_and_cert, OTOH< we return an error in that case
599
    // (because we can't possibly generate the missing subject key
600
    // without overwriting the cert of the missing key).
601
    ///
602
    /// This function validates the certificate using [`ToEncodableCert::validate`],
603
    /// returning an error if it is invalid or missing.
604
    #[cfg(feature = "experimental-api")]
605
4
    pub fn get_key_and_cert<K, C>(
606
4
        &self,
607
4
        spec: &dyn KeyCertificateSpecifier,
608
4
        signing_key_spec: &dyn KeySpecifier,
609
4
    ) -> Result<Option<(K, C)>>
610
4
    where
611
4
        K: ToEncodableKey,
612
4
        C: ToEncodableCert<K>,
613
    {
614
4
        let subject_key_spec = spec.subject_key_specifier();
615
        // Get the subject key...
616
4
        let Some(key) =
617
4
            self.get_from_store::<K>(subject_key_spec, &K::Key::item_type(), self.all_stores())?
618
        else {
619
            return Ok(None);
620
        };
621

            
622
4
        let cert_spec = spec
623
4
            .arti_path()
624
4
            .map_err(into_bad_api_usage!("invalid key certificate specifier"))?;
625

            
626
4
        let Some(cert) = self.get_from_store_raw::<C::ParsedCert>(
627
4
            &cert_spec,
628
4
            &<C::ParsedCert as ItemType>::item_type(),
629
4
            self.all_stores(),
630
        )?
631
        else {
632
            return Err(KeystoreCorruptionError::MissingCertificate.into());
633
        };
634

            
635
        // Finally, get the signing key and validate the cert
636
4
        let signed_with = self.get_cert_signing_key::<K, C>(signing_key_spec)?;
637
4
        let cert = C::validate(cert, &key, &signed_with)?;
638

            
639
4
        Ok(Some((key, cert)))
640
4
    }
641

            
642
    /// Like [`KeyMgr::get_key_and_cert`], except this function also generates the subject key
643
    /// and its corresponding certificate if they don't already exist.
644
    ///
645
    /// If the key certificate is missing, it will be generated
646
    /// from the subject key and signing key using the provided `make_certificate` callback.
647
    ///
648
    /// Generates the missing key and/or certificate as follows:
649
    ///
650
    /// ```text
651
    /// | Subject Key exists | Signing Key exists | Cert exists | Action                                 |
652
    /// |--------------------|--------------------|-------------|----------------------------------------|
653
    /// | Y                  | Y                  | Y           | Validate cert, return key and cert     |
654
    /// |                    |                    |             | if valid, error otherwise              |
655
    /// |--------------------|--------------------|-------------|----------------------------------------|
656
    /// | N                  | Y                  | N           | Generate subject key and               |
657
    /// |                    |                    |             | a new cert signed with signing key     |
658
    /// |--------------------|--------------------|-------------|----------------------------------------|
659
    /// | Y                  | Y                  | N           | Generate cert signed with signing key  |
660
    /// |--------------------|--------------------|-------------|----------------------------------------|
661
    /// | Y                  | N                  | N           | Error - cannot validate cert           |
662
    /// |                    |                    |             | if signing key is not available        |
663
    /// |--------------------|--------------------|-------------|----------------------------------------|
664
    /// | Y/N                | N                  | N           | Error - cannot generate cert           |
665
    /// |                    |                    |             | if signing key is not available        |
666
    /// |--------------------|--------------------|-------------|----------------------------------------|
667
    /// | N                  | Y/N                | Y           | Error - subject key was removed?       |
668
    /// |                    |                    |             | (we found the cert,                    |
669
    /// |                    |                    |             | but the subject key is missing)        |
670
    /// ```
671
    ///
672
    //
673
    // Note; the table above isn't a markdown table because CommonMark-flavor markdown
674
    // doesn't support multiline text in tables. Even if we trim down the text,
675
    // the resulting markdown table would be pretty unreadable in raw form
676
    // (it would have several excessively long lines, over 120 chars in len).
677
    #[cfg(feature = "experimental-api")]
678
60
    pub fn get_or_generate_key_and_cert<K, C>(
679
60
        &self,
680
60
        spec: &dyn KeyCertificateSpecifier,
681
60
        signing_key_spec: &dyn KeySpecifier,
682
60
        make_certificate: impl FnOnce(&K, &<C as ToEncodableCert<K>>::SigningKey) -> C,
683
60
        selector: KeystoreSelector,
684
60
        rng: &mut dyn KeygenRng,
685
60
    ) -> Result<(K, C)>
686
60
    where
687
60
        K: ToEncodableKey,
688
60
        K::Key: Keygen,
689
60
        C: ToEncodableCert<K>,
690
    {
691
60
        let subject_key_spec = spec.subject_key_specifier();
692
60
        let subject_key_arti_path = subject_key_spec
693
60
            .arti_path()
694
60
            .map_err(|_| bad_api_usage!("subject key does not have an ArtiPath?!"))?;
695

            
696
60
        let cert_specifier =
697
60
            ArtiPath::from_path_and_denotators(subject_key_arti_path, &spec.cert_denotators())
698
60
                .map_err(into_bad_api_usage!("invalid certificate specifier"))?;
699

            
700
60
        let maybe_cert = self.get_from_store_raw::<C::ParsedCert>(
701
60
            &cert_specifier,
702
60
            &C::ParsedCert::item_type(),
703
60
            self.all_stores(),
704
        )?;
705

            
706
60
        let maybe_subject_key = self.get::<K>(subject_key_spec)?;
707

            
708
60
        match (&maybe_cert, &maybe_subject_key) {
709
            (Some(_), None) => {
710
                return Err(KeystoreCorruptionError::MissingSubjectKey.into());
711
            }
712
60
            _ => {
713
60
                // generate key and/or cert
714
60
            }
715
        }
716
60
        let subject_key = match maybe_subject_key {
717
18
            Some(key) => key,
718
            _ => {
719
42
                let subject_keypair_spec =
720
42
                    subject_key_spec.keypair_specifier().ok_or_else(|| {
721
                        internal!(
722
                            "KeyCertificateSpecifier has no keypair specifier for the subject key?!"
723
                        )
724
                    })?;
725
42
                self.generate(&*subject_keypair_spec, selector, rng, false)?
726
            }
727
        };
728

            
729
60
        let signed_with = self.get_cert_signing_key::<K, C>(signing_key_spec)?;
730
56
        let cert = match maybe_cert {
731
            Some(cert) => C::validate(cert, &subject_key, &signed_with)?,
732
            None => {
733
56
                let cert = make_certificate(&subject_key, &signed_with);
734

            
735
56
                let () = self.insert_cert(cert.clone(), &cert_specifier, selector)?;
736

            
737
56
                cert
738
            }
739
        };
740

            
741
56
        Ok((subject_key, cert))
742
60
    }
743

            
744
    /// Return an iterator over all configured stores.
745
46056
    fn all_stores(&self) -> impl Iterator<Item = &BoxedKeystore> + Clone {
746
46056
        iter::once(&self.primary_store).chain(self.secondary_stores.iter())
747
46056
    }
748

            
749
    /// Return the [`Keystore`](crate::Keystore) matching the specified `selector`.
750
    ///
751
    /// Returns an error if the selected keystore is not the primary keystore or one of the
752
    /// configured secondary stores.
753
8980
    fn select_keystore(&self, selector: &KeystoreSelector) -> Result<&BoxedKeystore> {
754
8980
        match selector {
755
2566
            KeystoreSelector::Id(keystore_id) => self.find_keystore(keystore_id),
756
6414
            KeystoreSelector::Primary => Ok(&self.primary_store),
757
        }
758
8980
    }
759

            
760
    /// Return the [`Keystore`](crate::Keystore) with the specified `id`.
761
    ///
762
    /// Returns an error if the specified ID is not the ID of the primary keystore or
763
    /// the ID of one of the configured secondary stores.
764
3454
    fn find_keystore(&self, id: &KeystoreId) -> Result<&BoxedKeystore> {
765
3454
        self.all_stores()
766
4413
            .find(|keystore| keystore.id() == id)
767
3456
            .ok_or_else(|| crate::Error::KeystoreNotFound(id.clone()))
768
3454
    }
769

            
770
    /// Get the signing key of the certificate described by `spec`.
771
    ///
772
    /// Returns a [`KeystoreCorruptionError::MissingSigningKey`] error
773
    /// if the signing key doesn't exist in any of the keystores.
774
    #[cfg(feature = "experimental-api")]
775
86
    fn get_cert_signing_key<K, C>(
776
86
        &self,
777
86
        signing_key_spec: &dyn KeySpecifier,
778
86
    ) -> Result<C::SigningKey>
779
86
    where
780
86
        K: ToEncodableKey,
781
86
        C: ToEncodableCert<K>,
782
    {
783
86
        let Some(signing_key) = self.get_from_store::<C::SigningKey>(
784
86
            signing_key_spec,
785
86
            &<C::SigningKey as ToEncodableKey>::Key::item_type(),
786
86
            self.all_stores(),
787
        )?
788
        else {
789
4
            return Err(KeystoreCorruptionError::MissingSigningKey.into());
790
        };
791

            
792
82
        Ok(signing_key)
793
86
    }
794

            
795
    /// Insert `cert` into the [`Keystore`](crate::Keystore) specified by `selector`.
796
    ///
797
    /// If the key already exists in the specified key store, it will be overwritten.
798
    ///
799
    // NOTE: if we ever make this public we should rethink/improve its API.
800
    // TODO: maybe fold this into insert() somehow?
801
58
    fn insert_cert<K, C>(
802
58
        &self,
803
58
        cert: C,
804
58
        cert_spec: &dyn KeySpecifier,
805
58
        selector: KeystoreSelector,
806
58
    ) -> Result<()>
807
58
    where
808
58
        K: ToEncodableKey,
809
58
        K::Key: Keygen,
810
58
        C: ToEncodableCert<K>,
811
    {
812
58
        let cert = cert.to_encodable_cert();
813
58
        let store = self.select_keystore(&selector)?;
814

            
815
58
        let () = store.insert(&cert, cert_spec)?;
816
58
        Ok(())
817
58
    }
818
}
819

            
820
#[cfg(test)]
821
mod tests {
822
    // @@ begin test lint list maintained by maint/add_warning @@
823
    #![allow(clippy::bool_assert_comparison)]
824
    #![allow(clippy::clone_on_copy)]
825
    #![allow(clippy::dbg_macro)]
826
    #![allow(clippy::mixed_attributes_style)]
827
    #![allow(clippy::print_stderr)]
828
    #![allow(clippy::print_stdout)]
829
    #![allow(clippy::single_char_pattern)]
830
    #![allow(clippy::unwrap_used)]
831
    #![allow(clippy::unchecked_time_subtraction)]
832
    #![allow(clippy::useless_vec)]
833
    #![allow(clippy::needless_pass_by_value)]
834
    #![allow(clippy::string_slice)] // See arti#2571
835
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
836
    use super::*;
837
    use crate::keystore::arti::err::{ArtiNativeKeystoreError, MalformedPathError};
838
    use crate::raw::RawEntryId;
839
    use crate::test_utils::{TestDerivedKeySpecifier, TestDerivedKeypairSpecifier};
840
    use crate::{
841
        ArtiPath, ArtiPathUnavailableError, Error, KeyPath, KeystoreEntryResult, KeystoreError,
842
        UnrecognizedEntry, UnrecognizedEntryError,
843
    };
844
    use std::path::PathBuf;
845
    use std::result::Result as StdResult;
846
    use std::str::FromStr;
847
    use std::sync::{Arc, RwLock};
848
    use tor_basic_utils::test_rng::testing_rng;
849
    use tor_cert::CertifiedKey;
850
    use tor_cert::Ed25519Cert;
851
    use tor_checkable::TimeValidityError;
852
    use tor_error::{ErrorKind, HasKind};
853
    use tor_key_forge::{
854
        CertData, CertType, EncodableItem, EncodedEd25519Cert, ErasedKey, InvalidCertError,
855
        KeyType, KeystoreItem,
856
    };
857
    use tor_llcrypto::pk::ed25519::{self, Ed25519PublicKey as _};
858
    use tor_llcrypto::rng::FakeEntropicRng;
859
    use web_time_compat::{Duration, SystemTime, SystemTimeExt};
860

            
861
    #[cfg(feature = "experimental-api")]
862
    use {
863
        crate::CertSpecifierPattern,
864
        crate::test_utils::{TestCertSpecifier, TestCertSpecifierPattern},
865
    };
866

            
867
    /// Metadata structure for tracking key operations in tests.
868
    #[derive(Clone, Debug, PartialEq)]
869
    struct KeyMetadata {
870
        /// The identifier for the item (e.g., "coot", "moorhen").
871
        item_id: String,
872
        /// The keystore from which the item was retrieved.
873
        ///
874
        /// Set by `Keystore::get`.
875
        retrieved_from: Option<KeystoreId>,
876
        /// Whether the item was generated via `Keygen::generate`.
877
        is_generated: bool,
878
    }
879

            
880
    /// Metadata structure for tracking certificate operations in tests.
881
    #[derive(Clone, Debug, PartialEq)]
882
    struct CertMetadata {
883
        /// The identifier for the subject key (e.g., "coot").
884
        subject_key_id: String,
885
        /// The identifier for the signing key (e.g., "moorhen").
886
        signing_key_id: String,
887
        /// The keystore from which the certificate was retrieved.
888
        ///
889
        /// Set by `Keystore::get`.
890
        retrieved_from: Option<KeystoreId>,
891
        /// Whether the certificate was freshly generated (i.e. returned from the "or generate"
892
        /// branch of `get_or_generate()`) or retrieved from a keystore.
893
        is_generated: bool,
894
    }
895

            
896
    /// Metadata structure for tracking item operations in tests.
897
    #[derive(Clone, Debug, PartialEq, derive_more::From)]
898
    enum ItemMetadata {
899
        /// Metadata about a key.
900
        Key(KeyMetadata),
901
        /// Metadata about a certificate.
902
        Cert(CertMetadata),
903
    }
904

            
905
    impl ItemMetadata {
906
        /// Get the item ID.
907
        ///
908
        /// For keys, this returns the key's ID.
909
        /// For certificates, this returns a formatted string identifying the subject key.
910
        fn item_id(&self) -> &str {
911
            match self {
912
                ItemMetadata::Key(k) => &k.item_id,
913
                ItemMetadata::Cert(c) => &c.subject_key_id,
914
            }
915
        }
916

            
917
        /// Get retrieved_from.
918
        fn retrieved_from(&self) -> Option<&KeystoreId> {
919
            match self {
920
                ItemMetadata::Key(k) => k.retrieved_from.as_ref(),
921
                ItemMetadata::Cert(c) => c.retrieved_from.as_ref(),
922
            }
923
        }
924

            
925
        /// Get is_generated.
926
        fn is_generated(&self) -> bool {
927
            match self {
928
                ItemMetadata::Key(k) => k.is_generated,
929
                ItemMetadata::Cert(c) => c.is_generated,
930
            }
931
        }
932

            
933
        /// Set the retrieved_from field to the specified keystore ID.
934
        fn set_retrieved_from(&mut self, id: KeystoreId) {
935
            match self {
936
                ItemMetadata::Key(meta) => meta.retrieved_from = Some(id),
937
                ItemMetadata::Cert(meta) => meta.retrieved_from = Some(id),
938
            }
939
        }
940

            
941
        /// Returns a reference to key metadata if this is a Key variant.
942
        fn as_key(&self) -> Option<&KeyMetadata> {
943
            match self {
944
                ItemMetadata::Key(meta) => Some(meta),
945
                _ => None,
946
            }
947
        }
948

            
949
        /// Returns a reference to certificate metadata if this is a Cert variant.
950
        fn as_cert(&self) -> Option<&CertMetadata> {
951
            match self {
952
                ItemMetadata::Cert(meta) => Some(meta),
953
                _ => None,
954
            }
955
        }
956
    }
957

            
958
    /// The type of "key" stored in the test key stores.
959
    #[derive(Clone, Debug)]
960
    struct TestItem {
961
        /// The underlying key.
962
        item: KeystoreItem,
963
        /// Metadata about the key.
964
        meta: ItemMetadata,
965
    }
966

            
967
    /// The type of certificate stored in the test key stores.
968
    struct TestCert(TestItem);
969

            
970
    impl ItemType for TestCert {
971
        fn item_type() -> KeystoreItemType
972
        where
973
            Self: Sized,
974
        {
975
            CertType::Ed25519TorCert.into()
976
        }
977
    }
978

            
979
    /// A "certificate" used for testing purposes.
980
    #[derive(Clone, Debug)]
981
    struct AlwaysValidCert(TestItem);
982

            
983
    /// An expired "certificate" used for testing purposes.
984
    #[derive(Clone, Debug)]
985
    struct AlwaysExpiredCert(TestItem);
986

            
987
    /// The corresponding fake public key type.
988
    #[derive(Clone, Debug)]
989
    struct TestPublicKey {
990
        /// The underlying key.
991
        key: KeystoreItem,
992
        /// Metadata about the key.
993
        meta: ItemMetadata,
994
    }
995

            
996
    impl From<TestItem> for TestPublicKey {
997
        fn from(tk: TestItem) -> TestPublicKey {
998
            TestPublicKey {
999
                key: tk.item,
                meta: tk.meta,
            }
        }
    }
    impl TestItem {
        /// Create a new test key with the specified metadata.
        fn new(item_id: &str) -> Self {
            let mut rng = testing_rng();
            TestItem {
                item: ed25519::Keypair::generate(&mut rng)
                    .as_keystore_item()
                    .unwrap(),
                meta: ItemMetadata::Key(KeyMetadata {
                    item_id: item_id.to_string(),
                    retrieved_from: None,
                    is_generated: false,
                }),
            }
        }
    }
    impl Keygen for TestItem {
        fn generate(mut rng: &mut dyn KeygenRng) -> tor_key_forge::Result<Self>
        where
            Self: Sized,
        {
            Ok(TestItem {
                item: ed25519::Keypair::generate(&mut rng).as_keystore_item()?,
                meta: ItemMetadata::Key(KeyMetadata {
                    item_id: "generated_test_key".to_string(),
                    retrieved_from: None,
                    is_generated: true,
                }),
            })
        }
    }
    impl ItemType for TestItem {
        fn item_type() -> KeystoreItemType
        where
            Self: Sized,
        {
            // Dummy value
            KeyType::Ed25519Keypair.into()
        }
    }
    impl EncodableItem for TestItem {
        fn as_keystore_item(&self) -> tor_key_forge::Result<KeystoreItem> {
            Ok(self.item.clone())
        }
    }
    impl ToEncodableKey for TestItem {
        type Key = Self;
        type KeyPair = Self;
        fn to_encodable_key(self) -> Self::Key {
            self
        }
        fn from_encodable_key(key: Self::Key) -> Self {
            key
        }
    }
    impl ItemType for TestPublicKey {
        fn item_type() -> KeystoreItemType
        where
            Self: Sized,
        {
            KeyType::Ed25519PublicKey.into()
        }
    }
    impl EncodableItem for TestPublicKey {
        fn as_keystore_item(&self) -> tor_key_forge::Result<KeystoreItem> {
            Ok(self.key.clone())
        }
    }
    impl ToEncodableKey for TestPublicKey {
        type Key = Self;
        type KeyPair = TestItem;
        fn to_encodable_key(self) -> Self::Key {
            self
        }
        fn from_encodable_key(key: Self::Key) -> Self {
            key
        }
    }
    impl ToEncodableCert<TestItem> for AlwaysValidCert {
        type ParsedCert = TestCert;
        type EncodableCert = TestItem;
        type SigningKey = TestItem;
        fn validate(
            cert: Self::ParsedCert,
            _subject: &TestItem,
            _signed_with: &Self::SigningKey,
        ) -> StdResult<Self, InvalidCertError> {
            // AlwaysValidCert is always valid
            Ok(Self(cert.0))
        }
        /// Convert this cert to a type that implements [`EncodableKey`].
        fn to_encodable_cert(self) -> Self::EncodableCert {
            self.0
        }
    }
    impl ToEncodableCert<TestItem> for AlwaysExpiredCert {
        type ParsedCert = TestCert;
        type EncodableCert = TestItem;
        type SigningKey = TestItem;
        fn validate(
            _cert: Self::ParsedCert,
            _subject: &TestItem,
            _signed_with: &Self::SigningKey,
        ) -> StdResult<Self, InvalidCertError> {
            Err(InvalidCertError::TimeValidity(TimeValidityError::Expired(
                Duration::from_secs(60),
            )))
        }
        /// Convert this cert to a type that implements [`EncodableKey`].
        fn to_encodable_cert(self) -> Self::EncodableCert {
            self.0
        }
    }
    #[derive(thiserror::Error, Debug, Clone, derive_more::Display)]
    enum MockKeystoreError {
        NotFound,
    }
    impl KeystoreError for MockKeystoreError {}
    impl HasKind for MockKeystoreError {
        fn kind(&self) -> ErrorKind {
            // Return a dummy ErrorKind for the purposes of this test
            tor_error::ErrorKind::Other
        }
    }
    fn build_raw_id_path<T: ToString>(key_path: &T, key_type: &KeystoreItemType) -> RawEntryId {
        let mut path = key_path.to_string();
        path.push('.');
        path.push_str(&key_type.arti_extension());
        RawEntryId::Path(PathBuf::from(&path))
    }
    struct Keystore {
        inner: RwLock<Vec<KeystoreEntryResult<(ArtiPath, KeystoreItemType, TestItem)>>>,
        id: KeystoreId,
    }
    impl Keystore {
        fn new(id: &str) -> Self {
            let id = KeystoreId::from_str(id).unwrap();
            Self {
                inner: Default::default(),
                id,
            }
        }
        fn new_boxed(id: &str) -> BoxedKeystore {
            Box::new(Self::new(id))
        }
    }
    impl crate::Keystore for Keystore {
        fn contains(
            &self,
            key_spec: &dyn KeySpecifier,
            item_type: &KeystoreItemType,
        ) -> Result<bool> {
            let wanted_arti_path = key_spec.arti_path().unwrap();
            Ok(self.inner.read().unwrap().iter().any(|res| match res {
                Ok((spec, ty, _)) => spec == &wanted_arti_path && ty == item_type,
                Err(_) => false,
            }))
        }
        fn id(&self) -> &KeystoreId {
            &self.id
        }
        fn get(
            &self,
            key_spec: &dyn KeySpecifier,
            item_type: &KeystoreItemType,
        ) -> Result<Option<ErasedKey>> {
            let key_spec = key_spec.arti_path().unwrap();
            Ok(self.inner.read().unwrap().iter().find_map(|res| {
                if let Ok((arti_path, ty, k)) = res {
                    if arti_path == &key_spec && ty == item_type {
                        let mut k = k.clone();
                        k.meta.set_retrieved_from(self.id().clone());
                        match item_type {
                            KeystoreItemType::Key(_) => {
                                return Some(Box::new(k) as Box<dyn ItemType>);
                            }
                            KeystoreItemType::Cert(_) => {
                                // Hack: the KeyMgr code will want to downcast cert types
                                // to C::ParsedCert, so we need to avoid returning the bare
                                // TestItem here
                                return Some(Box::new(TestCert(k)) as Box<dyn ItemType>);
                            }
                            _ => panic!("unknown item type?!"),
                        }
                    }
                }
                None
            }))
        }
        #[cfg(feature = "onion-service-cli-extra")]
        fn raw_entry_id(&self, raw_id: &str) -> Result<RawEntryId> {
            Ok(RawEntryId::Path(PathBuf::from(raw_id.to_string())))
        }
        fn insert(&self, key: &dyn EncodableItem, key_spec: &dyn KeySpecifier) -> Result<()> {
            let key = key.downcast_ref::<TestItem>().unwrap();
            let item = key.as_keystore_item()?;
            let item_type = item.item_type()?;
            self.inner
                .write()
                .unwrap()
                // TODO: `insert` is used instead of `push`, because some of the
                // tests (mainly `insert_and_get` and `keygen`) fail otherwise.
                // It could be a good idea to use `push` and adapt the tests,
                // in order to reduce cognitive complexity.
                .insert(
                    0,
                    Ok((key_spec.arti_path().unwrap(), item_type, key.clone())),
                );
            Ok(())
        }
        fn remove(
            &self,
            key_spec: &dyn KeySpecifier,
            item_type: &KeystoreItemType,
        ) -> Result<Option<()>> {
            let wanted_arti_path = key_spec.arti_path().unwrap();
            let index = self.inner.read().unwrap().iter().position(|res| {
                if let Ok((arti_path, ty, _)) = res {
                    arti_path == &wanted_arti_path && ty == item_type
                } else {
                    false
                }
            });
            let Some(index) = index else {
                return Ok(None);
            };
            let _ = self.inner.write().unwrap().remove(index);
            Ok(Some(()))
        }
        #[cfg(feature = "onion-service-cli-extra")]
        fn remove_unchecked(&self, entry_id: &RawEntryId) -> Result<()> {
            let index = self.inner.read().unwrap().iter().position(|res| match res {
                Ok((spec, ty, _)) => {
                    let id = build_raw_id_path(spec, ty);
                    entry_id == &id
                }
                Err(e) => e.entry().raw_id() == entry_id,
            });
            let Some(index) = index else {
                return Err(Error::Keystore(Arc::new(MockKeystoreError::NotFound)));
            };
            let _ = self.inner.write().unwrap().remove(index);
            Ok(())
        }
        fn list(&self) -> Result<Vec<KeystoreEntryResult<KeystoreEntry>>> {
            Ok(self
                .inner
                .read()
                .unwrap()
                .iter()
                .map(|res| match res {
                    Ok((arti_path, ty, _)) => {
                        let raw_id = RawEntryId::Path(PathBuf::from(&arti_path.to_string()));
                        Ok(KeystoreEntry::new(
                            KeyPath::Arti(arti_path.clone()),
                            ty.clone(),
                            self.id(),
                            raw_id,
                        ))
                    }
                    Err(e) => Err(e.clone()),
                })
                .collect())
        }
    }
    // Populate `keystore` with the specified number of unrecognized entries.
    fn add_unrecognized_entries(keystore: &mut Keystore, count: usize) {
        for i in 0..count {
            let invalid_key_path = PathBuf::from(&format!("unrecognized_entry{}", i));
            let raw_id = RawEntryId::Path(invalid_key_path.clone());
            let entry = UnrecognizedEntry::new(raw_id, keystore.id.clone());
            let entry = UnrecognizedEntryError::new(
                entry,
                Arc::new(ArtiNativeKeystoreError::MalformedPath {
                    path: invalid_key_path,
                    err: MalformedPathError::NoExtension,
                }),
            );
            keystore.inner.write().unwrap().push(Err(entry));
        }
    }
    macro_rules! impl_specifier {
        ($name:tt, $id:expr) => {
            struct $name;
            impl KeySpecifier for $name {
                fn arti_path(&self) -> StdResult<ArtiPath, ArtiPathUnavailableError> {
                    Ok(ArtiPath::new($id.into()).map_err(|e| tor_error::internal!("{e}"))?)
                }
                fn ctor_path(&self) -> Option<crate::CTorPath> {
                    None
                }
                fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>> {
                    None
                }
            }
        };
    }
    impl_specifier!(TestKeySpecifier1, "spec1");
    impl_specifier!(TestKeySpecifier2, "spec2");
    impl_specifier!(TestKeySpecifier3, "spec3");
    impl_specifier!(TestKeySpecifier4, "spec4");
    impl_specifier!(TestPublicKeySpecifier1, "pub-spec1");
    /// Create a test `KeystoreEntry`.
    fn entry_descriptor(
        specifier: impl KeySpecifier,
        key_type: KeystoreItemType,
        keystore_id: &KeystoreId,
    ) -> KeystoreEntry {
        let arti_path = specifier.arti_path().unwrap();
        let raw_id = RawEntryId::Path(PathBuf::from(arti_path.as_ref()));
        KeystoreEntry {
            key_path: arti_path.into(),
            key_type,
            keystore_id,
            raw_id,
        }
    }
    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn insert_and_get() {
        let mut builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed("keystore1"));
        builder.secondary_stores().extend([
            Keystore::new_boxed("keystore2"),
            Keystore::new_boxed("keystore3"),
        ]);
        let mgr = builder.build().unwrap();
        // Insert a key into Keystore2
        let old_key = mgr
            .insert(
                TestItem::new("coot"),
                &TestKeySpecifier1,
                KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
                true,
            )
            .unwrap();
        assert!(old_key.is_none());
        let key = mgr.get::<TestItem>(&TestKeySpecifier1).unwrap().unwrap();
        assert_eq!(key.meta.item_id(), "coot");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore2").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
        // Insert a different key using the _same_ key specifier.
        let old_key = mgr
            .insert(
                TestItem::new("gull"),
                &TestKeySpecifier1,
                KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
                true,
            )
            .unwrap()
            .unwrap();
        assert_eq!(old_key.meta.item_id(), "coot");
        assert_eq!(
            old_key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore2").unwrap())
        );
        assert_eq!(old_key.meta.is_generated(), false);
        // Check that the original value was overwritten:
        let key = mgr.get::<TestItem>(&TestKeySpecifier1).unwrap().unwrap();
        assert_eq!(key.meta.item_id(), "gull");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore2").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
        // Insert a different key using the _same_ key specifier (overwrite = false)
        let err = mgr
            .insert(
                TestItem::new("gull"),
                &TestKeySpecifier1,
                KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
                false,
            )
            .unwrap_err();
        assert!(matches!(err, crate::Error::KeyAlreadyExists));
        // Insert a new key into Keystore2 (overwrite = false)
        let old_key = mgr
            .insert(
                TestItem::new("penguin"),
                &TestKeySpecifier2,
                KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
                false,
            )
            .unwrap();
        assert!(old_key.is_none());
        // Insert a key into the primary keystore
        let old_key = mgr
            .insert(
                TestItem::new("moorhen"),
                &TestKeySpecifier3,
                KeystoreSelector::Primary,
                true,
            )
            .unwrap();
        assert!(old_key.is_none());
        let key = mgr.get::<TestItem>(&TestKeySpecifier3).unwrap().unwrap();
        assert_eq!(key.meta.item_id(), "moorhen");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore1").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
        // The key doesn't exist in any of the stores yet.
        assert!(mgr.get::<TestItem>(&TestKeySpecifier4).unwrap().is_none());
        // Insert the same key into all 3 key stores, in reverse order of keystore priority
        // (otherwise KeyMgr::get will return the key from the primary store for each iteration and
        // we won't be able to see the key was actually inserted in each store).
        for store in ["keystore3", "keystore2", "keystore1"] {
            let old_key = mgr
                .insert(
                    TestItem::new("cormorant"),
                    &TestKeySpecifier4,
                    KeystoreSelector::Id(&KeystoreId::from_str(store).unwrap()),
                    true,
                )
                .unwrap();
            assert!(old_key.is_none());
            // Ensure the key now exists in `store`.
            let key = mgr.get::<TestItem>(&TestKeySpecifier4).unwrap().unwrap();
            assert_eq!(key.meta.item_id(), "cormorant");
            assert_eq!(
                key.meta.retrieved_from(),
                Some(&KeystoreId::from_str(store).unwrap())
            );
            assert_eq!(key.meta.is_generated(), false);
        }
        // The key exists in all key stores, but if no keystore_id is specified, we return the
        // value from the first key store it is found in (in this case, Keystore1)
        let key = mgr.get::<TestItem>(&TestKeySpecifier4).unwrap().unwrap();
        assert_eq!(key.meta.item_id(), "cormorant");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore1").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
    }
    #[test]
    #[cfg(feature = "onion-service-cli-extra")]
    fn get_from() {
        let mut builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed("keystore1"));
        builder.secondary_stores().extend([
            Keystore::new_boxed("keystore2"),
            Keystore::new_boxed("keystore3"),
        ]);
        let mgr = builder.build().unwrap();
        let keystore1_id = KeystoreId::from_str("keystore1").unwrap();
        let keystore2_id = KeystoreId::from_str("keystore2").unwrap();
        let key_id_1 = "mantis shrimp";
        let key_id_2 = "tardigrade";
        // Insert a key into Keystore1
        let _ = mgr
            .insert(
                TestItem::new(key_id_1),
                &TestKeySpecifier1,
                KeystoreSelector::Id(&keystore1_id),
                true,
            )
            .unwrap();
        // Insert a key into Keystore2
        let _ = mgr
            .insert(
                TestItem::new(key_id_2),
                &TestKeySpecifier1,
                KeystoreSelector::Id(&keystore2_id),
                true,
            )
            .unwrap();
        // Retrieve key
        let key = mgr
            .get_from::<TestItem>(&TestKeySpecifier1, &keystore2_id)
            .unwrap()
            .unwrap();
        assert_eq!(key.meta.item_id(), key_id_2);
        assert_eq!(key.meta.retrieved_from(), Some(&keystore2_id));
    }
    #[test]
    fn get_from_keypair() {
        const KEYSTORE_ID1: &str = "keystore1";
        const KEYSTORE_ID2: &str = "keystore2";
        let mut builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed(KEYSTORE_ID1));
        builder
            .secondary_stores()
            .extend([Keystore::new_boxed(KEYSTORE_ID2)]);
        let mgr = builder.build().unwrap();
        let keystore2 = KeystoreId::from_str(KEYSTORE_ID2).unwrap();
        // Insert a key into Keystore2
        let _ = mgr
            .insert(
                TestItem::new("nightjar"),
                &TestDerivedKeypairSpecifier,
                KeystoreSelector::Id(&keystore2),
                true,
            )
            .unwrap();
        macro_rules! boxed {
            ($closure:expr) => {
                Box::new($closure) as _
            };
        }
        #[allow(clippy::type_complexity)]
        let getters: &[(&'static str, Box<dyn Fn() -> Result<Option<TestPublicKey>>>)] = &[
            (
                "get",
                boxed!(|| mgr.get::<TestPublicKey>(&TestDerivedKeySpecifier)),
            ),
            #[cfg(feature = "onion-service-cli-extra")]
            (
                "get_from",
                boxed!(|| mgr.get_from::<TestPublicKey>(&TestDerivedKeySpecifier, &keystore2)),
            ),
            (
                "remove",
                boxed!(|| mgr.remove::<TestPublicKey>(
                    &TestDerivedKeySpecifier,
                    KeystoreSelector::Id(&keystore2)
                )),
            ),
        ];
        for (test_name, getter) in getters {
            // Retrieve the public key (internally, the keymgr should be able
            // to extract it from the TestItem "keypair" type).
            let key = getter().unwrap().expect(test_name);
            assert_eq!(key.meta.item_id(), "nightjar", "{test_name}");
            assert_eq!(key.meta.retrieved_from(), Some(&keystore2), "{test_name}");
        }
    }
    #[test]
    fn remove() {
        let mut builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed("keystore1"));
        builder.secondary_stores().extend([
            Keystore::new_boxed("keystore2"),
            Keystore::new_boxed("keystore3"),
        ]);
        let mgr = builder.build().unwrap();
        assert!(
            !mgr.secondary_stores[0]
                .contains(&TestKeySpecifier1, &TestItem::item_type())
                .unwrap()
        );
        // Insert a key into Keystore2
        mgr.insert(
            TestItem::new("coot"),
            &TestKeySpecifier1,
            KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
            true,
        )
        .unwrap();
        let key = mgr.get::<TestItem>(&TestKeySpecifier1).unwrap().unwrap();
        assert_eq!(key.meta.item_id(), "coot");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore2").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
        // Try to remove the key from a non-existent key store
        assert!(
            mgr.remove::<TestItem>(
                &TestKeySpecifier1,
                KeystoreSelector::Id(&KeystoreId::from_str("not_an_id_we_know_of").unwrap())
            )
            .is_err()
        );
        // The key still exists in Keystore2
        assert!(
            mgr.secondary_stores[0]
                .contains(&TestKeySpecifier1, &TestItem::item_type())
                .unwrap()
        );
        // Try to remove the key from the primary key store
        assert!(
            mgr.remove::<TestItem>(&TestKeySpecifier1, KeystoreSelector::Primary)
                .unwrap()
                .is_none()
        );
        // The key still exists in Keystore2
        assert!(
            mgr.secondary_stores[0]
                .contains(&TestKeySpecifier1, &TestItem::item_type())
                .unwrap()
        );
        // Removing from Keystore2 should succeed.
        let removed_key = mgr
            .remove::<TestItem>(
                &TestKeySpecifier1,
                KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
            )
            .unwrap()
            .unwrap();
        assert_eq!(removed_key.meta.item_id(), "coot");
        assert_eq!(
            removed_key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore2").unwrap())
        );
        assert_eq!(removed_key.meta.is_generated(), false);
        // The key doesn't exist in Keystore2 anymore
        assert!(
            !mgr.secondary_stores[0]
                .contains(&TestKeySpecifier1, &TestItem::item_type())
                .unwrap()
        );
    }
    #[test]
    fn keygen() {
        let mut rng = FakeEntropicRng(testing_rng());
        let mgr = KeyMgrBuilder::default()
            .primary_store(Keystore::new_boxed("keystore1"))
            .build()
            .unwrap();
        mgr.insert(
            TestItem::new("coot"),
            &TestKeySpecifier1,
            KeystoreSelector::Primary,
            true,
        )
        .unwrap();
        // There is no corresponding public key entry.
        assert!(
            mgr.get::<TestPublicKey>(&TestPublicKeySpecifier1)
                .unwrap()
                .is_none()
        );
        // Try to generate a new key (overwrite = false)
        let err = mgr
            .generate::<TestItem>(
                &TestKeySpecifier1,
                KeystoreSelector::Primary,
                &mut rng,
                false,
            )
            .unwrap_err();
        assert!(matches!(err, crate::Error::KeyAlreadyExists));
        // The previous entry was not overwritten because overwrite = false
        let key = mgr.get::<TestItem>(&TestKeySpecifier1).unwrap().unwrap();
        assert_eq!(key.meta.item_id(), "coot");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore1").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
        // We don't store public keys in the keystore
        assert!(
            mgr.get::<TestPublicKey>(&TestPublicKeySpecifier1)
                .unwrap()
                .is_none()
        );
        // Try to generate a new key (overwrite = true)
        let generated_key = mgr
            .generate::<TestItem>(
                &TestKeySpecifier1,
                KeystoreSelector::Primary,
                &mut rng,
                true,
            )
            .unwrap();
        assert_eq!(generated_key.meta.item_id(), "generated_test_key");
        // Not set in a freshly generated key, because KeyMgr::generate()
        // returns it straight away, without going through Keystore::get()
        assert_eq!(generated_key.meta.retrieved_from(), None);
        assert_eq!(generated_key.meta.is_generated(), true);
        // Retrieve the inserted key
        let retrieved_key = mgr.get::<TestItem>(&TestKeySpecifier1).unwrap().unwrap();
        assert_eq!(retrieved_key.meta.item_id(), "generated_test_key");
        assert_eq!(
            retrieved_key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore1").unwrap())
        );
        assert_eq!(retrieved_key.meta.is_generated(), true);
        // We don't store public keys in the keystore
        assert!(
            mgr.get::<TestPublicKey>(&TestPublicKeySpecifier1)
                .unwrap()
                .is_none()
        );
    }
    #[test]
    fn get_or_generate() {
        let mut rng = FakeEntropicRng(testing_rng());
        let mut builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed("keystore1"));
        builder.secondary_stores().extend([
            Keystore::new_boxed("keystore2"),
            Keystore::new_boxed("keystore3"),
        ]);
        let mgr = builder.build().unwrap();
        let keystore2 = KeystoreId::from_str("keystore2").unwrap();
        let entry_desc1 = entry_descriptor(TestKeySpecifier1, TestItem::item_type(), &keystore2);
        assert!(mgr.get_entry::<TestItem>(&entry_desc1).unwrap().is_none());
        mgr.insert(
            TestItem::new("coot"),
            &TestKeySpecifier1,
            KeystoreSelector::Id(&keystore2),
            true,
        )
        .unwrap();
        // The key already exists in keystore 2 so it won't be auto-generated.
        let key = mgr
            .get_or_generate::<TestItem>(&TestKeySpecifier1, KeystoreSelector::Primary, &mut rng)
            .unwrap();
        assert_eq!(key.meta.item_id(), "coot");
        assert_eq!(
            key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore2").unwrap())
        );
        assert_eq!(key.meta.is_generated(), false);
        assert_eq!(
            mgr.get_entry::<TestItem>(&entry_desc1)
                .unwrap()
                .map(|k| k.meta),
            Some(ItemMetadata::Key(KeyMetadata {
                item_id: "coot".to_string(),
                retrieved_from: Some(keystore2.clone()),
                is_generated: false,
            }))
        );
        // This key doesn't exist in any of the keystores, so it will be auto-generated and
        // inserted into keystore 3.
        let keystore3 = KeystoreId::from_str("keystore3").unwrap();
        let generated_key = mgr
            .get_or_generate::<TestItem>(
                &TestKeySpecifier2,
                KeystoreSelector::Id(&keystore3),
                &mut rng,
            )
            .unwrap();
        assert_eq!(generated_key.meta.item_id(), "generated_test_key");
        // Not set in a freshly generated key, because KeyMgr::get_or_generate()
        // returns it straight away, without going through Keystore::get()
        assert_eq!(generated_key.meta.retrieved_from(), None);
        assert_eq!(generated_key.meta.is_generated(), true);
        // Retrieve the inserted key
        let retrieved_key = mgr.get::<TestItem>(&TestKeySpecifier2).unwrap().unwrap();
        assert_eq!(retrieved_key.meta.item_id(), "generated_test_key");
        assert_eq!(
            retrieved_key.meta.retrieved_from(),
            Some(&KeystoreId::from_str("keystore3").unwrap())
        );
        assert_eq!(retrieved_key.meta.is_generated(), true);
        let entry_desc2 = entry_descriptor(TestKeySpecifier2, TestItem::item_type(), &keystore3);
        assert_eq!(
            mgr.get_entry::<TestItem>(&entry_desc2)
                .unwrap()
                .map(|k| k.meta),
            Some(ItemMetadata::Key(KeyMetadata {
                item_id: "generated_test_key".to_string(),
                retrieved_from: Some(keystore3.clone()),
                is_generated: true,
            }))
        );
        let arti_pat = KeyPathPattern::Arti("*".to_string());
        let matching = mgr.list_matching(&arti_pat).unwrap();
        assert_eq!(matching.len(), 2);
        assert!(matching.contains(&entry_desc1));
        assert!(matching.contains(&entry_desc2));
        assert_eq!(mgr.remove_entry(&entry_desc2).unwrap(), Some(()));
        assert!(mgr.get_entry::<TestItem>(&entry_desc2).unwrap().is_none());
        assert!(mgr.remove_entry(&entry_desc2).unwrap().is_none());
    }
    #[test]
    fn list_matching_ignores_unrecognized_keys() {
        let mut keystore = Keystore::new("keystore1");
        add_unrecognized_entries(&mut keystore, 1);
        let builder = KeyMgrBuilder::default().primary_store(Box::new(keystore));
        let mgr = builder.build().unwrap();
        let keystore1 = KeystoreId::from_str("keystore1").unwrap();
        mgr.insert(
            TestItem::new("whale shark"),
            &TestKeySpecifier1,
            KeystoreSelector::Id(&keystore1),
            true,
        )
        .unwrap();
        let arti_pat = KeyPathPattern::Arti("*".to_string());
        let valid_key_path = KeyPath::Arti(TestKeySpecifier1.arti_path().unwrap());
        let matching = mgr.list_matching(&arti_pat).unwrap();
        // assert the unrecognized key has been filtered out
        assert_eq!(matching.len(), 1);
        assert_eq!(matching.first().unwrap().key_path(), &valid_key_path);
    }
    #[cfg(feature = "onion-service-cli-extra")]
    #[test]
    /// Test all `arti keys` subcommands
    // TODO: split this in different tests
    fn keys_subcommands() {
        let mut keystore = Keystore::new("keystore1");
        add_unrecognized_entries(&mut keystore, 1);
        let mut builder = KeyMgrBuilder::default().primary_store(Box::new(keystore));
        builder.secondary_stores().extend([
            Keystore::new_boxed("keystore2"),
            Keystore::new_boxed("keystore3"),
        ]);
        let mgr = builder.build().unwrap();
        let keystore1id = KeystoreId::from_str("keystore1").unwrap();
        let keystore2id = KeystoreId::from_str("keystore2").unwrap();
        let keystore3id = KeystoreId::from_str("keystore3").unwrap();
        // Insert a key into Keystore1
        let _ = mgr
            .insert(
                TestItem::new("pangolin"),
                &TestKeySpecifier1,
                KeystoreSelector::Id(&keystore1id),
                true,
            )
            .unwrap();
        // Insert a key into Keystore2
        let _ = mgr
            .insert(
                TestItem::new("coot"),
                &TestKeySpecifier2,
                KeystoreSelector::Id(&keystore2id),
                true,
            )
            .unwrap();
        // Insert a key into Keystore3
        let _ = mgr
            .insert(
                TestItem::new("penguin"),
                &TestKeySpecifier3,
                KeystoreSelector::Id(&keystore3id),
                true,
            )
            .unwrap();
        let assert_key = |path, ty, expected_path: &ArtiPath, expected_type| {
            assert_eq!(ty, expected_type);
            assert_eq!(path, &KeyPath::Arti(expected_path.clone()));
        };
        let item_type = TestItem::new("axolotl").item.item_type().unwrap();
        let unrecognized_entry_id = RawEntryId::Path(PathBuf::from("unrecognized_entry0"));
        // Test `list`
        let entries = mgr.list().unwrap();
        let expected_items = [
            (keystore1id, TestKeySpecifier1.arti_path().unwrap()),
            (keystore2id, TestKeySpecifier2.arti_path().unwrap()),
            (keystore3id, TestKeySpecifier3.arti_path().unwrap()),
        ];
        // Secondary keystores contain 1 valid key each
        let mut recognized_entries = 0;
        let mut unrecognized_entries = 0;
        for entry in entries.iter() {
            match entry {
                Ok(e) => {
                    if let Some((_, expected_arti_path)) = expected_items
                        .iter()
                        .find(|(keystore_id, _)| keystore_id == e.keystore_id())
                    {
                        assert_key(e.key_path(), e.key_type(), expected_arti_path, &item_type);
                        recognized_entries += 1;
                        continue;
                    }
                    panic!("Unexpected key encountered {:?}", e);
                }
                Err(u) => {
                    assert_eq!(u.entry().raw_id(), &unrecognized_entry_id);
                    unrecognized_entries += 1;
                }
            }
        }
        assert_eq!(recognized_entries, 3);
        assert_eq!(unrecognized_entries, 1);
        // Test `list_keystores`
        let keystores = mgr.list_keystores().iter().len();
        assert_eq!(keystores, 3);
        // Test `list_by_id`
        let primary_keystore_id = KeystoreId::from_str("keystore1").unwrap();
        let entries = mgr.list_by_id(&primary_keystore_id).unwrap();
        // Primary keystore contains a valid key and an unrecognized key
        let mut recognized_entries = 0;
        let mut unrecognized_entries = 0;
        // A list of entries, in a form that can be consumed by remove_unchecked
        let mut all_entries = vec![];
        for entry in entries.iter() {
            match entry {
                Ok(entry) => {
                    assert_key(
                        entry.key_path(),
                        entry.key_type(),
                        &TestKeySpecifier1.arti_path().unwrap(),
                        &item_type,
                    );
                    recognized_entries += 1;
                    let raw_id = build_raw_id_path(entry.key_path(), entry.key_type());
                    let keystore_id = primary_keystore_id.clone();
                    all_entries.push((raw_id, keystore_id));
                }
                Err(u) => {
                    let raw_id = u.entry().raw_id().clone();
                    assert_eq!(raw_id, unrecognized_entry_id);
                    unrecognized_entries += 1;
                    let keystore_id = u.entry().keystore_id().clone();
                    all_entries.push((raw_id, keystore_id));
                }
            }
        }
        assert_eq!(recognized_entries, 1);
        assert_eq!(unrecognized_entries, 1);
        // Remove a recognized entry and an recognized one
        for (raw_id, keystore_id) in all_entries {
            mgr.remove_unchecked(&raw_id.to_string(), &keystore_id)
                .unwrap();
        }
        // Check the keys have been removed
        let entries = mgr.list_by_id(&primary_keystore_id).unwrap();
        assert_eq!(entries.len(), 0);
    }
    /// Whether to generate a given item before running the `run_certificate_test`.
    #[cfg(feature = "experimental-api")]
    #[derive(Clone, Copy, Debug, PartialEq)]
    enum GenerateItem {
        Yes,
        No,
    }
    fn make_certificate(subject_key: &TestItem, signed_with: &TestItem) -> AlwaysValidCert {
        let subject_id = subject_key.meta.as_key().unwrap().item_id.clone();
        let signing_id = signed_with.meta.as_key().unwrap().item_id.clone();
        let meta = ItemMetadata::Cert(CertMetadata {
            subject_key_id: subject_id,
            signing_key_id: signing_id,
            retrieved_from: None,
            is_generated: true,
        });
        // Note: this is not really a cert for `subject_key` signed with the `signed_with`
        // key!. The two are `TestItem`s and not keys, so we can't really generate a real
        // cert from them. We can, however, pretend we did, for testing purposes.
        // Eventually we might want to rewrite these tests to use real items
        // (like the `ArtiNativeKeystore` tests)
        let mut rng = FakeEntropicRng(testing_rng());
        let keypair = ed25519::Keypair::generate(&mut rng);
        let encoded_cert = Ed25519Cert::builder()
            .cert_type(tor_cert::CertType::IDENTITY_V_SIGNING)
            .expiration(SystemTime::get() + Duration::from_secs(180))
            .signing_key(keypair.public_key().into())
            .cert_key(CertifiedKey::Ed25519(keypair.public_key().into()))
            .encode_and_sign(&keypair)
            .unwrap();
        let test_cert = CertData::TorEd25519Cert(encoded_cert);
        AlwaysValidCert(TestItem {
            item: KeystoreItem::Cert(test_cert),
            meta,
        })
    }
    #[cfg(feature = "experimental-api")]
    macro_rules! run_certificate_test {
        (
            generate_subject_key = $generate_subject_key:expr,
            generate_signing_key = $generate_signing_key:expr,
            $($expected_err:tt)?
        ) => {{
            use GenerateItem::*;
            let mut rng = FakeEntropicRng(testing_rng());
            let mut builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed("keystore1"));
            builder
                .secondary_stores()
                .extend([Keystore::new_boxed("keystore2"), Keystore::new_boxed("keystore3")]);
            let mgr = builder.build().unwrap();
            let spec = crate::test_utils::TestCertSpecifier {
                subject_key_spec: TestDerivedKeySpecifier,
                denotator: "foo".into(),
            };
            if $generate_subject_key == Yes {
                let _ = mgr
                    .generate::<TestItem>(
                        &TestKeySpecifier1,
                        KeystoreSelector::Primary,
                        &mut rng,
                        false,
                    )
                    .unwrap();
            }
            if $generate_signing_key == Yes {
                let _ = mgr
                    .generate::<TestItem>(
                        &TestKeySpecifier2,
                        KeystoreSelector::Id(&KeystoreId::from_str("keystore2").unwrap()),
                        &mut rng,
                        false,
                    )
                    .unwrap();
            }
            let signing_key_spec = TestKeySpecifier2;
            let res = mgr
                .get_or_generate_key_and_cert::<TestItem, AlwaysValidCert>(
                    &spec,
                    &signing_key_spec,
                    &make_certificate,
                    KeystoreSelector::Primary,
                    &mut rng,
                );
            #[allow(unused_assignments)]
            #[allow(unused_mut)]
            let mut has_error = false;
            $(
                has_error = true;
                let err = res.clone().unwrap_err();
                assert!(
                    matches!(
                        err,
                        crate::Error::Corruption(KeystoreCorruptionError::$expected_err)
                    ),
                    "unexpected error: {err:?}",
                );
            )?
            if !has_error {
                let (key, cert) = res.unwrap();
                let expected_subj_key_id = if $generate_subject_key == Yes {
                    "generated_test_key"
                } else {
                    "generated_test_key"
                };
                assert_eq!(key.meta.item_id(), expected_subj_key_id);
                assert_eq!(
                    cert.0.meta.as_cert().unwrap().subject_key_id,
                    expected_subj_key_id
                );
                assert_eq!(
                    cert.0.meta.as_cert().unwrap().signing_key_id,
                    "generated_test_key"
                );
                assert_eq!(cert.0.meta.is_generated(), true);
            }
        }}
    }
    #[test]
    #[cfg(feature = "experimental-api")]
    #[rustfmt::skip] // preserve the layout for readability
    #[allow(clippy::cognitive_complexity)] // clippy seems confused here...
    fn get_certificate() {
        run_certificate_test!(
            generate_subject_key = No,
            generate_signing_key = No,
            MissingSigningKey
        );
        run_certificate_test!(
            generate_subject_key = Yes,
            generate_signing_key = No,
            MissingSigningKey
        );
        run_certificate_test!(
            generate_subject_key = No,
            generate_signing_key = Yes,
        );
        run_certificate_test!(
            generate_subject_key = Yes,
            generate_signing_key = Yes,
        );
    }
    #[test]
    #[cfg(feature = "experimental-api")]
    fn get_cert_entry() {
        let mut rng = FakeEntropicRng(testing_rng());
        let builder = KeyMgrBuilder::default().primary_store(Keystore::new_boxed("keystore1"));
        let mgr = builder.build().unwrap();
        // Generate the subject key
        let _ = mgr
            .generate::<TestItem>(
                &TestKeySpecifier1,
                KeystoreSelector::Primary,
                &mut rng,
                false,
            )
            .unwrap();
        // Generate the signing key
        let _ = mgr
            .generate::<TestItem>(
                &TestKeySpecifier2,
                KeystoreSelector::Primary,
                &mut rng,
                false,
            )
            .unwrap();
        // Generate multiple test certificates for the same subject key
        for cert_deno in 0..10 {
            let cert_spec = TestCertSpecifier {
                subject_key_spec: TestDerivedKeySpecifier,
                denotator: cert_deno.to_string(),
            };
            let res = mgr.get_or_generate_key_and_cert::<TestItem, AlwaysValidCert>(
                &cert_spec,
                &TestKeySpecifier2,
                &make_certificate,
                KeystoreSelector::Primary,
                &mut rng,
            );
            assert!(res.is_ok());
        }
        // Time to list all certs and retrieve them
        let any_pat = TestCertSpecifierPattern::new_any().arti_pattern().unwrap();
        // Ensure the pattern is what we expect it to be
        assert_eq!(
            any_pat,
            KeyPathPattern::Arti("test/simple_key+@*".to_string())
        );
        let certs = mgr.list_matching(&any_pat).unwrap();
        // We generated 10 certs, so there should be 10 matching entries
        assert_eq!(certs.len(), 10);
        // Ensure we collected all the expected paths
        let all_paths = certs
            .iter()
            .map(|entry| entry.key_path().arti().unwrap().as_str().to_string())
            .sorted()
            .collect::<Vec<_>>();
        let expected_paths = (0..10)
            .map(|i| format!("test/simple_key+@{i}"))
            .collect::<Vec<_>>();
        assert_eq!(all_paths, expected_paths);
        for entry in certs {
            let always_valid_cert = mgr
                .get_cert_entry::<TestCertSpecifier, TestItem, AlwaysValidCert>(
                    &entry,
                    &TestKeySpecifier2,
                )
                .unwrap();
            // Check that the cert was found...
            assert!(always_valid_cert.is_some());
        }
        /// A denotator for our expired cert specifier.
        const EXPIRED_DENO: &str = "expired";
        // Generate an invalid test certificate
        let cert_spec = TestCertSpecifier {
            subject_key_spec: TestDerivedKeySpecifier,
            denotator: EXPIRED_DENO.to_string(),
        };
        // Dummy metadata
        let meta = CertMetadata {
            subject_key_id: "foo".to_string(),
            signing_key_id: "bar".to_string(),
            retrieved_from: None,
            is_generated: false,
        };
        let test_cert =
            CertData::TorEd25519Cert(EncodedEd25519Cert::dangerously_from_bytes(b"foobar"));
        let cert = AlwaysExpiredCert(TestItem {
            item: KeystoreItem::Cert(test_cert),
            meta: ItemMetadata::Cert(meta),
        });
        let res = mgr.insert_cert::<TestItem, AlwaysExpiredCert>(
            cert,
            &cert_spec,
            KeystoreSelector::Primary,
        );
        assert!(res.is_ok());
        // Build a pattern for matching *only* the expired cert
        let pat = KeyPathPattern::Arti(format!("test/simple_key+@{EXPIRED_DENO}"));
        let certs = mgr.list_matching(&pat).unwrap();
        assert_eq!(certs.len(), 1);
        let entry = &certs[0];
        let err = mgr
            .get_cert_entry::<TestCertSpecifier, TestItem, AlwaysExpiredCert>(
                entry,
                &TestKeySpecifier2,
            )
            .unwrap_err();
        // Can't retrieve the cert because it's expired!
        assert!(
            matches!(err, Error::InvalidCert(InvalidCertError::TimeValidity(_))),
            "{err:?}"
        );
    }
}