Skip to main content

coven_crypto/custody/
keychain.rs

1//! One registered service: independent entries for each store, and the
2//! device secrets that belong to no store (E1, E11).
3
4use super::app_secrets::{self, SecretsOwner};
5use super::platform::NativeKeychain;
6use super::{KeyError, KeyMaterial, PersonRestoreCode};
7use crate::{MaterialError, MemberIdentity, SecretBytes, SecretText, StoreKeyring};
8use coven_foundation::id_source::{DeviceId, StoreId};
9use coven_foundation::locks::lock_unpoisoned;
10use std::{
11    marker::PhantomData,
12    sync::{Arc, Mutex},
13};
14
15fn validate_service(name: &str) -> Result<(), KeyError> {
16    if name.is_empty() || name.contains('\0') {
17        return Err(KeyError::InvalidServiceName);
18    }
19    Ok(())
20}
21
22const DEVICE_ID_ENTRY: &str = "device-id";
23const CREDENTIALS_ENTRY: &str = "storage-credentials";
24const INVITE_CODE_ENTRY: &str = "invite-code";
25const SETUP_CREDENTIALS_ENTRY: &str = "setup-credentials";
26const RESTORE_RECORD_ENTRY: &str = "restore-record";
27const REPLACEMENT_RECORD_ENTRY: &str = "replacement-record";
28
29#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub(crate) enum EntryScope {
31    /// This device's own entries, which never leave it.
32    DeviceOnly,
33    /// The person's entries, which reach their next devices: iCloud Keychain
34    /// carries them to every device on the person's Apple account, and Block
35    /// Store gives an Android phone's to a phone set up from it.
36    Person,
37}
38
39pub(crate) trait KeychainBackend: std::any::Any + Send + Sync {
40    fn read(
41        &self,
42        scope: EntryScope,
43        service: &str,
44        account: &str,
45    ) -> Result<Option<SecretBytes>, KeyError>;
46    fn write(
47        &self,
48        scope: EntryScope,
49        service: &str,
50        account: &str,
51        bytes: &[u8],
52    ) -> Result<(), KeyError>;
53    fn delete(&self, scope: EntryScope, service: &str, account: &str) -> Result<(), KeyError>;
54    fn person_restore_codes(&self, service: &str) -> Result<Vec<(StoreId, SecretBytes)>, KeyError>;
55    /// Every keychain group's copy of one person entry.
56    fn person_copies(&self, service: &str, account: &str) -> Result<Vec<SecretBytes>, KeyError>;
57    /// Leave exactly one copy of a person entry, holding `bytes`: write the
58    /// first group's copy, or a new entry when there is none, then delete the
59    /// other groups' copies. A failure part way leaves more than one copy.
60    fn replace_person_entry(
61        &self,
62        service: &str,
63        account: &str,
64        bytes: &[u8],
65    ) -> Result<(), KeyError>;
66    fn supports_person_entries(&self) -> bool;
67    /// The most bytes a person entry's value may take, or `None` when the
68    /// backend sets no limit a restore code could reach.
69    fn person_value_limit(&self, service: &str, account: &str) -> Option<usize>;
70    /// Whether each write of a person entry chooses again whether it goes to
71    /// a cloud backup, as Block Store's does.
72    fn person_backup_follows_writes(&self) -> bool;
73}
74
75/// The OS keychain capability, constructed only at a composition root.
76/// It never exposes native entries or its underlying credential store.
77pub struct Keychain {
78    name: String,
79    backend: Box<dyn KeychainBackend>,
80    /// Serializes updates of the app's secret name lists (D.6).
81    secret_names: Mutex<()>,
82}
83
84impl Keychain {
85    /// The OS keychain, every key and secret kept under the service `name`
86    /// (E1). Call only at a composition root, then inject it; no key is read
87    /// here.
88    pub fn native(name: impl Into<String>) -> Result<Arc<Self>, KeyError> {
89        let name = name.into();
90        validate_service(&name)?;
91        Ok(Arc::new(Self {
92            name,
93            backend: Box::new(NativeKeychain::new()?),
94            secret_names: Mutex::new(()),
95        }))
96    }
97
98    /// List this service's saved restore codes without knowing any store ids,
99    /// one per store, ordered by store id (§13.1). Apple searches iCloud
100    /// Keychain by service; account prefixes are filtered locally because its
101    /// keyring API supports exact matches only. Results are limited to the
102    /// app's accessible keychain groups; a store more than one of them holds
103    /// an entry for is `PersonRestoreCode::Ambiguous`. Block Store gives every
104    /// entry the app keeps, and only this service's restore codes are kept. Any read failure fails
105    /// the entire call; a missing or unreadable code is never silently omitted.
106    /// Keychains with neither iCloud Keychain nor Block Store return `KeyError::Unsupported`.
107    pub fn person_restore_codes(&self) -> Result<Vec<(StoreId, PersonRestoreCode)>, KeyError> {
108        Ok(by_store(self.backend.person_restore_codes(&self.name)?))
109    }
110
111    /// Whether this backend keeps the person's entries: iCloud Keychain on
112    /// Apple, Block Store on an Android phone with Google Play services, and
113    /// the memory backend on every test platform.
114    pub(super) fn supports_person_entries(&self) -> bool {
115        self.backend.supports_person_entries()
116    }
117
118    /// Whether each write of a person entry chooses again whether it goes to
119    /// a cloud backup (§13.1).
120    pub(super) fn person_backup_follows_writes(&self) -> bool {
121        self.backend.person_backup_follows_writes()
122    }
123
124    /// The most bytes the person entry `account` may hold (§13.1).
125    pub(super) fn person_value_limit(&self, account: &str) -> Option<usize> {
126        self.backend.person_value_limit(&self.name, account)
127    }
128
129    /// This device's secret `name`, which belongs to no store, or `None` if
130    /// it was never set (E11). A second store on this device reads the same
131    /// secret; deleting a store leaves it.
132    pub fn device_secret(&self, name: &str) -> Result<Option<String>, KeyError> {
133        app_secrets::read(self, SecretsOwner::Device, name)
134    }
135
136    /// Keep `value` as this device's secret `name`, in a device-only entry
137    /// with no store in its account, under the same access policy as coven's
138    /// keys (E11). Coven records the name in this device's secret list before
139    /// writing the value, so `delete_device_secrets` finds it; a failure
140    /// between the two may leave an extra name, and retrying is safe.
141    pub fn set_device_secret(&self, name: &str, value: &str) -> Result<(), KeyError> {
142        app_secrets::change(self, SecretsOwner::Device, name, Some(value))
143    }
144
145    /// Delete every listed device secret, then the list, without decoding a
146    /// value: an app's reset of this device (E11). Absent entries succeed,
147    /// so retrying after a failure finishes.
148    pub fn delete_device_secrets(&self) -> Result<(), KeyError> {
149        app_secrets::delete_all(self, SecretsOwner::Device)
150    }
151
152    /// Run `change` on the app's secret name lists, one change at a time in
153    /// this process (D.6).
154    pub(super) fn changing_secret_names<T>(&self, change: impl FnOnce() -> T) -> T {
155        let _guard = lock_unpoisoned(&self.secret_names);
156        change()
157    }
158
159    pub(super) fn read(
160        &self,
161        scope: EntryScope,
162        account: &str,
163    ) -> Result<Option<SecretBytes>, KeyError> {
164        self.backend.read(scope, &self.name, account)
165    }
166
167    pub(super) fn write(
168        &self,
169        scope: EntryScope,
170        account: &str,
171        bytes: &[u8],
172    ) -> Result<(), KeyError> {
173        self.backend.write(scope, &self.name, account, bytes)
174    }
175
176    pub(super) fn delete(&self, scope: EntryScope, account: &str) -> Result<(), KeyError> {
177        self.backend.delete(scope, &self.name, account)
178    }
179
180    pub(super) fn person_copies(&self, account: &str) -> Result<Vec<SecretBytes>, KeyError> {
181        self.backend.person_copies(&self.name, account)
182    }
183
184    pub(super) fn replace_person_entry(&self, account: &str, bytes: &[u8]) -> Result<(), KeyError> {
185        self.backend.replace_person_entry(&self.name, account, bytes)
186    }
187}
188
189impl std::fmt::Debug for Keychain {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        f.write_str("Keychain([REDACTED])")
192    }
193}
194
195/// One store's entries kept on this device only: its device id, store and
196/// member keys, provider credentials, the invite code of a join under way,
197/// the record of a restore or a replacement under way and the app's host
198/// secrets (§12.4, §13.1, §13.2, §19.3). They
199/// never leave the device, so deleting them reaches no other device of the
200/// person. Every read, write and deletion here uses the device-only scope; the
201/// person's entries belong to [`PersonEntries`](super::PersonEntries).
202pub struct StoreKeychain {
203    keychain: Arc<Keychain>,
204    store: StoreId,
205}
206
207impl StoreKeychain {
208    /// Bind the injected keychain to one store without reading a key (E1).
209    pub fn new(keychain: Arc<Keychain>, store: StoreId) -> Self {
210        Self { keychain, store }
211    }
212
213    fn account(&self, name: &str) -> String {
214        account(name, self.store)
215    }
216    fn read(&self, name: &str) -> Result<Option<SecretBytes>, KeyError> {
217        self.keychain.read(EntryScope::DeviceOnly, &self.account(name))
218    }
219    fn write(&self, name: &str, bytes: &[u8]) -> Result<(), KeyError> {
220        self.keychain.write(EntryScope::DeviceOnly, &self.account(name), bytes)
221    }
222    fn remove(&self, name: &str) -> Result<(), KeyError> {
223        self.keychain.delete(EntryScope::DeviceOnly, &self.account(name))
224    }
225
226    /// The installation id, in a device-only entry a backup doesn't carry to
227    /// another device (§19.3). Reading it does not unlock any member or store
228    /// key.
229    #[expect(clippy::map_err_ignore, reason = "a stored device id fails only by not being 8 bytes")]
230    pub fn device_id(&self) -> Result<Option<DeviceId>, KeyError> {
231        self.read(DEVICE_ID_ENTRY)?
232            .map(|bytes| {
233                let bytes: [u8; 8] =
234                    bytes.as_bytes().try_into().map_err(|_| KeyError::DeviceIdEncoding)?;
235                Ok(DeviceId(u64::from_be_bytes(bytes)))
236            })
237            .transpose()
238    }
239
240    /// Keep the installation id in this device's non-restored keychain scope.
241    pub fn set_device_id(&self, device: DeviceId) -> Result<(), KeyError> {
242        self.write(DEVICE_ID_ENTRY, &device.0.to_be_bytes())
243    }
244
245    /// Remove an unpublished installation's entry after creation failed.
246    pub fn delete_device_id(&self) -> Result<(), KeyError> {
247        self.remove(DEVICE_ID_ENTRY)
248    }
249
250    /// Provider-encoded credentials. Public storage settings never contain them.
251    pub fn storage_credentials(&self) -> Result<Option<SecretBytes>, KeyError> {
252        self.read(CREDENTIALS_ENTRY)
253    }
254
255    /// Commit provider-encoded credentials in this device's keychain scope.
256    pub fn set_storage_credentials(&self, bytes: &SecretBytes) -> Result<(), KeyError> {
257        self.write(CREDENTIALS_ENTRY, bytes.as_bytes())
258    }
259
260    /// Remove this device's provider credentials; an absent entry succeeds.
261    pub fn delete_storage_credentials(&self) -> Result<(), KeyError> {
262        self.remove(CREDENTIALS_ENTRY)
263    }
264
265    /// The credentials a storage setup under way connects with, kept apart
266    /// from the committed ones until it finishes, so undoing it leaves those
267    /// as they were (§11.6, §20.8).
268    pub fn setup_credentials(&self) -> Result<Option<SecretBytes>, KeyError> {
269        self.read(SETUP_CREDENTIALS_ENTRY)
270    }
271
272    /// Keep the credentials of a storage setup about to write to storage.
273    pub fn set_setup_credentials(&self, bytes: &SecretBytes) -> Result<(), KeyError> {
274        self.write(SETUP_CREDENTIALS_ENTRY, bytes.as_bytes())
275    }
276
277    /// Remove a finished or undone setup's credentials; an absent entry
278    /// succeeds.
279    pub fn delete_setup_credentials(&self) -> Result<(), KeyError> {
280        self.remove(SETUP_CREDENTIALS_ENTRY)
281    }
282
283    /// The invite code of a join under way for this store on this device:
284    /// its saved request is encrypted with the code's secret, so resuming
285    /// needs the code (§13.2). It is never synced.
286    #[expect(
287        clippy::map_err_ignore,
288        reason = "a saved invite code fails only by not being UTF-8, which Encoding names"
289    )]
290    pub fn invite_code(&self) -> Result<Option<SecretText>, KeyError> {
291        self.read(INVITE_CODE_ENTRY)?
292            .map(|bytes| {
293                std::str::from_utf8(bytes.as_bytes())
294                    .map(|code| SecretText::new(code.to_owned()))
295                    .map_err(|_| MaterialError::Encoding.into())
296            })
297            .transpose()
298    }
299
300    /// Keep a join's invite code until the join ends.
301    pub fn set_invite_code(&self, code: &SecretText) -> Result<(), KeyError> {
302        self.write(INVITE_CODE_ENTRY, code.as_str().as_bytes())
303    }
304
305    /// Remove a join's invite code once the join has ended; an absent entry
306    /// succeeds.
307    pub fn delete_invite_code(&self) -> Result<(), KeyError> {
308        self.remove(INVITE_CODE_ENTRY)
309    }
310
311    /// The record of a restore under way for this store on this device: the
312    /// restore code it loads with and the name it registers the device
313    /// under. A restore past its registration finishes from it, so the app
314    /// can resume it without the code (§13.1). It is never synced.
315    pub fn restore_record(&self) -> Result<Option<(SecretText, String)>, KeyError> {
316        self.read_code_record(RESTORE_RECORD_ENTRY)
317    }
318
319    /// Keep a restore's record from before it registers the device until the
320    /// restore ends: the code, which holds no NUL, then a NUL, then the
321    /// device's name.
322    pub fn set_restore_record(&self, code: &SecretText, device_name: &str) -> Result<(), KeyError> {
323        self.write_code_record(RESTORE_RECORD_ENTRY, code, device_name)
324    }
325
326    /// Remove a restore's record once the restore has ended; an absent entry
327    /// succeeds.
328    pub fn delete_restore_record(&self) -> Result<(), KeyError> {
329        self.remove(RESTORE_RECORD_ENTRY)
330    }
331
332    /// What a replacement of this device's installation under way keeps to
333    /// finish (§19.3): the restore code it loads with and the name it
334    /// registers the fresh device under. A replacement past its record
335    /// resumes from it with nothing from the app. It is never synced.
336    pub fn replacement_record(&self) -> Result<Option<(SecretText, String)>, KeyError> {
337        self.read_code_record(REPLACEMENT_RECORD_ENTRY)
338    }
339
340    /// Keep a replacement's code and device name from before it registers the
341    /// fresh device until it is published or ends, as a restore's record is
342    /// kept.
343    pub fn set_replacement_record(
344        &self,
345        code: &SecretText,
346        device_name: &str,
347    ) -> Result<(), KeyError> {
348        self.write_code_record(REPLACEMENT_RECORD_ENTRY, code, device_name)
349    }
350
351    /// Remove a replacement's record once it has been published or has ended;
352    /// an absent entry succeeds.
353    pub fn delete_replacement_record(&self) -> Result<(), KeyError> {
354        self.remove(REPLACEMENT_RECORD_ENTRY)
355    }
356
357    #[expect(
358        clippy::map_err_ignore,
359        reason = "a code record fails only by its layout, which Encoding names"
360    )]
361    fn read_code_record(&self, entry: &str) -> Result<Option<(SecretText, String)>, KeyError> {
362        self.read(entry)?
363            .map(|bytes| {
364                let text = std::str::from_utf8(bytes.as_bytes())
365                    .map_err(|_| KeyError::from(MaterialError::Encoding))?;
366                let (code, name) = text.split_once('\0').ok_or(MaterialError::Encoding)?;
367                Ok((SecretText::new(code.to_owned()), name.to_owned()))
368            })
369            .transpose()
370    }
371
372    fn write_code_record(
373        &self,
374        entry: &str,
375        code: &SecretText,
376        device_name: &str,
377    ) -> Result<(), KeyError> {
378        if code.as_str().contains('\0') {
379            return Err(MaterialError::Encoding.into());
380        }
381        let record = SecretText::new(format!("{}\0{device_name}", code.as_str()));
382        self.write(entry, record.as_str().as_bytes())
383    }
384
385    /// Remove this device's entries for the store, including all recorded host
386    /// secrets, without opening the database or decoding the values. Delete
387    /// listed secrets before the list, then coven's other entries. The person's
388    /// restore code and S3 key stay: they serve the person's next devices
389    /// (§13.1), and so do this device's own secrets, which belong to no store.
390    /// The caller holds the store's deletion lock; repeating after a failure
391    /// is safe, including absent listed entries.
392    pub fn delete_device_entries(&self) -> Result<(), KeyError> {
393        app_secrets::delete_all(&self.keychain, self.secrets())?;
394        for name in [
395            StoreKeyring::ENTRY,
396            MemberIdentity::ENTRY,
397            DEVICE_ID_ENTRY,
398            CREDENTIALS_ENTRY,
399            SETUP_CREDENTIALS_ENTRY,
400            INVITE_CODE_ENTRY,
401            RESTORE_RECORD_ENTRY,
402            REPLACEMENT_RECORD_ENTRY,
403        ] {
404            self.remove(name)?;
405        }
406        Ok(())
407    }
408
409    fn secrets(&self) -> SecretsOwner {
410        SecretsOwner::Store(self.store)
411    }
412
413    /// Records the name in a device-only keychain list before writing the value
414    /// to its own entry. Arbitrary names are encoded into native account names;
415    /// each value retains the platform's per-entry size limit. A failed write
416    /// may leave an extra name, so deletion can always find every saved secret.
417    /// The caller holds the store's writer lock; this capability serializes updates.
418    pub fn set_host_secret(&self, name: &str, value: &str) -> Result<(), KeyError> {
419        app_secrets::change(&self.keychain, self.secrets(), name, Some(value))
420    }
421
422    /// The app secret, or `None` if it was never set (E11).
423    pub fn host_secret(&self, name: &str) -> Result<Option<String>, KeyError> {
424        app_secrets::read(&self.keychain, self.secrets(), name)
425    }
426
427    /// Removes the secret before its recorded name (E11); absent entries succeed.
428    /// Failure can leave an extra name; retrying is safe. The caller holds the
429    /// store's writer lock.
430    pub fn delete_host_secret(&self, name: &str) -> Result<(), KeyError> {
431        app_secrets::change(&self.keychain, self.secrets(), name, None)
432    }
433}
434
435impl std::fmt::Debug for StoreKeychain {
436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
437        f.write_str("StoreKeychain([REDACTED])")
438    }
439}
440
441/// The account of one store's entry `name`, in device-only and person
442/// entries alike: `<name>:<store>`.
443pub(super) fn account(name: &str, store: StoreId) -> String {
444    format!("{name}:{store}")
445}
446
447/// OS keychain custody for `StoreKeyring` or `MemberIdentity`, built at a composition root.
448pub struct KeyringCustody<T> {
449    keychain: Arc<StoreKeychain>,
450    material: PhantomData<fn() -> T>,
451}
452
453impl<T> KeyringCustody<T> {
454    /// Retain the injected store keychain; construction reads no key (E1).
455    pub fn new(keychain: Arc<StoreKeychain>) -> Self {
456        Self { keychain, material: PhantomData }
457    }
458    pub(crate) fn read(&self, name: &str) -> Result<Option<SecretBytes>, KeyError> {
459        self.keychain.read(name)
460    }
461    pub(crate) fn write(&self, name: &str, bytes: &[u8]) -> Result<(), KeyError> {
462        self.keychain.write(name, bytes)
463    }
464    pub(crate) fn remove(&self, name: &str) -> Result<(), KeyError> {
465        self.keychain.remove(name)
466    }
467}
468
469impl<T> std::fmt::Debug for KeyringCustody<T> {
470    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
471        f.write_str("KeyringCustody([REDACTED])")
472    }
473}
474
475/// Group the restore codes a search found by store, ordered by store id. A
476/// store found more than once is ambiguous: no copy is the store's code.
477fn by_store(codes: Vec<(StoreId, SecretBytes)>) -> Vec<(StoreId, PersonRestoreCode)> {
478    let mut stores = std::collections::BTreeMap::new();
479    for (store, code) in codes {
480        stores
481            .entry(store)
482            .and_modify(|found| {
483                tracing::warn!(%store, "more than one keychain group holds a restore code");
484                *found = PersonRestoreCode::Ambiguous;
485            })
486            .or_insert(PersonRestoreCode::Saved(code));
487    }
488    stores.into_iter().collect()
489}
490
491#[cfg(test)]
492#[path = "keychain_tests.rs"]
493mod tests;
494
495#[cfg(any(test, feature = "in-memory-keychain"))]
496#[path = "keychain_test_utils.rs"]
497mod test_utils;