Skip to main content

keyring_core/sample/
store.rs

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/// The stored data for a credential
21#[derive(Debug, Serialize, Deserialize)]
22pub struct CredValue {
23    /// The stored secret.
24    pub secret: Vec<u8>,
25    /// The comment attribute, if any.
26    pub comment: Option<String>,
27    /// The creation date attribute, if any, as an RFC 2822 date.
28    pub creation_date: Option<String>,
29}
30
31impl CredValue {
32    /// Create a stored credential with the given secret and no other attributes.
33    pub fn new(secret: &[u8]) -> Self {
34        CredValue {
35            secret: secret.to_vec(),
36            comment: None,
37            creation_date: None,
38        }
39    }
40
41    /// Create a stored credential with an empty secret, the given comment, and the current date.
42    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
51/// A map from <service, user> pairs to matching credentials
52pub type CredMap = DashMap<CredId, DashMap<String, CredValue>>;
53
54/// A Store's mutable weak reference to itself
55///
56/// Because credentials contain an `Arc` to their store,
57/// the store needs to keep a `Weak` to itself which can be
58/// upgraded to create the credential. Because
59/// the Store has to be created and an `Arc` of it taken
60/// before that `Arc` can be downgraded and stored inside
61/// the Store, the self-reference must be mutable.
62pub struct SelfRef {
63    inner_store: Weak<Store>,
64}
65
66/// A credential store.
67///
68/// The credential data is kept in the CredMap. We keep the index of
69/// ourself in the STORES vector, so we can get a pointer to ourself
70/// whenever we need to build a credential.
71pub struct Store {
72    /// The unique ID for this store instance.
73    pub id: String,
74    /// The credentials in this store.
75    pub creds: CredMap,
76    /// The path of the backing file, if any.
77    pub backing: Option<String>,
78    /// The store's mutable weak reference to itself.
79    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    /// Create a new store with a default configuration.
109    ///
110    /// The default configuration is empty with no backing file.
111    pub fn new() -> Result<Arc<Self>> {
112        Ok(Self::new_internal(DashMap::new(), None))
113    }
114
115    /// Create a new store with a user-specified configuration.
116    ///
117    /// There are two allowed configuration keys: `persist` and `backing-file`. See
118    /// the module docs for details of how these affect the store's behavior.
119    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    /// Create a new store from a backing file.
137    ///
138    /// The backing file must be a valid path, but it need not exist,
139    /// in which case the store starts off empty. If the file does
140    /// exist, the initial contents of the store are loaded from it.
141    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    /// Save the current state of this store to its backing file.
149    ///
150    /// This is a no-op if there is no backing file.
151    ///
152    /// Yes, stores will save themselves to their backing file
153    /// when they go out of scope (i.e., are dropped).
154    /// But using this entry to take a snapshot can save
155    /// you from crashes or let you pass the store state
156    /// off to another process.
157    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    /// Create a store with the given credentials and backing file.
169    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    /// Loads store content from a backing file.
192    ///
193    /// If the backing file does not exist, the returned store is empty.
194    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    /// See the API docs.
222    fn vendor(&self) -> String {
223        String::from("Sample store, https://crates.io/crates/keyring-core")
224    }
225
226    /// See the API docs.
227    ///
228    /// The store ID is based on its sequence number
229    /// in the list of created stores.
230    fn id(&self) -> String {
231        self.id.clone()
232    }
233
234    /// See the API docs.
235    ///
236    /// The only modifier you can specify is `force-create`, which forces
237    /// immediate credential creation and can be used to create ambiguity.
238    ///
239    /// When the force-create modifier is specified, the created credential gets
240    /// an empty password/secret, a `comment` attribute with the value of the modifier,
241    /// and a `creation_`date` attribute with a string for the current local time.
242    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    /// See the API docs.
277    ///
278    /// The specification must contain exactly two keys - `service` and `user` -
279    /// and their values must be valid regular expressions.
280    /// Every credential whose service name matches the service regex
281    /// _and_ whose username matches the user regex will be returned.
282    /// (The match is a substring match, so the empty string will match every value.)
283    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    //// See the API docs.
328    fn as_any(&self) -> &dyn Any {
329        self
330    }
331
332    //// See the API docs.
333    ////
334    //// If this store has a backing file, credential persistence is
335    //// `UntilDelete`. Otherwise, it's `ProcessOnly`.
336    fn persistence(&self) -> CredentialPersistence {
337        if self.backing.is_none() {
338            CredentialPersistence::ProcessOnly
339        } else {
340            CredentialPersistence::UntilDelete
341        }
342    }
343
344    /// See the API docs.
345    fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
346        std::fmt::Debug::fmt(self, f)
347    }
348}