Skip to main content

subspace_core/
vault.rs

1//! Where Subspace keeps its saved secrets. Release builds use the system
2//! keychain ([`Keychain`]). Debug builds use an owner-only JSON file beside
3//! the state file instead, unless [`USE_KEYCHAIN_ENV`] is set: a debug build
4//! is ad hoc signed, so each rebuild is a new app to the keychain, which
5//! asks for access again or, when the running build no longer matches its
6//! bundle on disk, refuses without asking. Capture and test builds never
7//! touch the real keychain either.
8
9use std::collections::BTreeMap;
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::sync::{Mutex, MutexGuard, PoisonError};
13
14use serde::Serialize;
15use serde::de::DeserializeOwned;
16
17use crate::keychain::Keychain;
18use crate::{Secret, state};
19
20/// Debug builds only: set to keep secrets in the system keychain, as a
21/// release build does.
22pub const USE_KEYCHAIN_ENV: &str = "SUBSPACE_DEVELOPMENT_USE_KEYCHAIN";
23
24/// Serializes every read-modify-write of a vault file.
25static WRITES: Mutex<()> = Mutex::new(());
26
27/// The vault could not read or save a secret. No provider details.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct VaultError;
30
31/// Secrets by account name.
32pub trait Vault: Send + Sync {
33    fn load(&self, account: &str) -> Result<Option<Secret>, VaultError>;
34    fn save(&self, account: &str, secret: &Secret) -> Result<(), VaultError>;
35    fn delete(&self, account: &str) -> Result<(), VaultError>;
36}
37
38/// The build's vault: the keychain under `service`, or in a debug build the
39/// owner-only `file_name` beside the state file.
40pub fn system(service: impl Into<String>, file_name: &str) -> Box<dyn Vault> {
41    let use_file = cfg!(debug_assertions) && std::env::var_os(USE_KEYCHAIN_ENV).is_none();
42    match use_file {
43        true => Box::new(FileVault(state::sibling(file_name))),
44        false => Box::new(KeychainVault(Keychain::new(service))),
45    }
46}
47
48/// An owner-only JSON file of secrets, as debug builds and tests use.
49pub fn file(path: PathBuf) -> Box<dyn Vault> {
50    Box::new(FileVault(Some(path)))
51}
52
53/// Kept in memory for this run only, as tests need.
54pub fn memory() -> Box<dyn Vault> {
55    Box::new(MemoryVault::default())
56}
57
58struct KeychainVault(Keychain);
59
60impl Vault for KeychainVault {
61    fn load(&self, account: &str) -> Result<Option<Secret>, VaultError> {
62        self.0.load(account).map_err(|_| VaultError)
63    }
64
65    fn save(&self, account: &str, secret: &Secret) -> Result<(), VaultError> {
66        self.0.save(account, secret).map_err(|_| VaultError)
67    }
68
69    fn delete(&self, account: &str) -> Result<(), VaultError> {
70        self.0.delete(account).map_err(|_| VaultError)
71    }
72}
73
74/// An owner-only JSON object of account names and secrets.
75struct FileVault(Option<PathBuf>);
76
77impl Vault for FileVault {
78    fn load(&self, account: &str) -> Result<Option<Secret>, VaultError> {
79        let secrets: BTreeMap<String, String> = read_json(self.0.as_deref());
80        Ok(secrets.get(account).map(Secret::new))
81    }
82
83    fn save(&self, account: &str, secret: &Secret) -> Result<(), VaultError> {
84        let _writing = lock(&WRITES);
85        let mut secrets: BTreeMap<String, String> = read_json(self.0.as_deref());
86        secrets.insert(account.to_owned(), secret.expose().to_owned());
87        write_json(self.0.as_deref(), &secrets)
88    }
89
90    fn delete(&self, account: &str) -> Result<(), VaultError> {
91        let _writing = lock(&WRITES);
92        let mut secrets: BTreeMap<String, String> = read_json(self.0.as_deref());
93        secrets.remove(account);
94        write_json(self.0.as_deref(), &secrets)
95    }
96}
97
98#[derive(Default)]
99struct MemoryVault(Mutex<BTreeMap<String, Secret>>);
100
101impl Vault for MemoryVault {
102    fn load(&self, account: &str) -> Result<Option<Secret>, VaultError> {
103        Ok(lock(&self.0).get(account).cloned())
104    }
105
106    fn save(&self, account: &str, secret: &Secret) -> Result<(), VaultError> {
107        lock(&self.0).insert(account.to_owned(), secret.clone());
108        Ok(())
109    }
110
111    fn delete(&self, account: &str) -> Result<(), VaultError> {
112        lock(&self.0).remove(account);
113        Ok(())
114    }
115}
116
117pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
118    mutex.lock().unwrap_or_else(PoisonError::into_inner)
119}
120
121/// The JSON in `file`; a missing or unreadable file reads as the default.
122pub(crate) fn read_json<T: DeserializeOwned + Default>(file: Option<&Path>) -> T {
123    file.and_then(|file| fs::read(file).ok())
124        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
125        .unwrap_or_default()
126}
127
128/// Writes `value` to `file` atomically, readable by the owner only.
129pub(crate) fn write_json<T: Serialize>(file: Option<&Path>, value: &T) -> Result<(), VaultError> {
130    let file = file.ok_or(VaultError)?;
131    let text = serde_json::to_string_pretty(value).map_err(|_| VaultError)?;
132    state::write_atomic(file, &text).map_err(|_| VaultError)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::{file, memory};
138    use crate::Secret;
139
140    #[test]
141    fn a_file_vault_is_owner_only_and_forgets_deleted_secrets() {
142        let directory = tempfile::tempdir().unwrap();
143        let path = directory.path().join("secrets.json");
144        let vault = file(path.clone());
145        vault
146            .save("profile", &Secret::new("fixture-value"))
147            .unwrap();
148        let reopened = file(path.clone());
149        assert_eq!(
150            reopened.load("profile").unwrap(),
151            Some(Secret::new("fixture-value"))
152        );
153        assert!(crate::private_file::is_owner_only(&path).unwrap());
154        reopened.delete("profile").unwrap();
155        assert_eq!(reopened.load("profile").unwrap(), None);
156        assert!(
157            !std::fs::read_to_string(&path)
158                .unwrap()
159                .contains("fixture-value")
160        );
161    }
162
163    #[test]
164    fn a_memory_vault_keeps_secrets_by_account() {
165        let vault = memory();
166        vault.save("one", &Secret::new("a")).unwrap();
167        assert_eq!(vault.load("one").unwrap(), Some(Secret::new("a")));
168        assert_eq!(vault.load("two").unwrap(), None);
169        vault.delete("one").unwrap();
170        assert_eq!(vault.load("one").unwrap(), None);
171    }
172}