Skip to main content

coven/
error.rs

1//! Failures composing the store's directory, storage and custody capabilities.
2
3use crate::{
4    CryptoError, FileError, KeyError, OAuthError, StorageCheckError, StorageError, StoreLockError,
5    SyncError,
6};
7
8/// A failed setup commits no local storage settings or credentials.
9#[derive(Debug, thiserror::Error)]
10pub enum StorageSetupError {
11    /// A provider or S3 settings check refused the location.
12    #[error(transparent)]
13    Check(StorageCheckError),
14    /// Reconnecting cannot move an established store to another location.
15    #[error("storage location change is unsupported")]
16    LocationChangeUnsupported,
17    /// A classified storage failure.
18    #[error(transparent)]
19    Storage(StorageError),
20    /// Sign-in failed or was cancelled before setup could connect.
21    #[error(transparent)]
22    OAuth(#[from] OAuthError),
23    /// The facade could not commit to key custody.
24    #[error("secure storage: {0}")]
25    SecureStorage(KeyError),
26    /// This device or its member was removed from the store (§14.1).
27    #[error("this device or its member was removed")]
28    Removed,
29    /// This member's account holds the store, and setup signed in with
30    /// another account. Their access stays on the account that holds it:
31    /// the person signs in with that one (§10.1, §20.9).
32    #[error("the store's owner must sign in with the account that holds it")]
33    StoreOwner,
34    /// The store needs a newer app schema or coven format (§18).
35    #[error("an update is required: {0:?}")]
36    UpdateRequired(coven_format::RequiredUpdate),
37    /// The app cancelled setup before its point of no return, and what it
38    /// had written was undone (§11.6).
39    #[error("storage setup was cancelled and undone")]
40    Cancelled,
41    /// A setup on this device is past its point of no return and still
42    /// finishing, so another can't start; starting sync finishes it (§11.6).
43    #[error("a storage setup is still finishing")]
44    SetupRunning,
45    /// A local setup step failed, retaining its cause.
46    #[error("storage setup: {0}")]
47    Internal(#[source] Box<dyn std::error::Error + Send + Sync>),
48    /// Setup's runtime is shutting down and dropped it partway, so how much
49    /// of it was saved is unknown (E15).
50    #[error(transparent)]
51    Shutdown(#[from] coven_foundation::task::Shutdown),
52    /// Setup panicked: a bug, which the caller reports (E15). How much of it
53    /// was saved is unknown.
54    #[error(transparent)]
55    Bug(#[from] coven_foundation::task::Bug),
56}
57
58impl coven_foundation::task::CarriesBug for StorageSetupError {
59    fn bug(&self) -> Option<&coven_foundation::task::Bug> {
60        match self {
61            Self::Bug(bug) => Some(bug),
62            Self::SecureStorage(error) => error.bug(),
63            Self::Storage(error) => error.bug(),
64            Self::Check(error) => error.bug(),
65            Self::OAuth(error) => error.bug(),
66            _ => None,
67        }
68    }
69}
70
71impl From<StorageError> for StorageSetupError {
72    fn from(error: StorageError) -> Self {
73        match error {
74            StorageError::Bug(bug) => Self::Bug(bug),
75            error => Self::Storage(error),
76        }
77    }
78}
79
80/// A storage failure keeps its one spelling, `Storage`; the other refusals
81/// are checks.
82impl From<StorageCheckError> for StorageSetupError {
83    fn from(error: StorageCheckError) -> Self {
84        match error {
85            StorageCheckError::Storage(error) => Self::from(error),
86            error => Self::Check(error),
87        }
88    }
89}
90
91impl From<KeyError> for StorageSetupError {
92    fn from(error: KeyError) -> Self {
93        match error {
94            KeyError::Bug(bug) => Self::Bug(bug),
95            error => Self::SecureStorage(error),
96        }
97    }
98}
99
100impl From<coven_foundation::task::TaskFailed> for StorageSetupError {
101    fn from(failed: coven_foundation::task::TaskFailed) -> Self {
102        failed.into_error()
103    }
104}
105
106/// Why `use_access_key` failed (E9, §14.3). Before the call takes the key,
107/// each failure leaves everything as it was.
108#[derive(Debug, thiserror::Error)]
109pub enum UseAccessKeyError {
110    /// The app cancelled while the call checked the key. Nothing changed.
111    #[error("using the access key was cancelled while its check ran")]
112    Cancelled,
113    /// Checking the key with storage failed: storage refused the key
114    /// (`Authentication`, or `PermissionDenied` for a key that can't read
115    /// and write the location), or the check couldn't finish. Nothing
116    /// changed.
117    #[error(transparent)]
118    Check(StorageCheckError),
119    /// Anything else. Before the key was taken, nothing changed. Once it
120    /// was taken: the caught-up history refusing the entry after this
121    /// member's or device's removal (§14.1), or a failure of this device's
122    /// database, a bug or a shutdown.
123    #[error(transparent)]
124    Sync(SyncError),
125}
126
127impl coven_foundation::task::CarriesBug for UseAccessKeyError {
128    fn bug(&self) -> Option<&coven_foundation::task::Bug> {
129        match self {
130            Self::Cancelled => None,
131            Self::Check(error) => error.bug(),
132            Self::Sync(error) => error.bug(),
133        }
134    }
135}
136
137impl From<SyncError> for UseAccessKeyError {
138    fn from(error: SyncError) -> Self {
139        Self::Sync(error)
140    }
141}
142
143impl From<KeyError> for UseAccessKeyError {
144    fn from(error: KeyError) -> Self {
145        Self::Sync(error.into())
146    }
147}
148
149impl From<coven_foundation::task::TaskFailed> for UseAccessKeyError {
150    fn from(failed: coven_foundation::task::TaskFailed) -> Self {
151        Self::Sync(failed.into())
152    }
153}
154
155/// Creating a store failed, with publication and rollback made explicit (E1).
156#[derive(Debug, thiserror::Error)]
157pub enum StoreCreationError {
158    /// Preparing, publishing or removing the hidden directory failed.
159    #[error(transparent)]
160    Directory(coven_foundation::files::BootstrapDirectoryError),
161    /// Opening the database or custody failed.
162    #[error(transparent)]
163    Store(crate::CovenError),
164    /// The device is locked, and the protection class the app chose keeps
165    /// the new store's files from being made until it unlocks (api.md E1).
166    /// No store was made; the app waits for the unlock and creates it again.
167    #[error("{}: the device is locked, and the store's files are protected until it unlocks", path.display())]
168    DeviceLocked {
169        /// The first protected file the lock refused.
170        path: std::path::PathBuf,
171    },
172    /// Creating or persisting the member identity failed.
173    #[error(transparent)]
174    Identity(crate::IdentityError),
175    /// Closing the database or its workers failed.
176    #[error(transparent)]
177    Sync(SyncError),
178    /// Closing or rollback also failed; both causes remain available.
179    #[error("{operation}; cleanup failed: {cleanup}")]
180    Cleanup {
181        /// The original failure.
182        operation: Box<StoreCreationError>,
183        /// A cleanup failure.
184        #[source]
185        cleanup: Box<StoreCreationError>,
186    },
187    /// The complete store is visible and closed, but its directory sync failed.
188    #[error("store {store} was published but its directory sync failed: {source}")]
189    PublishedButNotSynced {
190        /// The published store; reopen it with `CovenBuilder::open`.
191        store: crate::StoreId,
192        /// The directory-sync failure, retaining any close failure as `Cleanup`.
193        #[source]
194        source: Box<StoreCreationError>,
195    },
196    /// Creation's runtime is shutting down and dropped its work (E15).
197    /// Creation runs as its own task, so with `ShutdownOutcome::Unknown` it
198    /// may have stopped anywhere, before or after publishing the store;
199    /// listing the stores shows which. A step on the blocking pool that the
200    /// runtime dropped is `NotRun`.
201    #[error(transparent)]
202    Shutdown(#[from] crate::task::Shutdown),
203    /// Creation panicked: a bug, which the caller reports (E15). As with
204    /// `Shutdown`, listing the stores shows whether it published the store.
205    #[error(transparent)]
206    Bug(#[from] crate::task::Bug),
207}
208
209impl From<coven_foundation::files::BootstrapDirectoryError> for StoreCreationError {
210    fn from(error: coven_foundation::files::BootstrapDirectoryError) -> Self {
211        if let coven_foundation::files::BootstrapDirectoryError::Bug(bug) = error {
212            return Self::Bug(bug);
213        }
214        match error.device_locked() {
215            Some(path) => Self::DeviceLocked { path: path.to_owned() },
216            None => Self::Directory(error),
217        }
218    }
219}
220
221impl From<crate::CovenError> for StoreCreationError {
222    fn from(error: crate::CovenError) -> Self {
223        match error {
224            crate::CovenError::DeviceLocked { path } => Self::DeviceLocked { path },
225            crate::CovenError::Bug(bug) => Self::Bug(bug),
226            error => Self::Store(error),
227        }
228    }
229}
230
231/// Opening the database fails as the store's open does.
232impl From<coven_database::OpenError> for StoreCreationError {
233    fn from(error: coven_database::OpenError) -> Self {
234        crate::CovenError::from(error).into()
235    }
236}
237
238impl From<crate::IdentityError> for StoreCreationError {
239    fn from(error: crate::IdentityError) -> Self {
240        match error {
241            crate::IdentityError::Bug(bug) => Self::Bug(bug),
242            error => Self::Identity(error),
243        }
244    }
245}
246
247impl From<SyncError> for StoreCreationError {
248    fn from(error: SyncError) -> Self {
249        match error {
250            SyncError::Bug(bug) => Self::Bug(bug),
251            error => Self::Sync(error),
252        }
253    }
254}
255
256impl crate::task::CarriesBug for StoreCreationError {
257    fn bug(&self) -> Option<&crate::task::Bug> {
258        match self {
259            Self::Bug(bug) => Some(bug),
260            Self::Directory(error) => error.bug(),
261            Self::Store(error) => error.bug(),
262            Self::Identity(error) => error.bug(),
263            Self::Sync(error) => error.bug(),
264            Self::Cleanup { operation, cleanup } => operation.bug().or_else(|| cleanup.bug()),
265            Self::PublishedButNotSynced { source, .. } => source.bug(),
266            _ => None,
267        }
268    }
269}
270
271impl From<crate::task::TaskFailed> for StoreCreationError {
272    fn from(failed: crate::task::TaskFailed) -> Self {
273        failed.into_error()
274    }
275}
276
277impl StoreCreationError {
278    pub(crate) fn with_cleanup(self, cleanup: Self) -> Self {
279        Self::Cleanup { operation: Box::new(self), cleanup: Box::new(cleanup) }
280    }
281}
282
283/// Deleting the local store stopped at a step the caller may retry (E1).
284#[derive(Debug, thiserror::Error)]
285pub enum StoreDeletionError {
286    /// The store is open or its lock could not be taken.
287    #[error(transparent)]
288    Lock(StoreLockError),
289    /// Writes or files wait to upload; nothing was deleted.
290    #[error("{} writes and {} files wait to upload", .0.writes, .0.files)]
291    Unsent(coven_database::UnsentWork),
292    /// Reading the queue, connecting, or journaling this device's removal
293    /// failed before the removal was journaled: nothing was deleted, nothing
294    /// in storage changed, and the store is as it was.
295    #[error(transparent)]
296    Sync(crate::SyncError),
297    /// A location is recorded for the store and this device holds no
298    /// credentials for it, so it can't publish its removal: the person
299    /// signs in to `provider`, then deletes again. Before the removal was
300    /// journaled nothing changed; after, the deletion stays recorded for
301    /// `CovenBuilder::resume_deletion`.
302    #[error("sign in to {0:?} to delete the store from this device")]
303    SignInRequired(crate::CloudProvider),
304    /// This device's removal is journaled, and the deletion failed before it
305    /// applied, with `0`'s cause. The deletion only goes forward: the handle
306    /// is closed, the store lists as being deleted and refuses opens, and
307    /// `CovenBuilder::resume_deletion` finishes it.
308    #[error("the store is being deleted from this device; finishing it failed: {0}")]
309    Unfinished(#[source] crate::SyncError),
310    /// This device's removal applied, or no storage was set up, and closing
311    /// the handle failed; nothing was deleted. A recorded deletion is
312    /// finished by `CovenBuilder::resume_deletion`, and either by
313    /// `Coven::discard_store`.
314    #[error("closing the store failed after this device left it: {0}")]
315    Closing(#[source] crate::SyncError),
316    /// Opening the store to finish its recorded deletion failed.
317    #[error(transparent)]
318    Open(crate::CovenError),
319    /// `resume_deletion` found no deletion of the store recorded on this
320    /// device.
321    #[error("no deletion of store {0} is under way")]
322    NoUnfinishedDeletion(crate::StoreId),
323    /// Removing a keychain entry failed.
324    #[error(transparent)]
325    Key(KeyError),
326    /// Removing the store directory failed.
327    #[error(transparent)]
328    File(FileError),
329    /// The deletion's runtime is shutting down and dropped it before it
330    /// started, so nothing was deleted (E15).
331    #[error(transparent)]
332    Shutdown(#[from] crate::task::Shutdown),
333    /// The deletion panicked: a bug, which the caller reports (E15).
334    /// Retrying finishes a deletion that stopped partway.
335    #[error(transparent)]
336    Bug(#[from] crate::task::Bug),
337}
338
339impl crate::task::CarriesBug for StoreDeletionError {
340    fn bug(&self) -> Option<&crate::task::Bug> {
341        match self {
342            Self::Bug(bug) => Some(bug),
343            Self::Lock(error) => error.bug(),
344            Self::Sync(error) | Self::Closing(error) | Self::Unfinished(error) => error.bug(),
345            Self::Open(error) => error.bug(),
346            Self::Key(error) => error.bug(),
347            Self::File(error) => error.bug(),
348            _ => None,
349        }
350    }
351}
352
353impl From<crate::SyncError> for StoreDeletionError {
354    fn from(error: crate::SyncError) -> Self {
355        match error {
356            crate::SyncError::Bug(bug) => Self::Bug(bug),
357            error => Self::Sync(error),
358        }
359    }
360}
361
362impl From<KeyError> for StoreDeletionError {
363    fn from(error: KeyError) -> Self {
364        match error {
365            KeyError::Bug(bug) => Self::Bug(bug),
366            error => Self::Key(error),
367        }
368    }
369}
370
371impl From<FileError> for StoreDeletionError {
372    fn from(error: FileError) -> Self {
373        match error {
374            FileError::Bug(bug) => Self::Bug(bug),
375            error => Self::File(error),
376        }
377    }
378}
379
380impl From<StoreLockError> for StoreDeletionError {
381    fn from(error: StoreLockError) -> Self {
382        match error {
383            StoreLockError::Bug(bug) => Self::Bug(bug),
384            error => Self::Lock(error),
385        }
386    }
387}
388
389impl From<crate::task::TaskFailed> for StoreDeletionError {
390    fn from(failed: crate::task::TaskFailed) -> Self {
391        failed.into_error()
392    }
393}
394
395/// Opening a read-only store or its saved file-storage connection failed.
396#[derive(Debug, thiserror::Error)]
397pub enum ReadOnlyOpenError {
398    /// The database or store directory could not be opened.
399    #[error(transparent)]
400    Local(crate::CovenError),
401    /// Saved settings, credential custody or provider construction failed.
402    #[error(transparent)]
403    Storage(crate::SyncError),
404    /// Opening panicked: a bug, which the caller reports (E15).
405    #[error(transparent)]
406    Bug(#[from] crate::task::Bug),
407}
408
409impl From<crate::CovenError> for ReadOnlyOpenError {
410    fn from(error: crate::CovenError) -> Self {
411        match error {
412            crate::CovenError::Bug(bug) => Self::Bug(bug),
413            error => Self::Local(error),
414        }
415    }
416}
417
418/// A database call's or opening's failure is the store's.
419impl From<crate::DbError> for ReadOnlyOpenError {
420    fn from(error: crate::DbError) -> Self {
421        crate::CovenError::from(error).into()
422    }
423}
424
425impl From<coven_database::OpenError> for ReadOnlyOpenError {
426    fn from(error: coven_database::OpenError) -> Self {
427        crate::CovenError::from(error).into()
428    }
429}
430
431impl From<crate::SyncError> for ReadOnlyOpenError {
432    fn from(error: crate::SyncError) -> Self {
433        match error {
434            crate::SyncError::Bug(bug) => Self::Bug(bug),
435            error => Self::Storage(error),
436        }
437    }
438}
439
440impl crate::task::CarriesBug for ReadOnlyOpenError {
441    fn bug(&self) -> Option<&crate::task::Bug> {
442        match self {
443            Self::Bug(bug) => Some(bug),
444            Self::Local(error) => error.bug(),
445            Self::Storage(error) => error.bug(),
446        }
447    }
448}
449
450/// Opening this member's sealed store keys failed.
451#[derive(Debug, thiserror::Error)]
452pub enum StoreKeyUnlockError {
453    /// No stored provider configuration or credentials are available.
454    #[error("no storage configured")]
455    NoStorage,
456    /// The provider refused or failed a request.
457    #[error(transparent)]
458    Storage(StorageError),
459    /// Unlocking connected while a storage setup past its point of no
460    /// return was still finishing, so it finished that setup (§11.6), and
461    /// making a key or sealing a key copy for an operation settled there
462    /// failed: the device's random source failed, or the recipient's
463    /// sealing key is of low order.
464    #[error(transparent)]
465    Crypto(CryptoError),
466    /// Custody refused to read or persist keys.
467    #[error(transparent)]
468    SecureStorage(KeyError),
469    /// This device or its member was removed from the store (§14.1).
470    #[error("this device or its member was removed")]
471    Removed,
472    /// The store needs a newer app schema or coven format (§18).
473    #[error("an update is required: {0:?}")]
474    UpdateRequired(crate::RequiredUpdate),
475    /// Sequence validation or local work failed, preserving its cause.
476    #[error("opening store keys: {0}")]
477    Other(#[source] Box<dyn std::error::Error + Send + Sync>),
478    /// Unlocking's runtime is shutting down and dropped it partway, so
479    /// whether it saved the keys it opened is unknown (E15).
480    #[error(transparent)]
481    Shutdown(#[from] crate::task::Shutdown),
482    /// Unlocking panicked: a bug, which the caller reports (E15). Whether
483    /// it saved the keys it opened is unknown.
484    #[error(transparent)]
485    Bug(#[from] crate::task::Bug),
486}
487
488impl crate::task::CarriesBug for StoreKeyUnlockError {
489    fn bug(&self) -> Option<&crate::task::Bug> {
490        match self {
491            Self::Bug(bug) => Some(bug),
492            Self::Storage(error) => error.bug(),
493            Self::SecureStorage(error) => error.bug(),
494            _ => None,
495        }
496    }
497}
498
499impl From<StorageError> for StoreKeyUnlockError {
500    fn from(error: StorageError) -> Self {
501        match error {
502            StorageError::Bug(bug) => Self::Bug(bug),
503            error => Self::Storage(error),
504        }
505    }
506}
507
508impl From<KeyError> for StoreKeyUnlockError {
509    fn from(error: KeyError) -> Self {
510        match error {
511            KeyError::Bug(bug) => Self::Bug(bug),
512            error => Self::SecureStorage(error),
513        }
514    }
515}
516
517impl From<crate::task::TaskFailed> for StoreKeyUnlockError {
518    fn from(failed: crate::task::TaskFailed) -> Self {
519        failed.into_error()
520    }
521}
522
523/// What setup and unlock report by name: a removal or a required update,
524/// whether the pass returned it or stopped at a record of it.
525enum Stopped {
526    Removed,
527    UpdateRequired(crate::RequiredUpdate),
528}
529
530fn stopped(error: &SyncError) -> Option<Stopped> {
531    let reason = match error {
532        // A joined store whose admission was refused never became a member:
533        // shown as a removal is (§13.2).
534        SyncError::Removed(_) => return Some(Stopped::Removed),
535        SyncError::UpdateRequired(update) => return Some(Stopped::UpdateRequired(*update)),
536        SyncError::Pending(record) => &record.reason,
537        _ => return None,
538    };
539    match reason {
540        crate::PendingReason::Removed(_) => Some(Stopped::Removed),
541        crate::PendingReason::UpdateRequired(update) => Some(Stopped::UpdateRequired(*update)),
542        _ => None,
543    }
544}
545
546pub(crate) fn setup_error(error: SyncError) -> StorageSetupError {
547    match stopped(&error) {
548        Some(Stopped::Removed) => return StorageSetupError::Removed,
549        Some(Stopped::UpdateRequired(update)) => return StorageSetupError::UpdateRequired(update),
550        None => {}
551    }
552    match error {
553        SyncError::SecureStorage(error) => error.into(),
554        SyncError::Storage(error) => error.into(),
555        SyncError::StoreOwner => StorageSetupError::StoreOwner,
556        SyncError::Shutdown(shutdown) => StorageSetupError::Shutdown(shutdown),
557        SyncError::Bug(bug) => StorageSetupError::Bug(bug),
558        error => StorageSetupError::Internal(Box::new(error)),
559    }
560}
561
562pub(crate) fn unlock_error(error: SyncError) -> StoreKeyUnlockError {
563    match stopped(&error) {
564        Some(Stopped::Removed) => return StoreKeyUnlockError::Removed,
565        Some(Stopped::UpdateRequired(update)) => {
566            return StoreKeyUnlockError::UpdateRequired(update)
567        }
568        None => {}
569    }
570    match error {
571        SyncError::NoStorage => StoreKeyUnlockError::NoStorage,
572        SyncError::SecureStorage(error) => error.into(),
573        SyncError::Crypto(error) => StoreKeyUnlockError::Crypto(error),
574        SyncError::Storage(error) => error.into(),
575        SyncError::Shutdown(shutdown) => StoreKeyUnlockError::Shutdown(shutdown),
576        SyncError::Bug(bug) => StoreKeyUnlockError::Bug(bug),
577        error => StoreKeyUnlockError::Other(Box::new(error)),
578    }
579}
580
581#[cfg(test)]
582#[path = "error_tests.rs"]
583mod tests;