tilo-secrets 0.5.2

App-scoped secret storage on Linux, macOS, Windows and the web: the Secret Service, the Keychain, Credential Manager, and WebCrypto-wrapped IndexedDB.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
#![cfg_attr(
    test,
    allow(
        clippy::disallowed_methods,
        reason = "in a test these are the assertion, not a hazard"
    )
)]
#![cfg_attr(
    all(target_arch = "wasm32", target_os = "unknown"),
    allow(
        clippy::future_not_send,
        reason = "browser futures hold JavaScript handles and run on the page's single thread"
    )
)]

//! App-scoped secret storage: one API on Linux, macOS, Windows and the web.
//!
//! A [`SecretStore`] belongs to one app ([`SecretStore::for_app`]), and its keys name
//! that app's secrets and no other app's. [`SecretStore::memory`] keeps them in the
//! process, for tests.
//!
//! | Target | Backend | [`Protection`] |
//! |---|---|---|
//! | Linux | the freedesktop Secret Service over D-Bus (GNOME Keyring, `KWallet`) | [`Protection::OsKeychain`] |
//! | Linux, in Tilo's sandbox | sealed files in the app's directory, keyed by the Secret portal | [`Protection::OsKeychain`] |
//! | macOS | the login Keychain's generic passwords | [`Protection::OsKeychain`] |
//! | Windows | generic credentials in the user's Credential Manager (DPAPI-encrypted, this machine only) | [`Protection::OsKeychain`] |
//! | Web | AES-GCM under a non-extractable `CryptoKey`; key and ciphertext in `IndexedDB` | [`Protection::BrowserWrapped`] |
//! | Linux, macOS with `TILO_SECRETS_DIR` | sealed owner-only files in that directory | [`Protection::LocalFile`] |
//!
//! [`SECRETS_DIR_ENV`] serves machines with no keychain to unlock: every process
//! given it keeps its secrets in that directory instead of the system store.
//! `BrowserWrapped` does not protect against script running in the page's origin
//! or an attacker holding the browser profile.
//!
//! The API is async because the browser's is, and its futures are `Send` on the
//! desktop only: spawn them on `tilo_rt::app()`, which accepts both. Desktop code
//! may use the `*_blocking` methods; the web answers them once the host has loaded
//! the page's secrets (`web::mirror`), and otherwise with [`Feature::Blocking`]
//! unsupported.

use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex};

use zeroize::Zeroizing;

#[cfg(target_os = "android")]
mod android;
mod caps;
pub mod conformance;
#[cfg(any(target_os = "windows", test))]
mod credential;
#[cfg(target_os = "linux")]
mod device_proof;
#[cfg(unix)]
mod files;
#[cfg(all(target_os = "linux", feature = "host-keyring"))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(all(target_os = "linux", feature = "host-keyring"))]
pub mod owner_migration;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
pub mod web;
#[cfg(target_os = "windows")]
mod windows;

pub use caps::{Availability, Feature, Unsupported, availability, available};
#[cfg(target_os = "linux")]
#[cfg(target_os = "linux")]
pub use device_proof::arm as arm_device_proof;
#[cfg(all(target_os = "linux", feature = "host-keyring"))]
pub use device_proof::prove as prove_device_caller;

/// Secret bytes: wiped from memory on drop and never printed by `Debug`.
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(Zeroizing<Vec<u8>>);

impl Secret {
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        Self(Zeroizing::new(bytes.into()))
    }

    pub fn expose(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Secret({} bytes)", self.0.len())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Protection {
    OsKeychain,
    /// Sealed in the workspace's vault, as an item the app keeps: synced to the person's other
    /// devices and released only to the app's own process.
    WorkspaceVault,
    /// Encrypted under a key the browser will not export through `WebCrypto`; not a
    /// boundary against a compromised browser or origin.
    BrowserWrapped,
    /// Sealed in owner-only files under a key file beside them: as private as the
    /// machine's disk and the Unix account that owns them.
    LocalFile,
    /// In this process only; gone when it exits.
    Memory,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SecretError {
    Unavailable(String),
    Unsupported(Unsupported),
    Denied,
    /// The key is empty or has control characters.
    InvalidKey,
    Failed(String),
}

impl fmt::Display for SecretError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unavailable(reason) => write!(f, "no secret store: {reason}"),
            Self::Unsupported(unsupported) => unsupported.fmt(f),
            Self::Denied => f.write_str("access to the secret store was refused"),
            Self::InvalidKey => f.write_str("a secret key must be non-empty text"),
            Self::Failed(reason) => f.write_str(reason),
        }
    }
}

