Skip to main content

keyring_core/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2/*!
3
4# Keyring-core
5
6This crate provides a cross-platform library that supports storage and retrieval
7of passwords (or other secrets) in a variety of secure credential stores.
8Please see
9[this document](https://github.com/open-source-cooperative/keyring-rs/wiki/Keyring)
10for an introduction to the keyring ecosystem and
11[this document](https://github.com/open-source-cooperative/keyring-rs/wiki/Keyring-Core)
12for a comprehensive treatment of this crate's APIs.
13
14This crate provides two cross-platform credential stores. These
15are provided to support client testing and as a guide for developers who
16would like to build keyring-compatible credential store modules. The
17stores in this crate are explicitly _not_ warranted to be either secure or robust.
18See the [mock] and [sample] modules for details. (Note: the [sample]
19module is only built if the `sample` feature is specified.)
20
21## Thread Safety
22
23While this crate's code is thread-safe,
24and requires credential store objects
25to be both Send and Sync, the underlying credential
26stores may not handle access to a single credential
27from different threads reliably.
28See the documentation of each credential store for details.
29 */
30
31use log::debug;
32use std::collections::HashMap;
33use std::sync::Arc;
34
35pub mod api;
36pub mod attributes;
37pub mod error;
38
39pub mod mock;
40
41#[cfg(feature = "sample")]
42pub mod sample;
43
44#[cfg(test)]
45mod tests;
46
47pub use api::{Credential, CredentialPersistence, CredentialStore};
48pub use error::{Error, Result};
49
50#[derive(Default, Debug)]
51struct NamedStores {
52    inner: Option<HashMap<String, Arc<CredentialStore>>>,
53}
54
55static NAMED_STORES: std::sync::RwLock<NamedStores> =
56    std::sync::RwLock::new(NamedStores { inner: None });
57
58/// Set the credential store used by default to create entries.
59///
60/// This is meant for use by clients who use one credential store.
61/// If you are using multiple credential stores and want
62/// precise control over which credential is in which store,
63/// you may prefer to have your store build entries directly.
64///
65/// This will block waiting for all other threads currently creating entries
66/// to complete what they are doing. It's really meant to be called
67/// at startup before creating any entries.
68pub fn set_default_store(new: Arc<CredentialStore>) {
69    debug!("setting the default credential store to {new:?}");
70    let mut guard = NAMED_STORES
71        .write()
72        .expect("Poisoned RwLock in keyring_core::set_default_store: please report a bug!");
73    guard
74        .inner
75        .get_or_insert_with(HashMap::new)
76        .insert("default".to_string(), new);
77}
78
79/// Get the default credential store.
80pub fn get_default_store() -> Option<Arc<CredentialStore>> {
81    debug!("getting the default credential store");
82    let guard = NAMED_STORES
83        .read()
84        .expect("Poisoned RwLock in keyring_core::get_default_store: please report a bug!");
85    guard
86        .inner
87        .as_ref()
88        .and_then(|map| map.get("default"))
89        .cloned()
90}
91
92/// Add or update a named credential store.
93///
94/// Returns any store that had previously been associated with `name`.
95///
96/// # Errors
97///
98/// Returns an [Invalid][Error::Invalid] error if `name` is `"default"`.
99pub fn add_named_store(
100    name: &str,
101    store: Arc<CredentialStore>,
102) -> Result<Option<Arc<CredentialStore>>> {
103    if name == "default" {
104        return Err(Error::Invalid(
105            "name".to_string(),
106            "cannot be 'default'".to_string(),
107        ));
108    }
109    debug!("adding named store {name} with {store:?}");
110    let mut guard = NAMED_STORES
111        .write()
112        .expect("Poisoned RwLock in keyring_core::add_named_store: please report a bug!");
113    Ok(guard
114        .inner
115        .get_or_insert_with(HashMap::new)
116        .insert(name.to_string(), store))
117}
118
119/// Drop a named credential store.
120///
121/// Returns any store that had previously been associated with `name`.
122///
123/// # Errors
124///
125/// Returns an [Invalid][Error::Invalid] error if `name` is `"default"`.
126pub fn drop_named_store(name: &str) -> Result<Option<Arc<CredentialStore>>> {
127    if name == "default" {
128        return Err(Error::Invalid(
129            "name".to_string(),
130            "cannot be 'default'".to_string(),
131        ));
132    }
133    debug!("dropping named store {name}");
134    let mut guard = NAMED_STORES
135        .write()
136        .expect("Poisoned RwLock in keyring_core::drop_named_store: please report a bug!");
137    Ok(guard.inner.as_mut().and_then(|map| map.remove(name)))
138}
139
140/// Get a named credential store.
141///
142/// Returns the store associated with `name`, if any.
143///
144/// # Errors
145///
146/// Returns an [Invalid][Error::Invalid] error if `name` is `"default"`.
147pub fn get_named_store(name: &str) -> Result<Option<Arc<CredentialStore>>> {
148    if name == "default" {
149        return Err(Error::Invalid(
150            "name".to_string(),
151            "cannot be 'default'".to_string(),
152        ));
153    }
154    debug!("getting named store {name}");
155    let guard = NAMED_STORES
156        .read()
157        .expect("Poisoned RwLock in keyring_core::get_named_store: please report a bug!");
158    Ok(guard.inner.as_ref().and_then(|map| map.get(name)).cloned())
159}
160
161/// Release the default credential store.
162///
163/// This returns the old value for the default credential store
164/// and forgets what it was. Since the default credential store
165/// is kept in a static variable, not releasing it will cause
166/// your credential store never to be released, which may have
167/// unintended side effects.
168pub fn unset_default_store() -> Option<Arc<CredentialStore>> {
169    debug!("unsetting the default credential store");
170    let mut guard = NAMED_STORES
171        .write()
172        .expect("Poisoned RwLock in keyring_core::unset_default_store: please report a bug!");
173    guard.inner.as_mut().and_then(|map| map.remove("default"))
174}
175
176fn build_default_credential(
177    service: &str,
178    user: &str,
179    attrs: Option<&HashMap<&str, &str>>,
180) -> Result<Entry> {
181    let guard = NAMED_STORES
182        .read()
183        .expect("Poisoned RwLock in keyring-core::build_default_credential: please report a bug!");
184    match guard.inner.as_ref().and_then(|map| map.get("default")) {
185        Some(store) => store.build(service, user, attrs),
186        None => Err(Error::NoDefaultStore),
187    }
188}
189
190/// A named entry in a credential store.
191#[derive(Debug)]
192pub struct Entry {
193    inner: Arc<Credential>,
194}
195
196impl Entry {
197    /// Create an entry for the given `service` and `user`.
198    ///
199    /// The default credential builder is used.
200    ///
201    /// # Errors
202    ///
203    /// Returns an [Invalid][Error::Invalid] error
204    /// if the `service` or `user` values are not
205    /// acceptable to the default credential store.
206    ///
207    /// Returns a [NoDefaultStore][Error::NoDefaultStore] error
208    /// if the default credential store has not been set.
209    pub fn new(service: &str, user: &str) -> Result<Entry> {
210        debug!("creating entry with service {service}, user {user}");
211        let entry = build_default_credential(service, user, None)?;
212        debug!("created entry {:?}", entry.inner);
213        Ok(entry)
214    }
215
216    /// Create an entry for the given `service` and `user` in the given `store`.
217    ///
218    /// # Errors
219    ///
220    /// Returns an [Invalid][Error::Invalid] error
221    /// if the `service` or `user` values are not
222    /// acceptable to the credential store.
223    pub fn new_in_store(store: &Arc<CredentialStore>, service: &str, user: &str) -> Result<Entry> {
224        debug!("creating entry with service {service}, user {user} in store {store:?}");
225        let entry = store.build(service, user, None)?;
226        debug!("created entry {:?}", entry.inner);
227        Ok(entry)
228    }
229
230    /// Create an entry for the given `service` and `user` in the named store.
231    ///
232    /// # Errors
233    ///
234    /// Returns an [Invalid][Error::Invalid] error if `name` is `"default"`, if no store
235    /// with that name exists, or if the `service` or `user` values are not acceptable to
236    /// the named store.
237    pub fn new_in_named_store(name: &str, service: &str, user: &str) -> Result<Entry> {
238        debug!("creating entry with service {service}, user {user} in named store {name}");
239        match get_named_store(name)? {
240            Some(store) => Self::new_in_store(&store, service, user),
241            None => Err(Error::Invalid(
242                "name".to_string(),
243                "no such store".to_string(),
244            )),
245        }
246    }
247
248    /// Create an entry for the given `service` and `user`, passing store-specific
249    /// modifiers.
250    ///
251    /// The default credential builder is used.
252    ///
253    /// See the documentation for each credential store to understand what
254    /// modifiers may be specified for that store.
255    ///
256    /// # Errors
257    ///
258    /// Returns an [Invalid][Error::Invalid] error
259    /// if the `service`, `user`, or `modifier` pairs are not
260    /// acceptable to the default credential store.
261    ///
262    /// Returns a [NoDefaultStore][Error::NoDefaultStore] error
263    /// if the default credential store has not been set.
264    pub fn new_with_modifiers(
265        service: &str,
266        user: &str,
267        modifiers: &HashMap<&str, &str>,
268    ) -> Result<Entry> {
269        debug!("creating entry with service {service}, user {user}, and mods {modifiers:?}");
270        let entry = build_default_credential(service, user, Some(modifiers))?;
271        debug!("created entry {:?}", entry.inner);
272        Ok(entry)
273    }
274
275    /// Create an entry for the given `service` and `user`, passing store-specific
276    /// modifiers, in the given `store`.
277    ///
278    /// See the documentation for each credential store to understand what
279    /// modifiers may be specified for that store.
280    ///
281    /// # Errors
282    ///
283    /// Returns an [Invalid][Error::Invalid] error
284    /// if the `service`, `user`, or `modifier` pairs are not
285    /// acceptable to the given credential store.
286    pub fn new_in_store_with_modifiers(
287        store: &Arc<CredentialStore>,
288        service: &str,
289        user: &str,
290        modifiers: &HashMap<&str, &str>,
291    ) -> Result<Entry> {
292        debug!(
293            "creating entry with service {service}, user {user}, and mods {modifiers:?} in store {store:?}"
294        );
295        let entry = store.build(service, user, Some(modifiers))?;
296        debug!("created entry {:?}", entry.inner);
297        Ok(entry)
298    }
299
300    /// Create an entry for the given `service` and `user`, passing store-specific
301    /// modifiers, in the named store.
302    ///
303    /// See the documentation for each credential store to understand what
304    /// modifiers may be specified for that store.
305    ///
306    /// # Errors
307    ///
308    /// Returns an [Invalid][Error::Invalid] error if `name` is `"default"`, if no store
309    /// with that name exists, or if the `service`, `user`, or `modifier` pairs are not
310    /// acceptable to the named store.
311    pub fn new_in_named_store_with_modifiers(
312        name: &str,
313        service: &str,
314        user: &str,
315        modifiers: &HashMap<&str, &str>,
316    ) -> Result<Entry> {
317        match get_named_store(name)? {
318            Some(store) => Self::new_in_store_with_modifiers(&store, service, user, modifiers),
319            None => Err(Error::Invalid(
320                "name".to_string(),
321                "no such store".to_string(),
322            )),
323        }
324    }
325
326    /// Create an entry that wraps a pre-existing credential. The credential can
327    /// be from any credential store.
328    pub fn new_with_credential(credential: Arc<Credential>) -> Entry {
329        debug!("create entry wrapping {credential:?}");
330        Entry { inner: credential }
331    }
332
333    /// Search for credentials, returning entries that wrap any found.
334    ///
335    /// The default credential store is searched.
336    /// See the documentation of each credential store for how searches are specified.
337    ///
338    /// # Errors
339    ///
340    /// Returns an [Invalid][Error::Invalid] error
341    /// if the `spec` value is not acceptable to the default credential store.
342    ///
343    /// Returns a [NoDefaultStore][Error::NoDefaultStore] error
344    /// if the default credential store has not been set.
345    pub fn search(spec: &HashMap<&str, &str>) -> Result<Vec<Entry>> {
346        debug!("searching for {spec:?}");
347        let guard = NAMED_STORES.read().expect(
348            "Poisoned RwLock in keyring-core::search_for_credentials: please report a bug!",
349        );
350        match guard.inner.as_ref().and_then(|map| map.get("default")) {
351            Some(store) => store.search(spec),
352            None => Err(Error::NoDefaultStore),
353        }
354    }
355
356    /// Search the given store for credentials, returning entries that wrap any found.
357    ///
358    /// See the documentation of each credential store for how searches are specified.
359    ///
360    /// # Errors
361    ///
362    /// Returns an [Invalid][Error::Invalid] error if the `spec` value is not acceptable
363    /// to the given credential store.
364    pub fn search_in_store(
365        store: &Arc<CredentialStore>,
366        spec: &HashMap<&str, &str>,
367    ) -> Result<Vec<Entry>> {
368        debug!("searching for {spec:?} in store {store:?}");
369        store.search(spec)
370    }
371
372    /// Search the named store for credentials, returning entries that wrap any found.
373    ///
374    /// See the documentation of each credential store for how searches are specified.
375    ///
376    /// # Errors
377    ///
378    /// Returns an [Invalid][Error::Invalid] error if `name` is `"default"`, if no store
379    /// with that name exists, or if the `spec` value is not acceptable to the named
380    /// store.
381    pub fn search_in_named_store(name: &str, spec: &HashMap<&str, &str>) -> Result<Vec<Entry>> {
382        match get_named_store(name)? {
383            Some(store) => store.search(spec),
384            None => Err(Error::Invalid(
385                "name".to_string(),
386                "no such store".to_string(),
387            )),
388        }
389    }
390
391    /// Set the password for this entry.
392    ///
393    /// If a credential for this entry already exists in the store,
394    /// this will update its password. Otherwise, a new credential
395    /// will be created to store the password.
396    ///
397    /// # Errors
398    ///
399    /// If this entry is a specifier,
400    /// and there is more than one matching credential in the store,
401    /// returns an [Ambiguous](Error::Ambiguous) error.
402    ///
403    /// If this entry is a wrapper, and the
404    /// underlying credential has been deleted,
405    /// may return a [NoEntry](Error::NoEntry) error.
406    ///
407    /// If a credential cannot store the given password (not
408    /// all stores support empty passwords, and some have length limits),
409    /// then an [Invalid](Error::Invalid) error is returned.
410    pub fn set_password(&self, password: &str) -> Result<()> {
411        debug!("set password for entry {:?}", self.inner);
412        self.inner.set_password(password)
413    }
414
415    /// Set the secret for this entry.
416    ///
417    /// If a credential for this entry already exists in the store,
418    /// this will update its secret. Otherwise, a new credential
419    /// will be created to store the secret.
420    ///
421    /// # Errors
422    ///
423    /// If this entry is a specifier,
424    /// and there is more than one matching credential in the store,
425    /// returns an [Ambiguous](Error::Ambiguous) error.
426    ///
427    /// If this entry is a wrapper, and the
428    /// underlying credential has been deleted,
429    /// may return a [NoEntry](Error::NoEntry) error.
430    ///
431    /// If a credential cannot store the given password (not
432    /// all stores support empty passwords, and some have length limits),
433    /// then an [Invalid](Error::Invalid) error is returned.
434    pub fn set_secret(&self, secret: &[u8]) -> Result<()> {
435        debug!("set secret for entry {:?}", self.inner);
436        self.inner.set_secret(secret)
437    }
438
439    /// Retrieve the password saved for this entry.
440    ///
441    /// # Errors
442    ///
443    /// If this entry is a specifier,
444    /// and there is no matching credential in the store,
445    /// returns a [NoEntry](Error::NoEntry) error.
446    ///
447    /// If this entry is a specifier,
448    /// and there is more than one matching credential in the store,
449    /// returns an [Ambiguous](Error::Ambiguous) error.
450    ///
451    /// If this entry is a wrapper,
452    /// the underlying credential has been deleted,
453    /// and the store cannot recreate it,
454    /// returns a [NoEntry](Error::NoEntry) error.
455    ///
456    /// Will return a [BadEncoding](Error::BadEncoding) error
457    /// containing the data as a byte array if the password is
458    /// not a valid UTF-8 string.
459    pub fn get_password(&self) -> Result<String> {
460        debug!("get password from entry {:?}", self.inner);
461        self.inner.get_password()
462    }
463
464    /// Retrieve the secret saved for this entry.
465    ///
466    /// # Errors
467    ///
468    /// If this entry is a specifier,
469    /// and there is no matching credential in the store,
470    /// returns a [NoEntry](Error::NoEntry) error.
471    ///
472    /// If this entry is a specifier,
473    /// and there is more than one matching credential in the store,
474    /// returns an [Ambiguous](Error::Ambiguous) error.
475    ///
476    /// If this entry is a wrapper,
477    /// and the underlying credential has been deleted,
478    /// returns a [NoEntry](Error::NoEntry) error.
479    pub fn get_secret(&self) -> Result<Vec<u8>> {
480        debug!("get secret from entry {:?}", self.inner);
481        self.inner.get_secret()
482    }
483
484    /// Get the store-specific decorations on this entry's credential.
485    ///
486    /// See the documentation for each credential store
487    /// for details of what decorations are supported
488    /// and how they are returned.
489    ///
490    /// # Errors
491    ///
492    /// If this entry is a specifier,
493    /// and there is no matching credential in the store,
494    /// returns a [NoEntry](Error::NoEntry) error.
495    ///
496    /// If this entry is a specifier,
497    /// and there is more than one matching credential in the store,
498    /// returns an [Ambiguous](Error::Ambiguous) error.
499    ///
500    /// If this entry is a wrapper,
501    /// and the underlying credential has been deleted,
502    /// returns a [NoEntry](Error::NoEntry) error.
503    pub fn get_attributes(&self) -> Result<HashMap<String, String>> {
504        debug!("get attributes from entry {:?}", self.inner);
505        self.inner.get_attributes()
506    }
507
508    /// Update the store-specific decorations on this entry's credential.
509    ///
510    /// See the documentation for each credential store
511    /// for details of what decorations can be updated
512    /// and how updates are expressed.
513    ///
514    /// # Errors
515    ///
516    /// If one of the attributes supplied is not valid for the underlying store,
517    /// returns an [Invalid](Error::Invalid) error.
518    ///
519    /// If this entry is a specifier,
520    /// and there is no matching credential in the store,
521    /// returns a [NoEntry](Error::NoEntry) error.
522    ///
523    /// If this entry is a specifier,
524    /// and there is more than one matching credential in the store,
525    /// returns an [Ambiguous](Error::Ambiguous) error.
526    ///
527    /// If this entry is a wrapper,
528    /// and the underlying credential has been deleted,
529    /// returns a [NoEntry](Error::NoEntry) error.
530    pub fn update_attributes(&self, attributes: &HashMap<&str, &str>) -> Result<()> {
531        debug!(
532            "update attributes for entry {:?} from map {attributes:?}",
533            self.inner
534        );
535        self.inner.update_attributes(attributes)
536    }
537
538    /// Delete the matching credential for this entry.
539    ///
540    /// This call does _not_ affect the lifetime of the [Entry]
541    /// structure, only that of the underlying credential.
542    ///
543    /// # Errors
544    ///
545    /// If this entry is a specifier,
546    /// and there is no matching credential in the store,
547    /// returns a [NoEntry](Error::NoEntry) error.
548    ///
549    /// If this entry is a specifier,
550    /// and there is more than one matching credential in the store,
551    /// returns an [Ambiguous](Error::Ambiguous) error.
552    ///
553    /// If this entry is a wrapper,
554    /// and the underlying credential has been deleted,
555    /// returns a [NoEntry](Error::NoEntry) error.
556    pub fn delete_credential(&self) -> Result<()> {
557        debug!("delete entry {:?}", self.inner);
558        self.inner.delete_credential()
559    }
560
561    /// Get a wrapper for the currently matching credential.
562    ///
563    /// # Errors
564    ///
565    /// If this entry is a specifier,
566    /// and there is no matching credential in the store,
567    /// returns a [NoEntry](Error::NoEntry) error.
568    ///
569    /// If this entry is a specifier,
570    /// and there is more than one matching credential in the store,
571    /// returns an [Ambiguous](Error::Ambiguous) error.
572    ///
573    /// If this entry is a wrapper,
574    /// and the underlying credential has been deleted,
575    /// returns a [NoEntry](Error::NoEntry) error.
576    pub fn get_credential(&self) -> Result<Entry> {
577        debug!("get credential for entry {:?}", self.inner);
578        match self.inner.get_credential() {
579            Ok(Some(inner)) => Ok(Entry { inner }),
580            Ok(None) => Ok(Entry {
581                inner: self.inner.clone(),
582            }),
583            Err(e) => Err(e),
584        }
585    }
586
587    /// Get the `<service, user>` pair for this entry, if any.
588    pub fn get_specifiers(&self) -> Option<(String, String)> {
589        self.inner.get_specifiers()
590    }
591
592    /// Return a reference to the inner store-specific object in this entry.
593    ///
594    /// The reference is of the [Any](std::any::Any) type, so it can be
595    /// downgraded to a concrete object for the containing store.
596    pub fn as_any(&self) -> &dyn std::any::Any {
597        self.inner.as_any()
598    }
599}
600
601#[cfg(doctest)]
602doc_comment::doctest!("../README.md", readme);