Skip to main content

keyring_core/
mock.rs

1/*!
2
3# Mock credential store
4
5To facilitate testing of clients, this crate provides a Mock credential store
6that is platform-independent, provides no persistence, and allows the client
7to specify the return values (including errors) for each call. The credentials
8in this store have no attributes at all.
9
10To use this credential store instead of the default, make this call during
11application startup _before_ creating any entries:
12```rust
13keyring_core::set_default_store(keyring_core::mock::Store::new().unwrap());
14```
15
16You can then create entries as usual and call their usual methods
17to set, get, and delete passwords. There is no persistence except in-memory
18so, once you drop the store, all the credentials will be gone.
19
20If you want a method call on an entry to fail in a specific way, you can
21downcast the entry to a [Cred] and then call [set_error](Cred::set_error)
22with the appropriate error.  The next entry method called on the credential
23will fail with the error you set.  The error will then be cleared, so the next
24call on the mock will operate as usual.  Setting an error will not affect
25the value of the credential (if any). Here's a complete example:
26
27```rust
28# use keyring_core::{Entry, Error, mock};
29keyring_core::set_default_store(mock::Store::new().unwrap());
30let entry = Entry::new("service", "user").unwrap();
31entry.set_password("test").expect("the entry's password is now test");
32let mock: &mock::Cred = entry.as_any().downcast_ref().unwrap();
33mock.set_error(Error::Invalid("mock error".to_string(), "takes precedence".to_string()));
34_ = entry.get_password().expect_err("the error will be returned");
35let val = entry.get_password().expect("the error has been cleared");
36assert_eq!(val, "test", "the error did not affect the password");
37```
38
39 */
40use std::cell::RefCell;
41use std::collections::HashMap;
42use std::sync::{Arc, Mutex};
43use std::time::{Duration, SystemTime, UNIX_EPOCH};
44
45use crate::api::{CredentialApi, CredentialStoreApi};
46use crate::{Credential, CredentialPersistence, Entry, Error, Result};
47
48/// The concrete mock credential
49///
50/// Mocks use an internal mutability pattern since entries are read-only.
51/// The mutex is used to make sure these are Sync.
52#[derive(Debug)]
53pub struct Cred {
54    /// The service name and username that identify this credential.
55    pub specifiers: (String, String),
56    /// The credential's data.
57    pub inner: Mutex<RefCell<CredData>>,
58}
59
60/// The (in-memory) persisted data for a mock credential.
61///
62/// We keep a password but, unlike most credentials stores,
63/// we also keep an intended error to return on the next call.
64///
65/// (Everything about this structure is public for transparency.
66/// Most credential store implementations hide their internals.)
67#[derive(Debug, Default)]
68pub struct CredData {
69    /// The stored secret, or `None` if the credential has none.
70    pub secret: Option<Vec<u8>>,
71    /// The error the next operation on this credential returns, if any.
72    pub error: Option<Error>,
73}
74
75impl CredentialApi for Cred {
76    /// See the API docs.
77    ///
78    /// If there is an error in the mock, it will be returned
79    /// and the secret will _not_ be set.  The error will
80    /// be cleared, so calling again will set the secret.
81    fn set_secret(&self, secret: &[u8]) -> Result<()> {
82        let mut inner = self
83            .inner
84            .lock()
85            .expect("Can't access mock data for set_secret: please report a bug!");
86        let data = inner.get_mut();
87        let err = data.error.take();
88        match err {
89            None => {
90                data.secret = Some(secret.to_vec());
91                Ok(())
92            }
93            Some(err) => Err(err),
94        }
95    }
96
97    /// See the API docs.
98    ///
99    /// If there is an error set in the mock, it will
100    /// be returned instead of a secret. The existing
101    /// secret will not change.
102    fn get_secret(&self) -> Result<Vec<u8>> {
103        let mut inner = self
104            .inner
105            .lock()
106            .expect("Can't access mock data for get: please report a bug!");
107        let data = inner.get_mut();
108        let err = data.error.take();
109        match err {
110            None => match &data.secret {
111                None => Err(Error::NoEntry),
112                Some(val) => Ok(val.clone()),
113            },
114            Some(err) => Err(err),
115        }
116    }
117
118    /// See the API docs.
119    ///
120    /// If there is an error, it will be returned and
121    /// cleared. Calling again will delete the cred.
122    fn delete_credential(&self) -> Result<()> {
123        let mut inner = self
124            .inner
125            .lock()
126            .expect("Can't access mock data for delete: please report a bug!");
127        let data = inner.get_mut();
128        let err = data.error.take();
129        match err {
130            None => match data.secret {
131                Some(_) => {
132                    data.secret = None;
133                    Ok(())
134                }
135                None => Err(Error::NoEntry),
136            },
137            Some(err) => Err(err),
138        }
139    }
140
141    /// See the API docs.
142    ///
143    /// If there is an error in the mock, it's returned instead and cleared.
144    /// Calling again will retry the operation.
145    fn get_credential(&self) -> Result<Option<Arc<Credential>>> {
146        let mut inner = self
147            .inner
148            .lock()
149            .expect("Can't access mock data for get_credential: please report a bug!");
150        let data = inner.get_mut();
151        let err = data.error.take();
152        match err {
153            None => match data.secret {
154                Some(_) => Ok(None),
155                None => Err(Error::NoEntry),
156            },
157            Some(err) => Err(err),
158        }
159    }
160
161    /// See the API docs.
162    fn get_specifiers(&self) -> Option<(String, String)> {
163        Some(self.specifiers.clone())
164    }
165
166    /// Return this mock credential concrete object
167    /// wrapped in the [Any](std::any::Any) trait,
168    /// so it can be downcast.
169    fn as_any(&self) -> &dyn std::any::Any {
170        self
171    }
172
173    /// Expose the concrete debug formatter for use via the [Credential] trait
174    fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175        std::fmt::Debug::fmt(self, f)
176    }
177}
178
179impl Cred {
180    /// Set an error to be returned from this mock credential.
181    ///
182    /// Error returns always take precedence over the normal
183    /// behavior of the mock.  But once an error has been
184    /// returned, it is removed, so the mock works thereafter.
185    pub fn set_error(&self, err: Error) {
186        let mut inner = self
187            .inner
188            .lock()
189            .expect("Can't access mock data for set_error: please report a bug!");
190        let data = inner.get_mut();
191        data.error = Some(err);
192    }
193}
194
195/// The builder for mock credentials.
196///
197/// We keep them in a vector so we can reuse them
198/// for entries with the same service and user.
199/// Yes, a hashmap might be faster, but this is
200/// way simpler.
201pub struct Store {
202    /// The unique ID for this store instance.
203    pub id: String,
204    /// The credentials in this store.
205    pub inner: Mutex<RefCell<Vec<Arc<Cred>>>>,
206}
207
208impl std::fmt::Debug for Store {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        f.debug_struct("Store")
211            .field("vendor", &self.vendor())
212            .field("id", &self.id)
213            .finish()
214    }
215}
216
217impl Store {
218    /// Create a new mock store with no credentials.
219    pub fn new() -> Result<Arc<Self>> {
220        Ok(Arc::new(Store {
221            id: format!(
222                "Crate version {}, Instantiated at {}",
223                env!("CARGO_PKG_VERSION"),
224                SystemTime::now()
225                    .duration_since(UNIX_EPOCH)
226                    .unwrap_or_else(|_| Duration::new(0, 0))
227                    .as_secs_f64()
228            ),
229            inner: Mutex::new(RefCell::new(Vec::new())),
230        }))
231    }
232}
233
234impl CredentialStoreApi for Store {
235    fn vendor(&self) -> String {
236        String::from("Mock store, https://crates.io/crates/keyring-core")
237    }
238
239    fn id(&self) -> String {
240        self.id.clone()
241    }
242
243    /// Build a mock credential for the service and user. No modifiers are allowed.
244    ///
245    /// Since mocks don't persist beyond the life of their entry, all mocks
246    /// start off without passwords.
247    fn build(
248        &self,
249        service: &str,
250        user: &str,
251        mods: Option<&HashMap<&str, &str>>,
252    ) -> Result<Entry> {
253        if mods.is_some_and(|m| !m.is_empty()) {
254            let msg = "The mock store doesn't allow entry modifiers";
255            return Err(Error::NotSupportedByStore(msg.to_string()));
256        }
257        let mut inner = self
258            .inner
259            .lock()
260            .expect("Can't access mock store data: please report a bug!");
261        let creds = inner.get_mut();
262        for cred in creds.iter() {
263            if service == cred.specifiers.0 && user == cred.specifiers.1 {
264                return Ok(Entry {
265                    inner: cred.clone(),
266                });
267            }
268        }
269        let cred = Arc::new(Cred {
270            specifiers: (service.to_string(), user.to_string()),
271            inner: Mutex::new(RefCell::new(Default::default())),
272        });
273        creds.push(cred.clone());
274        Ok(Entry { inner: cred })
275    }
276
277    /// Search for mock credentials matching the spec.
278    ///
279    /// Attributes other than `service` and `user` are ignored.
280    /// Their values are used in unanchored substring searches against the specifier.
281    fn search(&self, spec: &HashMap<&str, &str>) -> Result<Vec<Entry>> {
282        let mut result: Vec<Entry> = Vec::new();
283        let svc = spec.get("service").unwrap_or(&"");
284        let usr = spec.get("user").unwrap_or(&"");
285        let mut inner = self
286            .inner
287            .lock()
288            .expect("Can't access mock store data: please report a bug!");
289        let creds = inner.get_mut();
290        for cred in creds.iter() {
291            if !cred.specifiers.0.as_str().contains(svc) {
292                continue;
293            }
294            if !cred.specifiers.1.as_str().contains(usr) {
295                continue;
296            }
297            result.push(Entry {
298                inner: cred.clone(),
299            });
300        }
301        Ok(result)
302    }
303
304    /// Get an [Any][std::any::Any] reference to the mock credential builder.
305    fn as_any(&self) -> &dyn std::any::Any {
306        self
307    }
308
309    /// This keystore keeps the password in the entry!
310    fn persistence(&self) -> CredentialPersistence {
311        CredentialPersistence::ProcessOnly
312    }
313
314    /// Expose the concrete debug formatter
315    /// for use via the [CredentialStore](crate::CredentialStore) trait
316    fn debug_fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        std::fmt::Debug::fmt(self, f)
318    }
319}