impl std::error::Error for SecretError {}

#[derive(Clone, Debug, Default)]
pub struct PutOptions {
    pub label: Option<String>,
}

pub trait SecretBackend: Send + Sync {
    fn protection(&self) -> Protection;
    fn get(&self, app: &str, key: &str) -> Result<Option<Secret>, SecretError>;
    fn put(&self, app: &str, key: &str, value: &[u8], label: &str) -> Result<(), SecretError>;
    fn delete(&self, app: &str, key: &str) -> Result<(), SecretError>;
    /// Every entry this store holds on this machine, as `(app, key)`, whether or not this
    /// process may read its secret: what a migration that moves entries into a vault walks. A
    /// backend that keeps its entries where it cannot name them answers none, and whatever
    /// walks them then moves none, which is safe.
    fn entries(&self) -> Result<Vec<(String, String)>, SecretError> {
        Ok(Vec::new())
    }
    fn probe(&self) -> Result<(), SecretError> {
        Ok(())
    }
}

#[derive(Clone)]
enum Backend {
    Sync(Arc<dyn SecretBackend>),
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    Web,
}

#[derive(Clone)]
pub struct SecretStore {
    app: String,
    backend: Backend,
}

impl fmt::Debug for SecretStore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SecretStore")
            .field("app", &self.app)
            .field("protection", &self.protection())
            .finish_non_exhaustive()
    }
}

impl SecretStore {
    pub fn for_app(app_id: &str) -> Self {
        Self {
            app: app_id.to_owned(),
            backend: THREAD_BACKEND
                .with(|scoped| scoped.borrow().clone())
                .or_else(|| PROCESS_BACKEND.get().cloned())
                .map_or_else(machine_backend, Backend::Sync),
        }
    }

    pub fn memory(app_id: &str) -> Self {
        Self::with_backend(app_id, Arc::new(MemoryBackend::default()))
    }

    pub fn with_backend(app_id: &str, backend: Arc<dyn SecretBackend>) -> Self {
        Self {
            app: app_id.to_owned(),
            backend: Backend::Sync(backend),
        }
    }

    /// Start an immutable write, returning its key only after durable ownership. `None` means
    /// pending: retry the same namespace and bytes on a later turn.
    pub fn seal_blocking(
        &self,
        key: &str,
        value: &[u8],
        options: PutOptions,
    ) -> Result<Option<String>, SecretError> {
        check_key(key)?;
        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
        if matches!(self.backend, Backend::Web) {
            return web::seal_at_blocking(&self.app, key, value);
        }
        self.put_blocking(key, value, options)?;
        Ok(Some(key.to_owned()))
    }

    /// Whether page ownership has asynchronous operations awaiting a retry; native and
    /// host-injected synchronous stores never stage operations here.
    pub fn pending() -> bool {
        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
        {
            web::pending()
        }
        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
        {
            false
        }
    }

    pub fn app_id(&self) -> &str {
        &self.app
    }

    pub fn protection(&self) -> Protection {
        match &self.backend {
            Backend::Sync(backend) => backend.protection(),
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => Protection::BrowserWrapped,
        }
    }

    pub async fn get(&self, key: &str) -> Result<Option<Secret>, SecretError> {
        check_key(key)?;
        match &self.backend {
            Backend::Sync(backend) => {
                let (backend, app, key) = (backend.clone(), self.app.clone(), key.to_owned());
                off_thread(move || backend.get(&app, &key)).await
            }
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => web::get(&self.app, key).await,
        }
    }

    pub async fn put(
        &self,
        key: &str,
        value: &[u8],
        options: PutOptions,
    ) -> Result<(), SecretError> {
        check_key(key)?;
        let label = options
            .label
            .unwrap_or_else(|| format!("{} {key}", self.app));
        match &self.backend {
            Backend::Sync(backend) => {
                let (backend, app, key) = (backend.clone(), self.app.clone(), key.to_owned());
                let value = Zeroizing::new(value.to_vec());
                off_thread(move || backend.put(&app, &key, &value, &label)).await
            }
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => web::put(&self.app, key, value).await,
        }
    }

