Skip to main content

weirdnet_vault/
keystore.rs

1//! Places that keep the vault's database key by name: memory, the OS keychain (feature
2//! `keychain`) and weirdnet-sync secret stores (feature `sync`).
3use crate::error::{Result, VaultError};
4use std::collections::HashMap;
5use std::sync::Mutex;
6use weirdnet_keys::Key32;
7use zeroize::Zeroizing;
8
9/// Keeps secret bytes by name.
10pub trait KeyStore: Send + Sync {
11    /// The bytes, or `None` when nothing is stored under `name`.
12    fn load(&self, name: &str) -> Result<Option<Zeroizing<Vec<u8>>>>;
13    /// Store (replace) the bytes.
14    fn store(&self, name: &str, bytes: &[u8]) -> Result<()>;
15    /// Forget them (no error when there is nothing).
16    fn remove(&self, name: &str) -> Result<()>;
17}
18
19/// The 32-byte key stored under `name`, or a new random one, stored and read back.
20pub fn load_or_create_key(store: &dyn KeyStore, name: &str) -> Result<Key32> {
21    if let Some(b) = store.load(name)? {
22        return Key32::from_slice(&b).map_err(|_| VaultError::KeyStore(format!("{name:?} does not hold a 32-byte key")));
23    }
24    let k = Key32::random()?;
25    store.store(name, &k.0)?;
26    match store.load(name)? {
27        Some(b) if b.as_slice() == k.0.as_slice() => Ok(k),
28        _ => Err(VaultError::KeyStore(format!("{name:?} did not read back after storing"))),
29    }
30}
31
32/// An in-memory key store (tests, examples).
33#[derive(Default)]
34pub struct MemoryKeyStore {
35    map: Mutex<HashMap<String, Zeroizing<Vec<u8>>>>,
36}
37
38impl std::fmt::Debug for MemoryKeyStore {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        let n = self.map.lock().map(|m| m.len()).unwrap_or(0);
41        write!(f, "MemoryKeyStore({n} entries)")
42    }
43}
44
45impl MemoryKeyStore {
46    /// Empty.
47    pub fn new() -> Self {
48        Self::default()
49    }
50}
51
52impl KeyStore for MemoryKeyStore {
53    fn load(&self, name: &str) -> Result<Option<Zeroizing<Vec<u8>>>> {
54        Ok(self.map.lock().unwrap_or_else(|e| e.into_inner()).get(name).cloned())
55    }
56    fn store(&self, name: &str, bytes: &[u8]) -> Result<()> {
57        self.map.lock().unwrap_or_else(|e| e.into_inner()).insert(name.to_string(), Zeroizing::new(bytes.to_vec()));
58        Ok(())
59    }
60    fn remove(&self, name: &str) -> Result<()> {
61        self.map.lock().unwrap_or_else(|e| e.into_inner()).remove(name);
62        Ok(())
63    }
64}
65
66#[cfg(feature = "keychain")]
67pub use keychain::KeychainStore;
68
69#[cfg(feature = "keychain")]
70mod keychain {
71    use super::KeyStore;
72    use crate::error::{Result, VaultError};
73    use keyring_core::{CredentialStore, Entry, Error as KcError};
74    use std::sync::Arc;
75    use zeroize::Zeroizing;
76
77    fn kc(e: KcError) -> VaultError {
78        VaultError::KeyStore(e.to_string())
79    }
80
81    /// The OS keychain: macOS Keychain, Windows Credential Manager, or the Secret Service on
82    /// Linux and the BSDs. Entries are `(service, name)`.
83    ///
84    /// Calls block (some go over D-Bus or XPC); from async code, call them through
85    /// [`AsyncVault`](crate::AsyncVault) or `spawn_blocking`.
86    #[derive(Clone)]
87    pub struct KeychainStore {
88        store: Arc<CredentialStore>,
89        service: String,
90    }
91
92    impl std::fmt::Debug for KeychainStore {
93        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94            f.debug_struct("KeychainStore").field("service", &self.service).finish_non_exhaustive()
95        }
96    }
97
98    impl KeychainStore {
99        /// This platform's keychain, with entries under `service` (for example your app id).
100        pub fn native(service: &str) -> Result<Self> {
101            Ok(KeychainStore { store: native_store()?, service: service.to_string() })
102        }
103
104        /// Any `keyring-core` store (another backend, or `keyring_core::mock` in tests).
105        pub fn with_store(store: Arc<CredentialStore>, service: &str) -> Self {
106            KeychainStore { store, service: service.to_string() }
107        }
108
109        /// The service name.
110        pub fn service(&self) -> &str {
111            &self.service
112        }
113
114        fn entry(&self, name: &str) -> Result<Entry> {
115            Entry::new_in_store(&self.store, &self.service, name).map_err(kc)
116        }
117    }
118
119    #[cfg(target_os = "macos")]
120    fn native_store() -> Result<Arc<CredentialStore>> {
121        Ok(apple_native_keyring_store::keychain::Store::new().map_err(kc)?)
122    }
123
124    #[cfg(target_os = "windows")]
125    fn native_store() -> Result<Arc<CredentialStore>> {
126        Ok(windows_native_keyring_store::Store::new().map_err(kc)?)
127    }
128
129    #[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))]
130    fn native_store() -> Result<Arc<CredentialStore>> {
131        Ok(zbus_secret_service_keyring_store::Store::new().map_err(kc)?)
132    }
133
134    #[cfg(not(any(target_os = "macos", target_os = "windows", all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))))]
135    fn native_store() -> Result<Arc<CredentialStore>> {
136        Err(VaultError::KeyStore("no native keychain on this platform; use KeychainStore::with_store".into()))
137    }
138
139    impl KeyStore for KeychainStore {
140        fn load(&self, name: &str) -> Result<Option<Zeroizing<Vec<u8>>>> {
141            match self.entry(name)?.get_secret() {
142                Ok(b) => Ok(Some(Zeroizing::new(b))),
143                Err(KcError::NoEntry) => Ok(None),
144                Err(e) => Err(kc(e)),
145            }
146        }
147        fn store(&self, name: &str, bytes: &[u8]) -> Result<()> {
148            self.entry(name)?.set_secret(bytes).map_err(kc)
149        }
150        fn remove(&self, name: &str) -> Result<()> {
151            match self.entry(name)?.delete_credential() {
152                Ok(()) | Err(KcError::NoEntry) => Ok(()),
153                Err(e) => Err(kc(e)),
154            }
155        }
156    }
157}
158
159#[cfg(feature = "sync")]
160pub use sync::SyncSecrets;
161
162#[cfg(feature = "sync")]
163mod sync {
164    use super::KeyStore;
165    use crate::error::{Result, VaultError};
166    use zeroize::Zeroizing;
167
168    /// Any weirdnet-sync `SecretStore` (such as `FileSecrets`) as a [`KeyStore`].
169    #[derive(Debug, Clone)]
170    pub struct SyncSecrets<S>(pub S);
171
172    fn se(e: weirdnet_sync::SyncError) -> VaultError {
173        VaultError::KeyStore(e.to_string())
174    }
175
176    impl<S: weirdnet_sync::SecretStore> KeyStore for SyncSecrets<S> {
177        fn load(&self, name: &str) -> Result<Option<Zeroizing<Vec<u8>>>> {
178            self.0.read(name).map_err(se)
179        }
180        fn store(&self, name: &str, bytes: &[u8]) -> Result<()> {
181            self.0.write(name, bytes).map_err(se)
182        }
183        fn remove(&self, name: &str) -> Result<()> {
184            self.0.remove(name).map_err(se)
185        }
186    }
187
188    macro_rules! secret_store {
189        ($t:ty) => {
190            /// weirdnet-sync's `SecretStore`, so an `Identity` can keep its secrets here.
191            impl weirdnet_sync::SecretStore for $t {
192                fn read(&self, name: &str) -> weirdnet_sync::Result<Option<Zeroizing<Vec<u8>>>> {
193                    KeyStore::load(self, name).map_err(|e| weirdnet_sync::SyncError::Io(e.to_string()))
194                }
195                fn write(&self, name: &str, bytes: &[u8]) -> weirdnet_sync::Result<()> {
196                    KeyStore::store(self, name, bytes).map_err(|e| weirdnet_sync::SyncError::Io(e.to_string()))
197                }
198                fn remove(&self, name: &str) -> weirdnet_sync::Result<()> {
199                    KeyStore::remove(self, name).map_err(|e| weirdnet_sync::SyncError::Io(e.to_string()))
200                }
201            }
202        };
203    }
204
205    secret_store!(super::MemoryKeyStore);
206    #[cfg(feature = "keychain")]
207    secret_store!(super::KeychainStore);
208}