Skip to main content

tilo_secrets/
lib.rs

1#![cfg_attr(
2    test,
3    allow(
4        clippy::disallowed_methods,
5        reason = "in a test these are the assertion, not a hazard"
6    )
7)]
8#![cfg_attr(
9    all(target_arch = "wasm32", target_os = "unknown"),
10    allow(
11        clippy::future_not_send,
12        reason = "browser futures hold JavaScript handles and run on the page's single thread"
13    )
14)]
15
16//! App-scoped secret storage: one API on Linux, macOS, Windows and the web.
17//!
18//! A [`SecretStore`] belongs to one app ([`SecretStore::for_app`]), and its keys name
19//! that app's secrets and no other app's. [`SecretStore::memory`] keeps them in the
20//! process, for tests.
21//!
22//! | Target | Backend | [`Protection`] |
23//! |---|---|---|
24//! | Linux | the freedesktop Secret Service over D-Bus (GNOME Keyring, `KWallet`) | [`Protection::OsKeychain`] |
25//! | Linux, in Tilo's sandbox | sealed files in the app's directory, keyed by the Secret portal | [`Protection::OsKeychain`] |
26//! | macOS | the login Keychain's generic passwords | [`Protection::OsKeychain`] |
27//! | Windows | generic credentials in the user's Credential Manager (DPAPI-encrypted, this machine only) | [`Protection::OsKeychain`] |
28//! | Web | AES-GCM under a non-extractable `CryptoKey`; key and ciphertext in `IndexedDB` | [`Protection::BrowserWrapped`] |
29//! | Linux, macOS with `TILO_SECRETS_DIR` | sealed owner-only files in that directory | [`Protection::LocalFile`] |
30//!
31//! [`SECRETS_DIR_ENV`] serves machines with no keychain to unlock: every process
32//! given it keeps its secrets in that directory instead of the system store.
33//! `BrowserWrapped` does not protect against script running in the page's origin
34//! or an attacker holding the browser profile.
35//!
36//! The API is async because the browser's is, and its futures are `Send` on the
37//! desktop only: spawn them on `tilo_rt::app()`, which accepts both. Desktop code
38//! may use the `*_blocking` methods; the web answers them once the host has loaded
39//! the page's secrets (`web::mirror`), and otherwise with [`Feature::Blocking`]
40//! unsupported.
41
42use std::collections::HashMap;
43use std::fmt;
44use std::sync::{Arc, Mutex};
45
46use zeroize::Zeroizing;
47
48#[cfg(target_os = "android")]
49mod android;
50mod caps;
51pub mod conformance;
52#[cfg(any(target_os = "windows", test))]
53mod credential;
54#[cfg(target_os = "linux")]
55mod device_proof;
56#[cfg(unix)]
57mod files;
58#[cfg(all(target_os = "linux", feature = "host-keyring"))]
59mod linux;
60#[cfg(target_os = "macos")]
61mod macos;
62#[cfg(all(target_os = "linux", feature = "host-keyring"))]
63pub mod owner_migration;
64#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
65pub mod web;
66#[cfg(target_os = "windows")]
67mod windows;
68
69pub use caps::{Availability, Feature, Unsupported, availability, available};
70#[cfg(target_os = "linux")]
71#[cfg(target_os = "linux")]
72pub use device_proof::arm as arm_device_proof;
73#[cfg(all(target_os = "linux", feature = "host-keyring"))]
74pub use device_proof::prove as prove_device_caller;
75
76/// Secret bytes: wiped from memory on drop and never printed by `Debug`.
77#[derive(Clone, PartialEq, Eq)]
78pub struct Secret(Zeroizing<Vec<u8>>);
79
80impl Secret {
81    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
82        Self(Zeroizing::new(bytes.into()))
83    }
84
85    pub fn expose(&self) -> &[u8] {
86        &self.0
87    }
88}
89
90impl fmt::Debug for Secret {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "Secret({} bytes)", self.0.len())
93    }
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum Protection {
98    OsKeychain,
99    /// Sealed in the workspace's vault, as an item the app keeps: synced to the person's other
100    /// devices and released only to the app's own process.
101    WorkspaceVault,
102    /// Encrypted under a key the browser will not export through `WebCrypto`; not a
103    /// boundary against a compromised browser or origin.
104    BrowserWrapped,
105    /// Sealed in owner-only files under a key file beside them: as private as the
106    /// machine's disk and the Unix account that owns them.
107    LocalFile,
108    /// In this process only; gone when it exits.
109    Memory,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum SecretError {
114    Unavailable(String),
115    Unsupported(Unsupported),
116    Denied,
117    /// The key is empty or has control characters.
118    InvalidKey,
119    Failed(String),
120}
121
122impl fmt::Display for SecretError {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        match self {
125            Self::Unavailable(reason) => write!(f, "no secret store: {reason}"),
126            Self::Unsupported(unsupported) => unsupported.fmt(f),
127            Self::Denied => f.write_str("access to the secret store was refused"),
128            Self::InvalidKey => f.write_str("a secret key must be non-empty text"),
129            Self::Failed(reason) => f.write_str(reason),
130        }
131    }
132}
133
134impl std::error::Error for SecretError {}
135
136#[derive(Clone, Debug, Default)]
137pub struct PutOptions {
138    pub label: Option<String>,
139}
140
141pub trait SecretBackend: Send + Sync {
142    fn protection(&self) -> Protection;
143    fn get(&self, app: &str, key: &str) -> Result<Option<Secret>, SecretError>;
144    fn put(&self, app: &str, key: &str, value: &[u8], label: &str) -> Result<(), SecretError>;
145    fn delete(&self, app: &str, key: &str) -> Result<(), SecretError>;
146    /// Every entry this store holds on this machine, as `(app, key)`, whether or not this
147    /// process may read its secret: what a migration that moves entries into a vault walks. A
148    /// backend that keeps its entries where it cannot name them answers none, and whatever
149    /// walks them then moves none, which is safe.
150    fn entries(&self) -> Result<Vec<(String, String)>, SecretError> {
151        Ok(Vec::new())
152    }
153    fn probe(&self) -> Result<(), SecretError> {
154        Ok(())
155    }
156}
157
158#[derive(Clone)]
159enum Backend {
160    Sync(Arc<dyn SecretBackend>),
161    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
162    Web,
163}
164
165#[derive(Clone)]
166pub struct SecretStore {
167    app: String,
168    backend: Backend,
169}
170
171impl fmt::Debug for SecretStore {
172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173        f.debug_struct("SecretStore")
174            .field("app", &self.app)
175            .field("protection", &self.protection())
176            .finish_non_exhaustive()
177    }
178}
179
180impl SecretStore {
181    pub fn for_app(app_id: &str) -> Self {
182        Self {
183            app: app_id.to_owned(),
184            backend: THREAD_BACKEND
185                .with(|scoped| scoped.borrow().clone())
186                .or_else(|| PROCESS_BACKEND.get().cloned())
187                .map_or_else(machine_backend, Backend::Sync),
188        }
189    }
190
191    pub fn memory(app_id: &str) -> Self {
192        Self::with_backend(app_id, Arc::new(MemoryBackend::default()))
193    }
194
195    pub fn with_backend(app_id: &str, backend: Arc<dyn SecretBackend>) -> Self {
196        Self {
197            app: app_id.to_owned(),
198            backend: Backend::Sync(backend),
199        }
200    }
201
202    /// Start an immutable write, returning its key only after durable ownership. `None` means
203    /// pending: retry the same namespace and bytes on a later turn.
204    pub fn seal_blocking(
205        &self,
206        key: &str,
207        value: &[u8],
208        options: PutOptions,
209    ) -> Result<Option<String>, SecretError> {
210        check_key(key)?;
211        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
212        if matches!(self.backend, Backend::Web) {
213            return web::seal_at_blocking(&self.app, key, value);
214        }
215        self.put_blocking(key, value, options)?;
216        Ok(Some(key.to_owned()))
217    }
218
219    /// Whether page ownership has asynchronous operations awaiting a retry; native and
220    /// host-injected synchronous stores never stage operations here.
221    pub fn pending() -> bool {
222        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
223        {
224            web::pending()
225        }
226        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
227        {
228            false
229        }
230    }
231
232    pub fn app_id(&self) -> &str {
233        &self.app
234    }
235
236    pub fn protection(&self) -> Protection {
237        match &self.backend {
238            Backend::Sync(backend) => backend.protection(),
239            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
240            Backend::Web => Protection::BrowserWrapped,
241        }
242    }
243
244    pub async fn get(&self, key: &str) -> Result<Option<Secret>, SecretError> {
245        check_key(key)?;
246        match &self.backend {
247            Backend::Sync(backend) => {
248                let (backend, app, key) = (backend.clone(), self.app.clone(), key.to_owned());
249                off_thread(move || backend.get(&app, &key)).await
250            }
251            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
252            Backend::Web => web::get(&self.app, key).await,
253        }
254    }
255
256    pub async fn put(
257        &self,
258        key: &str,
259        value: &[u8],
260        options: PutOptions,
261    ) -> Result<(), SecretError> {
262        check_key(key)?;
263        let label = options
264            .label
265            .unwrap_or_else(|| format!("{} {key}", self.app));
266        match &self.backend {
267            Backend::Sync(backend) => {
268                let (backend, app, key) = (backend.clone(), self.app.clone(), key.to_owned());
269                let value = Zeroizing::new(value.to_vec());
270                off_thread(move || backend.put(&app, &key, &value, &label)).await
271            }
272            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
273            Backend::Web => web::put(&self.app, key, value).await,
274        }
275    }
276
277    pub async fn delete(&self, key: &str) -> Result<(), SecretError> {
278        check_key(key)?;
279        match &self.backend {
280            Backend::Sync(backend) => {
281                let (backend, app, key) = (backend.clone(), self.app.clone(), key.to_owned());
282                off_thread(move || backend.delete(&app, &key)).await
283            }
284            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
285            Backend::Web => web::delete(&self.app, key).await,
286        }
287    }
288
289    /// [`get`](Self::get), blocking the calling thread. Desktop code only.
290    ///
291    /// # Errors
292    /// As `get`, and [`Feature::Blocking`] unsupported on the web.
293    pub fn get_blocking(&self, key: &str) -> Result<Option<Secret>, SecretError> {
294        check_key(key)?;
295        self.sync()?.get(&self.app, key)
296    }
297
298    /// [`put`](Self::put), blocking the calling thread. Desktop code only.
299    ///
300    /// # Errors
301    /// As `put`, and [`Feature::Blocking`] unsupported on the web.
302    pub fn put_blocking(
303        &self,
304        key: &str,
305        value: &[u8],
306        options: PutOptions,
307    ) -> Result<(), SecretError> {
308        check_key(key)?;
309        let label = options
310            .label
311            .unwrap_or_else(|| format!("{} {key}", self.app));
312        self.sync()?.put(&self.app, key, value, &label)
313    }
314
315    /// [`delete`](Self::delete), blocking the calling thread. Desktop code
316    /// only.
317    ///
318    /// # Errors
319    /// As `delete`, and [`Feature::Blocking`] unsupported on the web.
320    pub fn delete_blocking(&self, key: &str) -> Result<(), SecretError> {
321        check_key(key)?;
322        self.sync()?.delete(&self.app, key)
323    }
324
325    /// Whether the store answers on this session, blocking the calling
326    /// thread. The web store always answers.
327    pub fn probe_blocking(&self) -> Result<(), SecretError> {
328        match &self.backend {
329            Backend::Sync(backend) => backend.probe(),
330            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
331            Backend::Web => Ok(()),
332        }
333    }
334
335    /// Every entry the platform's store holds on this machine, as `(app, key)`, whether or not
336    /// this process may read its secret. The store's own app does not narrow the answer: the
337    /// platform's store is shared, and a migration that moves its entries into a workspace vault
338    /// walks it for every app. Nothing here reads a secret.
339    ///
340    /// # Errors
341    /// The store could not be asked. On the web there is no such store to walk: the answer is
342    /// none.
343    pub fn entries_blocking(&self) -> Result<Vec<(String, String)>, SecretError> {
344        match &self.backend {
345            Backend::Sync(backend) => backend.entries(),
346            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
347            Backend::Web => Ok(Vec::new()),
348        }
349    }
350
351    #[cfg_attr(
352        not(all(target_arch = "wasm32", target_os = "unknown")),
353        allow(
354            clippy::unnecessary_wraps,
355            reason = "the web store has no synchronous access"
356        )
357    )]
358    fn sync(&self) -> Result<&dyn SecretBackend, SecretError> {
359        match &self.backend {
360            Backend::Sync(backend) => Ok(&**backend),
361            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
362            Backend::Web if web::mirrored() => Ok(&web::MirrorBackend),
363            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
364            Backend::Web => Err(SecretError::Unsupported(Unsupported::of(Feature::Blocking))),
365        }
366    }
367}
368
369impl SecretStore {
370    /// The secret one item of a document needs for `purpose`: a database
371    /// profile's password, a connection's SSH passphrase, an account's
372    /// one-time-password seed. The document names the item by its id and
373    /// never holds the secret; the secret stays in this store on this
374    /// device.
375    ///
376    /// `purpose` is one of the app's own fixed names and contains no `/`;
377    /// `item` is the item's id in the document.
378    #[must_use]
379    pub fn item(&self, purpose: &str, item: &str) -> ItemSecret {
380        debug_assert!(
381            !purpose.is_empty() && !purpose.contains('/'),
382            "an item secret's purpose is a plain name: {purpose:?}"
383        );
384        ItemSecret {
385            store: self.clone(),
386            key: format!("{purpose}/{item}"),
387            label: format!("{} {purpose} for {item}", self.app),
388        }
389    }
390}
391
392#[derive(Clone, Debug)]
393pub struct ItemSecret {
394    store: SecretStore,
395    key: String,
396    label: String,
397}
398
399impl ItemSecret {
400    #[must_use]
401    pub fn key(&self) -> &str {
402        &self.key
403    }
404
405    pub async fn get(&self) -> Result<Option<Secret>, SecretError> {
406        self.store.get(&self.key).await
407    }
408
409    pub async fn put(&self, value: &[u8]) -> Result<(), SecretError> {
410        let options = PutOptions {
411            label: Some(self.label.clone()),
412        };
413        self.store.put(&self.key, value, options).await
414    }
415
416    pub async fn delete(&self) -> Result<(), SecretError> {
417        self.store.delete(&self.key).await
418    }
419
420    /// [`get`](Self::get), blocking the calling thread. Desktop code only.
421    ///
422    /// # Errors
423    /// As `get`, and [`Feature::Blocking`] unsupported on the web.
424    pub fn get_blocking(&self) -> Result<Option<Secret>, SecretError> {
425        self.store.get_blocking(&self.key)
426    }
427
428    /// [`put`](Self::put), blocking the calling thread. Desktop code only.
429    ///
430    /// # Errors
431    /// As `put`, and [`Feature::Blocking`] unsupported on the web.
432    pub fn put_blocking(&self, value: &[u8]) -> Result<(), SecretError> {
433        let options = PutOptions {
434            label: Some(self.label.clone()),
435        };
436        self.store.put_blocking(&self.key, value, options)
437    }
438
439    /// [`delete`](Self::delete), blocking the calling thread. Desktop code
440    /// only.
441    ///
442    /// # Errors
443    /// As `delete`, and [`Feature::Blocking`] unsupported on the web.
444    pub fn delete_blocking(&self) -> Result<(), SecretError> {
445        self.store.delete_blocking(&self.key)
446    }
447
448    #[must_use]
449    pub fn present_blocking(&self) -> bool {
450        matches!(self.get_blocking(), Ok(Some(_)))
451    }
452}
453
454/// Whether what this build puts in the system store stays readable by later builds of
455/// the same program. On macOS only a Developer ID signature does; an ad-hoc or dev
456/// signature's items are readable by that build alone.
457#[must_use]
458pub fn items_outlive_rebuilds() -> bool {
459    #[cfg(target_os = "macos")]
460    return macos::developer_id_signed();
461    #[cfg(not(target_os = "macos"))]
462    true
463}
464
465static PROCESS_BACKEND: std::sync::OnceLock<Arc<dyn SecretBackend>> = std::sync::OnceLock::new();
466
467/// From now on, every [`SecretStore::for_app`] in this process shares one in-memory store
468/// and never reaches the platform's, which may prompt and holds the user's real
469/// secrets.
470pub fn keep_in_memory_for_process() {
471    PROCESS_BACKEND.get_or_init(|| Arc::new(MemoryBackend::default()));
472}
473
474thread_local! {
475    static THREAD_BACKEND: std::cell::RefCell<Option<Arc<dyn SecretBackend>>> =
476        const { std::cell::RefCell::new(None) };
477}
478
479/// Keeps a thread's stores in one backend until it is dropped: see
480/// [`scope_thread`].
481#[must_use = "the scope ends when the guard is dropped"]
482pub struct SecretsScope {
483    earlier: Option<Arc<dyn SecretBackend>>,
484}
485
486impl Drop for SecretsScope {
487    fn drop(&mut self) {
488        THREAD_BACKEND.with(|scoped| *scoped.borrow_mut() = self.earlier.take());
489    }
490}
491
492/// From now until the guard drops, every [`SecretStore::for_app`] this thread creates
493/// keeps its secrets in `backend`, never the platform's store.
494pub fn scope_thread(backend: Arc<dyn SecretBackend>) -> SecretsScope {
495    let earlier = THREAD_BACKEND.with(|scoped| scoped.borrow_mut().replace(backend));
496    SecretsScope { earlier }
497}
498
499pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
500    let _scope = SecretsScope {
501        earlier: THREAD_BACKEND.with(|scoped| scoped.borrow_mut().take()),
502    };
503    work()
504}
505
506#[must_use]
507pub fn memory_backend() -> Arc<dyn SecretBackend> {
508    Arc::new(MemoryBackend::default())
509}
510
511fn check_key(key: &str) -> Result<(), SecretError> {
512    if key.is_empty() || key.chars().any(char::is_control) {
513        Err(SecretError::InvalidKey)
514    } else {
515        Ok(())
516    }
517}
518
519/// Run a blocking store call on the app runtime's blocking pool, or inline
520/// where there are no threads (an in-memory store in a browser).
521async fn off_thread<T: Send + 'static>(
522    call: impl FnOnce() -> Result<T, SecretError> + Send + 'static,
523) -> Result<T, SecretError> {
524    if matches!(
525        tilo_rt::availability(tilo_rt::Feature::Threads),
526        tilo_rt::Availability::Unsupported(_)
527    ) {
528        return call();
529    }
530    tilo_rt::app()
531        .spawn_blocking(call)
532        .await
533        .unwrap_or_else(|error| {
534            Err(SecretError::Failed(format!(
535                "secret store task failed: {error}"
536            )))
537        })
538}
539
540pub const SECRETS_DIR_ENV: &str = "TILO_SECRETS_DIR";
541
542/// The sealed file stores this process opened, each by the directory it seals.
543#[cfg(unix)]
544type FileStores =
545    std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, Arc<dyn SecretBackend>>>;
546
547fn machine_backend() -> Backend {
548    #[cfg(unix)]
549    if let Some(dir) = std::env::var_os(SECRETS_DIR_ENV).filter(|dir| !dir.is_empty()) {
550        // The store is the directory's, and a process can meet more than one name: a test suite
551        // gives each test its own home and names its store while that test runs. Opened once
552        // per directory, so a name this process meets later opens its own store rather than
553        // borrowing the first one's, whose directory may no longer be there.
554        static FILES: std::sync::OnceLock<FileStores> = std::sync::OnceLock::new();
555        let stores = FILES.get_or_init(FileStores::default);
556        let dir = std::path::PathBuf::from(dir);
557        let opened = {
558            let files = stores
559                .lock()
560                .unwrap_or_else(std::sync::PoisonError::into_inner);
561            files.get(&dir).cloned()
562        };
563        if let Some(store) = opened {
564            return Backend::Sync(store);
565        }
566        let store = match files::FileStore::open(&dir) {
567            Ok(store) => Arc::new(store) as Arc<dyn SecretBackend>,
568            Err(error) => return Backend::Sync(Arc::new(Refused(error))),
569        };
570        stores
571            .lock()
572            .unwrap_or_else(std::sync::PoisonError::into_inner)
573            .insert(dir, store.clone());
574        return Backend::Sync(store);
575    }
576    system_backend()
577}
578
579/// A configured store that could not be opened: every call says why,
580/// rather than falling back to another store.
581#[cfg(unix)]
582struct Refused(SecretError);
583
584#[cfg(unix)]
585impl SecretBackend for Refused {
586    fn protection(&self) -> Protection {
587        Protection::LocalFile
588    }
589    fn get(&self, _app: &str, _key: &str) -> Result<Option<Secret>, SecretError> {
590        Err(self.0.clone())
591    }
592    fn put(&self, _app: &str, _key: &str, _value: &[u8], _label: &str) -> Result<(), SecretError> {
593        Err(self.0.clone())
594    }
595    fn delete(&self, _app: &str, _key: &str) -> Result<(), SecretError> {
596        Err(self.0.clone())
597    }
598    fn probe(&self) -> Result<(), SecretError> {
599        Err(self.0.clone())
600    }
601}
602
603/// A host process asks the operating system's Secret Service, which only a host build links
604/// (`host-keyring`). An app process keeps its secrets in the workspace's vault, which its SDK
605/// hands it as its store ([`SecretStore::with_backend`]); a build that links neither answers
606/// that it has no store rather than writing a secret somewhere nobody sealed.
607#[cfg(target_os = "linux")]
608fn system_backend() -> Backend {
609    #[cfg(feature = "host-keyring")]
610    {
611        Backend::Sync(Arc::new(linux::SecretService))
612    }
613    #[cfg(not(feature = "host-keyring"))]
614    {
615        Backend::Sync(Arc::new(NoStore))
616    }
617}
618
619/// The store of a build that links neither the workspace's connection nor a keychain: every call
620/// says so instead of writing a secret where nothing sealed it.
621#[cfg(all(target_os = "linux", not(feature = "host-keyring")))]
622struct NoStore;
623
624#[cfg(all(target_os = "linux", not(feature = "host-keyring")))]
625impl SecretBackend for NoStore {
626    fn protection(&self) -> Protection {
627        Protection::Memory
628    }
629    fn get(&self, _app: &str, _key: &str) -> Result<Option<Secret>, SecretError> {
630        Err(SecretError::Unavailable(NO_STORE.to_owned()))
631    }
632    fn put(&self, _app: &str, _key: &str, _value: &[u8], _label: &str) -> Result<(), SecretError> {
633        Err(SecretError::Unavailable(NO_STORE.to_owned()))
634    }
635    fn delete(&self, _app: &str, _key: &str) -> Result<(), SecretError> {
636        Err(SecretError::Unavailable(NO_STORE.to_owned()))
637    }
638}
639
640#[cfg(all(target_os = "linux", not(feature = "host-keyring")))]
641const NO_STORE: &str =
642    "this process holds no connection to its daemon and this build links no keychain";
643
644/// A debug build inside `tools/with-test-environment.sh` (which cargo runs
645/// every test binary in) never reaches the user's login Keychain, just as the
646/// environment gives Linux tests no Secret Service. `TILO_SECRETS_SYSTEM_TEST`
647/// is the explicit request to test the real store.
648#[cfg(target_os = "macos")]
649fn system_backend() -> Backend {
650    if cfg!(debug_assertions)
651        && std::env::var_os("TILO_TEST_ENVIRONMENT").is_some()
652        && std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_none()
653    {
654        return Backend::Sync(Arc::new(UnsupportedBackend(
655            "the test environment has no login Keychain",
656        )));
657    }
658    Backend::Sync(Arc::new(macos::Keychain::new()))
659}
660
661/// As on macOS, a debug test build in the test environment never writes the
662/// user's own Credential Manager unless `TILO_SECRETS_SYSTEM_TEST` asks.
663#[cfg(target_os = "windows")]
664fn system_backend() -> Backend {
665    if cfg!(debug_assertions)
666        && std::env::var_os("TILO_TEST_ENVIRONMENT").is_some()
667        && std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_none()
668    {
669        return Backend::Sync(Arc::new(UnsupportedBackend(
670            "the test environment has no Credential Manager",
671        )));
672    }
673    Backend::Sync(Arc::new(windows::CredentialManager))
674}
675
676#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
677fn system_backend() -> Backend {
678    Backend::Web
679}
680
681/// The app's sealed files, under a store key the Android Keystore wraps.
682#[cfg(target_os = "android")]
683fn system_backend() -> Backend {
684    static KEYSTORE: std::sync::OnceLock<Arc<dyn SecretBackend>> = std::sync::OnceLock::new();
685    Backend::Sync(
686        KEYSTORE
687            .get_or_init(|| Arc::new(android::KeystoreStore::default()))
688            .clone(),
689    )
690}
691
692#[cfg(not(any(
693    target_os = "linux",
694    target_os = "android",
695    target_os = "macos",
696    target_os = "windows",
697    all(target_arch = "wasm32", target_os = "unknown")
698)))]
699fn system_backend() -> Backend {
700    Backend::Sync(Arc::new(UnsupportedBackend(
701        "this platform has no secret store backend",
702    )))
703}
704
705/// No secret store, and why: a target without one, or a macOS or Windows
706/// test environment.
707#[cfg(not(any(
708    target_os = "linux",
709    target_os = "android",
710    all(target_arch = "wasm32", target_os = "unknown")
711)))]
712struct UnsupportedBackend(&'static str);
713
714#[cfg(not(any(
715    target_os = "linux",
716    target_os = "android",
717    all(target_arch = "wasm32", target_os = "unknown")
718)))]
719impl SecretBackend for UnsupportedBackend {
720    fn protection(&self) -> Protection {
721        Protection::Memory
722    }
723    fn get(&self, _app: &str, _key: &str) -> Result<Option<Secret>, SecretError> {
724        Err(SecretError::Unavailable(self.0.into()))
725    }
726    fn put(&self, _app: &str, _key: &str, _value: &[u8], _label: &str) -> Result<(), SecretError> {
727        self.get("", "").map(drop)
728    }
729    fn delete(&self, _app: &str, _key: &str) -> Result<(), SecretError> {
730        self.get("", "").map(drop)
731    }
732    fn probe(&self) -> Result<(), SecretError> {
733        self.get("", "").map(drop)
734    }
735}
736
737#[derive(Default)]
738struct MemoryBackend {
739    secrets: Mutex<HashMap<(String, String), Secret>>,
740}
741
742impl SecretBackend for MemoryBackend {
743    fn protection(&self) -> Protection {
744        Protection::Memory
745    }
746
747    fn get(&self, app: &str, key: &str) -> Result<Option<Secret>, SecretError> {
748        let secrets = self
749            .secrets
750            .lock()
751            .map_err(|_| SecretError::Failed("poisoned".into()))?;
752        Ok(secrets.get(&(app.to_owned(), key.to_owned())).cloned())
753    }
754
755    fn put(&self, app: &str, key: &str, value: &[u8], _label: &str) -> Result<(), SecretError> {
756        self.secrets
757            .lock()
758            .map_err(|_| SecretError::Failed("poisoned".into()))?
759            .insert((app.to_owned(), key.to_owned()), Secret::new(value));
760        Ok(())
761    }
762
763    fn delete(&self, app: &str, key: &str) -> Result<(), SecretError> {
764        self.secrets
765            .lock()
766            .map_err(|_| SecretError::Failed("poisoned".into()))?
767            .remove(&(app.to_owned(), key.to_owned()));
768        Ok(())
769    }
770
771    fn entries(&self) -> Result<Vec<(String, String)>, SecretError> {
772        Ok(self
773            .secrets
774            .lock()
775            .map_err(|_| SecretError::Failed("poisoned".into()))?
776            .keys()
777            .cloned()
778            .collect())
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    #[tokio::test(flavor = "current_thread")]
787    async fn the_memory_store_conforms() {
788        conformance::check_store(&SecretStore::memory("so.tilo.secrets-test")).await;
789    }
790
791    tilo_test_env::scenario! {
792        fn a_store_over_a_given_backend_keeps_each_apps_secrets_and_never_prints_them;
793
794        phase immutable_seals_acknowledge_injected_storage_and_validate_keys;
795        {
796            let store = SecretStore::memory("so.tilo.secrets-test");
797            let key = "credentials/first";
798            assert_eq!(
799                store
800                    .seal_blocking(key, b"private", PutOptions::default())
801                    .unwrap(),
802                Some(key.into())
803            );
804            assert_eq!(
805                store.get_blocking(key).unwrap().unwrap().expose(),
806                b"private"
807            );
808            assert!(
809                store
810                    .seal_blocking("", b"private", PutOptions::default())
811                    .is_err()
812            );
813        }
814
815        phase the_memory_store_conforms_blocking;
816        {
817            conformance::check_store_blocking(&SecretStore::memory("so.tilo.secrets-test"));
818        }
819
820        phase apps_do_not_see_each_others_secrets;
821        {
822            let shared: Arc<dyn SecretBackend> = Arc::new(MemoryBackend::default());
823            let a = SecretStore::with_backend("so.tilo.a", shared.clone());
824            let b = SecretStore::with_backend("so.tilo.b", shared);
825            a.put_blocking("token", b"a's", PutOptions::default())
826                .unwrap();
827            assert_eq!(b.get_blocking("token").unwrap(), None);
828            assert_eq!(a.get_blocking("token").unwrap().unwrap().expose(), b"a's");
829        }
830
831        phase item_secrets_are_kept_per_purpose_and_item;
832        {
833            let store = SecretStore::memory("so.tilo.db-client");
834            let alpha = store.item("password", "profile-alpha");
835            let beta = store.item("password", "profile-beta");
836            let alpha_key = store.item("key-passphrase", "profile-alpha");
837            assert!(!alpha.present_blocking());
838            alpha.put_blocking(b"hunter2").unwrap();
839            assert!(alpha.present_blocking());
840            assert!(!beta.present_blocking());
841            assert!(!alpha_key.present_blocking());
842            assert_eq!(alpha.key(), "password/profile-alpha");
843            assert_eq!(
844                store
845                    .get_blocking("password/profile-alpha")
846                    .unwrap()
847                    .unwrap()
848                    .expose(),
849                b"hunter2"
850            );
851            alpha.delete_blocking().unwrap();
852            assert_eq!(alpha.get_blocking().unwrap(), None);
853        }
854
855        phase secrets_never_print;
856        {
857            assert_eq!(
858                format!("{:?}", Secret::new(b"hunter2".to_vec())),
859                "Secret(7 bytes)"
860            );
861        }
862    }
863
864    #[cfg(target_os = "macos")]
865    #[test]
866    fn tests_never_reach_the_login_keychain() {
867        assert!(
868            std::env::var_os("TILO_TEST_ENVIRONMENT").is_some(),
869            "run tests through cargo, whose runner (tools/cargo-runner.sh) starts \
870             them in tools/with-test-environment.sh"
871        );
872        if std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_some() {
873            return;
874        }
875        let store = SecretStore::for_app("so.tilo.secrets-isolation");
876        assert!(matches!(
877            store.put_blocking("probe", b"x", PutOptions::default()),
878            Err(SecretError::Unavailable(_))
879        ));
880        assert!(matches!(
881            store.probe_blocking(),
882            Err(SecretError::Unavailable(_))
883        ));
884    }
885
886    #[test]
887    fn the_system_store_conforms_when_asked() {
888        if std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_none() {
889            return;
890        }
891        let store = SecretStore::for_app("so.tilo.secrets-conformance");
892        store.probe_blocking().unwrap();
893        conformance::check_store_blocking(&store);
894    }
895}