bitwarden_crypto/store/backend/implementation/
basic.rs

1use zeroize::ZeroizeOnDrop;
2
3use crate::{store::backend::StoreBackend, KeyId};
4
5/// This is a basic key store backend that stores keys in a HashMap memory.
6/// No protections are provided for the keys stored in this backend, beyond enforcing
7/// zeroization on drop.
8pub(crate) struct BasicBackend<Key: KeyId> {
9    keys: std::collections::HashMap<Key, Key::KeyValue>,
10}
11
12impl<Key: KeyId> BasicBackend<Key> {
13    pub fn new() -> Self {
14        Self {
15            keys: std::collections::HashMap::new(),
16        }
17    }
18}
19
20impl<Key: KeyId> StoreBackend<Key> for BasicBackend<Key> {
21    fn upsert(&mut self, key_id: Key, key: <Key as KeyId>::KeyValue) {
22        self.keys.insert(key_id, key);
23    }
24
25    fn get(&self, key_id: Key) -> Option<&<Key as KeyId>::KeyValue> {
26        self.keys.get(&key_id)
27    }
28
29    fn remove(&mut self, key_id: Key) {
30        self.keys.remove(&key_id);
31    }
32
33    fn clear(&mut self) {
34        self.keys.clear();
35    }
36
37    fn retain(&mut self, f: fn(Key) -> bool) {
38        self.keys.retain(|k, _| f(*k));
39    }
40}
41
42/// [KeyId::KeyValue] already implements [ZeroizeOnDrop],
43/// so we only need to ensure the map is cleared on drop.
44impl<Key: KeyId> ZeroizeOnDrop for BasicBackend<Key> {}
45impl<Key: KeyId> Drop for BasicBackend<Key> {
46    fn drop(&mut self) {
47        self.clear();
48    }
49}