    pub async fn delete(&self, key: &str) -> Result<(), SecretError> {
        check_key(key)?;
        match &self.backend {
            Backend::Sync(backend) => {
                let (backend, app, key) = (backend.clone(), self.app.clone(), key.to_owned());
                off_thread(move || backend.delete(&app, &key)).await
            }
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => web::delete(&self.app, key).await,
        }
    }

    /// [`get`](Self::get), blocking the calling thread. Desktop code only.
    ///
    /// # Errors
    /// As `get`, and [`Feature::Blocking`] unsupported on the web.
    pub fn get_blocking(&self, key: &str) -> Result<Option<Secret>, SecretError> {
        check_key(key)?;
        self.sync()?.get(&self.app, key)
    }

    /// [`put`](Self::put), blocking the calling thread. Desktop code only.
    ///
    /// # Errors
    /// As `put`, and [`Feature::Blocking`] unsupported on the web.
    pub fn put_blocking(
        &self,
        key: &str,
        value: &[u8],
        options: PutOptions,
    ) -> Result<(), SecretError> {
        check_key(key)?;
        let label = options
            .label
            .unwrap_or_else(|| format!("{} {key}", self.app));
        self.sync()?.put(&self.app, key, value, &label)
    }

    /// [`delete`](Self::delete), blocking the calling thread. Desktop code
    /// only.
    ///
    /// # Errors
    /// As `delete`, and [`Feature::Blocking`] unsupported on the web.
    pub fn delete_blocking(&self, key: &str) -> Result<(), SecretError> {
        check_key(key)?;
        self.sync()?.delete(&self.app, key)
    }

    /// Whether the store answers on this session, blocking the calling
    /// thread. The web store always answers.
    pub fn probe_blocking(&self) -> Result<(), SecretError> {
        match &self.backend {
            Backend::Sync(backend) => backend.probe(),
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => Ok(()),
        }
    }

    /// Every entry the platform's store holds on this machine, as `(app, key)`, whether or not
    /// this process may read its secret. The store's own app does not narrow the answer: the
    /// platform's store is shared, and a migration that moves its entries into a workspace vault
    /// walks it for every app. Nothing here reads a secret.
    ///
    /// # Errors
    /// The store could not be asked. On the web there is no such store to walk: the answer is
    /// none.
    pub fn entries_blocking(&self) -> Result<Vec<(String, String)>, SecretError> {
        match &self.backend {
            Backend::Sync(backend) => backend.entries(),
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => Ok(Vec::new()),
        }
    }

    #[cfg_attr(
        not(all(target_arch = "wasm32", target_os = "unknown")),
        allow(
            clippy::unnecessary_wraps,
            reason = "the web store has no synchronous access"
        )
    )]
    fn sync(&self) -> Result<&dyn SecretBackend, SecretError> {
        match &self.backend {
            Backend::Sync(backend) => Ok(&**backend),
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web if web::mirrored() => Ok(&web::MirrorBackend),
            #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
            Backend::Web => Err(SecretError::Unsupported(Unsupported::of(Feature::Blocking))),
        }
    }
}

impl SecretStore {
    /// The secret one item of a document needs for `purpose`: a database
    /// profile's password, a connection's SSH passphrase, an account's
    /// one-time-password seed. The document names the item by its id and
    /// never holds the secret; the secret stays in this store on this
    /// device.
    ///
    /// `purpose` is one of the app's own fixed names and contains no `/`;
    /// `item` is the item's id in the document.
    #[must_use]
    pub fn item(&self, purpose: &str, item: &str) -> ItemSecret {
        debug_assert!(
            !purpose.is_empty() && !purpose.contains('/'),
            "an item secret's purpose is a plain name: {purpose:?}"
        );
        ItemSecret {
            store: self.clone(),
            key: format!("{purpose}/{item}"),
            label: format!("{} {purpose} for {item}", self.app),
        }
    }
}

