Skip to main content

sefy_core/
error.rs

1//! What can go wrong, phrased so that no message carries secret material.
2
3use std::path::PathBuf;
4
5/// Result alias used across the core library.
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// Everything that can go wrong while working with a vault.
9///
10/// Error messages never contain secret material: no passwords, no item
11/// contents, no attachment bytes.
12#[derive(Debug, thiserror::Error)]
13pub enum Error {
14    /// The password did not decrypt the vault, or the file is not a vault at
15    /// all. These two cases are indistinguishable by design: an unauthenticated
16    /// blob carries nothing to tell them apart.
17    #[error("wrong password or not a vault file")]
18    WrongPasswordOrNotAVault,
19
20    /// The file is too short to hold a salt, a nonce and an authentication tag.
21    #[error("file is too small to be a vault")]
22    TooSmall,
23
24    /// The decrypted payload declares a format version this build cannot read.
25    #[error("unsupported vault format version {0}; upgrade sefy")]
26    UnsupportedFormat(u8),
27
28    /// The vault file exists and would be overwritten.
29    #[error("vault already exists: {0}")]
30    AlreadyExists(PathBuf),
31
32    /// The vault's file is no longer the version this value read: something
33    /// else wrote it, or removed it. Nothing was written over it.
34    #[error(
35        "{0} changed on disk after it was opened, and writing now would erase that; \
36         nothing was written, so run the command again"
37    )]
38    ChangedOnDisk(PathBuf),
39
40    /// A vault can only be set to the values on offer ([`crate::policy`]).
41    #[error("a vault cannot be set to that")]
42    PolicyNotOffered,
43
44    /// The requested item is not in the vault.
45    #[error("no item with id {0}")]
46    ItemNotFound(i64),
47
48    /// Nothing in the vault matches what the user asked for.
49    #[error("nothing matches {0:?}")]
50    NotFound(String),
51
52    /// More than one item matches, so the caller has to narrow it down.
53    ///
54    /// The candidates travel with the error to be shown to the user; they carry
55    /// item titles, so treat them as vault contents rather than log material.
56    #[error("{} items match {reference:?}", candidates.len())]
57    Ambiguous {
58        /// What the user typed.
59        reference: String,
60        /// Every item it could have meant.
61        candidates: Vec<crate::model::ItemSummary>,
62    },
63
64    /// The requested item does not hold the kind of payload asked for.
65    #[error("item {id} is a {actual}, not a {expected}")]
66    ItemKindMismatch {
67        /// Item that was addressed.
68        id: i64,
69        /// Kind the item actually has.
70        actual: String,
71        /// Kind the caller asked for.
72        expected: String,
73    },
74
75    /// The item was written by a newer sefy, which knows a kind this one does
76    /// not.
77    ///
78    /// Reading its contents, editing it or extracting it would all mean
79    /// guessing at a shape this build has never seen. Listing, searching,
80    /// exporting and merging work regardless: those need the item's identity,
81    /// not its meaning.
82    #[error("item {id} is a {kind}, a kind this version of sefy does not know")]
83    UnknownItemKind {
84        /// Item that was addressed.
85        id: i64,
86        /// The name the kind was stored under.
87        kind: String,
88    },
89
90    /// The item has no earlier version by that identity.
91    #[error("item {id} has no version {version}")]
92    VersionNotFound {
93        /// Item that was addressed.
94        id: i64,
95        /// Identity of the version asked for.
96        version: String,
97    },
98
99    /// A version asked to give back one field did not have it.
100    ///
101    /// Carries the names it did have, which are labels rather than values and
102    /// safe to show.
103    #[error("that version has no field named {name:?}")]
104    FieldNotInVersion {
105        /// The field asked for.
106        name: String,
107        /// The fields the version did hold.
108        available: Vec<String>,
109    },
110
111    /// A kept version could not be read back.
112    ///
113    /// Written by this build it cannot happen; a damaged or hand-edited
114    /// database can, and the version is reported rather than read as empty.
115    #[error("an earlier version of an item cannot be read")]
116    UnreadableVersion,
117
118    /// The export file declares a version this build cannot read.
119    #[error("unsupported export format version {0}; upgrade sefy")]
120    UnsupportedExport(u32),
121
122    /// The file handed to an import is none of the formats sefy reads.
123    #[error(
124        "not a file sefy can import: expected a sefy export, a Bitwarden JSON export, \
125         a KeePass XML export, or a CSV of passwords with a header row"
126    )]
127    UnrecognizedImport,
128
129    /// The file looks like one of the formats sefy reads, but is not a usable
130    /// one.
131    #[error("this looks like {format}, but it cannot be read: {reason}")]
132    UnreadableImport {
133        /// What the file looked like, as in "a KeePass XML export".
134        format: &'static str,
135        /// What is wrong with it, without quoting anything secret.
136        reason: String,
137    },
138
139    /// The file is an export another tool sealed under its own password, so
140    /// its contents are not there to read.
141    #[error("this {format} is encrypted: {advice}")]
142    SealedImport {
143        /// What the file is, as in "Bitwarden export".
144        format: &'static str,
145        /// How to get one that is not.
146        advice: &'static str,
147    },
148
149    /// An item holds something the chosen export format has no way to carry.
150    #[error("{title:?} cannot be exported as {format}: {reason}")]
151    Unexportable {
152        /// The item's title.
153        title: String,
154        /// The format being written, as in "KeePass XML".
155        format: &'static str,
156        /// What it holds that the format cannot.
157        reason: String,
158    },
159
160    /// An entry in an export is missing a field or holds something unusable.
161    #[error("item {index} in the export is malformed: {reason}")]
162    MalformedExport {
163        /// Position of the offending entry, counting from zero.
164        index: usize,
165        /// What is wrong with it, without quoting the item's contents.
166        reason: String,
167    },
168
169    /// A plugin was found but sefy will not run it.
170    ///
171    /// Refusing before the call is deliberate: running a transport that cannot
172    /// do what was asked turns a knowable mismatch into a failure the user has
173    /// to interpret from someone else's error message.
174    #[error("plugin {name} cannot be used: {reason}")]
175    PluginUnusable {
176        /// Short name of the plugin.
177        name: String,
178        /// Why it will not be run.
179        reason: String,
180    },
181
182    /// A plugin ran and did not carry out the operation.
183    ///
184    /// The reason comes from the plugin itself and is shown as given; a
185    /// transport's own output is never quoted back verbatim, since it may
186    /// carry credentials for the remote.
187    #[error("plugin {name} failed: {reason}")]
188    PluginFailed {
189        /// Short name of the plugin.
190        name: String,
191        /// What the plugin said went wrong.
192        reason: String,
193    },
194
195    /// Key derivation failed (only on absurd parameters or allocation failure).
196    #[error("key derivation failed")]
197    KeyDerivation,
198
199    /// The operating system refused to provide random bytes.
200    #[error("system random number generator unavailable")]
201    Random,
202
203    /// A generated secret was asked to be shorter than its recipe allows, or
204    /// longer than sefy generates.
205    #[error("cannot generate {length} {unit}; the range is {minimum} to {maximum}")]
206    GeneratorLength {
207        /// What was asked for.
208        length: usize,
209        /// The fewest the recipe can work with.
210        minimum: usize,
211        /// The most sefy generates.
212        maximum: usize,
213        /// What is being counted: characters or words.
214        unit: &'static str,
215    },
216
217    /// What was offered as a one-time password key is not one.
218    ///
219    /// The reason is one of a fixed set of phrases: the text itself is a
220    /// secret and is never quoted back.
221    #[error("not a one-time password key: {0}")]
222    InvalidOtpKey(&'static str),
223
224    /// What was offered as the date a record stops working is not one.
225    ///
226    /// The text is quoted: a date is a public field, and seeing what was
227    /// typed is the quickest way to see what is wrong with it.
228    #[error(
229        "{0:?} is not a date sefy can read; write the day as 2027-01-31, \
230         or a month as 2027-01 or 01/27, the way a card prints it"
231    )]
232    UnreadableExpiry(String),
233
234    /// The clipboard could not be reached or written.
235    ///
236    /// The message is the platform's, which describes the clipboard and
237    /// never what was being put on it.
238    #[error("{0}")]
239    Clipboard(String),
240
241    /// Whoever holds the password has locked, or is no longer there.
242    #[error("the vault was locked while this was running")]
243    KeysGone,
244
245    /// What was offered for sealing is not the password this vault was opened
246    /// with: another agent took the place of the first, or the password typed
247    /// when the first had gone was mistyped. Sealing under it would quietly
248    /// move the vault to a password its owner is not thinking of.
249    #[error("that is not the password this vault was opened with; nothing was written")]
250    KeysChanged,
251
252    /// This takes the password itself, and the vault was opened through a key
253    /// someone else derived.
254    #[error("this needs the master password typed, not an unlocked vault")]
255    PasswordNeeded,
256
257    /// A filesystem operation failed.
258    #[error("{context}: {source}")]
259    Io {
260        /// What was being attempted.
261        context: String,
262        /// Underlying OS error.
263        #[source]
264        source: std::io::Error,
265    },
266
267    /// The embedded database rejected an operation.
268    #[error("database error: {0}")]
269    Db(#[from] rusqlite::Error),
270}
271
272impl Error {
273    /// Attaches a human-readable context to an I/O failure.
274    pub(crate) fn io(context: impl Into<String>, source: std::io::Error) -> Self {
275        Self::Io {
276            context: context.into(),
277            source,
278        }
279    }
280}