Skip to main content

coven/
coven.rs

1//! This app's stores on this device: where they live, the keychain their
2//! entries are kept in, and the device's network; and the calls that create,
3//! list, locate, open and remove them (E1).
4
5use crate::{
6    BootstrapError, CovenBuilder, CovenError, DbError, FileError, SavedRestoreEntry,
7    StoreDeletionError, StoreDir, StoreId, StoreLockError,
8};
9use coven_crypto::custody::{KeyError, Keychain, StoreKeychain};
10use coven_foundation::files::{FileBudget, ReplacedBy, StoreDirAccess, StoreDirectories};
11use coven_foundation::network_watch::NetworkSource;
12use std::path::PathBuf;
13use std::sync::Arc;
14
15/// This app's stores on this device (E1): the app directory each has its own
16/// directory under, the OS keychain service their keys and secrets are kept
17/// under, and the device's network, which each open store watches. The app
18/// builds one at startup and holds it.
19#[derive(Clone)]
20pub struct Coven {
21    directories: StoreDirectories,
22    keychain: Arc<Keychain>,
23    network: NetworkSource,
24    /// The app's places for open files, which every store this installation
25    /// opens shares (§17.3).
26    files: FileBudget,
27}
28
29/// A store on this device (E1).
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct StoreInfo {
32    /// The store's identity.
33    pub id: StoreId,
34    /// The current name from this device's committed database state. While
35    /// a replacement is unfinished, the name its new installation loaded.
36    pub name: String,
37    /// The work that must finish before the store opens, if any.
38    pub unfinished: Option<Unfinished>,
39}
40
41/// A closed store's sync status, as `Coven::closed_sync_status` reads it
42/// (E1): the state opening shows before sync starts, and what deleting the
43/// store would lose. A queued write or file waits to sync with `NotSyncing`,
44/// as sync isn't running; `unsent` counts them.
45#[derive(Clone, Debug, PartialEq)]
46pub struct ClosedSyncStatus {
47    /// The sync state and the last synced time.
48    pub sync: crate::SyncStatus,
49    /// The writes and files this device committed and has not uploaded.
50    pub unsent: crate::UnsentWork,
51}
52
53/// Work on a store that must finish before it opens (E1).
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum Unfinished {
56    /// A replacement of this device's installation, which the call it names
57    /// finishes, or `CovenBuilder::resume_replacement` (§19.3).
58    Replacement(ReplacedBy),
59    /// This device is deleting the store and leaving it, its removal
60    /// journaled or about to be: `CovenBuilder::resume_deletion` finishes it
61    /// (§11.6).
62    Deletion,
63}
64
65/// A store on this device as the listing found it (E1).
66#[derive(Debug)]
67pub enum ListedStore {
68    /// Its name and state read.
69    Readable(StoreInfo),
70    /// Its settings, replacement record or name can't be read, for `reason`.
71    /// The app shows it as damaged and can offer `discard_store` for it.
72    Unreadable {
73        /// The store whose settings, record or name can't be read.
74        id: StoreId,
75        /// Why it can't be read.
76        reason: CovenError,
77    },
78}
79
80impl ListedStore {
81    /// The store this entry lists.
82    pub fn id(&self) -> StoreId {
83        match self {
84            Self::Readable(info) => info.id,
85            Self::Unreadable { id, .. } => *id,
86        }
87    }
88}
89
90/// A failure listing the stores. A store that can't be read is not one: it
91/// is listed as `ListedStore::Unreadable`.
92#[derive(Debug, thiserror::Error)]
93pub enum StoreListError {
94    /// The directory listing or an identity settings read failed.
95    #[error(transparent)]
96    File(FileError),
97    /// The runtime is shutting down and dropped the listing's work (E15).
98    #[error(transparent)]
99    Shutdown(#[from] crate::task::Shutdown),
100    /// Listing the stores panicked on the blocking pool: a bug, which the
101    /// caller reports (E15).
102    #[error(transparent)]
103    Bug(#[from] crate::task::Bug),
104    /// Finishing the recorded deletion of `store` failed (E1). The store is
105    /// not listed, and the next listing finishes the deletion.
106    #[error("finishing the deletion of store {store} failed: {source}")]
107    Deletion {
108        /// The store being deleted.
109        store: StoreId,
110        /// Why its deletion stopped.
111        #[source]
112        source: StoreDeletionError,
113    },
114}
115
116impl From<FileError> for StoreListError {
117    fn from(error: FileError) -> Self {
118        match error {
119            FileError::Bug(bug) => Self::Bug(bug),
120            FileError::Shutdown(shutdown) => Self::Shutdown(shutdown),
121            error => Self::File(error),
122        }
123    }
124}
125
126impl crate::task::CarriesBug for StoreListError {
127    fn bug(&self) -> Option<&crate::task::Bug> {
128        match self {
129            Self::Bug(bug) => Some(bug),
130            Self::File(error) => error.bug(),
131            Self::Deletion { source, .. } => source.bug(),
132            Self::Shutdown(_) => None,
133        }
134    }
135}
136
137impl Coven {
138    /// The stores under `app_dir`, their keys and secrets in the OS keychain
139    /// under the service `keyring_service`, watching the platform's network.
140    /// The app creates `app_dir`; coven creates directories only inside it
141    /// and never opens a directory above it, which Android refuses. No key
142    /// is read here. A bug in work nobody waits for, in any store, goes to
143    /// `bugs`, the app's crash reporter (E15). Every read of a user's
144    /// original and every file stream, in every store, holds a place of
145    /// `files`, the app's budget of open files (§17.3). An empty service name,
146    /// or one containing NUL, fails with `KeyError::InvalidServiceName`; an OS
147    /// keychain coven can't reach fails with its `KeyError`.
148    pub fn new(
149        app_dir: PathBuf,
150        keyring_service: &str,
151        bugs: crate::task::BugSinkRef,
152        files: FileBudget,
153    ) -> Result<Self, KeyError> {
154        Ok(Self {
155            directories: StoreDirectories::new(app_dir, bugs),
156            keychain: Keychain::native(keyring_service)?,
157            network: NetworkSource::Platform,
158            files,
159        })
160    }
161
162    /// Read the saved storage location without opening the store or its custody.
163    /// None means storage has never been set up; once set up, the location stays.
164    pub async fn storage_config(
165        store_dir: &StoreDir,
166    ) -> Result<Option<crate::StorageConfig>, crate::SyncError> {
167        let store_dir = store_dir.clone();
168        let bugs = store_dir.bugs().clone();
169        crate::task::blocking_completing("read the storage settings", bugs, move || {
170            coven_storage::recorded_config(&store_dir)
171        })
172        .await?
173        .map_err(crate::SyncError::from)
174    }
175
176    /// A closed store's sync state, last synced time and unsent work, read
177    /// without opening it (E1, E5): the state opening shows before sync
178    /// starts. It holds the store's writer lock while it reads, since only
179    /// that lock shows that no handle runs the store's sync: an open handle,
180    /// here or in another process, refuses it with
181    /// `StoreLockError::AlreadyOpen` at once, and the app reads that handle.
182    /// An instance closing in this process is waited for first, and an open
183    /// of the store in this process meanwhile waits for this read. Whether
184    /// this device holds the location's credentials is read from the
185    /// keychain, as opening reads it. A store whose replacement or deletion
186    /// is unfinished is refused as opening refuses it, and one whose device
187    /// entry the keychain doesn't hold fails with `DeviceKeyMissing`.
188    pub async fn closed_sync_status(
189        &self,
190        store_dir: &StoreDir,
191    ) -> Result<ClosedSyncStatus, CovenError> {
192        let lock = store_dir.lock_closed().await?;
193        let location = {
194            let directory = store_dir.clone();
195            let keys = StoreKeychain::new(self.keychain.clone(), store_dir.id());
196            let bugs = store_dir.bugs().clone();
197            crate::task::blocking_completing("read the closed store's location", bugs, move || {
198                let store = directory.id();
199                crate::builder::refuse_unfinished_deletion(&directory, store)?;
200                // A copy whose keychain no longer names its device doesn't
201                // open, so it has no state to show (§19.3).
202                if keys.device_id()? != Some(directory.settings()?.device_id) {
203                    return Err(CovenError::DeviceKeyMissing { store });
204                }
205                let location = coven_sync::read_location(&directory, &keys)?;
206                Ok::<_, CovenError>(location.map(|location| location.provider()))
207            })
208            .await??
209        };
210        let facts = coven_database::closed_sync_facts(store_dir.clone(), lock).await?;
211        let unsent = facts.unsent;
212        let sync = coven_sync::SyncStatus::closed(facts, location)?;
213        Ok(ClosedSyncStatus { sync, unsent })
214    }
215
216    /// Keep SQLite's temporary tables in `directory`, such as the app's cache
217    /// folder, for every store this process opens. An Android app calls this
218    /// before opening its first store: SQLite finds no folder there by itself,
219    /// and temporary tables that outgrow a connection's cache fail without
220    /// one. Elsewhere SQLite uses the system's.
221    pub fn set_temporary_directory(
222        directory: &std::path::Path,
223    ) -> Result<(), crate::TemporaryDirectoryError> {
224        coven_database::set_temporary_directory(directory)
225    }
226
227    /// Stores on this device, ordered by id, with their committed names.
228    /// A store whose settings file, replacement record or name can't be read
229    /// is listed as `Unreadable` with why; a listing never substitutes an older name.
230    /// A store whose replacement or deletion is unfinished lists with the
231    /// work that must finish, so the app can offer to finish it; an
232    /// unfinished first installation is not listed. First it finishes every
233    /// deletion from the device that a cut call left under the directory's
234    /// deletion name, which no call holds (§19.3, E1); a failure there fails
235    /// the listing with `StoreListError::Deletion`.
236    pub async fn stores(&self) -> Result<Vec<ListedStore>, StoreListError> {
237        for store in self.directories.recorded_deletions().await? {
238            let directory = self.store_dir(&store);
239            let keys = StoreKeychain::new(self.keychain.clone(), store);
240            match finish_deletion(&directory, keys).await {
241                Ok(()) => tracing::info!(%store, "finished a recorded deletion"),
242                // A call is deleting it now, and finishes it.
243                Err(StoreDeletionError::Lock(StoreLockError::AlreadyOpen(_))) => {
244                    tracing::debug!(%store, "a call holds a recorded deletion")
245                }
246                Err(StoreDeletionError::Bug(bug)) => return Err(StoreListError::Bug(bug)),
247                Err(StoreDeletionError::Shutdown(shutdown)) => {
248                    return Err(StoreListError::Shutdown(shutdown))
249                }
250                Err(source) => return Err(StoreListError::Deletion { store, source }),
251            }
252        }
253        let mut stores = Vec::new();
254        for listed in self.directories.store_listing().await? {
255            let id = listed.id;
256            // A settings file that doesn't read leaves the store listed,
257            // unreadable, so the app can offer to discard it.
258            let read = match listed.settings {
259                Ok(()) => self.read_listed(id).await,
260                Err(error) => Err(CovenError::from(error)),
261            };
262            stores.push(match read {
263                Ok(info) => ListedStore::Readable(info),
264                Err(error) => {
265                    if let Some(bug) = crate::task::CarriesBug::bug(&error) {
266                        return Err(StoreListError::Bug(bug.clone()));
267                    }
268                    match error {
269                        CovenError::Shutdown(shutdown)
270                        | CovenError::Database(DbError::Shutdown(shutdown)) => {
271                            return Err(StoreListError::Shutdown(shutdown));
272                        }
273                        reason => ListedStore::Unreadable { id, reason },
274                    }
275                }
276            });
277        }
278        Ok(stores)
279    }
280
281    async fn read_listed(&self, id: StoreId) -> Result<StoreInfo, CovenError> {
282        let directory = self.store_dir(&id);
283        let (replacement, deletion) = {
284            let directory = directory.clone();
285            let bugs = directory.bugs().clone();
286            crate::task::blocking_completing("read the store's records", bugs, move || {
287                Ok::<_, CovenError>((
288                    directory.unfinished_replacement()?,
289                    directory.unfinished_deletion().map_err(DbError::from)?,
290                ))
291            })
292            .await??
293        };
294        Ok(match replacement {
295            Some(record) => StoreInfo {
296                id,
297                name: record.name,
298                unfinished: Some(Unfinished::Replacement(record.by)),
299            },
300            None => StoreInfo {
301                id,
302                name: coven_database::read_store_name(directory).await?,
303                unfinished: deletion.map(|_| Unfinished::Deletion),
304            },
305        })
306    }
307
308    /// Address a store without reading settings or acquiring the writer lock.
309    pub fn store_dir(&self, id: &StoreId) -> StoreDir {
310        self.directories.store_dir(id)
311    }
312
313    /// Configure creating, opening, restoring or joining a store.
314    pub fn builder(&self) -> CovenBuilder {
315        CovenBuilder::new(
316            self.directories.clone(),
317            self.keychain.clone(),
318            self.network.clone(),
319            self.files.clone(),
320        )
321    }
322
323    /// Deletes a closed store from this device without opening it: this
324    /// device's own keychain entries for it, including every saved host
325    /// secret, then its directory. The person's saved restore code and S3 key
326    /// stay for their next devices; they go only when the
327    /// person leaves the store (§13.1). Unsent writes and files are lost, and
328    /// this device stays registered with the store until it is removed; prefer
329    /// `CovenHandle::delete_store`. Use this for a store that cannot open, or
330    /// to finish a handle's deletion that failed after closing. A store whose
331    /// `reset_device` or `restore_device` stopped past its record is deleted
332    /// whole: both installations, the replacement's directory and record,
333    /// and this device's entries, which by then may name either device.
334    /// Refused while a writer, read-only handle, file stream or a running
335    /// replacement remains; storage is untouched. A handle of it in this
336    /// process that is closing, or whose last clone was dropped, is waited
337    /// for. Its first step renames the store's directory, which hides the
338    /// store and records the deletion: one that stops part way, a crash
339    /// included, is finished by retrying, by the next `stores()`, or by a
340    /// restore or join of the store (§19.3).
341    pub async fn discard_store(&self, store_dir: &StoreDir) -> Result<(), StoreDeletionError> {
342        let keys = StoreKeychain::new(self.keychain.clone(), store_dir.id());
343        finish_deletion(store_dir, keys).await
344    }
345
346    /// The saved entries of this app's keychain service, in iCloud Keychain on
347    /// Apple and in this phone's Block Store on Android, one per store,
348    /// ordered by store id; empty when none are saved. An entry coven can't
349    /// restore from is listed as `Unreadable`, never omitted, so the person
350    /// can forget it. A keychain read failure (the search, an entry's bytes
351    /// or an S3 key's presence) fails the whole call, as does a restore-code
352    /// account with no store id, `KeyError::RestoreCodeStoreId`. A keychain
353    /// with neither iCloud Keychain nor Block Store fails with
354    /// `BootstrapError::SecureStorage(KeyError::Unsupported)`. Pass a readable
355    /// entry to `restore_from_saved_code`, which reads its current code and key.
356    pub async fn saved_restore_codes(&self) -> Result<Vec<SavedRestoreEntry>, BootstrapError> {
357        let keychain = self.keychain.clone();
358        let bugs = self.directories.bugs().clone();
359        crate::task::blocking_completing("list saved restore codes", bugs, move || {
360            crate::saved_restore::list(keychain)
361        })
362        .await?
363    }
364
365    /// Delete the store's saved S3 key, then its restore code: from iCloud
366    /// Keychain, and so from every one of the person's Apple devices, or from
367    /// this phone's Block Store, leaving other phones' own (§13.1). Readable
368    /// and unreadable entries alike; every keychain group's copy goes. The
369    /// store, its storage and every device's copy stay; no store need be open
370    /// and no provider connected. Absent entries succeed; after a failure
371    /// part way the store is still listed, and calling again finishes. A
372    /// later join, restore, reset or member-key replacement saves the entry
373    /// again. A keychain with neither iCloud Keychain nor Block Store fails
374    /// with `BootstrapError::SecureStorage(KeyError::Unsupported)`.
375    pub async fn forget_saved_restore_code(&self, store: StoreId) -> Result<(), BootstrapError> {
376        let keychain = self.keychain.clone();
377        let bugs = self.directories.bugs().clone();
378        crate::task::blocking_completing("forget the saved restore code", bugs, move || {
379            crate::saved_restore::forget(keychain, store)
380        })
381        .await?
382    }
383}
384
385/// Delete the store at `directory` from this device, or finish a deletion a
386/// cut call left recorded, once no instance of it in this process is
387/// closing.
388pub(crate) async fn finish_deletion<E>(directory: &StoreDir, keys: StoreKeychain) -> Result<(), E>
389where
390    E: From<StoreLockError>
391        + From<FileError>
392        + From<KeyError>
393        + From<crate::task::TaskFailed>
394        + crate::task::CarriesBug
395        + Send
396        + 'static,
397{
398    directory.closed().await?;
399    let directory = directory.clone();
400    let bugs = directory.bugs().clone();
401    crate::task::blocking_completing("delete the store", bugs, move || delete(&directory, &keys))
402        .await?
403}
404
405/// Delete the store at `directory` from this device: rename its directory to
406/// its deletion name, which hides the store and records the deletion, then
407/// delete this device's entries for it, then the directory and its lock
408/// files (§19.3, E1). Each step finds the last one's work done, so a
409/// deletion stopped anywhere is finished by deleting again.
410pub(crate) fn delete<E>(directory: &StoreDir, keys: &StoreKeychain) -> Result<(), E>
411where
412    E: From<StoreLockError> + From<FileError> + From<KeyError>,
413{
414    let mut lock = directory.lock_for_deletion()?;
415    if let Some(lock) = &mut lock {
416        lock.unpublish()?;
417    }
418    keys.delete_device_entries()?;
419    if let Some(lock) = lock {
420        lock.remove_directory()?;
421    }
422    Ok(())
423}
424
425#[path = "coven_device_secrets.rs"]
426mod device_secrets;
427
428#[cfg(any(test, feature = "in-memory-keychain"))]
429#[path = "test_utils.rs"]
430mod test_utils;
431
432#[cfg(test)]
433#[path = "coven_tests.rs"]
434mod tests;