Skip to main content

keyring_core/
error.rs

1/*!
2
3Platform-independent error model.
4
5There is an escape hatch here for surfacing platform-specific
6error information returned by the platform-specific storage provider,
7but the concrete objects returned must be `Send` so they can be
8moved from one thread to another. (Since most platform errors
9are integer error codes, this requirement
10is not much of a burden on the platform-specific store providers.)
11 */
12
13use crate::Entry;
14
15/// A boxed platform-specific error.
16pub type PlatformError = Box<dyn std::error::Error + Send + Sync>;
17
18/// Each variant of the `Error` enum provides a summary of the error.
19/// More details, if relevant, are contained in the associated value,
20/// which may be platform-specific.
21///
22/// This enum is non-exhaustive so that more values can be added to it
23/// without a SemVer break. Clients should always have default handling
24/// for variants they don't understand.
25#[non_exhaustive]
26#[derive(Debug)]
27pub enum Error {
28    /// This indicates runtime failure in the underlying platform storage
29    /// system.  The details of the failure can be retrieved from the
30    /// attached platform error.
31    PlatformFailure(PlatformError),
32    /// This indicates that the underlying secure storage holding saved
33    /// items could not be accessed.  Typically, this is because of access
34    /// rules in the platform; for example, it might be that the credential
35    /// store is locked.  The underlying platform error will typically give
36    /// the reason.
37    NoStorageAccess(PlatformError),
38    /// This indicates that there is no underlying credential entry in the
39    /// platform for this entry.  Either one was never set, or it was
40    /// deleted.
41    NoEntry,
42    /// This indicates that the retrieved password blob was not a UTF-8
43    /// string.  The underlying bytes are available for examination in the
44    /// attached value.
45    BadEncoding(Vec<u8>),
46    /// This indicates that the retrieved secret blob was not formatted as
47    /// expected by the store. (Some stores perform encryption or other
48    /// transformations when storing secrets.) The raw data of the
49    /// retrieved blob are attached, as is an underlying error indicating
50    /// what went wrong.
51    BadDataFormat(Vec<u8>, PlatformError),
52    /// This indicates that the store itself was not formatted as expected.
53    ///  The attached value describes the problem.
54    BadStoreFormat(String),
55    /// This indicates that one of the entry's credential attributes
56    /// exceeded a length limit in the underlying platform.  The attached
57    /// values give the name of the attribute and the platform length limit
58    /// that was exceeded.
59    TooLong(String, u32),
60    /// This indicates that one of the parameters passed to the operation
61    /// was invalid. The attached value gives the parameter and describes
62    /// the problem.
63    Invalid(String, String),
64    /// This indicates that there is more than one credential found in the
65    /// store that matches the entry.  Its value is a vector of entries
66    /// wrapping the matching credentials.
67    Ambiguous(Vec<Entry>),
68    /// This indicates that there was no default credential builder to use;
69    /// the client must set one before creating entries.
70    NoDefaultStore,
71    /// This indicates that the requested operation is unsupported by the
72    /// store handling the request. The value describes why the requested
73    /// operation could not be performed.
74    NotSupportedByStore(String),
75}
76
77/// A `Result` type with [`Error`] as its error value.
78pub type Result<T> = std::result::Result<T, Error>;
79
80impl std::fmt::Display for Error {
81    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
82        match self {
83            Error::PlatformFailure(err) => write!(f, "Platform failure: {err}"),
84            Error::NoStorageAccess(err) => {
85                write!(f, "Couldn't access platform storage: {err}")
86            }
87            Error::NoEntry => write!(f, "No matching credential found"),
88            Error::BadEncoding(_) => write!(f, "Password data is not valid UTF-8"),
89            Error::BadDataFormat(_, err) => {
90                write!(f, "Secret data is malformed: {err:?}")
91            }
92            Error::BadStoreFormat(reason) => write!(f, "Store data is malformed: {reason}"),
93            Error::TooLong(name, len) => write!(
94                f,
95                "Value of '{name}' is longer than the platform limit of {len} chars"
96            ),
97            Error::Invalid(attr, reason) => {
98                write!(f, "Value of '{attr}' is invalid: {reason}")
99            }
100            Error::Ambiguous(items) => {
101                write!(
102                    f,
103                    "Entry is matched by {} credentials: {items:?}",
104                    items.len(),
105                )
106            }
107            Error::NoDefaultStore => {
108                write!(
109                    f,
110                    "No default store has been set, so cannot search or create entries"
111                )
112            }
113            Error::NotSupportedByStore(issue) => write!(f, "Unsupported: {issue}"),
114        }
115    }
116}
117
118impl std::error::Error for Error {
119    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
120        match self {
121            Error::PlatformFailure(err) => Some(err.as_ref()),
122            Error::NoStorageAccess(err) => Some(err.as_ref()),
123            Error::BadDataFormat(_, err) => Some(err.as_ref()),
124            _ => None,
125        }
126    }
127}
128
129/// Try to interpret a byte vector as a password string
130pub fn decode_password(bytes: Vec<u8>) -> Result<String> {
131    String::from_utf8(bytes).map_err(|err| Error::BadEncoding(err.into_bytes()))
132}