Skip to main content

coven_sync/
credential_custody.rs

1//! Device credentials and the person's saved recovery values commit together.
2
3use crate::{saved_code, SavedName, SyncError};
4use coven_crypto::{
5    custody::{PersonEntries, StoreKeychain},
6    SecretBytes,
7};
8use coven_format::codes::RestoreCode;
9use coven_foundation::files::StoreDir;
10use coven_storage::StorageCredentials;
11use std::sync::Arc;
12
13/// The keychain entries a credential change commits: this device's provider
14/// credentials, and the person's restore code and S3 key, saved for their next
15/// devices (§13.1).
16pub struct CredentialKeychains {
17    /// This device's own entries for the store.
18    device: Arc<StoreKeychain>,
19    /// The person's entries for the store, shared by all their devices.
20    person: Arc<PersonEntries>,
21    /// The store's directory, whose settings file records the location these
22    /// credentials are for.
23    directory: StoreDir,
24}
25
26impl CredentialKeychains {
27    /// Pair one store's device-only entries and the person's entries, beside
28    /// the store's directory.
29    pub fn new(
30        device: Arc<StoreKeychain>,
31        person: Arc<PersonEntries>,
32        directory: StoreDir,
33    ) -> Self {
34        Self { device, person, directory }
35    }
36
37    /// This device's committed provider credentials, if any.
38    pub fn storage_credentials(&self) -> Result<Option<SecretBytes>, SyncError> {
39        Ok(self.device.storage_credentials()?)
40    }
41
42    /// Save the saved restore code with the store's name, or the entry's
43    /// when that is newer, where the keychain keeps person entries (§13.1).
44    pub fn refresh_restore_code(
45        &self,
46        code: &RestoreCode,
47        name: &SavedName,
48    ) -> Result<(), SyncError> {
49        if self.person.supported() {
50            saved_code::save(&self.person, code, name)?;
51        }
52        Ok(())
53    }
54
55    /// The saved location with this device's credentials; None when either is absent.
56    pub fn connection(&self) -> Result<Option<coven_storage::ConnectionCredentials>, SyncError> {
57        crate::read_connection(&self.directory, &self.device)
58    }
59
60    /// The recorded location, with its labels, and whether this device's
61    /// credentials for it are held, as the sync state reads it (§19.1).
62    pub fn location(
63        &self,
64    ) -> Result<coven_database::RecordedLocation<coven_storage::StorageConfig>, SyncError> {
65        crate::restore_codes::read_location(&self.directory, &self.device)
66    }
67}
68
69#[derive(Clone, Copy)]
70enum CredentialEntry {
71    DeviceCredentials,
72    RestoreCode,
73    S3Credentials,
74}
75
76impl CredentialEntry {
77    fn read(&self, keychains: &CredentialKeychains) -> Result<Option<SecretBytes>, SyncError> {
78        Ok(match self {
79            Self::DeviceCredentials => keychains.device.storage_credentials()?,
80            Self::RestoreCode => keychains.person.restore_code()?,
81            Self::S3Credentials => keychains.person.s3_credentials()?,
82        })
83    }
84
85    fn write(&self, keychains: &CredentialKeychains, bytes: &SecretBytes) -> Result<(), SyncError> {
86        match self {
87            Self::DeviceCredentials => keychains.device.set_storage_credentials(bytes),
88            Self::RestoreCode => keychains.person.set_restore_code(bytes),
89            Self::S3Credentials => keychains.person.set_s3_credentials(bytes),
90        }
91        .map_err(SyncError::from)
92    }
93
94    fn delete(&self, keychains: &CredentialKeychains) -> Result<(), SyncError> {
95        match self {
96            Self::DeviceCredentials => keychains.device.delete_storage_credentials(),
97            Self::RestoreCode => keychains.person.delete_restore_code(),
98            Self::S3Credentials => keychains.person.delete_s3_credentials(),
99        }
100        .map_err(SyncError::from)
101    }
102
103    fn replace(
104        &self,
105        keychain: &CredentialKeychains,
106        value: Option<&SecretBytes>,
107    ) -> Result<(), SyncError> {
108        match value {
109            Some(bytes) => self.write(keychain, bytes),
110            None => self.delete(keychain),
111        }
112    }
113}
114
115/// What a credential commit puts in one entry.
116enum Update<'a> {
117    /// Exactly these bytes, or nothing.
118    Value(Option<SecretBytes>),
119    /// The restore code, with the newer of this name and the entry's (§13.1).
120    Code(&'a RestoreCode, &'a SavedName),
121}
122
123impl Update<'_> {
124    fn apply(
125        &self,
126        entry: CredentialEntry,
127        keychain: &CredentialKeychains,
128    ) -> Result<(), SyncError> {
129        match self {
130            Self::Value(value) => entry.replace(keychain, value.as_ref()),
131            Self::Code(code, name) => saved_code::save(&keychain.person, code, name),
132        }
133    }
134}
135
136/// Previous values of exactly the custody entries a credential commit changes.
137/// Setup and bootstrap retain this until their whole operation has committed.
138pub struct CredentialRollback {
139    entries: Vec<(CredentialEntry, Option<SecretBytes>)>,
140}
141
142impl CredentialRollback {
143    /// Restore every captured value, retaining all failures for the initiator.
144    pub fn restore(self, keychain: &CredentialKeychains) -> Result<(), SyncError> {
145        let mut failure = None;
146        for (entry, bytes) in self.entries.into_iter().rev() {
147            let result = entry.replace(keychain, bytes.as_ref());
148            if let Err(error) = result {
149                failure = Some(match failure {
150                    Some(operation) => SyncError::cleanup(operation, error),
151                    None => error,
152                });
153            }
154        }
155        match failure {
156            Some(error) => Err(error),
157            None => Ok(()),
158        }
159    }
160}
161
162/// Commit device credentials and, on Apple, the separate S3 key. Setup and
163/// bootstrap also supply the restore code with the store's name, and remove
164/// any S3 entry when setting up an account provider. Replacing credentials
165/// supplies no code; OAuth refresh touches neither person entry. A failed
166/// write restores every prior value and returns any rollback failures with
167/// the original cause.
168pub fn commit_credentials(
169    keychain: &CredentialKeychains,
170    credentials: &StorageCredentials,
171    code: Option<(&RestoreCode, &SavedName)>,
172) -> Result<CredentialRollback, SyncError> {
173    let mut updates =
174        vec![(CredentialEntry::DeviceCredentials, Update::Value(Some(credentials.encode()?)))];
175    if keychain.person.supported() {
176        if let StorageCredentials::S3(keys) = credentials {
177            updates.push((CredentialEntry::S3Credentials, Update::Value(Some(keys.encode()?))));
178        } else if code.is_some() {
179            updates.push((CredentialEntry::S3Credentials, Update::Value(None)));
180        }
181        if let Some((code, name)) = code {
182            updates.push((CredentialEntry::RestoreCode, Update::Code(code, name)));
183        }
184    }
185    apply(keychain, updates)
186}
187
188/// Commit an account provider's person entries beside device credentials
189/// already in place: the restore code with the store's name, and no S3 key.
190/// A join publishes this way, its sign-in kept on the device since it saved
191/// its invite code (§13.2). A failed write restores every prior value.
192pub(crate) fn commit_account_code(
193    keychain: &CredentialKeychains,
194    code: &RestoreCode,
195    name: &SavedName,
196) -> Result<CredentialRollback, SyncError> {
197    let updates = if keychain.person.supported() {
198        vec![
199            (CredentialEntry::S3Credentials, Update::Value(None)),
200            (CredentialEntry::RestoreCode, Update::Code(code, name)),
201        ]
202    } else {
203        Vec::new()
204    };
205    apply(keychain, updates)
206}
207
208/// Write each update in order, after reading the value each replaces. A
209/// failed write restores every prior value and returns any rollback failure
210/// with the original cause.
211fn apply(
212    keychain: &CredentialKeychains,
213    updates: Vec<(CredentialEntry, Update<'_>)>,
214) -> Result<CredentialRollback, SyncError> {
215    let previous = CredentialRollback {
216        entries: updates
217            .iter()
218            .map(|(entry, _)| Ok((*entry, entry.read(keychain)?)))
219            .collect::<Result<_, SyncError>>()?,
220    };
221    for (entry, update) in updates {
222        if let Err(operation) = update.apply(entry, keychain) {
223            return Err(match previous.restore(keychain) {
224                Ok(()) => operation,
225                Err(cleanup) => SyncError::cleanup(operation, cleanup),
226            });
227        }
228    }
229    Ok(previous)
230}
231
232#[cfg(test)]
233#[path = "credential_custody_tests.rs"]
234mod tests;