Skip to main content

mortise_core/runtime/
secrets.rs

1//! The secrets of the environments: a token, a password or a header value.
2//!
3//! A secret goes to the credential store of the operating system: Keychain,
4//! Credential Manager, Secret Service. It is never written to a file. When no
5//! store is running the secret is kept in memory, until Mortise closes.
6
7use std::collections::BTreeMap;
8use std::path::Path;
9use std::sync::Mutex;
10
11/// The name Mortise's entries have in the credential store.
12#[cfg(feature = "os-secrets")]
13const SERVICE: &str = "Mortise";
14
15/// Where a secret went.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Kept {
18    /// In the credential store of this computer.
19    Stored,
20    /// No credential store is running: the secret is kept until Mortise closes.
21    UntilClose,
22}
23
24/// The secrets Mortise keeps, by app folder and environment name.
25pub struct Secrets {
26    /// False for a store that is only in memory, which tests use.
27    os: bool,
28    /// What was read or written in this run. `None`: the store has no such secret.
29    known: Mutex<BTreeMap<String, Option<String>>>,
30}
31
32impl Secrets {
33    /// The credential store of the operating system.
34    #[cfg(feature = "os-secrets")]
35    pub fn os() -> Self {
36        Self {
37            os: true,
38            known: Mutex::default(),
39        }
40    }
41
42    /// A store that forgets everything when it is dropped.
43    pub fn memory() -> Self {
44        Self {
45            os: false,
46            known: Mutex::default(),
47        }
48    }
49
50    /// Keeps a secret, in place of the one that was there.
51    pub fn set(&self, root: &Path, environment: &str, secret: &str) -> Kept {
52        let key = key(root, environment);
53        let kept = if !self.os || store_set(&key, secret) {
54            Kept::Stored
55        } else {
56            Kept::UntilClose
57        };
58        self.known().insert(key, Some(secret.to_owned()));
59        kept
60    }
61
62    /// The secret of an environment, when there is one.
63    pub fn get(&self, root: &Path, environment: &str) -> Option<String> {
64        let key = key(root, environment);
65        if let Some(known) = self.known().get(&key) {
66            return known.clone();
67        }
68        let secret = if self.os { store_get(&key) } else { None };
69        self.known().insert(key, secret.clone());
70        secret
71    }
72
73    /// True when the environment has a secret. The secret itself is not given out.
74    pub fn has(&self, root: &Path, environment: &str) -> bool {
75        self.get(root, environment).is_some()
76    }
77
78    /// Forgets the secret of an environment.
79    pub fn remove(&self, root: &Path, environment: &str) {
80        let key = key(root, environment);
81        if self.os {
82            store_remove(&key);
83        }
84        self.known().insert(key, None);
85    }
86
87    fn known(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, Option<String>>> {
88        self.known.lock().expect("the secrets are never poisoned")
89    }
90}
91
92/// The account name of an entry: the app folder and the environment.
93fn key(root: &Path, environment: &str) -> String {
94    format!("{}#{environment}", root.display())
95}
96
97#[cfg(feature = "os-secrets")]
98fn store_set(key: &str, secret: &str) -> bool {
99    keyring::Entry::new(SERVICE, key)
100        .and_then(|entry| entry.set_password(secret))
101        .is_ok()
102}
103
104#[cfg(feature = "os-secrets")]
105fn store_get(key: &str) -> Option<String> {
106    keyring::Entry::new(SERVICE, key)
107        .and_then(|entry| entry.get_password())
108        .ok()
109}
110
111#[cfg(feature = "os-secrets")]
112fn store_remove(key: &str) {
113    if let Ok(entry) = keyring::Entry::new(SERVICE, key) {
114        let _ = entry.delete_credential();
115    }
116}
117
118#[cfg(not(feature = "os-secrets"))]
119fn store_set(_: &str, _: &str) -> bool {
120    false
121}
122
123#[cfg(not(feature = "os-secrets"))]
124fn store_get(_: &str) -> Option<String> {
125    None
126}
127
128#[cfg(not(feature = "os-secrets"))]
129fn store_remove(_: &str) {}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    #[test]
136    fn a_secret_is_kept_by_app_and_environment() {
137        let secrets = Secrets::memory();
138        let shop = Path::new("/code/shop-api");
139        assert!(!secrets.has(shop, "staging"));
140        assert_eq!(secrets.set(shop, "staging", "s3cret"), Kept::Stored);
141        assert_eq!(secrets.get(shop, "staging").as_deref(), Some("s3cret"));
142        assert_eq!(secrets.get(shop, "local"), None);
143        assert_eq!(secrets.get(Path::new("/code/crm"), "staging"), None);
144        secrets.remove(shop, "staging");
145        assert!(!secrets.has(shop, "staging"));
146    }
147}