1use std::any::Any;
2use std::collections::HashMap;
3use std::sync::{Arc, RwLock, Weak};
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use dashmap::DashMap;
7use log::{debug, error};
8use serde::{Deserialize, Serialize};
9use uuid::Uuid;
10
11use super::credential::{CredId, CredKey};
12use crate::{
13 Entry,
14 Error::{Invalid, PlatformFailure},
15 Result,
16 api::{CredentialPersistence, CredentialStoreApi},
17 attributes::parse_attributes,
18};
19
20#[derive(Debug, Serialize, Deserialize)]
22pub struct CredValue {
23 pub secret: Vec<u8>,
25 pub comment: Option<String>,
27 pub creation_date: Option<String>,
29}
30
31impl CredValue {
32 pub fn new(secret: &[u8]) -> Self {
34 CredValue {
35 secret: secret.to_vec(),
36 comment: None,
37 creation_date: None,
38 }
39 }
40
41 pub fn new_ambiguous(comment: &str) -> CredValue {
43 CredValue {
44 secret: vec![],
45 comment: Some(comment.to_string()),
46 creation_date: Some(chrono::Local::now().to_rfc2822()),
47 }
48 }
49}
50
51pub type CredMap = DashMap<CredId, DashMap<String, CredValue>>;
53
54pub struct SelfRef {
63 inner_store: Weak<Store>,
64}
65
66pub struct Store {
72 pub id: String,
74 pub creds: CredMap,
76 pub backing: Option<String>,
78 pub self_ref: RwLock<SelfRef>,
80}
81
82impl std::fmt::Debug for Store {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 f.debug_struct("Store")
85 .field("vendor", &self.vendor())
86 .field("id", &self.id)
87 .field("backing", &self.backing)
88 .field("cred-count", &self.creds.len())
89 .finish()
90 }
91}
92
93impl Drop for Store {
94 fn drop(&mut self) {
95 if self.backing.is_none() {
96 debug!("dropping store {self:?}")
97 } else {
98 debug!("Saving store {self:?} on drop...");
99 match self.save() {
100 Ok(_) => debug!("Save of store {self:?} completed"),
101 Err(e) => error!("Save of store {self:?} failed: {e:?}"),
102 }
103 }
104 }
105}
106
107impl Store {
108 pub fn new() -> Result<Arc<Self>> {
112 Ok(Self::new_internal(DashMap::new(), None))
113 }
114
115 pub fn new_with_configuration(config: &HashMap<&str, &str>) -> Result<Arc<Self>> {
120 let mods = parse_attributes(&["backing-file", "*persist"], Some(config))?;
121 if let Some(path) = mods.get("backing-file") {
122 Self::new_with_backing(path)
123 } else if let Some(persist) = mods.get("persist") {
124 if persist == "true" {
125 let dir = std::env::temp_dir();
126 let path = dir.join("keyring-sample-store.ron");
127 Self::new_with_backing(path.to_str().expect("Invalid backing path"))
128 } else {
129 Self::new()
130 }
131 } else {
132 Self::new()
133 }
134 }
135
136 pub fn new_with_backing(path: &str) -> Result<Arc<Self>> {
142 Ok(Self::new_internal(
143 Self::load_credentials(path)?,
144 Some(String::from(path)),
145 ))
146 }
147
148 pub fn save(&self) -> Result<()> {
158 if self.backing.is_none() {
159 return Ok(());
160 };
161 let content = ron::ser::to_string_pretty(&self.creds, ron::ser::PrettyConfig::new())
162 .map_err(|e| PlatformFailure(Box::from(e)))?;
163 std::fs::write(self.backing.as_ref().unwrap(), content)
164 .map_err(|e| PlatformFailure(Box::from(e)))?;
165 Ok(())
166 }
167
168 pub fn new_internal(creds: CredMap, backing: Option<String>) -> Arc<Self> {
170 let store = Store {
171 id: format!(
172 "Crate version {}, Instantiated at {}",
173 env!("CARGO_PKG_VERSION"),
174 SystemTime::now()
175 .duration_since(UNIX_EPOCH)
176 .unwrap_or_else(|_| Duration::new(0, 0))
177 .as_secs_f64()
178 ),
179 creds,
180 backing,
181 self_ref: RwLock::new(SelfRef {
182 inner_store: Weak::new(),
183 }),
184 };
185 debug!("Created new store: {store:?}");
186 let result = Arc::new(store);
187 result.set_store(result.clone());
188 result
189 }
190
191 pub fn load_credentials(path: &str) -> Result<CredMap> {
195 match std::fs::exists(path) {
196 Ok(true) => match std::fs::read_to_string(path) {
197 Ok(s) => Ok(ron::de::from_str(&s).map_err(|e| PlatformFailure(Box::from(e)))?),
198 Err(e) => Err(PlatformFailure(Box::from(e))),
199 },
200 Ok(false) => Ok(DashMap::new()),
201 Err(e) => Err(Invalid("Invalid path".to_string(), e.to_string())),
202 }
203 }
204
205 fn get_store(&self) -> Arc<Store> {
206 self.self_ref
207 .read()
208 .expect("RwLock bug at get!")
209 .inner_store
210 .upgrade()
211 .expect("Arc bug at get!")
212 }
213
214 fn set_store(&self, store: Arc<Store>) {
215 let mut guard = self.self_ref.write().expect("RwLock bug at set!");
216 guard.inner_store = Arc::downgrade(&store);
217 }
218}
219
220impl CredentialStoreApi for Store {
221 fn vendor(&self) -> String {
223 String::from("Sample store, https://crates.io/crates/keyring-core")
224 }
225
226 fn id(&self) -> String {
231 self.id.clone()
232 }
233
234 fn build(
243 &self,
244 service: &str,
245 user: &str,
246 mods: Option<&HashMap<&str, &str>>,
247 ) -> Result<Entry> {
248 let id = CredId {
249 service: service.to_owned(),
250 user: user.to_owned(),
251 };
252 let key = CredKey {
253 store: self.get_store(),
254 id: id.clone(),
255 uuid: None,
256 };
257 if let Some(force_create) = parse_attributes(&["force-create"], mods)?.get("force-create") {
258 let uuid = Uuid::new_v4().to_string();
259 let value = CredValue::new_ambiguous(force_create);
260 match self.creds.get(&id) {
261 None => {
262 let creds = DashMap::new();
263 creds.insert(uuid, value);
264 self.creds.insert(id, creds);
265 }
266 Some(creds) => {
267 creds.value().insert(uuid, value);
268 }
269 };
270 }
271 Ok(Entry {
272 inner: Arc::new(key),
273 })
274 }
275
276 fn search(&self, spec: &HashMap<&str, &str>) -> Result<Vec<Entry>> {
284 let spec = parse_attributes(&["service", "user", "uuid", "comment"], Some(spec))?;
285 let mut result: Vec<Entry> = Vec::new();
286 let empty = String::new();
287 let svc = regex::Regex::new(spec.get("service").unwrap_or(&empty))
288 .map_err(|e| Invalid("service regex".to_string(), e.to_string()))?;
289 let usr = regex::Regex::new(spec.get("user").unwrap_or(&empty))
290 .map_err(|e| Invalid("user regex".to_string(), e.to_string()))?;
291 let comment = regex::Regex::new(spec.get("comment").unwrap_or(&empty))
292 .map_err(|e| Invalid("comment regex".to_string(), e.to_string()))?;
293 let uuid = regex::Regex::new(spec.get("uuid").unwrap_or(&empty))
294 .map_err(|e| Invalid("uuid regex".to_string(), e.to_string()))?;
295 let store = self.get_store();
296 for pair in self.creds.iter() {
297 if !svc.is_match(pair.key().service.as_str()) {
298 continue;
299 }
300 if !usr.is_match(pair.key().user.as_str()) {
301 continue;
302 }
303 for cred in pair.value().iter() {
304 if !uuid.is_match(cred.key()) {
305 continue;
306 }
307 if spec.contains_key("comment") {
308 if cred.value().comment.is_none() {
309 continue;
310 }
311 if !comment.is_match(cred.value().comment.as_ref().unwrap()) {
312 continue;
313 }
314 }
315 result.push(Entry {
316 inner: Arc::new(CredKey {
317 store: store.clone(),
318 id: pair.key().clone(),
319 uuid: Some(cred.key().clone()),
320 }),
321 })
322 }
323 }
324 Ok(result)
325 }
326
327 fn as_any(&self) -> &dyn Any {
329 self
330 }
331
332 fn persistence(&self) -> CredentialPersistence {
337 if self.backing.is_none() {
338 CredentialPersistence::ProcessOnly
339 } else {
340 CredentialPersistence::UntilDelete
341 }
342 }
343
344 fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346 std::fmt::Debug::fmt(self, f)
347 }
348}