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