#[derive(Clone, Debug)]
pub struct ItemSecret {
    store: SecretStore,
    key: String,
    label: String,
}

impl ItemSecret {
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    pub async fn get(&self) -> Result<Option<Secret>, SecretError> {
        self.store.get(&self.key).await
    }

    pub async fn put(&self, value: &[u8]) -> Result<(), SecretError> {
        let options = PutOptions {
            label: Some(self.label.clone()),
        };
        self.store.put(&self.key, value, options).await
    }

    pub async fn delete(&self) -> Result<(), SecretError> {
        self.store.delete(&self.key).await
    }

    /// [`get`](Self::get), blocking the calling thread. Desktop code only.
    ///
    /// # Errors
    /// As `get`, and [`Feature::Blocking`] unsupported on the web.
    pub fn get_blocking(&self) -> Result<Option<Secret>, SecretError> {
        self.store.get_blocking(&self.key)
    }

    /// [`put`](Self::put), blocking the calling thread. Desktop code only.
    ///
    /// # Errors
    /// As `put`, and [`Feature::Blocking`] unsupported on the web.
    pub fn put_blocking(&self, value: &[u8]) -> Result<(), SecretError> {
        let options = PutOptions {
            label: Some(self.label.clone()),
        };
        self.store.put_blocking(&self.key, value, options)
    }

    /// [`delete`](Self::delete), blocking the calling thread. Desktop code
    /// only.
    ///
    /// # Errors
    /// As `delete`, and [`Feature::Blocking`] unsupported on the web.
    pub fn delete_blocking(&self) -> Result<(), SecretError> {
        self.store.delete_blocking(&self.key)
    }

    #[must_use]
    pub fn present_blocking(&self) -> bool {
        matches!(self.get_blocking(), Ok(Some(_)))
    }
}

/// Whether what this build puts in the system store stays readable by later builds of
/// the same program. On macOS only a Developer ID signature does; an ad-hoc or dev
/// signature's items are readable by that build alone.
#[must_use]
pub fn items_outlive_rebuilds() -> bool {
    #[cfg(target_os = "macos")]
    return macos::developer_id_signed();
    #[cfg(not(target_os = "macos"))]
    true
}

static PROCESS_BACKEND: std::sync::OnceLock<Arc<dyn SecretBackend>> = std::sync::OnceLock::new();

/// From now on, every [`SecretStore::for_app`] in this process shares one in-memory store
/// and never reaches the platform's, which may prompt and holds the user's real
/// secrets.
pub fn keep_in_memory_for_process() {
    PROCESS_BACKEND.get_or_init(|| Arc::new(MemoryBackend::default()));
}

thread_local! {
    static THREAD_BACKEND: std::cell::RefCell<Option<Arc<dyn SecretBackend>>> =
        const { std::cell::RefCell::new(None) };
}

/// Keeps a thread's stores in one backend until it is dropped: see
/// [`scope_thread`].
#[must_use = "the scope ends when the guard is dropped"]
pub struct SecretsScope {
    earlier: Option<Arc<dyn SecretBackend>>,
}

impl Drop for SecretsScope {
    fn drop(&mut self) {
        THREAD_BACKEND.with(|scoped| *scoped.borrow_mut() = self.earlier.take());
    }
}

/// From now until the guard drops, every [`SecretStore::for_app`] this thread creates
/// keeps its secrets in `backend`, never the platform's store.
pub fn scope_thread(backend: Arc<dyn SecretBackend>) -> SecretsScope {
    let earlier = THREAD_BACKEND.with(|scoped| scoped.borrow_mut().replace(backend));
    SecretsScope { earlier }
}

pub fn unscoped<R>(work: impl FnOnce() -> R) -> R {
    let _scope = SecretsScope {
        earlier: THREAD_BACKEND.with(|scoped| scoped.borrow_mut().take()),
    };
    work()
}

#[must_use]
pub fn memory_backend() -> Arc<dyn SecretBackend> {
    Arc::new(MemoryBackend::default())
}

fn check_key(key: &str) -> Result<(), SecretError> {
    if key.is_empty() || key.chars().any(char::is_control) {
        Err(SecretError::InvalidKey)
    } else {
        Ok(())
    }
}

