Skip to main content

subspace_core/
keychain.rs

1//! The system credential store: the macOS Keychain, Windows Credential
2//! Manager or the Secret Service. Never a file fallback, and no error carries
3//! the provider's details.
4
5use crate::Secret;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
8#[error("The credential store is unavailable. Unlock your system keychain and try again.")]
9pub struct KeychainError;
10
11/// The secrets of one service name, one per account.
12pub struct Keychain {
13    service: String,
14}
15
16impl Keychain {
17    /// Use a stable product/channel namespace to keep independent apps separate.
18    pub fn new(service: impl Into<String>) -> Self {
19        Self {
20            service: service.into(),
21        }
22    }
23
24    fn entry(&self, account: &str) -> Result<keyring::v1::Entry, KeychainError> {
25        keyring::v1::Entry::new(&self.service, account).map_err(|_| KeychainError)
26    }
27
28    pub fn load(&self, account: &str) -> Result<Option<Secret>, KeychainError> {
29        optional(self.entry(account)?.get_password()).map(|value| value.map(Secret::new))
30    }
31
32    pub fn save(&self, account: &str, secret: &Secret) -> Result<(), KeychainError> {
33        self.entry(account)?
34            .set_password(secret.expose())
35            .map_err(|_| KeychainError)
36    }
37
38    /// Deletes the account's secret; a missing one is not an error.
39    pub fn delete(&self, account: &str) -> Result<(), KeychainError> {
40        optional(self.entry(account)?.delete_credential()).map(|_| ())
41    }
42}
43
44fn optional<T>(result: keyring::v1::Result<T>) -> Result<Option<T>, KeychainError> {
45    match result {
46        Ok(value) => Ok(Some(value)),
47        Err(keyring::v1::Error::NoEntry) => Ok(None),
48        Err(_) => Err(KeychainError),
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::{KeychainError, optional};
55
56    #[test]
57    fn store_errors_never_expose_provider_details() {
58        assert_eq!(optional::<()>(Err(keyring::v1::Error::NoEntry)), Ok(None));
59        assert_eq!(optional(Ok("fake")), Ok(Some("fake")));
60        assert!(!KeychainError.to_string().contains("fake"));
61    }
62}