keymgr: Add a Keystore::contains accessor.

This commit is contained in:
Gabriela Moldovan 2023-07-14 11:08:54 +01:00
parent 19f097d1fa
commit e36e7db6e7
No known key found for this signature in database
GPG Key ID: 3946E0ADE72BAC99
4 changed files with 34 additions and 1 deletions

View File

@ -12,4 +12,4 @@ BREAKING: `KeyMgr::insert`, `KeyMgr::remove` now take an
REMOVED: the `has_key_bundle` function (from the `Keystore` trait)
ADDED: `PartialEq`, `Eq`, `Hash` derives for `ArtiPath` and `KeyType`
ADDED: a `to_bytes` function to `EncodableKey` trait
ADDED: `Keystore::contains()`

View File

@ -26,6 +26,9 @@ pub trait Keystore: Send + Sync + 'static {
/// store.
fn id(&self) -> &KeystoreId;
/// Check if the the key identified by `key_spec` exists in this key store.
fn contains(&self, key_spec: &dyn KeySpecifier, key_type: KeyType) -> Result<bool>;
/// Retrieve the key identified by `key_spec`.
///
/// Returns `Ok(Some(key))` if the key was successfully retrieved. Returns `Ok(None)` if the

View File

@ -68,6 +68,10 @@ impl Keystore for ArtiNativeKeystore {
&self.id
}
fn contains(&self, key_spec: &dyn KeySpecifier, key_type: KeyType) -> Result<bool> {
Ok(self.key_path(key_spec, key_type)?.exists())
}
fn get(&self, key_spec: &dyn KeySpecifier, key_type: KeyType) -> Result<Option<ErasedKey>> {
let path = self.key_path(key_spec, key_type)?;

View File

@ -210,6 +210,14 @@ mod tests {
}
impl Keystore for $name {
fn contains(&self, key_spec: &dyn KeySpecifier, key_type: KeyType) -> Result<bool> {
Ok(self
.inner
.read()
.unwrap()
.contains_key(&(key_spec.arti_path()?, key_type)))
}
fn id(&self) -> &KeystoreId {
&self.id
}
@ -363,6 +371,10 @@ mod tests {
vec![Keystore2::new_boxed(), Keystore3::new_boxed()],
);
assert!(!mgr.key_stores[0]
.contains(&TestKeySpecifier1, TestKey::key_type())
.unwrap());
// Insert a key into Keystore2
mgr.insert(
"coot".to_string(),
@ -382,6 +394,10 @@ mod tests {
KeystoreSelector::Id(&KeystoreId::from_str("not_an_id_we_know_of").unwrap())
)
.is_err());
// The key still exists in Keystore2
assert!(mgr.key_stores[0]
.contains(&TestKeySpecifier1, TestKey::key_type())
.unwrap());
// Try to remove the key from the default key store
assert_eq!(
@ -390,6 +406,11 @@ mod tests {
None
);
// The key still exists in Keystore2
assert!(mgr.key_stores[0]
.contains(&TestKeySpecifier1, TestKey::key_type())
.unwrap());
// Removing from Keystore2 should succeed.
assert_eq!(
mgr.remove::<TestKey>(
@ -399,5 +420,10 @@ mod tests {
.unwrap(),
Some(())
);
// The key doesn't exist in Keystore2 anymore
assert!(!mgr.key_stores[0]
.contains(&TestKeySpecifier1, TestKey::key_type())
.unwrap());
}
}