Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

11.0 KB
Raw Blame
//! The engine's errors and the codes the host reports them as.

use serde::{Deserialize, Serialize};

use crate::common::error::VaultError;

/// The client error codes the engine reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ErrorCode {
    /// No encryption key in the session.
    #[serde(rename = "E-202")]
    VaultLocked,
    /// The stored vault does not decrypt with the session key.
    #[serde(rename = "E-203")]
    VaultDecryptFailed,
    /// The unlock key does not open the account key (wrong password).
    #[serde(rename = "E-206")]
    UnlockKeyRejected,
    /// The account key opened, the vault encryption key under it did not.
    #[serde(rename = "E-207")]
    KeyChainUnreadable,
    /// The session key does not open the key chain the server holds; only a re-login recovers.
    #[serde(rename = "E-208")]
    KeyOutOfSync,
    /// The account public key the server serves does not belong to the account private key this session holds.
    #[serde(rename = "E-217")]
    AccountKeyMismatch,
    /// The server's snapshot cannot be assembled into a vault.
    #[serde(rename = "E-502")]
    SyncVaultFetchFailed,
    /// A server manifest or bucket fails its hash check or does not decrypt.
    #[serde(rename = "E-503")]
    SyncVaultDecryptFailed,
    /// The server cannot be reached and there is no local vault to fall back on.
    #[serde(rename = "E-505")]
    SyncServerUnreachable,
    /// The server answered a request with an unexpected HTTP failure.
    #[serde(rename = "E-506")]
    SyncServerError,
    /// A server response (or a request body) is not the JSON shape this client expects.
    #[serde(rename = "E-507")]
    SyncResponseInvalid,
    /// The core library (codec, merge or crypto) refused the vault data.
    #[serde(rename = "E-508")]
    SyncCodecFailed,
    /// The engine hit a state it has no rule for; the message says which.
    #[serde(rename = "E-509")]
    SyncEngineFailed,
    /// The host failed a read command.
    #[serde(rename = "E-601")]
    StorageReadFailed,
    /// The host failed a write command.
    #[serde(rename = "E-602")]
    StorageWriteFailed,
    /// The engine's staging database failed.
    #[serde(rename = "E-603")]
    DatabaseInitFailed,
    /// The server kept refusing the write as outdated after the re-sync limit.
    #[serde(rename = "E-702")]
    MergeConflict,
    /// The write was rejected: integrity check, or blobs the server asked for that this client cannot supply.
    #[serde(rename = "E-801")]
    UploadFailed,
    #[serde(rename = "E-804")]
    UploadTooLarge,
    #[serde(rename = "E-805")]
    UploadTimeout,
    /// LEGACY: the vault is not on the latest pre-manifest-v1 schema, so the migration cannot run yet.
    #[serde(rename = "E-901")]
    MigrationCheckFailed,
    #[serde(rename = "E-903")]
    ServerUpdateRequired,
}

/// Why the host has to log the user out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum LogoutReason {
    ClientVersionNotSupported,
    ServerVersionNotSupported,
    SessionExpired,
    PasswordChanged,
    VaultVersionIncompatible,
}

/// How the host reports a failure: a forced logout, or a coded error it translates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Failure {
    Logout(LogoutReason),
    Coded(ErrorCode),
}