/// Run a blocking store call on the app runtime's blocking pool, or inline
/// where there are no threads (an in-memory store in a browser).
async fn off_thread<T: Send + 'static>(
    call: impl FnOnce() -> Result<T, SecretError> + Send + 'static,
) -> Result<T, SecretError> {
    if matches!(
        tilo_rt::availability(tilo_rt::Feature::Threads),
        tilo_rt::Availability::Unsupported(_)
    ) {
        return call();
    }
    tilo_rt::app()
        .spawn_blocking(call)
        .await
        .unwrap_or_else(|error| {
            Err(SecretError::Failed(format!(
                "secret store task failed: {error}"
            )))
        })
}

pub const SECRETS_DIR_ENV: &str = "TILO_SECRETS_DIR";

/// The sealed file stores this process opened, each by the directory it seals.
#[cfg(unix)]
type FileStores =
    std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, Arc<dyn SecretBackend>>>;

fn machine_backend() -> Backend {
    #[cfg(unix)]
    if let Some(dir) = std::env::var_os(SECRETS_DIR_ENV).filter(|dir| !dir.is_empty()) {
        // The store is the directory's, and a process can meet more than one name: a test suite
        // gives each test its own home and names its store while that test runs. Opened once
        // per directory, so a name this process meets later opens its own store rather than
        // borrowing the first one's, whose directory may no longer be there.
        static FILES: std::sync::OnceLock<FileStores> = std::sync::OnceLock::new();
        let stores = FILES.get_or_init(FileStores::default);
        let dir = std::path::PathBuf::from(dir);
        let opened = {
            let files = stores
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            files.get(&dir).cloned()
        };
        if let Some(store) = opened {
            return Backend::Sync(store);
        }
        let store = match files::FileStore::open(&dir) {
            Ok(store) => Arc::new(store) as Arc<dyn SecretBackend>,
            Err(error) => return Backend::Sync(Arc::new(Refused(error))),
        };
        stores
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(dir, store.clone());
        return Backend::Sync(store);
    }
    system_backend()
}

/// A configured store that could not be opened: every call says why,
/// rather than falling back to another store.
#[cfg(unix)]
struct Refused(SecretError);

#[cfg(unix)]
impl SecretBackend for Refused {
    fn protection(&self) -> Protection {
        Protection::LocalFile
    }
    fn get(&self, _app: &str, _key: &str) -> Result<Option<Secret>, SecretError> {
        Err(self.0.clone())
    }
    fn put(&self, _app: &str, _key: &str, _value: &[u8], _label: &str) -> Result<(), SecretError> {
        Err(self.0.clone())
    }
    fn delete(&self, _app: &str, _key: &str) -> Result<(), SecretError> {
        Err(self.0.clone())
    }
    fn probe(&self) -> Result<(), SecretError> {
        Err(self.0.clone())
    }
}

/// A host process asks the operating system's Secret Service, which only a host build links
/// (`host-keyring`). An app process keeps its secrets in the workspace's vault, which its SDK
/// hands it as its store ([`SecretStore::with_backend`]); a build that links neither answers
/// that it has no store rather than writing a secret somewhere nobody sealed.
#[cfg(target_os = "linux")]
fn system_backend() -> Backend {
    #[cfg(feature = "host-keyring")]
    {
        Backend::Sync(Arc::new(linux::SecretService))
    }
    #[cfg(not(feature = "host-keyring"))]
    {
        Backend::Sync(Arc::new(NoStore))
    }
}

/// The store of a build that links neither the workspace's connection nor a keychain: every call
/// says so instead of writing a secret where nothing sealed it.
#[cfg(all(target_os = "linux", not(feature = "host-keyring")))]
struct NoStore;

#[cfg(all(target_os = "linux", not(feature = "host-keyring")))]
impl SecretBackend for NoStore {
    fn protection(&self) -> Protection {
        Protection::Memory
    }
    fn get(&self, _app: &str, _key: &str) -> Result<Option<Secret>, SecretError> {
        Err(SecretError::Unavailable(NO_STORE.to_owned()))
    }
    fn put(&self, _app: &str, _key: &str, _value: &[u8], _label: &str) -> Result<(), SecretError> {
        Err(SecretError::Unavailable(NO_STORE.to_owned()))
    }
    fn delete(&self, _app: &str, _key: &str) -> Result<(), SecretError> {
        Err(SecretError::Unavailable(NO_STORE.to_owned()))
    }
}

