subspace_core/
keychain.rs1mod 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
26const LIMITS: Option<Limits> = if cfg!(windows) {
28 Some(Limits::WINDOWS)
29} else {
30 None
31};
32
33static SPLIT: Mutex<()> = Mutex::new(());
36
37pub struct Keychain {
39 service: String,
40}
41
42impl Keychain {
43 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 pub fn delete(&self, account: &str) -> Result<(), KeychainError> {
62 let _split = serialise();
63 split::delete(&System(&self.service), LIMITS, account)
64 }
65}
66
67fn serialise() -> Option<MutexGuard<'static, ()>> {
69 LIMITS.map(|_| lock(&SPLIT))
70}
71
72enum Item {
75 Text(String),
76 Bytes(Zeroizing<Vec<u8>>),
77}
78
79trait 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 fn delete(&self, account: &str) -> Result<(), KeychainError>;
87 fn find(&self, pattern: &str) -> Result<Vec<String>, KeychainError>;
90}
91
92struct 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 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
140fn 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
158fn target_of(attributes: keyring::v1::Result<HashMap<String, String>>) -> Option<String> {
160 attributes.ok()?.remove("target_name")
161}
162
163#[cfg(test)]
164mod tests;