sefy-core 0.20.0

Core library for sefy: an inconspicuous encrypted secret store in a single file
Documentation
//! What can go wrong, phrased so that no message carries secret material.

use std::path::PathBuf;

/// Result alias used across the core library.
pub type Result<T> = std::result::Result<T, Error>;

/// Everything that can go wrong while working with a vault.
///
/// Error messages never contain secret material: no passwords, no item
/// contents, no attachment bytes.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// The password did not decrypt the vault, or the file is not a vault at
    /// all. These two cases are indistinguishable by design: an unauthenticated
    /// blob carries nothing to tell them apart.
    #[error("wrong password or not a vault file")]
    WrongPasswordOrNotAVault,

    /// The file is too short to hold a salt, a nonce and an authentication tag.
    #[error("file is too small to be a vault")]
    TooSmall,

    /// The decrypted payload declares a format version this build cannot read.
    #[error("unsupported vault format version {0}; upgrade sefy")]
    UnsupportedFormat(u8),

    /// The vault file exists and would be overwritten.
    #[error("vault already exists: {0}")]
    AlreadyExists(PathBuf),

    /// The vault's file is no longer the version this value read: something
    /// else wrote it, or removed it. Nothing was written over it.
    #[error(
        "{0} changed on disk after it was opened, and writing now would erase that; \
         nothing was written, so run the command again"
    )]
    ChangedOnDisk(PathBuf),

    /// A vault can only be set to the values on offer ([`crate::policy`]).
    #[error("a vault cannot be set to that")]
    PolicyNotOffered,

    /// The requested item is not in the vault.
    #[error("no item with id {0}")]
    ItemNotFound(i64),

    /// Nothing in the vault matches what the user asked for.
    #[error("nothing matches {0:?}")]
    NotFound(String),

    /// More than one item matches, so the caller has to narrow it down.
    ///
    /// The candidates travel with the error to be shown to the user; they carry
    /// item titles, so treat them as vault contents rather than log material.
    #[error("{} items match {reference:?}", candidates.len())]
    Ambiguous {
        /// What the user typed.
        reference: String,
        /// Every item it could have meant.
        candidates: Vec<crate::model::ItemSummary>,
    },

    /// The requested item does not hold the kind of payload asked for.
    #[error("item {id} is a {actual}, not a {expected}")]
    ItemKindMismatch {
        /// Item that was addressed.
        id: i64,
        /// Kind the item actually has.
        actual: String,
        /// Kind the caller asked for.
        expected: String,
    },

    /// The item was written by a newer sefy, which knows a kind this one does
    /// not.
    ///
    /// Reading its contents, editing it or extracting it would all mean
    /// guessing at a shape this build has never seen. Listing, searching,
    /// exporting and merging work regardless: those need the item's identity,
    /// not its meaning.
    #[error("item {id} is a {kind}, a kind this version of sefy does not know")]
    UnknownItemKind {
        /// Item that was addressed.
        id: i64,
        /// The name the kind was stored under.
        kind: String,
    },

    /// The item has no earlier version by that identity.
    #[error("item {id} has no version {version}")]
    VersionNotFound {
        /// Item that was addressed.
        id: i64,
        /// Identity of the version asked for.
        version: String,
    },

    /// A version asked to give back one field did not have it.
    ///
    /// Carries the names it did have, which are labels rather than values and
    /// safe to show.
    #[error("that version has no field named {name:?}")]
    FieldNotInVersion {
        /// The field asked for.
        name: String,
        /// The fields the version did hold.
        available: Vec<String>,
    },

    /// A kept version could not be read back.
    ///
    /// Written by this build it cannot happen; a damaged or hand-edited
    /// database can, and the version is reported rather than read as empty.
    #[error("an earlier version of an item cannot be read")]
    UnreadableVersion,

    /// The export file declares a version this build cannot read.
    #[error("unsupported export format version {0}; upgrade sefy")]
    UnsupportedExport(u32),

    /// The file handed to an import is none of the formats sefy reads.
    #[error(
        "not a file sefy can import: expected a sefy export, a Bitwarden JSON export, \
         a KeePass XML export, or a CSV of passwords with a header row"
    )]
    UnrecognizedImport,

    /// The file looks like one of the formats sefy reads, but is not a usable
    /// one.
    #[error("this looks like {format}, but it cannot be read: {reason}")]
    UnreadableImport {
        /// What the file looked like, as in "a KeePass XML export".
        format: &'static str,
        /// What is wrong with it, without quoting anything secret.
        reason: String,
    },

    /// The file is an export another tool sealed under its own password, so
    /// its contents are not there to read.
    #[error("this {format} is encrypted: {advice}")]
    SealedImport {
        /// What the file is, as in "Bitwarden export".
        format: &'static str,
        /// How to get one that is not.
        advice: &'static str,
    },

    /// An item holds something the chosen export format has no way to carry.
    #[error("{title:?} cannot be exported as {format}: {reason}")]
    Unexportable {
        /// The item's title.
        title: String,
        /// The format being written, as in "KeePass XML".
        format: &'static str,
        /// What it holds that the format cannot.
        reason: String,
    },

    /// An entry in an export is missing a field or holds something unusable.
    #[error("item {index} in the export is malformed: {reason}")]
    MalformedExport {
        /// Position of the offending entry, counting from zero.
        index: usize,
        /// What is wrong with it, without quoting the item's contents.
        reason: String,
    },

    /// A plugin was found but sefy will not run it.
    ///
    /// Refusing before the call is deliberate: running a transport that cannot
    /// do what was asked turns a knowable mismatch into a failure the user has
    /// to interpret from someone else's error message.
    #[error("plugin {name} cannot be used: {reason}")]
    PluginUnusable {
        /// Short name of the plugin.
        name: String,
        /// Why it will not be run.
        reason: String,
    },

    /// A plugin ran and did not carry out the operation.
    ///
    /// The reason comes from the plugin itself and is shown as given; a
    /// transport's own output is never quoted back verbatim, since it may
    /// carry credentials for the remote.
    #[error("plugin {name} failed: {reason}")]
    PluginFailed {
        /// Short name of the plugin.
        name: String,
        /// What the plugin said went wrong.
        reason: String,
    },

    /// Key derivation failed (only on absurd parameters or allocation failure).
    #[error("key derivation failed")]
    KeyDerivation,

    /// The operating system refused to provide random bytes.
    #[error("system random number generator unavailable")]
    Random,

    /// A generated secret was asked to be shorter than its recipe allows, or
    /// longer than sefy generates.
    #[error("cannot generate {length} {unit}; the range is {minimum} to {maximum}")]
    GeneratorLength {
        /// What was asked for.
        length: usize,
        /// The fewest the recipe can work with.
        minimum: usize,
        /// The most sefy generates.
        maximum: usize,
        /// What is being counted: characters or words.
        unit: &'static str,
    },

    /// What was offered as a one-time password key is not one.
    ///
    /// The reason is one of a fixed set of phrases: the text itself is a
    /// secret and is never quoted back.
    #[error("not a one-time password key: {0}")]
    InvalidOtpKey(&'static str),

    /// What was offered as the date a record stops working is not one.
    ///
    /// The text is quoted: a date is a public field, and seeing what was
    /// typed is the quickest way to see what is wrong with it.
    #[error(
        "{0:?} is not a date sefy can read; write the day as 2027-01-31, \
         or a month as 2027-01 or 01/27, the way a card prints it"
    )]
    UnreadableExpiry(String),

    /// The clipboard could not be reached or written.
    ///
    /// The message is the platform's, which describes the clipboard and
    /// never what was being put on it.
    #[error("{0}")]
    Clipboard(String),

    /// Whoever holds the password has locked, or is no longer there.
    #[error("the vault was locked while this was running")]
    KeysGone,

    /// What was offered for sealing is not the password this vault was opened
    /// with: another agent took the place of the first, or the password typed
    /// when the first had gone was mistyped. Sealing under it would quietly
    /// move the vault to a password its owner is not thinking of.
    #[error("that is not the password this vault was opened with; nothing was written")]
    KeysChanged,

    /// This takes the password itself, and the vault was opened through a key
    /// someone else derived.
    #[error("this needs the master password typed, not an unlocked vault")]
    PasswordNeeded,

    /// A filesystem operation failed.
    #[error("{context}: {source}")]
    Io {
        /// What was being attempted.
        context: String,
        /// Underlying OS error.
        #[source]
        source: std::io::Error,
    },

    /// The embedded database rejected an operation.
    #[error("database error: {0}")]
    Db(#[from] rusqlite::Error),
}

impl Error {
    /// Attaches a human-readable context to an I/O failure.
    pub(crate) fn io(context: impl Into<String>, source: std::io::Error) -> Self {
        Self::Io {
            context: context.into(),
            source,
        }
    }
}