#[cfg(all(target_os = "linux", not(feature = "host-keyring")))]
const NO_STORE: &str =
    "this process holds no connection to its daemon and this build links no keychain";

/// A debug build inside `tools/with-test-environment.sh` (which cargo runs
/// every test binary in) never reaches the user's login Keychain, just as the
/// environment gives Linux tests no Secret Service. `TILO_SECRETS_SYSTEM_TEST`
/// is the explicit request to test the real store.
#[cfg(target_os = "macos")]
fn system_backend() -> Backend {
    if cfg!(debug_assertions)
        && std::env::var_os("TILO_TEST_ENVIRONMENT").is_some()
        && std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_none()
    {
        return Backend::Sync(Arc::new(UnsupportedBackend(
            "the test environment has no login Keychain",
        )));
    }
    Backend::Sync(Arc::new(macos::Keychain::new()))
}

/// As on macOS, a debug test build in the test environment never writes the
/// user's own Credential Manager unless `TILO_SECRETS_SYSTEM_TEST` asks.
#[cfg(target_os = "windows")]
fn system_backend() -> Backend {
    if cfg!(debug_assertions)
        && std::env::var_os("TILO_TEST_ENVIRONMENT").is_some()
        && std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_none()
    {
        return Backend::Sync(Arc::new(UnsupportedBackend(
            "the test environment has no Credential Manager",
        )));
    }
    Backend::Sync(Arc::new(windows::CredentialManager))
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn system_backend() -> Backend {
    Backend::Web
}

/// The app's sealed files, under a store key the Android Keystore wraps.
#[cfg(target_os = "android")]
fn system_backend() -> Backend {
    static KEYSTORE: std::sync::OnceLock<Arc<dyn SecretBackend>> = std::sync::OnceLock::new();
    Backend::Sync(
        KEYSTORE
            .get_or_init(|| Arc::new(android::KeystoreStore::default()))
            .clone(),
    )
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_os = "macos",
    target_os = "windows",
    all(target_arch = "wasm32", target_os = "unknown")
)))]
fn system_backend() -> Backend {
    Backend::Sync(Arc::new(UnsupportedBackend(
        "this platform has no secret store backend",
    )))
}

/// No secret store, and why: a target without one, or a macOS or Windows
/// test environment.
#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    all(target_arch = "wasm32", target_os = "unknown")
)))]
struct UnsupportedBackend(&'static str);

#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    all(target_arch = "wasm32", target_os = "unknown")
)))]
impl SecretBackend for UnsupportedBackend {
    fn protection(&self) -> Protection {
        Protection::Memory
    }
    fn get(&self, _app: &str, _key: &str) -> Result<Option<Secret>, SecretError> {
        Err(SecretError::Unavailable(self.0.into()))
    }
    fn put(&self, _app: &str, _key: &str, _value: &[u8], _label: &str) -> Result<(), SecretError> {
        self.get("", "").map(drop)
    }
    fn delete(&self, _app: &str, _key: &str) -> Result<(), SecretError> {
        self.get("", "").map(drop)
    }
    fn probe(&self) -> Result<(), SecretError> {
        self.get("", "").map(drop)
    }
}

#[derive(Default)]
struct MemoryBackend {
    secrets: Mutex<HashMap<(String, String), Secret>>,
}

impl SecretBackend for MemoryBackend {
    fn protection(&self) -> Protection {
        Protection::Memory
    }

    fn get(&self, app: &str, key: &str) -> Result<Option<Secret>, SecretError> {
        let secrets = self
            .secrets
            .lock()
            .map_err(|_| SecretError::Failed("poisoned".into()))?;
        Ok(secrets.get(&(app.to_owned(), key.to_owned())).cloned())
    }

    fn put(&self, app: &str, key: &str, value: &[u8], _label: &str) -> Result<(), SecretError> {
        self.secrets
            .lock()
            .map_err(|_| SecretError::Failed("poisoned".into()))?
            .insert((app.to_owned(), key.to_owned()), Secret::new(value));
        Ok(())
    }

