Skip to main content

coven_crypto/custody/
keychain_test_utils.rs

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
11/// The first bytes of a keychain's saved device-only entries: their magic
12/// and version.
13const SAVED_DEVICE_ENTRIES_MAGIC: &[u8] = b"CVDE\x01";
14
15/// The synced entries iCloud Keychain carries to every device of one person:
16/// each in-memory keychain of the person holds a share, which only a keychain
17/// makes, its first device's for itself and each other device's from one it
18/// already has.
19#[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/// The keychain groups an app can read. Apple keeps one copy of an entry per
29/// group: a write naming no group adds to the default group, or, when that
30/// group already holds the entry, updates every group's copy; a read naming
31/// none gives the first copy, and a deletion naming none deletes them all.
32#[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
84/// Where an in-memory keychain keeps the person's entries.
85pub(super) enum MemoryPerson {
86    /// iCloud Keychain: shared with every keychain made by `another_device`.
87    ICloud(SyncedEntries),
88    /// Block Store: this phone's own, given to phones set up from it.
89    BlockStore(BlockStore<MemoryBlockStore>),
90}
91
92pub(super) struct MemoryEntries {
93    /// This device's own entries.
94    device: BTreeMap<String, SecretBytes>,
95    /// The person's entries.
96    person: MemoryPerson,
97    fail_after: std::collections::VecDeque<usize>,
98    /// Refuse this device's calls on the person's entries while set.
99    refuse_person: bool,
100    /// Panic in the next read, write, delete or list, as a bug in the
101    /// keychain's code would.
102    panic_next: bool,
103}
104
105/// Panic if a test asked the next read, write, delete or list to, before it
106/// changes anything and with the entries' lock released, so the entries
107/// stay usable after it.
108fn 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    /// Run `device` on this device's entries, or `person` on the person's.
139    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    /// An isolated in-memory keychain with separate device-only entries and
290    /// person entries. The person's entries behave as iCloud Keychain keeps
291    /// them, on every test platform, without touching the OS.
292    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    /// An isolated in-memory keychain whose person entries behave as Block
298    /// Store keeps them on an Android phone: this phone's own, with Block
299    /// Store's limits, given only to a phone set up from it.
300    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    /// An isolated in-memory keychain, as `in_memory` makes, whose
308    /// device-only entries are the ones `save_device_entries` saved at
309    /// `path`: the same device again, in another process. Its person entries
310    /// start empty. Bytes `save_device_entries` didn't write fail with
311    /// `KeyError::Material`.
312    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    /// Save this keychain's device-only entries at `path`, replacing what is
324    /// there: each store's device id, store keys and member keys, and every
325    /// other entry that never leaves the device. The person's entries stay
326    /// out. Panics if this is a native keychain.
327    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    /// Another device of the same person: its own empty device-only entries.
333    /// With iCloud Keychain it has the same person entries, as iCloud
334    /// Keychain carries them between the person's devices; with Block Store
335    /// its own, empty. Failures injected into either keychain refuse only its
336    /// own calls. Panics if this is a native keychain.
337    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    /// A share of the person's iCloud Keychain entries, for another of the
346    /// person's devices; none with Block Store, whose entries are each
347    /// phone's own.
348    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    /// A new phone set up from this one by direct transfer: no device-only
356    /// entries, and a copy of every Block Store entry. Requires an in-memory
357    /// Block Store keychain.
358    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    /// A new phone set up from this phone's last cloud backup: no device-only
365    /// entries, and the Block Store entries that backup holds. Requires an
366    /// in-memory Block Store keychain.
367    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    /// Google's periodic cloud backup of this phone's Block Store: the entries
374    /// stored to be backed up. Requires an in-memory Block Store keychain.
375    pub fn back_up_to_cloud(&self) {
376        self.memory_block_store(MemoryBlockStore::back_up_to_cloud);
377    }
378
379    /// Whether this phone's cloud backup would be end-to-end encrypted: it has
380    /// a screen lock. Requires an in-memory Block Store keychain.
381    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    /// Run `change` on the in-memory keychain's entries. Panics if this is
408    /// a native keychain.
409    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    /// Run `change` on this device's own entries, as a test inspects or
417    /// moves them.
418    #[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    /// Make the fake refuse the next read, write, delete or list before changing state.
427    /// Panics if this is a native keychain.
428    pub fn fail_next_operation(&self) {
429        self.fail_operations_after(&[0]);
430    }
431
432    /// Make the fake panic in the next read, write, delete or list before
433    /// changing state, as a bug in the keychain's code would. Panics if
434    /// this is a native keychain.
435    pub fn panic_next_operation(&self) {
436        self.with_memory(|memory| memory.panic_next = true);
437    }
438
439    /// Run `run` while every call on this keychain's entries waits, as a
440    /// keychain slow to answer would: for a test that acts while a call
441    /// waits on the keychain. Panics if this is a native keychain.
442    pub fn with_operations_held<T>(&self, run: impl FnOnce() -> T) -> T {
443        self.with_memory(|_entries| run())
444    }
445
446    /// Refuse successive operations after each given number of successful calls.
447    /// For example `[2, 0]` refuses the third call and its immediate rollback.
448    /// Replaces any existing failure schedule; requires an in-memory keychain.
449    pub fn fail_operations_after(&self, successes: &[usize]) {
450        self.with_memory(|memory| memory.fail_after = successes.iter().copied().collect());
451    }
452
453    /// Save a person entry's copy in a second keychain group, as an app that
454    /// moved to a new group can find its old copy beside the new one.
455    /// Requires an in-memory iCloud keychain.
456    #[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    /// While `refuse` holds, refuse every call this device makes on a person
470    /// entry before changing state, letting its device-only calls through.
471    /// Requires an in-memory keychain.
472    pub fn refuse_person_entry_operations(&self, refuse: bool) {
473        self.with_memory(|memory| memory.refuse_person = refuse);
474    }
475}
476
477/// The magic, the number of entries, then each entry's account and bytes,
478/// each after its length.
479fn 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    // Allocate once: growing a secret Vec would abandon an unerased copy.
482    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
494/// Read what `encode_device_entries` wrote.
495fn 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}