1use super::*;
2use crate::custody::block_store::BlockStore;
3use crate::custody::block_store_test_utils::MemoryBlockStore;
4use crate::custody::person_entries::restore_code_store;
5use crate::custody::KeychainError;
6use crate::wire;
7use std::collections::BTreeMap;
8use std::path::Path;
9use zeroize::Zeroizing;
10
11const SAVED_DEVICE_ENTRIES_MAGIC: &[u8] = b"CVDE\x01";
14
15#[derive(Clone)]
20pub(super) struct SyncedEntries(Arc<Mutex<SyncedGroups>>);
21
22impl SyncedEntries {
23 fn groups(&self) -> std::sync::MutexGuard<'_, SyncedGroups> {
24 self.0.lock().expect("in-memory synced keychain entries lock is poisoned")
25 }
26}
27
28#[derive(Default)]
33pub(super) struct SyncedGroups {
34 default: BTreeMap<String, SecretBytes>,
35 another: BTreeMap<String, SecretBytes>,
36}
37
38impl SyncedGroups {
39 fn read(&self, account: &str) -> Option<SecretBytes> {
40 self.copies(account).into_iter().next()
41 }
42
43 fn write(&mut self, account: &str, bytes: &[u8]) {
44 if self.default.contains_key(account) {
45 if let Some(copy) = self.another.get_mut(account) {
46 *copy = SecretBytes::new(bytes.to_vec());
47 }
48 }
49 self.default.insert(account.to_owned(), SecretBytes::new(bytes.to_vec()));
50 }
51
52 fn delete(&mut self, account: &str) {
53 self.default.remove(account);
54 self.another.remove(account);
55 }
56
57 fn copies(&self, account: &str) -> Vec<SecretBytes> {
58 [&self.default, &self.another]
59 .into_iter()
60 .filter_map(|group| group.get(account))
61 .map(|bytes| SecretBytes::new(bytes.as_bytes().to_vec()))
62 .collect()
63 }
64
65 fn replace(&mut self, account: &str, bytes: &[u8]) {
66 let bytes = SecretBytes::new(bytes.to_vec());
67 if self.default.contains_key(account) || !self.another.contains_key(account) {
68 self.default.insert(account.to_owned(), bytes);
69 self.another.remove(account);
70 } else {
71 self.another.insert(account.to_owned(), bytes);
72 }
73 }
74
75 fn all(&self) -> Vec<(String, SecretBytes)> {
76 [&self.default, &self.another]
77 .into_iter()
78 .flatten()
79 .map(|(account, bytes)| (account.clone(), SecretBytes::new(bytes.as_bytes().to_vec())))
80 .collect()
81 }
82}
83
84pub(super) enum MemoryPerson {
86 ICloud(SyncedEntries),
88 BlockStore(BlockStore<MemoryBlockStore>),
90}
91
92pub(super) struct MemoryEntries {
93 device: BTreeMap<String, SecretBytes>,
95 person: MemoryPerson,
97 fail_after: std::collections::VecDeque<usize>,
98 refuse_person: bool,
100 panic_next: bool,
103}
104
105fn panic_if_asked(backend: &Mutex<MemoryEntries>) {
109 let asked = std::mem::take(
110 &mut backend.lock().expect("in-memory keychain entries lock is poisoned").panic_next,
111 );
112 if asked {
113 panic!("the in-memory keychain's operation panicked");
114 }
115}
116
117impl MemoryEntries {
118 fn check(&mut self, scope: EntryScope) -> Result<(), KeyError> {
119 let person = scope == EntryScope::Person && self.refuse_person;
120 if person || self.fail_after.front() == Some(&0) {
121 if !person {
122 self.fail_after.pop_front();
123 }
124 return Err(KeychainError::from(keyring_core::Error::NoStorageAccess(Box::new(
125 std::io::Error::new(
126 std::io::ErrorKind::PermissionDenied,
127 "in-memory keychain refused the operation",
128 ),
129 )))
130 .into());
131 }
132 if let Some(remaining) = self.fail_after.front_mut() {
133 *remaining -= 1;
134 }
135 Ok(())
136 }
137
138 fn change<T>(
140 &mut self,
141 scope: EntryScope,
142 device: impl FnOnce(&mut BTreeMap<String, SecretBytes>) -> T,
143 person: impl FnOnce(&mut MemoryPerson) -> Result<T, KeyError>,
144 ) -> Result<T, KeyError> {
145 self.check(scope)?;
146 match scope {
147 EntryScope::DeviceOnly => Ok(device(&mut self.device)),
148 EntryScope::Person => person(&mut self.person),
149 }
150 }
151
152 fn person<T>(
153 &mut self,
154 change: impl FnOnce(&mut MemoryPerson) -> Result<T, KeyError>,
155 ) -> Result<T, KeyError> {
156 self.check(EntryScope::Person)?;
157 change(&mut self.person)
158 }
159}
160
161impl KeychainBackend for Mutex<MemoryEntries> {
162 fn supports_person_entries(&self) -> bool {
163 true
164 }
165
166 fn person_backup_follows_writes(&self) -> bool {
167 matches!(
168 self.lock().expect("in-memory keychain entries lock is poisoned").person,
169 MemoryPerson::BlockStore(_)
170 )
171 }
172
173 fn person_value_limit(&self, service: &str, account: &str) -> Option<usize> {
174 match &self.lock().expect("in-memory keychain entries lock is poisoned").person {
175 MemoryPerson::ICloud(_) => None,
176 MemoryPerson::BlockStore(_) => {
177 Some(BlockStore::<MemoryBlockStore>::value_limit(service, account))
178 }
179 }
180 }
181
182 fn read(
183 &self,
184 scope: EntryScope,
185 service: &str,
186 account: &str,
187 ) -> Result<Option<SecretBytes>, KeyError> {
188 panic_if_asked(self);
189 self.lock().expect("in-memory keychain entries lock is poisoned").change(
190 scope,
191 |entries| entries.get(account).map(|bytes| SecretBytes::new(bytes.as_bytes().to_vec())),
192 |person| match person {
193 MemoryPerson::ICloud(entries) => Ok(entries.groups().read(account)),
194 MemoryPerson::BlockStore(store) => store.read(service, account),
195 },
196 )
197 }
198
199 fn write(
200 &self,
201 scope: EntryScope,
202 service: &str,
203 account: &str,
204 bytes: &[u8],
205 ) -> Result<(), KeyError> {
206 panic_if_asked(self);
207 self.lock().expect("in-memory keychain entries lock is poisoned").change(
208 scope,
209 |entries| {
210 entries.insert(account.to_owned(), SecretBytes::new(bytes.to_vec()));
211 },
212 |person| match person {
213 MemoryPerson::ICloud(entries) => {
214 entries.groups().write(account, bytes);
215 Ok(())
216 }
217 MemoryPerson::BlockStore(store) => store.write(service, account, bytes),
218 },
219 )
220 }
221
222 fn delete(&self, scope: EntryScope, service: &str, account: &str) -> Result<(), KeyError> {
223 panic_if_asked(self);
224 self.lock().expect("in-memory keychain entries lock is poisoned").change(
225 scope,
226 |entries| {
227 entries.remove(account);
228 },
229 |person| match person {
230 MemoryPerson::ICloud(entries) => {
231 entries.groups().delete(account);
232 Ok(())
233 }
234 MemoryPerson::BlockStore(store) => store.delete(service, account),
235 },
236 )
237 }
238
239 fn person_restore_codes(&self, service: &str) -> Result<Vec<(StoreId, SecretBytes)>, KeyError> {
240 panic_if_asked(self);
241 self.lock().expect("in-memory keychain entries lock is poisoned").person(|person| {
242 match person {
243 MemoryPerson::ICloud(entries) => {
244 let mut codes = Vec::new();
245 for (account, bytes) in entries.groups().all() {
246 if let Some(store) = restore_code_store(&account)? {
247 codes.push((store, bytes));
248 }
249 }
250 Ok(codes)
251 }
252 MemoryPerson::BlockStore(store) => store.restore_codes(service),
253 }
254 })
255 }
256
257 fn person_copies(&self, service: &str, account: &str) -> Result<Vec<SecretBytes>, KeyError> {
258 panic_if_asked(self);
259 self.lock().expect("in-memory keychain entries lock is poisoned").person(|person| {
260 match person {
261 MemoryPerson::ICloud(entries) => Ok(entries.groups().copies(account)),
262 MemoryPerson::BlockStore(store) => {
263 Ok(store.read(service, account)?.into_iter().collect())
264 }
265 }
266 })
267 }
268
269 fn replace_person_entry(
270 &self,
271 service: &str,
272 account: &str,
273 bytes: &[u8],
274 ) -> Result<(), KeyError> {
275 panic_if_asked(self);
276 self.lock().expect("in-memory keychain entries lock is poisoned").person(|person| {
277 match person {
278 MemoryPerson::ICloud(entries) => {
279 entries.groups().replace(account, bytes);
280 Ok(())
281 }
282 MemoryPerson::BlockStore(store) => store.write(service, account, bytes),
283 }
284 })
285 }
286}
287
288impl Keychain {
289 pub fn in_memory(name: impl Into<String>) -> Result<Arc<Self>, KeyError> {
293 let entries = SyncedEntries(Arc::new(Mutex::new(SyncedGroups::default())));
294 Self::memory(name.into(), MemoryPerson::ICloud(entries))
295 }
296
297 pub fn in_memory_block_store(name: impl Into<String>) -> Result<Arc<Self>, KeyError> {
301 Self::memory(
302 name.into(),
303 MemoryPerson::BlockStore(BlockStore::new(MemoryBlockStore::new())),
304 )
305 }
306
307 pub fn in_memory_with_saved_device_entries(
313 name: impl Into<String>,
314 path: &Path,
315 ) -> Result<Arc<Self>, KeyError> {
316 let bytes = Zeroizing::new(coven_foundation::files::read_existing(path)?);
317 let device = decode_device_entries(&bytes)?;
318 let keychain = Self::in_memory(name)?;
319 keychain.with_memory(|memory| memory.device = device);
320 Ok(keychain)
321 }
322
323 pub fn save_device_entries(&self, path: &Path) -> Result<(), KeyError> {
328 let bytes = self.with_memory(|memory| encode_device_entries(&memory.device));
329 Ok(coven_foundation::files::write_atomic(path, &bytes)?)
330 }
331
332 pub fn another_device(&self) -> Arc<Self> {
338 let person = match self.synced_entries() {
339 Some(entries) => MemoryPerson::ICloud(entries),
340 None => MemoryPerson::BlockStore(BlockStore::new(MemoryBlockStore::new())),
341 };
342 Self::memory(self.name.clone(), person).expect("registered service name is valid")
343 }
344
345 fn synced_entries(&self) -> Option<SyncedEntries> {
349 self.with_memory(|memory| match &memory.person {
350 MemoryPerson::ICloud(entries) => Some(entries.clone()),
351 MemoryPerson::BlockStore(_) => None,
352 })
353 }
354
355 pub fn set_up_new_device(&self) -> Arc<Self> {
359 let store = self.memory_block_store(|store| store.set_up_new_phone());
360 Self::memory(self.name.clone(), MemoryPerson::BlockStore(BlockStore::new(store)))
361 .expect("registered service name is valid")
362 }
363
364 pub fn restore_new_device_from_cloud(&self) -> Arc<Self> {
368 let store = self.memory_block_store(|store| store.restore_new_phone_from_cloud());
369 Self::memory(self.name.clone(), MemoryPerson::BlockStore(BlockStore::new(store)))
370 .expect("registered service name is valid")
371 }
372
373 pub fn back_up_to_cloud(&self) {
376 self.memory_block_store(MemoryBlockStore::back_up_to_cloud);
377 }
378
379 pub fn set_end_to_end_encryption(&self, available: bool) {
382 self.memory_block_store(|store| store.set_end_to_end_encryption(available));
383 }
384
385 fn memory_block_store<T>(&self, f: impl FnOnce(&MemoryBlockStore) -> T) -> T {
386 self.with_memory(|memory| match &memory.person {
387 MemoryPerson::BlockStore(store) => f(store.api()),
388 MemoryPerson::ICloud(_) => panic!("this in-memory keychain keeps no Block Store"),
389 })
390 }
391
392 fn memory(name: String, person: MemoryPerson) -> Result<Arc<Self>, KeyError> {
393 validate_service(&name)?;
394 Ok(Arc::new(Self {
395 name,
396 backend: Box::new(Mutex::new(MemoryEntries {
397 device: BTreeMap::new(),
398 person,
399 fail_after: std::collections::VecDeque::new(),
400 refuse_person: false,
401 panic_next: false,
402 })),
403 secret_names: Mutex::new(()),
404 }))
405 }
406
407 fn with_memory<T>(&self, change: impl FnOnce(&mut MemoryEntries) -> T) -> T {
410 let backend: &dyn std::any::Any = self.backend.as_ref();
411 let memory: &Mutex<MemoryEntries> =
412 backend.downcast_ref().expect("failure injection requires an in-memory keychain");
413 change(&mut memory.lock().expect("in-memory keychain entries lock is poisoned"))
414 }
415
416 #[cfg(test)]
419 pub(super) fn with_device_entries<T>(
420 &self,
421 change: impl FnOnce(&mut BTreeMap<String, SecretBytes>) -> T,
422 ) -> T {
423 self.with_memory(|memory| change(&mut memory.device))
424 }
425
426 pub fn fail_next_operation(&self) {
429 self.fail_operations_after(&[0]);
430 }
431
432 pub fn panic_next_operation(&self) {
436 self.with_memory(|memory| memory.panic_next = true);
437 }
438
439 pub fn with_operations_held<T>(&self, run: impl FnOnce() -> T) -> T {
443 self.with_memory(|_entries| run())
444 }
445
446 pub fn fail_operations_after(&self, successes: &[usize]) {
450 self.with_memory(|memory| memory.fail_after = successes.iter().copied().collect());
451 }
452
453 #[cfg(any(test, feature = "test-utils"))]
457 pub(crate) fn write_in_another_group(&self, account: &str, bytes: &[u8]) {
458 self.with_memory(|memory| match &memory.person {
459 MemoryPerson::ICloud(entries) => {
460 entries
461 .groups()
462 .another
463 .insert(account.to_owned(), SecretBytes::new(bytes.to_vec()));
464 }
465 MemoryPerson::BlockStore(_) => panic!("Block Store has no keychain groups"),
466 });
467 }
468
469 pub fn refuse_person_entry_operations(&self, refuse: bool) {
473 self.with_memory(|memory| memory.refuse_person = refuse);
474 }
475}
476
477fn encode_device_entries(entries: &BTreeMap<String, SecretBytes>) -> Zeroizing<Vec<u8>> {
480 let fields = entries.iter().flat_map(|(account, bytes)| [account.as_bytes(), bytes.as_bytes()]);
481 let length = fields.clone().map(|field| 8 + field.len()).sum::<usize>();
483 let mut encoded =
484 Zeroizing::new(Vec::with_capacity(SAVED_DEVICE_ENTRIES_MAGIC.len() + 8 + length));
485 encoded.extend_from_slice(SAVED_DEVICE_ENTRIES_MAGIC);
486 encoded.extend_from_slice(&(entries.len() as u64).to_le_bytes());
487 for field in fields {
488 encoded.extend_from_slice(&(field.len() as u64).to_le_bytes());
489 encoded.extend_from_slice(field);
490 }
491 encoded
492}
493
494fn decode_device_entries(
496 mut encoded: &[u8],
497) -> Result<BTreeMap<String, SecretBytes>, MaterialError> {
498 fn field<'a>(encoded: &mut &'a [u8]) -> Result<&'a [u8], MaterialError> {
499 let length = usize::try_from(wire::number(encoded)?).or(Err(MaterialError::Encoding))?;
500 wire::take(encoded, length)
501 }
502 wire::prefix(&mut encoded, SAVED_DEVICE_ENTRIES_MAGIC)?;
503 let mut entries = BTreeMap::new();
504 for _ in 0..wire::number(&mut encoded)? {
505 let account =
506 String::from_utf8(field(&mut encoded)?.to_vec()).or(Err(MaterialError::Encoding))?;
507 let bytes = SecretBytes::new(field(&mut encoded)?.to_vec());
508 if entries.insert(account, bytes).is_some() {
509 return Err(MaterialError::Encoding);
510 }
511 }
512 wire::end(encoded)?;
513 Ok(entries)
514}