    fn delete(&self, app: &str, key: &str) -> Result<(), SecretError> {
        self.secrets
            .lock()
            .map_err(|_| SecretError::Failed("poisoned".into()))?
            .remove(&(app.to_owned(), key.to_owned()));
        Ok(())
    }

    fn entries(&self) -> Result<Vec<(String, String)>, SecretError> {
        Ok(self
            .secrets
            .lock()
            .map_err(|_| SecretError::Failed("poisoned".into()))?
            .keys()
            .cloned()
            .collect())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test(flavor = "current_thread")]
    async fn the_memory_store_conforms() {
        conformance::check_store(&SecretStore::memory("so.tilo.secrets-test")).await;
    }

    tilo_test_env::scenario! {
        fn a_store_over_a_given_backend_keeps_each_apps_secrets_and_never_prints_them;

        phase immutable_seals_acknowledge_injected_storage_and_validate_keys;
        {
            let store = SecretStore::memory("so.tilo.secrets-test");
            let key = "credentials/first";
            assert_eq!(
                store
                    .seal_blocking(key, b"private", PutOptions::default())
                    .unwrap(),
                Some(key.into())
            );
            assert_eq!(
                store.get_blocking(key).unwrap().unwrap().expose(),
                b"private"
            );
            assert!(
                store
                    .seal_blocking("", b"private", PutOptions::default())
                    .is_err()
            );
        }

        phase the_memory_store_conforms_blocking;
        {
            conformance::check_store_blocking(&SecretStore::memory("so.tilo.secrets-test"));
        }

        phase apps_do_not_see_each_others_secrets;
        {
            let shared: Arc<dyn SecretBackend> = Arc::new(MemoryBackend::default());
            let a = SecretStore::with_backend("so.tilo.a", shared.clone());
            let b = SecretStore::with_backend("so.tilo.b", shared);
            a.put_blocking("token", b"a's", PutOptions::default())
                .unwrap();
            assert_eq!(b.get_blocking("token").unwrap(), None);
            assert_eq!(a.get_blocking("token").unwrap().unwrap().expose(), b"a's");
        }

        phase item_secrets_are_kept_per_purpose_and_item;
        {
            let store = SecretStore::memory("so.tilo.db-client");
            let alpha = store.item("password", "profile-alpha");
            let beta = store.item("password", "profile-beta");
            let alpha_key = store.item("key-passphrase", "profile-alpha");
            assert!(!alpha.present_blocking());
            alpha.put_blocking(b"hunter2").unwrap();
            assert!(alpha.present_blocking());
            assert!(!beta.present_blocking());
            assert!(!alpha_key.present_blocking());
            assert_eq!(alpha.key(), "password/profile-alpha");
            assert_eq!(
                store
                    .get_blocking("password/profile-alpha")
                    .unwrap()
                    .unwrap()
                    .expose(),
                b"hunter2"
            );
            alpha.delete_blocking().unwrap();
            assert_eq!(alpha.get_blocking().unwrap(), None);
        }

        phase secrets_never_print;
        {
            assert_eq!(
                format!("{:?}", Secret::new(b"hunter2".to_vec())),
                "Secret(7 bytes)"
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn tests_never_reach_the_login_keychain() {
        assert!(
            std::env::var_os("TILO_TEST_ENVIRONMENT").is_some(),
            "run tests through cargo, whose runner (tools/cargo-runner.sh) starts \
             them in tools/with-test-environment.sh"
        );
        if std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_some() {
            return;
        }
        let store = SecretStore::for_app("so.tilo.secrets-isolation");
        assert!(matches!(
            store.put_blocking("probe", b"x", PutOptions::default()),
            Err(SecretError::Unavailable(_))
        ));
        assert!(matches!(
            store.probe_blocking(),
            Err(SecretError::Unavailable(_))
        ));
    }

    #[test]
    fn the_system_store_conforms_when_asked() {
        if std::env::var_os("TILO_SECRETS_SYSTEM_TEST").is_none() {
            return;
        }
        let store = SecretStore::for_app("so.tilo.secrets-conformance");
        store.probe_blocking().unwrap();
        conformance::check_store_blocking(&store);
    }
}