#[derive(Debug, thiserror::Error)]
pub enum SyncError {
    /// The server could not be reached.
    #[error("Network error: {0}")]
    Network(String),
    /// A request exceeded its timeout.
    #[error("Request timed out: {0}")]
    Timeout(String),
    /// The session is no longer valid.
    #[error("Session expired")]
    Auth,
    /// The server refuses this client version (HTTP 426).
    #[error("The server no longer supports this client version")]
    ClientUpgradeRequired,
    /// The server predates the v2 API.
    #[error("The server predates the v2 API and has to be updated")]
    ServerUpdateRequired,
    /// HTTP 413.
    #[error("Request rejected with HTTP 413: payload exceeds server limit")]
    PayloadTooLarge,
    /// The server's SRP salt no longer matches the one this device derived its keys from.
    #[error("Password was changed on another device")]
    PasswordChangedElsewhere,
    /// The local vault's data version cannot be read by this client.
    #[error("{0}")]
    VaultVersionIncompatible(String),
    /// Any other HTTP failure, with the API error code its body names.
    #[error("HTTP {status}: {body}")]
    Http { status: u16, code: Option<String>, body: String },
    /// The session holds no encryption key.
    #[error("No encryption key available")]
    VaultLocked,
    /// The stored vault does not decrypt with the session key.
    #[error("Vault could not be decrypted: {0}")]
    VaultDecryptFailed(String),
    /// The unlock key does not open the account key (wrong password).
    #[error("The unlock key does not open the account key")]
    UnlockKeyRejected,
    /// The account key opened, the vault encryption key under it did not.
    #[error("The account key does not open the vault encryption key: {0}")]
    KeyChainUnreadable(String),
    /// The session key opens neither the server's chain nor its VEK; only a re-login recovers.
    #[error("Vault encryption key out of sync with the server; log in again")]
    KeyOutOfSync,
    /// The account public key the server serves is not the public half of the account private key this session holds.
    #[error("The account public key the server serves does not belong to this account's private key")]
    AccountKeyMismatch,
    /// A server manifest or bucket failed its hash check or did not decrypt.
    #[error("Server vault could not be opened: {0}")]
    ServerVaultUnreadable(String),
    /// The server's snapshot is inconsistent and cannot be assembled.
    #[error("Server snapshot cannot be assembled: {0}")]
    Snapshot(String),
    /// The vault data decrypted and decoded, but its rows do not load into the database.
    #[error("Vault data does not load into the database: {0}")]
    VaultDataRejected(String),
    /// The server kept refusing the write as outdated after the re-sync limit.
    #[error("The server keeps refusing the write as outdated")]
    ResyncLimitReached,
    /// The write failed the vault integrity check; the failed rules.
    #[error("Upload rejected by the vault integrity check: {}", .0.join("; "))]
    UploadRejected(Vec<String>),
    /// The server asked for blobs this client cannot supply.
    #[error("Server reported blobs this client cannot supply: {}", .0.join(", "))]
    MissingBlobs(Vec<String>),
    /// LEGACY: the manifest migration cannot run before the sqlite-blob upgrade chain.
    #[error("The vault has to walk the legacy upgrade chain first")]
    LegacyUpgradePending,
    /// The engine's in-process staging database failed.
    #[error("Staging database failed: {0}")]
    Staging(String),
    /// The host reported a failure for a command.
    #[error("Host command {command} failed: {message}")]
    Host { command: &'static str, message: String },
    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
    /// A codec, merge or crypto failure from the core library.
    #[error(transparent)]
    Core(#[from] VaultError),
    /// Anything else.
    #[error("{0}")]
    Other(String),
}

impl From<crate::crypto::KeyChainError> for SyncError {
    fn from(error: crate::crypto::KeyChainError) -> Self {
        match error {
            // Either rejection is a wrong key to the host.
            crate::crypto::KeyChainError::UnlockKeyRejected | crate::crypto::KeyChainError::AccountKeyRejected => SyncError::UnlockKeyRejected,
            crate::crypto::KeyChainError::KeyChainUnreadable(message) => SyncError::KeyChainUnreadable(message),
        }
    }
}

impl SyncError {
    /// The API error code the server refused the request with, when it named one.
    pub fn api_error_code(&self) -> Option<String> {
        match self {
            SyncError::Http { code, .. } => code.clone(),
            _ => None,
        }
    }

    /// How the host reports this failure.
    pub fn failure(&self) -> Failure {
        match self {
            SyncError::Auth => Failure::Logout(LogoutReason::SessionExpired),
            SyncError::ClientUpgradeRequired => Failure::Logout(LogoutReason::ClientVersionNotSupported),
            SyncError::PasswordChangedElsewhere => Failure::Logout(LogoutReason::PasswordChanged),
            SyncError::VaultVersionIncompatible(_) => Failure::Logout(LogoutReason::VaultVersionIncompatible),
            SyncError::Network(_) => Failure::Coded(ErrorCode::SyncServerUnreachable),
            SyncError::Timeout(_) => Failure::Coded(ErrorCode::UploadTimeout),
            SyncError::ServerUpdateRequired => Failure::Coded(ErrorCode::ServerUpdateRequired),
            SyncError::PayloadTooLarge => Failure::Coded(ErrorCode::UploadTooLarge),
            // The server holds no key chain for this session: only a re-login recovers.
            SyncError::Http { code: Some(code), .. } if code == "VAULT_KEY_NOT_FOUND" => Failure::Logout(LogoutReason::PasswordChanged),
            SyncError::Http { .. } => Failure::Coded(ErrorCode::SyncServerError),
            SyncError::VaultLocked => Failure::Coded(ErrorCode::VaultLocked),
            SyncError::VaultDecryptFailed(_) => Failure::Coded(ErrorCode::VaultDecryptFailed),
            SyncError::UnlockKeyRejected => Failure::Coded(ErrorCode::UnlockKeyRejected),
            SyncError::KeyChainUnreadable(_) => Failure::Coded(ErrorCode::KeyChainUnreadable),
            SyncError::KeyOutOfSync => Failure::Logout(LogoutReason::PasswordChanged),
            SyncError::AccountKeyMismatch => Failure::Coded(ErrorCode::AccountKeyMismatch),
            SyncError::ServerVaultUnreadable(_) => Failure::Coded(ErrorCode::SyncVaultDecryptFailed),
            SyncError::Snapshot(_) => Failure::Coded(ErrorCode::SyncVaultFetchFailed),
            SyncError::VaultDataRejected(_) => Failure::Coded(ErrorCode::SyncCodecFailed),
            SyncError::ResyncLimitReached => Failure::Coded(ErrorCode::MergeConflict),
            SyncError::UploadRejected(_) | SyncError::MissingBlobs(_) => Failure::Coded(ErrorCode::UploadFailed),
            SyncError::LegacyUpgradePending => Failure::Coded(ErrorCode::MigrationCheckFailed),
            SyncError::Staging(_) => Failure::Coded(ErrorCode::DatabaseInitFailed),
            SyncError::Host { command, .. } => Failure::Coded(storage_error_code(command)),
            SyncError::Json(_) => Failure::Coded(ErrorCode::SyncResponseInvalid),
            SyncError::Core(_) => Failure::Coded(ErrorCode::SyncCodecFailed),
            SyncError::Other(_) => Failure::Coded(ErrorCode::SyncEngineFailed),
        }
    }
}

/// The error code a failed host command maps to.
fn storage_error_code(command: &str) -> ErrorCode {
    match command {
        "stateGet" | "dbQuery" | "dbExport" | "vaultLoad" => ErrorCode::StorageReadFailed,
        "stateSet" | "stateRemove" | "dbExec" | "vaultStore" | "markClean" => ErrorCode::StorageWriteFailed,
        _ => ErrorCode::SyncEngineFailed,
    }
}

pub type SyncResult<T> = Result<T, SyncError>;