Skip to main content

lb_rs/model/
errors.rs

1use std::backtrace::Backtrace;
2use std::fmt::{self, Display, Formatter};
3use std::io;
4use std::panic::Location;
5use std::path::PathBuf;
6use std::sync::PoisonError;
7
8use aes_gcm::aead;
9use db_rs::errors::Error as DbError;
10use hmac::crypto_mac::MacError;
11use serde::ser::SerializeStruct;
12use serde::{Serialize, Serializer};
13use tracing::error;
14use uuid::Uuid;
15
16use crate::io::network::ApiError;
17use crate::model::ValidationFailure;
18
19use super::api;
20
21pub type LbResult<T> = Result<T, LbErr>;
22
23pub struct LbErr {
24    pub kind: LbErrKind,
25    pub backtrace: Option<Backtrace>,
26}
27
28impl fmt::Debug for LbErr {
29    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
30        write!(f, "{:?}", self.kind)?;
31        if let Some(backtrace) = &self.backtrace {
32            write!(f, "\n{}", backtrace.to_string().trim_end())?;
33        }
34        Ok(())
35    }
36}
37
38/// Using this within core has limited meaning as the unexpected / expected error
39/// calculation that happens in lib.rs won't have taken place. So in some sense
40/// printing this out anywhere within core is going to be _unexpected_
41impl Display for LbErr {
42    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
43        write!(f, "{}", self.kind)
44    }
45}
46
47/// The purpose of this Display implementation is to provide uniformity for the
48/// description of errors that a customer may see. And to provide a productivity
49/// boost for the UI developer processing (and ultimately showing) these errors.
50/// If an error is not expected to be propegated outside of this crate the
51/// the language associated with the error will reflect that (and may use an
52/// uglier debug impl for details).
53impl Display for LbErrKind {
54    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
55        match self {
56            LbErrKind::AccountExists => write!(f, "An account already exists"),
57            LbErrKind::AccountNonexistent => write!(f, "You need an account to do that"),
58            LbErrKind::AccountStringCorrupted => write!(f, "That account key is invalid"),
59            LbErrKind::AlreadyCanceled => write!(f, "Your subscription has already been cancelled"),
60            LbErrKind::AlreadyPremium => write!(f, "Your account is already premium"),
61            LbErrKind::AppStoreAccountAlreadyLinked => {
62                write!(f, "Your account is already linked to the App Store")
63            }
64            LbErrKind::CannotCancelSubscriptionForAppStore => {
65                write!(f, "You cannot cancel an app store subscription from here")
66            }
67            LbErrKind::CardDecline => write!(f, "Your card was declined"),
68            LbErrKind::CardExpired => write!(f, "Your card is expired"),
69            LbErrKind::CardInsufficientFunds => write!(f, "This card has insufficient funds"),
70            LbErrKind::CardInvalidCvc => write!(f, "Your CVC is invalid"),
71            LbErrKind::CardInvalidExpMonth => write!(f, "Your expiration month is invalid"),
72            LbErrKind::CardInvalidExpYear => write!(f, "Your expiration year is invalid"),
73            LbErrKind::CardInvalidNumber => write!(f, "Your card number is invalid"),
74            LbErrKind::CardNotSupported => write!(f, "That card is not supported by stripe"),
75            LbErrKind::ClientUpdateRequired => {
76                write!(f, "You must update your Lockbook to do that")
77            }
78            LbErrKind::CurrentUsageIsMoreThanNewTier => {
79                write!(f, "You need to delete some files before downgrading your usage")
80            }
81            LbErrKind::DiskPathInvalid => write!(f, "That disk path is invalid"),
82            LbErrKind::DiskPathTaken => write!(f, "That disk path is not available"),
83            LbErrKind::ExistingRequestPending => {
84                write!(f, "Existing billing request in progress, please wait and try again")
85            }
86            LbErrKind::FileNameContainsSlash => write!(f, "A file name cannot contain slashes"),
87            LbErrKind::FileNameTooLong => write!(f, "That file name is too long"),
88            LbErrKind::FileNameEmpty => write!(f, "A file name cannot be empty"),
89            LbErrKind::FileNonexistent => write!(f, "That file does not exist"),
90            LbErrKind::FileNotDocument => write!(f, "That file is not a document"),
91            LbErrKind::FileParentNonexistent => write!(f, "Could not find that file parent"),
92            LbErrKind::InsufficientPermission => {
93                write!(f, "You don't have the permission to do that")
94            }
95            LbErrKind::InvalidPurchaseToken => write!(f, "That purchase token is invalid"),
96            LbErrKind::InvalidAuthDetails => {
97                write!(f, "Our server failed to authenticate your request, please try again")
98            }
99            LbErrKind::KeyPhraseInvalid => {
100                write!(f, "Your private key phrase is wrong")
101            }
102            LbErrKind::NotPremium => write!(f, "You do not have a premium subscription"),
103            LbErrKind::UsageIsOverDataCap => {
104                write!(f, "You're out of space")
105            }
106            LbErrKind::UsageIsOverFreeTierDataCap => {
107                write!(f, "You're out of space, you can purchase additional space")
108            }
109            LbErrKind::OldCardDoesNotExist => write!(f, "No existing card found"),
110            LbErrKind::PathContainsEmptyFileName => {
111                write!(f, "That path contains an empty file name")
112            }
113            LbErrKind::RootModificationInvalid => write!(f, "You cannot modify your root"),
114            LbErrKind::RootNonexistent => write!(f, "Could not find your root file"),
115            LbErrKind::ServerDisabled => write!(
116                f,
117                "The server is not accepting this action at the moment, please try again later"
118            ),
119            LbErrKind::ServerUnreachable => write!(f, "Could not reach server"),
120            LbErrKind::ShareAlreadyExists => write!(f, "That share already exists"),
121            LbErrKind::ShareNonexistent => write!(f, "That share does not exist"),
122            LbErrKind::TryAgain => write!(f, "Please try again"),
123            LbErrKind::UsernameInvalid => write!(f, "That username is invalid"),
124            LbErrKind::UsernameNotFound => write!(f, "That username is not found"),
125            LbErrKind::UsernamePublicKeyMismatch => {
126                write!(f, "That username doesn't match that public key")
127            }
128            LbErrKind::ImportFailed { paths, total } => {
129                let name = paths
130                    .first()
131                    .and_then(|p| p.file_name())
132                    .unwrap_or_default()
133                    .to_string_lossy();
134                match paths.len() {
135                    1 => write!(f, "{name} couldn't be imported"),
136                    n => write!(f, "{n} of {total} files couldn't be imported, including {name}"),
137                }
138            }
139            LbErrKind::UsernameTaken => write!(f, "That username is not available"),
140            LbErrKind::Unexpected(msg) => write!(f, "Unexpected error: {msg}"),
141            LbErrKind::AlreadySyncing => {
142                write!(f, "A sync is already in progress, cannot begin another sync at this time!")
143            }
144            LbErrKind::ReReadRequired => {
145                write!(f, "This document changed since you last read it, please re-read it!")
146            }
147            LbErrKind::Validation(validation_failure) => match validation_failure {
148                ValidationFailure::Cycle(_) => write!(f, "Cannot move a folder into itself"),
149                ValidationFailure::NonFolderWithChildren(_) => {
150                    write!(f, "A document or a link was treated as a folder.")
151                }
152                ValidationFailure::PathConflict(_) => {
153                    write!(f, "A file already exists at that path.")
154                }
155                ValidationFailure::DeletedFileUpdated(id) => {
156                    write!(f, "this file has been deleted {id}")
157                }
158                ValidationFailure::FileNameTooLong(_) => write!(f, "this filename is too long!"),
159                ValidationFailure::OwnedLink(_) => {
160                    write!(f, "you cannot have a link to a file you own")
161                }
162                ValidationFailure::BrokenLink(_) => write!(f, "that link target does not exist!"),
163                ValidationFailure::DuplicateLink { .. } => {
164                    write!(f, "you already have a link to that file")
165                }
166                ValidationFailure::SharedLink { .. } => {
167                    write!(f, "you cannot place a link inside a shared folder!")
168                }
169                ValidationFailure::SelfShare(_) => {
170                    write!(f, "you cannot share a file with its owner or yourself")
171                }
172                _ => write!(f, "unexpected validation failure: {validation_failure:?}"),
173            },
174            LbErrKind::Diff(diff_error) => {
175                write!(f, "unexpected diff error: {diff_error:?}")
176            }
177            LbErrKind::Sign(sign_error) => {
178                write!(f, "unexpected signing error: {sign_error:?}")
179            }
180            LbErrKind::Crypto(crypto_error) => {
181                write!(f, "unexpected crypto error: {crypto_error:?}")
182            }
183        }
184    }
185}
186
187impl From<LbErrKind> for LbErr {
188    fn from(kind: LbErrKind) -> Self {
189        Self { kind, backtrace: Some(Backtrace::force_capture()) }
190    }
191}
192
193pub trait Unexpected<T> {
194    fn log_and_ignore(self) -> Option<T>;
195    fn map_unexpected(self) -> LbResult<T>;
196}
197
198impl<T, E: std::fmt::Debug> Unexpected<T> for Result<T, E> {
199    #[track_caller]
200    fn map_unexpected(self) -> LbResult<T> {
201        let location = Location::caller();
202        self.map_err(|err| {
203            LbErrKind::Unexpected(format!(
204                "unexpected error at {}:{} {err:?}",
205                location.file(),
206                location.line(),
207            ))
208            .into()
209        })
210    }
211
212    #[track_caller]
213    fn log_and_ignore(self) -> Option<T> {
214        let location = Location::caller();
215        if let Err(e) = &self {
216            error!("error ignored at {}:{} {e:?}", location.file(), location.line());
217        }
218
219        self.ok()
220    }
221}
222
223#[derive(Debug)]
224pub struct UnexpectedError {
225    pub msg: String,
226    pub backtrace: Option<Backtrace>,
227}
228
229impl UnexpectedError {
230    pub fn new(s: impl ToString) -> Self {
231        Self { msg: s.to_string(), backtrace: Some(Backtrace::force_capture()) }
232    }
233}
234
235impl fmt::Display for UnexpectedError {
236    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
237        write!(f, "unexpected error: {}", self.msg)
238    }
239}
240
241impl From<LbErr> for UnexpectedError {
242    fn from(err: LbErr) -> Self {
243        Self { msg: format!("{:?}", err.kind), backtrace: err.backtrace }
244    }
245}
246
247impl<T> From<PoisonError<T>> for UnexpectedError {
248    fn from(err: PoisonError<T>) -> Self {
249        Self::new(format!("{err:#?}"))
250    }
251}
252
253impl From<crossbeam::channel::RecvError> for UnexpectedError {
254    fn from(err: crossbeam::channel::RecvError) -> Self {
255        Self::new(format!("{err:#?}"))
256    }
257}
258
259impl From<crossbeam::channel::RecvTimeoutError> for UnexpectedError {
260    fn from(err: crossbeam::channel::RecvTimeoutError) -> Self {
261        Self::new(format!("{err:#?}"))
262    }
263}
264
265impl<T> From<crossbeam::channel::SendError<T>> for UnexpectedError {
266    fn from(err: crossbeam::channel::SendError<T>) -> Self {
267        Self::new(format!("{err:#?}"))
268    }
269}
270
271impl Serialize for UnexpectedError {
272    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
273    where
274        S: Serializer,
275    {
276        let mut state = serializer.serialize_struct("UnexpectedError", 2)?;
277        state.serialize_field("tag", "Unexpected")?;
278        state.serialize_field("content", &self.msg)?;
279        state.end()
280    }
281}
282
283#[macro_export]
284macro_rules! unexpected_only {
285    ($base:literal $(, $args:tt )*) => {{
286        debug!($base $(, $args )*);
287        debug!("{:?}", std::backtrace::Backtrace::force_capture());
288        debug!($base $(, $args )*);
289        UnexpectedError::new(format!($base $(, $args )*))
290    }};
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub enum LbErrKind {
295    AccountExists,
296    AccountNonexistent,
297    AccountStringCorrupted,
298    AlreadyCanceled,
299    AlreadyPremium,
300    AppStoreAccountAlreadyLinked,
301    AlreadySyncing,
302    // todo: group billing
303    CannotCancelSubscriptionForAppStore,
304    CardDecline,
305    CardExpired,
306    CardInsufficientFunds,
307    CardInvalidCvc,
308    CardInvalidExpMonth,
309    CardInvalidExpYear,
310    CardInvalidNumber,
311    CardNotSupported,
312    ClientUpdateRequired,
313    CurrentUsageIsMoreThanNewTier,
314    DiskPathInvalid,
315    DiskPathTaken,
316    ExistingRequestPending,
317    // todo: Group
318    FileNameContainsSlash,
319    // todo: #[deprecated]
320    FileNameTooLong,
321    FileNameEmpty,
322    FileNonexistent,
323    FileNotDocument,
324    FileParentNonexistent,
325    /// These of the `total` files an import meant to write weren't written.
326    ImportFailed {
327        paths: Vec<PathBuf>,
328        total: usize,
329    },
330    InsufficientPermission,
331    InvalidPurchaseToken,
332    InvalidAuthDetails,
333    KeyPhraseInvalid,
334    NotPremium,
335    UsageIsOverDataCap,
336    UsageIsOverFreeTierDataCap,
337    OldCardDoesNotExist,
338    PathContainsEmptyFileName,
339    RootModificationInvalid,
340    RootNonexistent,
341    ServerDisabled,
342    ServerUnreachable,
343    ShareAlreadyExists,
344    ShareNonexistent,
345    TryAgain,
346    // todo: group username errors
347    UsernameInvalid,
348    UsernameNotFound,
349    UsernamePublicKeyMismatch,
350    UsernameTaken,
351    ReReadRequired,
352    Diff(DiffError),
353
354    /// Errors that describe invalid modifications to trees. See [ValidationFailure] for more info
355    Validation(ValidationFailure),
356    Sign(SignError),
357    Crypto(CryptoError),
358
359    /// If no programmer in any part of the stack (including tests) expects
360    /// to see a particular error, we debug format the underlying error to
361    /// keep the number of error types in check. Commonly used for errors
362    /// originating in other crates.
363    Unexpected(String),
364}
365
366#[derive(Debug, Clone, PartialEq, Eq)]
367pub enum DiffError {
368    OldVersionIncorrect,
369    OldFileNotFound,
370    OldVersionRequired,
371    DiffMalformed,
372    HmacModificationInvalid,
373    SizeModificationInvalid,
374}
375
376#[derive(Debug, Clone, PartialEq, Eq)]
377pub enum SignError {
378    SignatureInvalid,
379    // todo: candidate for unexpected
380    SignatureParseError(libsecp256k1::Error),
381    WrongPublicKey,
382    SignatureInTheFuture(u64),
383    SignatureExpired(u64),
384}
385
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub enum CryptoError {
388    Decryption(aead::Error),
389    HmacVerification(MacError),
390}
391
392impl From<bincode::Error> for LbErr {
393    fn from(err: bincode::Error) -> Self {
394        core_err_unexpected(err).into()
395    }
396}
397
398pub fn core_err_unexpected<T: fmt::Debug>(err: T) -> LbErrKind {
399    LbErrKind::Unexpected(format!("{err:?}"))
400}
401
402// todo call location becomes useless here, and we want that
403pub fn unexpected<T: fmt::Debug>(err: T) -> LbErr {
404    LbErrKind::Unexpected(format!("{err:?}")).into()
405}
406
407impl From<DbError> for LbErr {
408    fn from(err: DbError) -> Self {
409        core_err_unexpected(err).into()
410    }
411}
412
413impl<G> From<PoisonError<G>> for LbErr {
414    fn from(err: PoisonError<G>) -> Self {
415        core_err_unexpected(err).into()
416    }
417}
418
419impl From<io::Error> for LbErr {
420    fn from(e: io::Error) -> Self {
421        match e.kind() {
422            io::ErrorKind::NotFound
423            | io::ErrorKind::PermissionDenied
424            | io::ErrorKind::InvalidInput => LbErrKind::DiskPathInvalid,
425            io::ErrorKind::AlreadyExists => LbErrKind::DiskPathTaken,
426            _ => core_err_unexpected(e),
427        }
428        .into()
429    }
430}
431
432impl From<serde_json::Error> for LbErr {
433    fn from(err: serde_json::Error) -> Self {
434        LbErrKind::Unexpected(format!("{err}")).into()
435    }
436}
437
438impl From<ApiError<api::NewAccountError>> for LbErr {
439    fn from(err: ApiError<api::NewAccountError>) -> Self {
440        match err {
441            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
442            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
443            ApiError::Endpoint(api::NewAccountError::UsernameTaken) => LbErrKind::UsernameTaken,
444            ApiError::Endpoint(api::NewAccountError::InvalidUsername) => LbErrKind::UsernameInvalid,
445            ApiError::Endpoint(api::NewAccountError::Disabled) => LbErrKind::ServerDisabled,
446            e => core_err_unexpected(e),
447        }
448        .into()
449    }
450}
451
452impl From<ApiError<api::GetPublicKeyError>> for LbErr {
453    fn from(err: ApiError<api::GetPublicKeyError>) -> Self {
454        match err {
455            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
456            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
457            ApiError::Endpoint(api::GetPublicKeyError::UserNotFound) => {
458                LbErrKind::AccountNonexistent
459            }
460            e => core_err_unexpected(e),
461        }
462        .into()
463    }
464}
465
466impl From<ApiError<api::GetUsernameError>> for LbErr {
467    fn from(err: ApiError<api::GetUsernameError>) -> Self {
468        match err {
469            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
470            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
471            ApiError::Endpoint(api::GetUsernameError::UserNotFound) => {
472                LbErrKind::AccountNonexistent
473            }
474            e => core_err_unexpected(e),
475        }
476        .into()
477    }
478}
479
480impl From<ApiError<api::GetFileIdsError>> for LbErr {
481    fn from(e: ApiError<api::GetFileIdsError>) -> Self {
482        match e {
483            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
484            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
485            e => core_err_unexpected(e),
486        }
487        .into()
488    }
489}
490
491impl From<ApiError<api::GetUpdatesError>> for LbErr {
492    fn from(e: ApiError<api::GetUpdatesError>) -> Self {
493        match e {
494            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
495            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
496            e => core_err_unexpected(e),
497        }
498        .into()
499    }
500}
501
502impl From<ApiError<api::GetDocumentError>> for LbErr {
503    fn from(e: ApiError<api::GetDocumentError>) -> Self {
504        match e {
505            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
506            ApiError::Endpoint(api::GetDocumentError::DocumentNotFound) => {
507                LbErrKind::FileNonexistent
508            }
509            ApiError::Endpoint(api::GetDocumentError::NotPermissioned) => {
510                LbErrKind::InsufficientPermission
511            }
512            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
513            e => core_err_unexpected(e),
514        }
515        .into()
516    }
517}
518
519impl From<ApiError<api::UpsertError>> for LbErr {
520    fn from(e: ApiError<api::UpsertError>) -> Self {
521        match e {
522            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
523            ApiError::Endpoint(api::UpsertError::UsageIsOverDataCap) => {
524                LbErrKind::UsageIsOverDataCap
525            }
526            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
527            e => core_err_unexpected(e),
528        }
529        .into()
530    }
531}
532
533impl From<ApiError<api::UpsertDebugInfoError>> for LbErr {
534    fn from(e: ApiError<api::UpsertDebugInfoError>) -> Self {
535        match e {
536            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
537            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
538            e => core_err_unexpected(e),
539        }
540        .into()
541    }
542}
543
544impl From<ApiError<api::ChangeDocError>> for LbErr {
545    fn from(e: ApiError<api::ChangeDocError>) -> Self {
546        match e {
547            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
548            ApiError::Endpoint(api::ChangeDocError::UsageIsOverDataCap) => {
549                LbErrKind::UsageIsOverDataCap
550            }
551            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
552            e => core_err_unexpected(e),
553        }
554        .into()
555    }
556}
557
558impl From<ApiError<api::GetUsageError>> for LbErr {
559    fn from(e: ApiError<api::GetUsageError>) -> Self {
560        match e {
561            ApiError::SendFailed(_) => LbErrKind::ServerUnreachable,
562            ApiError::ClientUpdateRequired => LbErrKind::ClientUpdateRequired,
563            e => core_err_unexpected(e),
564        }
565        .into()
566    }
567}
568
569#[derive(Debug, Clone, Serialize)]
570pub enum Warning {
571    EmptyFile(Uuid),
572    InvalidUTF8(Uuid),
573}
574
575impl fmt::Display for Warning {
576    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577        match self {
578            Self::EmptyFile(id) => write!(f, "empty file: {id}"),
579            Self::InvalidUTF8(id) => write!(f, "invalid utf8 in file: {id}"),
580        }
581    }
582}