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//!
5//! One Windows credential holds at most 1,280 UTF-16 code units, so on Windows
6//! a longer secret is split across several credentials (the private `split`
7//! module describes how). A secret that fits is still one credential under
8//! the account's name, as earlier builds wrote it. The other stores have no
9//! such limit and keep every secret as one item, unchanged.
10
11mod split;
12
13use std::collections::HashMap;
14use std::sync::{Mutex, MutexGuard};
15
16use zeroize::Zeroizing;
17
18use crate::Secret;
19use crate::vault::lock;
20use split::Limits;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
23#[error("The credential store is unavailable. Unlock your system keychain and try again.")]
24pub struct KeychainError;
25
26/// Where one stored item holds too little for a long secret, how much it holds.
27const LIMITS: Option<Limits> = if cfg!(windows) {
28    Some(Limits::WINDOWS)
29} else {
30    None
31};
32
33/// Serialises split loads, saves and deletes in this process, so a load
34/// never reads a manifest whose chunks a save is deleting.
35static SPLIT: Mutex<()> = Mutex::new(());
36
37/// The secrets of one service name, one per account.
38pub struct Keychain {
39    service: String,
40}
41
42impl Keychain {
43    /// Use a stable product/channel namespace to keep independent apps separate.
44    pub fn new(service: impl Into<String>) -> Self {
45        Self {
46            service: service.into(),
47        }
48    }
49
50    pub fn load(&self, account: &str) -> Result<Option<Secret>, KeychainError> {
51        let _split = serialise();
52        split::load(&System(&self.service), LIMITS, account).map(|value| value.map(Secret::new))
53    }
54
55    pub fn save(&self, account: &str, secret: &Secret) -> Result<(), KeychainError> {
56        let _split = serialise();
57        split::save(&System(&self.service), LIMITS, account, secret.expose())
58    }
59
60    /// Deletes the account's secret; a missing one is not an error.
61    pub fn delete(&self, account: &str) -> Result<(), KeychainError> {
62        let _split = serialise();
63        split::delete(&System(&self.service), LIMITS, account)
64    }
65}
66
67/// The split lock, where secrets are split.
68fn serialise() -> Option<MutexGuard<'static, ()>> {
69    LIMITS.map(|_| lock(&SPLIT))
70}
71
72/// What one stored item holds: text, as [`Store::set_text`] writes it, or
73/// bytes that are not text, as only [`Store::set_bytes`] writes them.
74enum Item {
75    Text(String),
76    Bytes(Zeroizing<Vec<u8>>),
77}
78
79/// One stored item per account name, under one service.
80trait Store {
81    fn service(&self) -> &str;
82    fn get(&self, account: &str) -> Result<Option<Item>, KeychainError>;
83    fn set_text(&self, account: &str, value: &str) -> Result<(), KeychainError>;
84    fn set_bytes(&self, account: &str, value: &[u8]) -> Result<(), KeychainError>;
85    /// Deletes the account's item; a missing one is not an error.
86    fn delete(&self, account: &str) -> Result<(), KeychainError>;
87    /// The target names, `<account>.<service>` as the store holds them, of
88    /// every item whose target name matches the regular expression `pattern`.
89    fn find(&self, pattern: &str) -> Result<Vec<String>, KeychainError>;
90}
91
92/// The system credential store, under one service name.
93struct System<'a>(&'a str);
94
95impl Store for System<'_> {
96    fn service(&self) -> &str {
97        self.0
98    }
99
100    fn get(&self, account: &str) -> Result<Option<Item>, KeychainError> {
101        item(entry(self.0, account)?.get_password())
102    }
103
104    fn set_text(&self, account: &str, value: &str) -> Result<(), KeychainError> {
105        entry(self.0, account)?
106            .set_password(value)
107            .map_err(|_| KeychainError)
108    }
109
110    fn set_bytes(&self, account: &str, value: &[u8]) -> Result<(), KeychainError> {
111        entry(self.0, account)?
112            .set_secret(value)
113            .map_err(|_| KeychainError)
114    }
115
116    fn delete(&self, account: &str) -> Result<(), KeychainError> {
117        optional(entry(self.0, account)?.delete_credential()).map(|_| ())
118    }
119
120    /// Windows Credential Manager only, the one store whose secrets are
121    /// split: its search matches `pattern` against every target name. A found
122    /// credential whose name cannot be read is left out.
123    fn find(&self, pattern: &str) -> Result<Vec<String>, KeychainError> {
124        keyring::v1::Entry::store_status()
125            .as_ref()
126            .map_err(|_| KeychainError)?;
127        let found = keyring_core::Entry::search(&HashMap::from([("pattern", pattern)]))
128            .map_err(|_| KeychainError)?;
129        Ok(found
130            .iter()
131            .filter_map(|entry| target_of(entry.get_attributes()))
132            .collect())
133    }
134}
135
136fn entry(service: &str, account: &str) -> Result<keyring::v1::Entry, KeychainError> {
137    keyring::v1::Entry::new(service, account).map_err(|_| KeychainError)
138}
139
140/// A read item: text, or bytes the store could not read as text.
141fn item(result: keyring::v1::Result<String>) -> Result<Option<Item>, KeychainError> {
142    match result {
143        Ok(text) => Ok(Some(Item::Text(text))),
144        Err(keyring::v1::Error::BadEncoding(bytes)) => Ok(Some(Item::Bytes(Zeroizing::new(bytes)))),
145        Err(keyring::v1::Error::NoEntry) => Ok(None),
146        Err(_) => Err(KeychainError),
147    }
148}
149
150fn optional<T>(result: keyring::v1::Result<T>) -> Result<Option<T>, KeychainError> {
151    match result {
152        Ok(value) => Ok(Some(value)),
153        Err(keyring::v1::Error::NoEntry) => Ok(None),
154        Err(_) => Err(KeychainError),
155    }
156}
157
158/// A found credential's target name, unless it cannot be read.
159fn target_of(attributes: keyring::v1::Result<HashMap<String, String>>) -> Option<String> {
160    attributes.ok()?.remove("target_name")
161}
162
163#[cfg(test)]
164mod tests;