uv_keyring/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2/*!
3
4# Keyring
5
6This is a cross-platform library that does storage and retrieval of passwords
7(or other secrets) in an underlying platform-specific secure credential store.
8A top-level introduction to the library's usage, as well as a small code sample,
9may be found in [the library's entry on crates.io](https://crates.io/crates/keyring).
10Currently supported platforms are
11Linux,
12FreeBSD,
13OpenBSD,
14Windows,
15and macOS.
16
17## Design
18
19This crate implements a very simple, platform-independent concrete object called an _entry_.
20Each entry is identified by a <_service name_, _user name_> pair of UTF-8 strings.
21Entries support setting, getting, and forgetting (aka deleting) passwords (UTF-8 strings)
22and binary secrets (byte arrays). Each created entry provides security and persistence
23of its secret by wrapping a credential held in a platform-specific, secure credential store.
24
25The cross-platform API for creating an _entry_ supports specifying an (optional)
26UTF-8 _target_ attribute on entries, but the meaning of this
27attribute is credential-store (and thus platform) specific,
28and should not be thought of as part of the credential's identification. See the
29documentation of each credential store to understand the
30effect of specifying the _target_ attribute on entries in that store,
31as well as which values are allowed for _target_ by that store.
32
33The abstract behavior of entries and credential stores are captured
34by two types (with associated traits):
35
36- a _credential builder_, represented by the [`CredentialBuilder`] type
37 (and [`CredentialBuilderApi`](credential::CredentialBuilderApi) trait). Credential
38 builders are given the identifying information (and target, if any)
39 provided for an entry and map
40 it to the identifying information for a platform-specific credential.
41- a _credential_, represented by the [`Credential`] type
42 (and [`CredentialApi`](credential::CredentialApi) trait). The platform-specific credential
43 identified by the builder for an entry is what provides the secure storage
44 for that entry's password/secret.
45
46## Crate-provided Credential Stores
47
48This crate runs on several different platforms, and on each one
49it provides (by default) an implementation of a default credential store used
50on that platform (see [`default_credential_builder`]).
51These implementations work by mapping the data used to identify an entry
52to data used to identify platform-specific storage objects.
53For example, on macOS, the service and user provided for an entry
54are mapped to the service and user attributes that identify a
55generic credential in the macOS keychain.
56
57Typically, platform-specific credential stores (called _keystores_ in this crate)
58have a richer model of a credential than
59the one used by this crate to identify entries.
60These keystores expose their specific model in the
61concrete credential objects they use to implement the Credential trait.
62In order to allow clients to access this richer model, the Credential trait
63has an [`as_any`](credential::CredentialApi::as_any) method that returns a
64reference to the underlying
65concrete object typed as [`Any`](std::any::Any), so that it can be downgraded to
66its concrete type.
67
68### Credential store features
69
70Each of the platform-specific credential stores is associated a feature.
71This feature controls whether that store is included when the crate is built
72for its specific platform. For example, the macOS Keychain credential store
73implementation is only included if the `"apple-native"` feature is specified and the crate
74is built with a macOS target.
75
76The available credential store features, listed here, are all included in the
77default feature set:
78
79- `apple-native`: Provides access to the Keychain credential store on macOS.
80
81- `windows-native`: Provides access to the Windows Credential Store on Windows.
82
83- `secret-service`: Provides access to Secret Service.
84
85If you suppress the default feature set when building this crate, and you
86don't separately specify one of the included keystore features for your platform,
87then no keystore will be built in, and calls to [`Entry::new`] and [`Entry::new_with_target`]
88will fail unless the client brings their own keystore (see next section).
89
90## Client-provided Credential Stores
91
92In addition to the keystores implemented by this crate, clients
93are free to provide their own keystores and use those. There are
94two mechanisms provided for this:
95
96- Clients can give their desired credential builder to the crate
97 for use by the [`Entry::new`] and [`Entry::new_with_target`] calls.
98 This is done by making a call to [`set_default_credential_builder`].
99 The major advantage of this approach is that client code remains
100 independent of the credential builder being used.
101
102- Clients can construct their concrete credentials directly and
103 then turn them into entries by using the [`Entry::new_with_credential`]
104 call. The major advantage of this approach is that credentials
105 can be identified however clients want, rather than being restricted
106 to the simple model used by this crate.
107
108## Mock Credential Store
109
110In addition to the platform-specific credential stores, this crate
111always provides a mock credential store that clients can use to
112test their code in a platform independent way. The mock credential
113store allows for pre-setting errors as well as password values to
114be returned from [`Entry`] method calls. If you want to use the mock
115credential store as your default in tests, make this call:
116```
117uv_keyring::set_default_credential_builder(uv_keyring::mock::default_credential_builder())
118```
119
120## Interoperability with Third Parties
121
122Each of the platform-specific credential stores provided by this crate uses
123an underlying store that may also be used by modules written
124in other languages. If you want to interoperate with these third party
125credential writers, then you will need to understand the details of how the
126target, service, and user of this crate's generic model
127are used to identify credentials in the platform-specific store.
128These details are in the implementation of this crate's keystores,
129and are documented in the headers of those modules.
130
131(_N.B._ Since the included credential store implementations are platform-specific,
132you may need to use the Platform drop-down on [docs.rs](https://docs.rs/keyring) to
133view the storage module documentation for your desired platform.)
134
135## Caveats
136
137This module expects passwords to be UTF-8 encoded strings,
138so if a third party has stored an arbitrary byte string
139then retrieving that as a password will return a
140[`BadEncoding`](Error::BadEncoding) error.
141The returned error will have the raw bytes attached,
142so you can access them, but you can also just fetch
143them directly using [`get_secret`](Entry::get_secret) rather than
144[`get_password`](Entry::get_password).
145
146While this crate's code is thread-safe, the underlying credential
147stores may not handle access from different threads reliably.
148In particular, accessing the same credential
149from multiple threads at the same time can fail, especially on
150Windows and Linux, because the accesses may not be serialized in the same order
151they are made. And for RPC-based credential stores such as the dbus-based Secret
152Service, accesses from multiple threads (and even the same thread very quickly)
153are not recommended, as they may cause the RPC mechanism to fail.
154 */
155
156use std::collections::HashMap;
157
158pub use credential::{Credential, CredentialBuilder};
159pub use error::{Error, Result};
160
161#[cfg(any(target_os = "macos", target_os = "windows"))]
162mod blocking;
163pub mod mock;
164
165//
166// pick the *nix keystore
167//
168#[cfg(all(
169 any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"),
170 feature = "secret-service"
171))]
172#[cfg_attr(
173 docsrs,
174 doc(cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd")))
175)]
176pub mod secret_service;
177
178//
179// pick the Apple keystore
180//
181#[cfg(all(target_os = "macos", feature = "apple-native"))]
182#[cfg_attr(docsrs, doc(cfg(target_os = "macos")))]
183pub mod macos;
184
185//
186// pick the Windows keystore
187//
188#[cfg(all(target_os = "windows", feature = "windows-native"))]
189#[cfg_attr(docsrs, doc(cfg(target_os = "windows")))]
190pub mod windows;
191
192pub mod credential;
193pub mod error;
194
195#[derive(Default, Debug)]
196struct EntryBuilder {
197 inner: Option<Box<CredentialBuilder>>,
198}
199
200static DEFAULT_BUILDER: std::sync::RwLock<EntryBuilder> =
201 std::sync::RwLock::new(EntryBuilder { inner: None });
202
203/// Set the credential builder used by default to create entries.
204///
205/// This is really meant for use by clients who bring their own credential
206/// store and want to use it everywhere. If you are using multiple credential
207/// stores and want precise control over which credential is in which store,
208/// then use [`new_with_credential`](Entry::new_with_credential).
209///
210/// This will block waiting for all other threads currently creating entries
211/// to complete what they are doing. It's really meant to be called
212/// at app startup before you start creating entries.
213pub fn set_default_credential_builder(new: Box<CredentialBuilder>) {
214 let mut guard = DEFAULT_BUILDER
215 .write()
216 .expect("Poisoned RwLock in keyring-rs: please report a bug!");
217 guard.inner = Some(new);
218}
219
220pub fn default_credential_builder() -> Box<CredentialBuilder> {
221 #[cfg(any(
222 all(target_os = "linux", feature = "secret-service"),
223 all(target_os = "freebsd", feature = "secret-service"),
224 all(target_os = "openbsd", feature = "secret-service")
225 ))]
226 return secret_service::default_credential_builder();
227 #[cfg(all(target_os = "macos", feature = "apple-native"))]
228 return macos::default_credential_builder();
229 #[cfg(all(target_os = "windows", feature = "windows-native"))]
230 return windows::default_credential_builder();
231 #[cfg(not(any(
232 all(target_os = "linux", feature = "secret-service"),
233 all(target_os = "freebsd", feature = "secret-service"),
234 all(target_os = "openbsd", feature = "secret-service"),
235 all(target_os = "macos", feature = "apple-native"),
236 all(target_os = "windows", feature = "windows-native"),
237 )))]
238 credential::nop_credential_builder()
239}
240
241fn build_default_credential(target: Option<&str>, service: &str, user: &str) -> Result<Entry> {
242 static DEFAULT: std::sync::LazyLock<Box<CredentialBuilder>> =
243 std::sync::LazyLock::new(default_credential_builder);
244 let guard = DEFAULT_BUILDER
245 .read()
246 .expect("Poisoned RwLock in keyring-rs: please report a bug!");
247 let builder = guard.inner.as_ref().unwrap_or_else(|| &DEFAULT);
248 let credential = builder.build(target, service, user)?;
249 Ok(Entry { inner: credential })
250}
251
252#[derive(Debug)]
253pub struct Entry {
254 inner: Box<Credential>,
255}
256
257impl Entry {
258 /// Create an entry for the given service and user.
259 ///
260 /// The default credential builder is used.
261 ///
262 /// # Errors
263 ///
264 /// This function will return an [`Error`] if the `service` or `user` values are invalid.
265 /// The specific reasons for invalidity are platform-dependent, but include length constraints.
266 ///
267 /// # Panics
268 ///
269 /// In the very unlikely event that the internal credential builder's `RwLock` is poisoned, this function
270 /// will panic. If you encounter this, and especially if you can reproduce it, please report a bug with the
271 /// details (and preferably a backtrace) so the developers can investigate.
272 pub fn new(service: &str, user: &str) -> Result<Self> {
273 let entry = build_default_credential(None, service, user)?;
274 Ok(entry)
275 }
276
277 /// Create an entry for the given target, service, and user.
278 ///
279 /// The default credential builder is used.
280 pub fn new_with_target(target: &str, service: &str, user: &str) -> Result<Self> {
281 let entry = build_default_credential(Some(target), service, user)?;
282 Ok(entry)
283 }
284
285 /// Create an entry from a credential that may be in any credential store.
286 pub fn new_with_credential(credential: Box<Credential>) -> Self {
287 Self { inner: credential }
288 }
289
290 /// Set the password for this entry.
291 ///
292 /// Can return an [`Ambiguous`](Error::Ambiguous) error
293 /// if there is more than one platform credential
294 /// that matches this entry. This can only happen
295 /// on some platforms, and then only if a third-party
296 /// application wrote the ambiguous credential.
297 pub async fn set_password(&self, password: &str) -> Result<()> {
298 self.inner.set_password(password).await
299 }
300
301 /// Set the secret for this entry.
302 ///
303 /// Can return an [`Ambiguous`](Error::Ambiguous) error
304 /// if there is more than one platform credential
305 /// that matches this entry. This can only happen
306 /// on some platforms, and then only if a third-party
307 /// application wrote the ambiguous credential.
308 pub async fn set_secret(&self, secret: &[u8]) -> Result<()> {
309 self.inner.set_secret(secret).await
310 }
311
312 /// Retrieve the password saved for this entry.
313 ///
314 /// Returns a [`NoEntry`](Error::NoEntry) error if there isn't one.
315 ///
316 /// Can return an [`Ambiguous`](Error::Ambiguous) error
317 /// if there is more than one platform credential
318 /// that matches this entry. This can only happen
319 /// on some platforms, and then only if a third-party
320 /// application wrote the ambiguous credential.
321 pub async fn get_password(&self) -> Result<String> {
322 self.inner.get_password().await
323 }
324
325 /// Retrieve the secret saved for this entry.
326 ///
327 /// Returns a [`NoEntry`](Error::NoEntry) error if there isn't one.
328 ///
329 /// Can return an [`Ambiguous`](Error::Ambiguous) error
330 /// if there is more than one platform credential
331 /// that matches this entry. This can only happen
332 /// on some platforms, and then only if a third-party
333 /// application wrote the ambiguous credential.
334 pub async fn get_secret(&self) -> Result<Vec<u8>> {
335 self.inner.get_secret().await
336 }
337
338 /// Get the attributes on the underlying credential for this entry.
339 ///
340 /// Some of the underlying credential stores allow credentials to have named attributes
341 /// that can be set to string values. See the documentation for each credential store
342 /// for a list of which attribute names are supported by that store.
343 ///
344 /// Returns a [`NoEntry`](Error::NoEntry) error if there isn't a credential for this entry.
345 ///
346 /// Can return an [`Ambiguous`](Error::Ambiguous) error
347 /// if there is more than one platform credential
348 /// that matches this entry. This can only happen
349 /// on some platforms, and then only if a third-party
350 /// application wrote the ambiguous credential.
351 pub async fn get_attributes(&self) -> Result<HashMap<String, String>> {
352 self.inner.get_attributes().await
353 }
354
355 /// Update the attributes on the underlying credential for this entry.
356 ///
357 /// Some of the underlying credential stores allow credentials to have named attributes
358 /// that can be set to string values. See the documentation for each credential store
359 /// for a list of which attribute names can be given values by this call. To support
360 /// cross-platform use, each credential store ignores (without error) any specified attributes
361 /// that aren't supported by that store.
362 ///
363 /// Returns a [`NoEntry`](Error::NoEntry) error if there isn't a credential for this entry.
364 ///
365 /// Can return an [`Ambiguous`](Error::Ambiguous) error
366 /// if there is more than one platform credential
367 /// that matches this entry. This can only happen
368 /// on some platforms, and then only if a third-party
369 /// application wrote the ambiguous credential.
370 pub async fn update_attributes(&self, attributes: &HashMap<&str, &str>) -> Result<()> {
371 self.inner.update_attributes(attributes).await
372 }
373
374 /// Delete the underlying credential for this entry.
375 ///
376 /// Returns a [`NoEntry`](Error::NoEntry) error if there isn't one.
377 ///
378 /// Can return an [`Ambiguous`](Error::Ambiguous) error
379 /// if there is more than one platform credential
380 /// that matches this entry. This can only happen
381 /// on some platforms, and then only if a third-party
382 /// application wrote the ambiguous credential.
383 ///
384 /// Note: This does _not_ affect the lifetime of the [Entry]
385 /// structure, which is controlled by Rust. It only
386 /// affects the underlying credential store.
387 pub async fn delete_credential(&self) -> Result<()> {
388 self.inner.delete_credential().await
389 }
390
391 /// Return a reference to this entry's wrapped credential.
392 ///
393 /// The reference is of the [Any](std::any::Any) type, so it can be
394 /// downgraded to a concrete credential object. The client must know
395 /// what type of concrete object to cast to.
396 pub fn get_credential(&self) -> &dyn std::any::Any {
397 self.inner.as_any()
398 }
399}
400
401#[cfg(doctest)]
402doc_comment::doctest!("../README.md", readme);
403
404#[cfg(test)]
405/// There are no actual tests in this module.
406/// Instead, it contains generics that each keystore invokes in their tests,
407/// passing their store-specific parameters for the generic ones.
408mod tests {
409 use super::{Entry, Error};
410 #[cfg(feature = "native-auth")]
411 use super::{Result, credential::CredentialApi};
412 use std::collections::HashMap;
413
414 /// Create a platform-specific credential given the constructor, service, and user
415 #[cfg(feature = "native-auth")]
416 pub(crate) fn entry_from_constructor<F, T>(f: F, service: &str, user: &str) -> Entry
417 where
418 F: FnOnce(Option<&str>, &str, &str) -> Result<T>,
419 T: 'static + CredentialApi + Send + Sync,
420 {
421 match f(None, service, user) {
422 Ok(credential) => Entry::new_with_credential(Box::new(credential)),
423 Err(err) => {
424 panic!("Couldn't create entry (service: {service}, user: {user}): {err:?}")
425 }
426 }
427 }
428
429 async fn test_round_trip_no_delete(case: &str, entry: &Entry, in_pass: &str) {
430 entry
431 .set_password(in_pass)
432 .await
433 .unwrap_or_else(|err| panic!("Can't set password for {case}: {err:?}"));
434 let out_pass = entry
435 .get_password()
436 .await
437 .unwrap_or_else(|err| panic!("Can't get password for {case}: {err:?}"));
438 assert_eq!(
439 in_pass, out_pass,
440 "Passwords don't match for {case}: set='{in_pass}', get='{out_pass}'",
441 );
442 }
443
444 /// A basic round-trip unit test given an entry and a password.
445 pub(crate) async fn test_round_trip(case: &str, entry: &Entry, in_pass: &str) {
446 test_round_trip_no_delete(case, entry, in_pass).await;
447 entry
448 .delete_credential()
449 .await
450 .unwrap_or_else(|err| panic!("Can't delete password for {case}: {err:?}"));
451 let password = entry.get_password().await;
452 assert!(
453 matches!(password, Err(Error::NoEntry)),
454 "Read deleted password for {case}",
455 );
456 }
457
458 /// A basic round-trip unit test given an entry and a password.
459 pub(crate) async fn test_round_trip_secret(case: &str, entry: &Entry, in_secret: &[u8]) {
460 entry
461 .set_secret(in_secret)
462 .await
463 .unwrap_or_else(|err| panic!("Can't set secret for {case}: {err:?}"));
464 let out_secret = entry
465 .get_secret()
466 .await
467 .unwrap_or_else(|err| panic!("Can't get secret for {case}: {err:?}"));
468 assert_eq!(
469 in_secret, &out_secret,
470 "Passwords don't match for {case}: set='{in_secret:?}', get='{out_secret:?}'",
471 );
472 entry
473 .delete_credential()
474 .await
475 .unwrap_or_else(|err| panic!("Can't delete password for {case}: {err:?}"));
476 let password = entry.get_secret().await;
477 assert!(
478 matches!(password, Err(Error::NoEntry)),
479 "Read deleted password for {case}",
480 );
481 }
482
483 /// When tests fail, they leave keys behind, and those keys
484 /// have to be cleaned up before the tests can be run again
485 /// in order to avoid bad results. So it's a lot easier just
486 /// to have tests use a random string for key names to avoid
487 /// the conflicts, and then do any needed cleanup once everything
488 /// is working correctly. So we export this function for tests to use.
489 pub(crate) fn generate_random_string_of_len(len: usize) -> String {
490 use fastrand;
491 use std::iter::repeat_with;
492 repeat_with(fastrand::alphanumeric).take(len).collect()
493 }
494
495 pub(crate) fn generate_random_string() -> String {
496 generate_random_string_of_len(30)
497 }
498
499 fn generate_random_bytes_of_len(len: usize) -> Vec<u8> {
500 use fastrand;
501 use std::iter::repeat_with;
502 repeat_with(|| fastrand::u8(..)).take(len).collect()
503 }
504
505 pub(crate) async fn test_missing_entry<F>(f: F)
506 where
507 F: FnOnce(&str, &str) -> Entry,
508 {
509 let name = generate_random_string();
510 let entry = f(&name, &name);
511 assert!(
512 matches!(entry.get_password().await, Err(Error::NoEntry)),
513 "Missing entry has password"
514 );
515 }
516
517 pub(crate) async fn test_empty_password<F>(f: F)
518 where
519 F: FnOnce(&str, &str) -> Entry,
520 {
521 let name = generate_random_string();
522 let entry = f(&name, &name);
523 test_round_trip("empty password", &entry, "").await;
524 }
525
526 pub(crate) async fn test_round_trip_ascii_password<F>(f: F)
527 where
528 F: FnOnce(&str, &str) -> Entry,
529 {
530 let name = generate_random_string();
531 let entry = f(&name, &name);
532 test_round_trip("ascii password", &entry, "test ascii password").await;
533 }
534
535 pub(crate) async fn test_round_trip_non_ascii_password<F>(f: F)
536 where
537 F: FnOnce(&str, &str) -> Entry,
538 {
539 let name = generate_random_string();
540 let entry = f(&name, &name);
541 test_round_trip("non-ascii password", &entry, "このきれいな花は桜です").await;
542 }
543
544 pub(crate) async fn test_round_trip_random_secret<F>(f: F)
545 where
546 F: FnOnce(&str, &str) -> Entry,
547 {
548 let name = generate_random_string();
549 let entry = f(&name, &name);
550 let secret = generate_random_bytes_of_len(24);
551 test_round_trip_secret("non-ascii password", &entry, secret.as_slice()).await;
552 }
553
554 pub(crate) async fn test_update<F>(f: F)
555 where
556 F: FnOnce(&str, &str) -> Entry,
557 {
558 let name = generate_random_string();
559 let entry = f(&name, &name);
560 test_round_trip_no_delete("initial ascii password", &entry, "test ascii password").await;
561 test_round_trip(
562 "updated non-ascii password",
563 &entry,
564 "このきれいな花は桜です",
565 )
566 .await;
567 }
568
569 pub(crate) async fn test_noop_get_update_attributes<F>(f: F)
570 where
571 F: FnOnce(&str, &str) -> Entry,
572 {
573 let name = generate_random_string();
574 let entry = f(&name, &name);
575 assert!(
576 matches!(entry.get_attributes().await, Err(Error::NoEntry)),
577 "Read missing credential in attribute test",
578 );
579 let mut map: HashMap<&str, &str> = HashMap::new();
580 map.insert("test attribute name", "test attribute value");
581 assert!(
582 matches!(entry.update_attributes(&map).await, Err(Error::NoEntry)),
583 "Updated missing credential in attribute test",
584 );
585 // create the credential and test again
586 entry
587 .set_password("test password for attributes")
588 .await
589 .unwrap_or_else(|err| panic!("Can't set password for attribute test: {err:?}"));
590 match entry.get_attributes().await {
591 Err(err) => panic!("Couldn't get attributes: {err:?}"),
592 Ok(attrs) if attrs.is_empty() => {}
593 Ok(attrs) => panic!("Unexpected attributes: {attrs:?}"),
594 }
595 assert!(
596 matches!(entry.update_attributes(&map).await, Ok(())),
597 "Couldn't update attributes in attribute test",
598 );
599 match entry.get_attributes().await {
600 Err(err) => panic!("Couldn't get attributes after update: {err:?}"),
601 Ok(attrs) if attrs.is_empty() => {}
602 Ok(attrs) => panic!("Unexpected attributes after update: {attrs:?}"),
603 }
604 entry
605 .delete_credential()
606 .await
607 .unwrap_or_else(|err| panic!("Can't delete credential for attribute test: {err:?}"));
608 assert!(
609 matches!(entry.get_attributes().await, Err(Error::NoEntry)),
610 "Read deleted credential in attribute test",
611 );
612 }
613}