Skip to main content

coven_sync/
restore_codes.rs

1//! Restore-code generation and credential replacement (§13.1, E9).
2
3use crate::{commit_credentials, CredentialRollback, DeviceCredentials, SessionSignIn, SyncError};
4use coven_crypto::{
5    custody::{KeySession, StoreKeychain},
6    MemberIdentity, SecretText,
7};
8use coven_database::{DbError, StoreDatabase};
9use coven_format::codes::RestoreCode;
10use coven_foundation::files::StoreDir;
11use coven_storage::{
12    ConnectionCredentials, RestoreStorage, S3Credentials, Storage, StorageConfig,
13    StorageCredentials,
14};
15use std::sync::Arc;
16
17/// This member's restore code from the applied `state`: their stable id and
18/// the held pair it binds now, the store id and `storage` (§13.1).
19pub(crate) fn member_code(
20    state: &coven_database::StoreState,
21    identity: &MemberIdentity,
22    storage: &RestoreStorage,
23) -> Result<RestoreCode, SyncError> {
24    let store = state.store.as_ref().ok_or(SyncError::NoStorage)?;
25    let current = state
26        .active_member(&identity.member())
27        .ok_or(SyncError::Removed(coven_database::Removal::Member))?
28        .keys;
29    // A kept self-replacement's candidate is current before custody
30    // installs it; a retired pair never is.
31    let selected = identity
32        .activate(&current)
33        .ok_or(SyncError::MemberKeysReplaced { member: identity.member() })?;
34    Ok(RestoreCode {
35        store: store.id,
36        member: identity.member(),
37        member_keys: selected.keys().clone(),
38        storage: storage.encode()?,
39    })
40}
41
42/// The restore code that names `identity`'s held pair and the store's
43/// `location`, with no credentials (§13.1).
44pub fn location_code(
45    store: coven_foundation::id_source::StoreId,
46    identity: &MemberIdentity,
47    location: StorageConfig,
48) -> Result<RestoreCode, SyncError> {
49    Ok(RestoreCode {
50        store,
51        member: identity.member(),
52        member_keys: identity.keys().clone(),
53        storage: RestoreStorage::location_only(location).encode()?,
54    })
55}
56
57/// Owns code generation and credential changes for one open handle, for
58/// its whole lifetime: connected or not, one change runs at a time, and a
59/// read waits for the change in flight. A change that needs the connection
60/// takes its sequence owner as an argument. Closing waits for updates
61/// holding the lock, even when their app futures were dropped.
62#[derive(Clone)]
63pub struct RestoreCodes {
64    inner: Arc<tokio::sync::Mutex<Option<RestoreCodesInner>>>,
65    credentials: Arc<DeviceCredentials>,
66    /// Where a bug in a replacement its caller stopped waiting for goes.
67    bugs: coven_foundation::task::BugSinkRef,
68}
69
70struct RestoreCodesInner {
71    directory: StoreDir,
72    database: StoreDatabase,
73    identity: Arc<KeySession<MemberIdentity>>,
74    credentials: Arc<DeviceCredentials>,
75}
76
77impl RestoreCodes {
78    /// The recorded location survives losing this device's credentials.
79    pub async fn location(&self) -> Result<Option<coven_storage::StorageConfig>, SyncError> {
80        let owner = self.inner.lock().await;
81        let owner = owner.as_ref().ok_or(coven_database::DbError::StoreClosed)?;
82        Ok(coven_storage::recorded_config(&owner.directory)?)
83    }
84
85    /// Record `location`, the recorded location as a connection made from it
86    /// just labelled it (§20.2), and write it to the sync status row, which
87    /// an app's live query reads it from (api.md E4). Writes only when its
88    /// labels changed.
89    pub async fn record_labels(&self, location: &StorageConfig) -> Result<(), SyncError> {
90        let owner = self.inner.lock().await;
91        let owner = owner.as_ref().ok_or(coven_database::DbError::StoreClosed)?;
92        let recorded =
93            coven_storage::recorded_config(&owner.directory)?.ok_or(SyncError::NoStorage)?;
94        if recorded != *location {
95            coven_storage::record_config(&owner.directory, location)?;
96            // The connection that labelled it used this device's credentials.
97            let connected = coven_database::RecordedLocation::Connected(location.clone());
98            crate::record_location(&owner.database, connected, None).await?;
99        }
100        Ok(())
101    }
102
103    /// Compose at the facade's opening boundary. The settings and credentials
104    /// are also the narrow persisted connection contract used by storage setup.
105    pub fn new(
106        directory: StoreDir,
107        database: StoreDatabase,
108        identity: Arc<KeySession<MemberIdentity>>,
109        credentials: Arc<DeviceCredentials>,
110    ) -> Self {
111        Self {
112            bugs: database.bugs().clone(),
113            inner: Arc::new(tokio::sync::Mutex::new(Some(RestoreCodesInner {
114                directory,
115                database,
116                identity,
117                credentials: credentials.clone(),
118            }))),
119            credentials,
120        }
121    }
122
123    /// How a connection reaches storage with these committed credentials: a
124    /// rejected OAuth token refreshes in this installation's device custody,
125    /// which takes no lock held by credential changes (§20.2).
126    pub fn provider_auth(&self, credentials: StorageCredentials) -> coven_storage::ProviderAuth {
127        coven_storage::ProviderAuth::new(credentials, self.credentials.clone())
128    }
129
130    /// Encode this member's stable id and current private pair, store id and
131    /// storage location only. The pair is the held one the applied
132    /// history binds now; without it the call reports `MemberKeysReplaced` rather
133    /// than exporting a retired pair (§13.1).
134    pub async fn restore_code(&self) -> Result<String, SyncError> {
135        let guard = self.inner.lock().await;
136        let owner = guard.as_ref().ok_or(DbError::StoreClosed)?;
137        let location =
138            coven_storage::recorded_config(&owner.directory)?.ok_or(SyncError::NoStorage)?;
139        Ok(owner.code(&RestoreStorage::location_only(location)).await?.to_text()?.to_string())
140    }
141
142    /// Replace this member's pair on `sync`, the connection's sequence
143    /// owner, and return the code for that exact result. The change holds
144    /// this owner from the call on, so credential changes, reads and
145    /// `settled` wait for it, even once its caller stops waiting.
146    pub async fn replace_member_keys(
147        &self,
148        sync: Arc<crate::SequenceSync>,
149    ) -> Result<SecretText, SyncError> {
150        let guard = self.inner.clone().lock_owned().await;
151        let replacing = async move {
152            let owner = guard.as_ref().ok_or(DbError::StoreClosed)?;
153            // Reject missing location before publishing a new binding.
154            coven_storage::recorded_config(&owner.directory)?.ok_or(SyncError::NoStorage)?;
155            sync.replace_member_keys().await?;
156            Ok(sync
157                .finish_member_keys(true, |identity, store| owner.refresh_code(identity, store))
158                .await?
159                .expect("the initiating replacement owns code completion"))
160        };
161        coven_foundation::task::spawn_completing(
162            "replace member keys",
163            self.bugs.clone(),
164            replacing,
165        )
166        .await?
167    }
168
169    /// Finish the code step of a self-replacement a pass of `sync` resumed
170    /// (§11.5).
171    pub(crate) async fn resume_member_keys(
172        &self,
173        sync: &crate::SequenceSync,
174    ) -> Result<(), SyncError> {
175        let guard = self.inner.lock().await;
176        let owner = guard.as_ref().ok_or(DbError::StoreClosed)?;
177        sync.finish_member_keys(false, |identity, store| owner.refresh_code(identity, store))
178            .await?;
179        Ok(())
180    }
181
182    /// The connection credentials for the S3 key `key` at the recorded
183    /// location, for a connection that uses it before custody holds it. A
184    /// member whose removal applied gets `Removed` (§14.1).
185    pub async fn s3_connection(
186        &self,
187        key: S3Credentials,
188    ) -> Result<ConnectionCredentials, SyncError> {
189        let guard = self.inner.lock().await;
190        let owner = guard.as_ref().ok_or(DbError::StoreClosed)?;
191        let next = owner.s3_connection(key)?;
192        next.validate()?;
193        refuse_after_leaving(&owner.database, &owner.identity).await?;
194        Ok(next)
195    }
196
197    /// Use the S3 key the person made in the provider's console, once its
198    /// provider check passed, without changing identity, location or code
199    /// (§14.3): journal the entry that records it as this member's access
200    /// on `sync`, whose connection signs with the key; take it in custody
201    /// and on `live`, the owner of the store's connection when that is
202    /// another; and claim the entry with it. Answers the key id the record
203    /// named before, when the call has an entry. A member whose removal
204    /// applied gets `Removed` (§14.1). The change holds this owner as
205    /// `replace_member_keys` does.
206    pub async fn use_access_key(
207        &self,
208        sync: Arc<crate::SequenceSync>,
209        live: Option<Arc<crate::SequenceSync>>,
210        key: S3Credentials,
211    ) -> Result<Option<String>, SyncError> {
212        let guard = self.inner.clone().lock_owned().await;
213        let using = async move {
214            let owner = guard.as_ref().ok_or(DbError::StoreClosed)?;
215            let access_key_id = key.access_key_id.clone();
216            let next = owner.s3_connection(key)?;
217            next.validate()?;
218            refuse_after_leaving(&owner.database, &owner.identity).await?;
219            sync.use_access_key(access_key_id, owner.install(next, live.as_deref())).await
220        };
221        coven_foundation::task::spawn_completing("use the access key", self.bugs.clone(), using)
222            .await?
223    }
224
225    /// Read committed provider data without exposing custody or a connection.
226    pub async fn connection(&self) -> Result<Option<ConnectionCredentials>, SyncError> {
227        let guard = self.inner.lock().await;
228        guard.as_ref().ok_or(DbError::StoreClosed)?.connection()
229    }
230
231    /// Reserve the credential owner until remote setup either commits or fails.
232    /// The returned commit includes the saved restore code and location, and its
233    /// compensation remains available until store keys and the origin are applied.
234    /// An OAuth setup commits `sign_in`'s current tokens, which then refresh in
235    /// device custody; a rollback holds them in the session again. Reconnecting
236    /// with device custody keeps its current tokens, including any refresh.
237    pub async fn prepare_setup(
238        &self,
239        data: ConnectionCredentials,
240        sign_in: Option<Arc<SessionSignIn>>,
241    ) -> Result<(crate::StorageCommit, SecretText), SyncError> {
242        data.validate()?;
243        let guard = self.inner.clone().lock_owned().await;
244        let owner = guard.as_ref().ok_or(DbError::StoreClosed)?;
245        let identity =
246            owner.identity.read()?.ok_or(coven_storage::StorageFailure::MemberKeysMissing)?;
247        // The code names the stable id its unchanged private-pair blob belongs to (D13).
248        let code = location_code(owner.directory.id(), &identity, data.location.clone())?;
249        let text = SecretText::new(code.to_text()?.to_string());
250        // The creation slot will publish the name chosen locally (§13.1).
251        let (name, named_at) = owner.database.named_store().await?;
252        let name = crate::SavedName { name, named_at };
253        let previous_location = coven_storage::recorded_config(&owner.directory)?;
254        Ok((
255            Box::new(move || {
256                let owner = guard.as_ref().expect("reserved credential owner");
257                let previous = match &sign_in {
258                    Some(session) => session.publish(&owner.credentials, |keychain, tokens| {
259                        commit_credentials(
260                            keychain,
261                            &StorageCredentials::OAuth(tokens.clone()),
262                            Some((&code, &name)),
263                        )
264                    })?,
265                    None => owner.credentials.write(|keychain| {
266                        let credentials = match &data.credentials {
267                            StorageCredentials::OAuth(_) => {
268                                StorageCredentials::OAuth(crate::sign_in::held_tokens(keychain)?)
269                            }
270                            credentials => credentials.clone(),
271                        };
272                        commit_credentials(keychain, &credentials, Some((&code, &name)))
273                    })?,
274                };
275                let rollback = move |owner: &RestoreCodesInner, previous| {
276                    let result = owner.restore_connection(previous_location, previous);
277                    if let Some(session) = &sign_in {
278                        session.unpublish();
279                    }
280                    result
281                };
282                if let Err(error) = coven_storage::record_config(&owner.directory, &data.location) {
283                    return Err(match rollback(owner, previous) {
284                        Ok(()) => error.into(),
285                        Err(cleanup) => SyncError::cleanup(error.into(), cleanup),
286                    });
287                }
288                Ok(Box::new(move || {
289                    rollback(guard.as_ref().expect("reserved credential owner"), previous)
290                }))
291            }),
292            text,
293        ))
294    }
295
296    /// Wait for a credential change in flight, even one whose caller stopped
297    /// waiting: a connection closes only after the change it runs.
298    pub async fn settled(&self) {
299        drop(self.inner.lock().await);
300    }
301
302    /// Finish the current update, then release custody and connection owners.
303    /// Updates that have not acquired the lock receive StoreClosed.
304    pub async fn close(&self) {
305        self.inner.lock().await.take();
306    }
307
308    /// Run `work`, named `operation`, on the store's directory while this
309    /// owner stays open: closing waits for it, so the store's writer lock
310    /// isn't released under a write of its files, and a closed store refuses
311    /// it with `StoreClosed`.
312    pub async fn while_open(
313        &self,
314        operation: &'static str,
315        work: impl FnOnce(&StoreDir) -> Result<(), coven_foundation::files::FileError> + Send + 'static,
316    ) -> Result<(), SyncError> {
317        let owner = self.inner.lock().await;
318        let directory = owner.as_ref().ok_or(DbError::StoreClosed)?.directory.clone();
319        coven_foundation::task::blocking_completing(operation, self.bugs.clone(), move || {
320            work(&directory)
321        })
322        .await??;
323        Ok(())
324    }
325}
326
327impl RestoreCodesInner {
328    fn refresh_code(
329        &self,
330        identity: &MemberIdentity,
331        store: &coven_database::StoreIdentity,
332    ) -> Result<SecretText, SyncError> {
333        let code = location_code(
334            store.id,
335            identity,
336            coven_storage::recorded_config(&self.directory)?.ok_or(SyncError::NoStorage)?,
337        )?;
338        let text = SecretText::new(code.to_text()?.to_string());
339        self.credentials.write(|keychains| {
340            keychains.refresh_restore_code(&code, &crate::SavedName::of(store))
341        })?;
342        Ok(text)
343    }
344
345    fn restore_connection(
346        &self,
347        location: Option<StorageConfig>,
348        credentials: CredentialRollback,
349    ) -> Result<(), SyncError> {
350        let credentials = self.credentials.write(|keychain| credentials.restore(keychain));
351        let location = match location {
352            Some(location) => coven_storage::record_config(&self.directory, &location),
353            None => coven_storage::remove_recorded_config(&self.directory),
354        }
355        .map_err(SyncError::from);
356        match (credentials, location) {
357            (Ok(()), result) | (result, Ok(())) => result,
358            (Err(operation), Err(cleanup)) => Err(SyncError::cleanup(operation, cleanup)),
359        }
360    }
361
362    fn connection(&self) -> Result<Option<ConnectionCredentials>, SyncError> {
363        self.credentials.connection()
364    }
365
366    async fn code(&self, storage: &RestoreStorage) -> Result<RestoreCode, SyncError> {
367        let state = self.database.store_state().await?;
368        let identity =
369            self.identity.read()?.ok_or(coven_storage::StorageFailure::MemberKeysMissing)?;
370        member_code(&state, &identity, storage)
371    }
372
373    /// `key` as the connection credentials at the recorded location.
374    fn s3_connection(&self, key: S3Credentials) -> Result<ConnectionCredentials, SyncError> {
375        let location =
376            coven_storage::recorded_config(&self.directory)?.ok_or(SyncError::NoStorage)?;
377        Ok(ConnectionCredentials { location, credentials: StorageCredentials::S3(key) })
378    }
379
380    async fn install(
381        &self,
382        next: ConnectionCredentials,
383        sync: Option<&crate::SequenceSync>,
384    ) -> Result<(), SyncError> {
385        next.validate()?;
386        let previous = self.connection()?;
387        let credentials = next.credentials.clone();
388        let custody = self.credentials.clone();
389        let commit: crate::StorageCommit = Box::new(move || {
390            let previous =
391                custody.write(|keychain| commit_credentials(keychain, &credentials, None))?;
392            Ok(Box::new(move || custody.write(|keychain| previous.restore(keychain))))
393        });
394        match sync {
395            Some(sync) => sync.install_credentials(previous, next, commit).await,
396            // Without a connection, no pass can apply a removal meanwhile.
397            None => {
398                refuse_after_leaving(&self.database, &self.identity).await?;
399                commit().map(drop)
400            }
401        }
402    }
403}
404
405/// Refuse a credential change once this member's removal has applied. The
406/// person has no storage access left to change, and saving an S3 key would
407/// write it back into the person entries their removal emptied (§14.1).
408pub(crate) async fn refuse_after_leaving(
409    database: &StoreDatabase,
410    identity: &KeySession<MemberIdentity>,
411) -> Result<(), SyncError> {
412    let member = identity.read()?.ok_or(coven_storage::StorageFailure::MemberKeysMissing)?.member();
413    if crate::effects::left(&database.store_state().await?, &member) {
414        return Err(SyncError::Removed(coven_database::Removal::Member));
415    }
416    Ok(())
417}
418
419pub(crate) async fn install_session(
420    storage: &dyn Storage,
421    credentials: StorageCredentials,
422) -> Result<(), coven_storage::StorageError> {
423    match credentials {
424        StorageCredentials::S3(keys) => storage.set_s3_credentials(keys).await,
425        StorageCredentials::OAuth(tokens) => storage.set_oauth_tokens(tokens).await,
426        StorageCredentials::CloudKit => Ok(()),
427    }
428}
429
430/// Read the saved provider location and custody credentials without opening a
431/// database. Shared by normal sync, read-only file access and damaged-database
432/// recovery. Absence means storage is not configured on this installation.
433pub fn read_connection(
434    directory: &StoreDir,
435    keychain: &StoreKeychain,
436) -> Result<Option<ConnectionCredentials>, SyncError> {
437    let Some(location) = coven_storage::recorded_config(directory)? else {
438        return Ok(None);
439    };
440    connection_at(location, keychain)
441}
442
443/// The storage location recorded on this installation, with its labels, and
444/// whether custody holds credentials for it, as the sync state reads it
445/// (§19.1): as a store opens, and as its closed status is read (api.md E1).
446pub fn read_location(
447    directory: &StoreDir,
448    keychain: &StoreKeychain,
449) -> Result<coven_database::RecordedLocation<StorageConfig>, SyncError> {
450    let Some(location) = coven_storage::recorded_config(directory)? else {
451        return Ok(coven_database::RecordedLocation::None);
452    };
453    Ok(match connection_at(location.clone(), keychain)? {
454        Some(_) => coven_database::RecordedLocation::Connected(location),
455        None => coven_database::RecordedLocation::SignedOut(location),
456    })
457}
458
459/// The recorded `location` with custody's credentials for it, if custody
460/// holds them.
461fn connection_at(
462    location: coven_storage::StorageConfig,
463    keychain: &StoreKeychain,
464) -> Result<Option<ConnectionCredentials>, SyncError> {
465    let Some(bytes) = keychain.storage_credentials()? else {
466        return Ok(None);
467    };
468    let data = ConnectionCredentials {
469        location,
470        credentials: StorageCredentials::decode(bytes.as_bytes())?,
471    };
472    data.validate()?;
473    Ok(Some(data))
474}