Skip to main content

obsidianlog_cli/
keystore.rs

1//! Local credential storage (ADR-0015): the archive's AES-256 encryption
2//! key, and — when the Sia backend is configured — the indexd application
3//! key, stored together as one [`CredentialBundle`].
4//!
5//! Generated/collected once during `obsidianlog init` and never
6//! transmitted. Stored in the OS keychain (Keychain on macOS, Credential
7//! Manager on Windows, Secret Service on Linux) via the `keyring` crate, or
8//! — when the keychain is genuinely unreachable — a `0600` local file. This
9//! module is the only place credentials are read or written.
10//!
11//! On macOS specifically, creating a fresh bundle uses a direct, "create
12//! only" write (see [`BundleStore::create`]) rather than the generic
13//! `keyring` crate's check-then-write pattern, so a fresh `obsidianlog
14//! init` costs exactly one keychain authorization, not two. See ADR-0015
15//! for the full design and the reasoning behind it.
16
17use std::path::PathBuf;
18
19use anyhow::{Context, Result};
20use serde::{Deserialize, Serialize};
21
22/// Service name used to namespace ObsidianLog entries in the OS keychain.
23pub const KEYRING_SERVICE: &str = "obsidianlog";
24/// Keychain account / file name for the bundled credential.
25pub const CREDENTIAL_BUNDLE_ACCOUNT: &str = "credentials";
26
27/// The encryption key and, if the Sia backend is configured, the Sia app
28/// key — stored together as one credential rather than as two independent
29/// keychain items (ADR-0015).
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct CredentialBundle {
32    pub encryption_key: [u8; 32],
33    pub sia_app_key: Option<[u8; 32]>,
34}
35
36impl CredentialBundle {
37    fn to_json(&self) -> String {
38        serde_json::to_string(self).expect("CredentialBundle always serializes")
39    }
40
41    fn from_json(text: &str) -> Result<Self> {
42        serde_json::from_str(text).context("the stored credential bundle is not valid")
43    }
44}
45
46/// The result of [`BundleStore::create`]: whether a new bundle was written,
47/// or one was already there and preserved untouched.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum BundleCreateOutcome {
50    Created,
51    AlreadyExists,
52}
53
54/// Where the bundled credential lives. Implemented by [`KeyringBundleStore`]
55/// (the OS keychain) and [`FileBundleStore`] (a `0600` file); tests use
56/// [`MockBundleStore`] so they never touch the real keychain or filesystem.
57pub trait BundleStore {
58    /// Read the stored bundle, or `None` if nothing is stored yet.
59    fn read(&self) -> Result<Option<CredentialBundle>>;
60
61    /// Unconditionally persist `bundle`, overwriting any existing one. Used
62    /// for explicit rotation and for a repair that merges in new credential
63    /// material — both read first, then write, deliberately never trying to
64    /// collapse that into one call (ADR-0015).
65    fn write(&self, bundle: &CredentialBundle) -> Result<()>;
66
67    /// Write `bundle` only if nothing is stored yet. Returns
68    /// [`BundleCreateOutcome::AlreadyExists`], leaving the existing bundle
69    /// untouched, if one is already present — never overwrites.
70    fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome>;
71
72    /// A short, human-readable description of where the bundle lives (e.g.
73    /// "the OS keychain" or a file path), for prompts and confirmations.
74    fn describe(&self) -> String;
75}
76
77/// Stores the bundle in the OS keychain via the `keyring` crate.
78pub struct KeyringBundleStore {
79    service: String,
80    account: String,
81}
82
83impl KeyringBundleStore {
84    pub fn new() -> Self {
85        Self {
86            service: KEYRING_SERVICE.to_string(),
87            account: CREDENTIAL_BUNDLE_ACCOUNT.to_string(),
88        }
89    }
90
91    fn entry(&self) -> Result<keyring::Entry> {
92        keyring::Entry::new(&self.service, &self.account).context("opening the OS keychain entry")
93    }
94}
95
96impl Default for KeyringBundleStore {
97    fn default() -> Self {
98        Self::new()
99    }
100}
101
102impl BundleStore for KeyringBundleStore {
103    fn read(&self) -> Result<Option<CredentialBundle>> {
104        match self.entry()?.get_password() {
105            Ok(text) => Ok(Some(CredentialBundle::from_json(&text)?)),
106            Err(keyring::Error::NoEntry) => Ok(None),
107            Err(e) => Err(e).context("reading the credential bundle from the OS keychain"),
108        }
109    }
110
111    fn write(&self, bundle: &CredentialBundle) -> Result<()> {
112        self.entry()?
113            .set_password(&bundle.to_json())
114            .context("writing the credential bundle to the OS keychain")
115    }
116
117    #[cfg(target_os = "macos")]
118    fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome> {
119        macos::create_only(&self.service, &self.account, bundle.to_json().as_bytes())
120    }
121
122    /// Windows and Linux have different credential-store write semantics
123    /// and no evidence of the same multi-prompt problem macOS has, so they
124    /// keep the generic check-then-write pattern here (ADR-0015) — still
125    /// one item instead of two, just without a specific one-call claim.
126    #[cfg(not(target_os = "macos"))]
127    fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome> {
128        if self.read()?.is_some() {
129            return Ok(BundleCreateOutcome::AlreadyExists);
130        }
131        self.write(bundle)?;
132        Ok(BundleCreateOutcome::Created)
133    }
134
135    fn describe(&self) -> String {
136        "the OS keychain".to_string()
137    }
138}
139
140/// The macOS-specific create-only path (ADR-0015): calls the lower-level
141/// keychain API directly instead of the `keyring` crate's `set_password`,
142/// which always does its own internal existence check before writing.
143#[cfg(target_os = "macos")]
144mod macos {
145    use super::{BundleCreateOutcome, Result};
146    use anyhow::Context;
147    use security_framework::os::macos::keychain::SecKeychain;
148
149    /// `errSecDuplicateItem` — the item already exists.
150    const ERR_SEC_DUPLICATE_ITEM: i32 = -25299;
151
152    pub(super) fn create_only(
153        service: &str,
154        account: &str,
155        secret: &[u8],
156    ) -> Result<BundleCreateOutcome> {
157        let keychain = SecKeychain::default().context("opening the default macOS keychain")?;
158        match keychain.add_generic_password(service, account, secret) {
159            Ok(()) => Ok(BundleCreateOutcome::Created),
160            Err(e) if e.code() == ERR_SEC_DUPLICATE_ITEM => Ok(BundleCreateOutcome::AlreadyExists),
161            Err(e) => Err(anyhow::Error::from(e))
162                .context("creating the credential bundle in the OS keychain"),
163        }
164    }
165}
166
167/// Stores the bundle as JSON in a file with `0600` permissions (best-effort
168/// on platforms without POSIX permission bits) — the fallback when the OS
169/// keychain is genuinely unreachable.
170pub struct FileBundleStore {
171    path: PathBuf,
172}
173
174impl FileBundleStore {
175    pub fn new(path: impl Into<PathBuf>) -> Self {
176        Self { path: path.into() }
177    }
178
179    /// The default fallback location: `~/.obsidianlog/credentials.json`,
180    /// matching this repo's `.gitignore` (`/.obsidianlog`).
181    pub fn default_path() -> Result<PathBuf> {
182        let home = std::env::var("HOME")
183            .context("HOME is not set; cannot resolve the default secrets path")?;
184        Ok(PathBuf::from(home)
185            .join(".obsidianlog")
186            .join("credentials.json"))
187    }
188
189    fn ensure_parent(&self) -> Result<()> {
190        if let Some(parent) = self.path.parent() {
191            std::fs::create_dir_all(parent)
192                .with_context(|| format!("creating secrets directory {}", parent.display()))?;
193        }
194        Ok(())
195    }
196
197    #[cfg(unix)]
198    fn restrict_permissions(&self) -> Result<()> {
199        use std::os::unix::fs::PermissionsExt;
200        std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600))
201            .with_context(|| format!("setting permissions on {}", self.path.display()))
202    }
203
204    #[cfg(not(unix))]
205    fn restrict_permissions(&self) -> Result<()> {
206        Ok(())
207    }
208}
209
210impl BundleStore for FileBundleStore {
211    fn read(&self) -> Result<Option<CredentialBundle>> {
212        match std::fs::read_to_string(&self.path) {
213            Ok(text) => Ok(Some(CredentialBundle::from_json(&text)?)),
214            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
215            Err(e) => Err(e)
216                .with_context(|| format!("reading credential file at {}", self.path.display())),
217        }
218    }
219
220    fn write(&self, bundle: &CredentialBundle) -> Result<()> {
221        self.ensure_parent()?;
222        std::fs::write(&self.path, bundle.to_json())
223            .with_context(|| format!("writing credential file at {}", self.path.display()))?;
224        self.restrict_permissions()
225    }
226
227    fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome> {
228        self.ensure_parent()?;
229        use std::io::Write;
230        match std::fs::OpenOptions::new()
231            .write(true)
232            .create_new(true)
233            .open(&self.path)
234        {
235            Ok(mut file) => {
236                file.write_all(bundle.to_json().as_bytes())
237                    .with_context(|| {
238                        format!("writing credential file at {}", self.path.display())
239                    })?;
240                drop(file);
241                self.restrict_permissions()?;
242                Ok(BundleCreateOutcome::Created)
243            }
244            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
245                Ok(BundleCreateOutcome::AlreadyExists)
246            }
247            Err(e) => Err(e)
248                .with_context(|| format!("creating credential file at {}", self.path.display())),
249        }
250    }
251
252    fn describe(&self) -> String {
253        self.path.display().to_string()
254    }
255}
256
257/// Whether `err` (from a [`BundleStore`] call against [`KeyringBundleStore`])
258/// indicates the OS keychain itself is genuinely unreachable, as opposed to
259/// a user-driven cancellation/denial or any other failure that should
260/// surface rather than silently trigger the file-store fallback.
261///
262/// Two variants indicate genuine unavailability: `NoStorageAccess` (a store
263/// exists but can't be reached — e.g. locked) and `NoDefaultStore` (no
264/// store could be registered at all — e.g. a headless Linux environment
265/// with no D-Bus Secret Service running, such as a bare CI runner or many
266/// minimal containers).
267fn is_keychain_unavailable(err: &anyhow::Error) -> bool {
268    matches!(
269        err.downcast_ref::<keyring::Error>(),
270        Some(keyring::Error::NoStorageAccess(_) | keyring::Error::NoDefaultStore)
271    )
272}
273
274/// Run `op` against the OS keychain bundle store; if that fails
275/// specifically because the keychain itself is unreachable, retry the same
276/// operation against the file-backed fallback instead. Any other error —
277/// notably the user cancelling or denying an authorization prompt —
278/// propagates rather than silently redirecting to a file. Returns the
279/// result alongside a description of wherever it ended up, for user-facing
280/// messages.
281fn with_bundle_fallback<T>(op: impl Fn(&dyn BundleStore) -> Result<T>) -> Result<(T, String)> {
282    let keyring = KeyringBundleStore::new();
283    match op(&keyring) {
284        Ok(v) => Ok((v, keyring.describe())),
285        Err(e) if is_keychain_unavailable(&e) => {
286            let file = FileBundleStore::new(FileBundleStore::default_path()?);
287            let v = op(&file)?;
288            Ok((v, file.describe()))
289        }
290        Err(e) => Err(e),
291    }
292}
293
294/// Read the stored credential bundle, if any, from the OS keychain (or the
295/// file fallback). Returns `None` when nothing has been stored yet.
296pub fn read_bundle() -> Result<(Option<CredentialBundle>, String)> {
297    with_bundle_fallback(|store| store.read())
298}
299
300/// Load the stored credential bundle, erroring clearly if `obsidianlog
301/// init` hasn't been run yet. Used by `serve`/`query`/backend resolution.
302pub fn load_credential_bundle() -> Result<CredentialBundle> {
303    let (bundle, _) = read_bundle()?;
304    bundle.ok_or_else(|| anyhow::anyhow!("no credentials found — run `obsidianlog init` first"))
305}
306
307/// Create the bundle only if nothing is stored yet — the fresh-install and
308/// pure-reuse-repair path (ADR-0015): one call, one keychain prompt.
309pub fn create_bundle(bundle: &CredentialBundle) -> Result<(BundleCreateOutcome, String)> {
310    with_bundle_fallback(|store| store.create(bundle))
311}
312
313/// Unconditionally overwrite the stored bundle — used for explicit
314/// rotation and for a repair that merges in new credential material, both
315/// of which read the existing bundle first (ADR-0015).
316pub fn write_bundle(bundle: &CredentialBundle) -> Result<String> {
317    with_bundle_fallback(|store| store.write(bundle)).map(|(_, desc)| desc)
318}
319
320/// The production [`BundleStore`]: adapts the free-function keychain-with-
321/// file-fallback behavior above into a single implementation, so `init`'s
322/// core logic can be written against one [`BundleStore`] regardless of
323/// which concrete backend a given call ends up using. Tracks the
324/// description of whichever backend last succeeded, for [`describe`].
325///
326/// [`describe`]: BundleStore::describe
327pub struct DefaultBundleStore {
328    last_location: std::cell::RefCell<String>,
329}
330
331impl DefaultBundleStore {
332    pub fn new() -> Self {
333        Self {
334            last_location: std::cell::RefCell::new("the OS keychain".to_string()),
335        }
336    }
337}
338
339impl Default for DefaultBundleStore {
340    fn default() -> Self {
341        Self::new()
342    }
343}
344
345impl BundleStore for DefaultBundleStore {
346    fn read(&self) -> Result<Option<CredentialBundle>> {
347        let (v, location) = with_bundle_fallback(|store| store.read())?;
348        *self.last_location.borrow_mut() = location;
349        Ok(v)
350    }
351
352    fn write(&self, bundle: &CredentialBundle) -> Result<()> {
353        let (_, location) = with_bundle_fallback(|store| store.write(bundle))?;
354        *self.last_location.borrow_mut() = location;
355        Ok(())
356    }
357
358    fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome> {
359        let (v, location) = with_bundle_fallback(|store| store.create(bundle))?;
360        *self.last_location.borrow_mut() = location;
361        Ok(v)
362    }
363
364    fn describe(&self) -> String {
365        self.last_location.borrow().clone()
366    }
367}
368
369/// An in-memory [`BundleStore`] for tests, so they never touch the real OS
370/// keychain or filesystem. Also counts calls to each method, so tests can
371/// assert exactly how many keychain round-trips a code path costs — not
372/// just that the end state is correct.
373#[cfg(test)]
374pub struct MockBundleStore {
375    bundle: std::sync::Mutex<Option<CredentialBundle>>,
376    read_calls: std::sync::atomic::AtomicUsize,
377    write_calls: std::sync::atomic::AtomicUsize,
378    create_calls: std::sync::atomic::AtomicUsize,
379}
380
381#[cfg(test)]
382impl MockBundleStore {
383    pub fn empty() -> Self {
384        Self {
385            bundle: std::sync::Mutex::new(None),
386            read_calls: std::sync::atomic::AtomicUsize::new(0),
387            write_calls: std::sync::atomic::AtomicUsize::new(0),
388            create_calls: std::sync::atomic::AtomicUsize::new(0),
389        }
390    }
391
392    pub fn seeded(bundle: CredentialBundle) -> Self {
393        Self {
394            bundle: std::sync::Mutex::new(Some(bundle)),
395            read_calls: std::sync::atomic::AtomicUsize::new(0),
396            write_calls: std::sync::atomic::AtomicUsize::new(0),
397            create_calls: std::sync::atomic::AtomicUsize::new(0),
398        }
399    }
400
401    pub fn read_calls(&self) -> usize {
402        self.read_calls.load(std::sync::atomic::Ordering::SeqCst)
403    }
404
405    pub fn write_calls(&self) -> usize {
406        self.write_calls.load(std::sync::atomic::Ordering::SeqCst)
407    }
408
409    pub fn create_calls(&self) -> usize {
410        self.create_calls.load(std::sync::atomic::Ordering::SeqCst)
411    }
412}
413
414#[cfg(test)]
415impl Default for MockBundleStore {
416    fn default() -> Self {
417        Self::empty()
418    }
419}
420
421#[cfg(test)]
422impl BundleStore for MockBundleStore {
423    fn read(&self) -> Result<Option<CredentialBundle>> {
424        self.read_calls
425            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
426        Ok(self.bundle.lock().unwrap().clone())
427    }
428
429    fn write(&self, bundle: &CredentialBundle) -> Result<()> {
430        self.write_calls
431            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
432        *self.bundle.lock().unwrap() = Some(bundle.clone());
433        Ok(())
434    }
435
436    fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome> {
437        self.create_calls
438            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
439        let mut guard = self.bundle.lock().unwrap();
440        if guard.is_some() {
441            return Ok(BundleCreateOutcome::AlreadyExists);
442        }
443        *guard = Some(bundle.clone());
444        Ok(BundleCreateOutcome::Created)
445    }
446
447    fn describe(&self) -> String {
448        "a mock bundle store (tests only)".to_string()
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    fn bundle(seed: u8) -> CredentialBundle {
457        CredentialBundle {
458            encryption_key: [seed; 32],
459            sia_app_key: None,
460        }
461    }
462
463    fn platform_error() -> Box<dyn std::error::Error + Send + Sync> {
464        Box::new(std::io::Error::other("test platform error"))
465    }
466
467    #[test]
468    fn no_storage_access_is_treated_as_keychain_unavailable() {
469        let err = anyhow::Error::new(keyring::Error::NoStorageAccess(platform_error()));
470        assert!(is_keychain_unavailable(&err));
471    }
472
473    /// A headless Linux environment with no D-Bus Secret Service running
474    /// (a bare CI runner, many minimal containers) never registers a
475    /// default credential store at all, so `keyring` returns this distinct
476    /// variant rather than `NoStorageAccess` — the fallback must still
477    /// trigger for it. Regression: broke the `demo.yml` CI pipeline, and
478    /// would break real headless-Linux `obsidianlog init` the same way.
479    #[test]
480    fn no_default_store_is_treated_as_keychain_unavailable() {
481        let err = anyhow::Error::new(keyring::Error::NoDefaultStore);
482        assert!(is_keychain_unavailable(&err));
483    }
484
485    #[test]
486    fn platform_failure_is_not_treated_as_keychain_unavailable() {
487        // Covers cancellation/denial, which the keyring crate also surfaces
488        // as `PlatformFailure` — this must NOT silently fall back to the
489        // file store, it must surface as a real error.
490        let err = anyhow::Error::new(keyring::Error::PlatformFailure(platform_error()));
491        assert!(!is_keychain_unavailable(&err));
492    }
493
494    #[test]
495    fn no_entry_is_not_treated_as_keychain_unavailable() {
496        let err = anyhow::Error::new(keyring::Error::NoEntry);
497        assert!(!is_keychain_unavailable(&err));
498    }
499
500    #[test]
501    fn an_unrelated_error_is_not_treated_as_keychain_unavailable() {
502        let err = anyhow::anyhow!("some unrelated error");
503        assert!(!is_keychain_unavailable(&err));
504    }
505
506    #[test]
507    fn credential_bundle_round_trips_through_json() {
508        let original = CredentialBundle {
509            encryption_key: [0x42; 32],
510            sia_app_key: Some([0x24; 32]),
511        };
512        let parsed = CredentialBundle::from_json(&original.to_json()).unwrap();
513        assert_eq!(parsed, original);
514    }
515
516    #[test]
517    fn credential_bundle_without_a_sia_key_round_trips() {
518        let original = bundle(0x11);
519        let parsed = CredentialBundle::from_json(&original.to_json()).unwrap();
520        assert_eq!(parsed, original);
521    }
522
523    #[test]
524    fn mock_bundle_store_create_then_read_round_trips() {
525        let store = MockBundleStore::empty();
526        assert!(store.read().unwrap().is_none());
527
528        let outcome = store.create(&bundle(1)).unwrap();
529        assert_eq!(outcome, BundleCreateOutcome::Created);
530        assert_eq!(store.read().unwrap(), Some(bundle(1)));
531    }
532
533    #[test]
534    fn mock_bundle_store_create_preserves_an_existing_bundle() {
535        let store = MockBundleStore::seeded(bundle(1));
536        let outcome = store.create(&bundle(2)).unwrap();
537        assert_eq!(outcome, BundleCreateOutcome::AlreadyExists);
538        assert_eq!(
539            store.read().unwrap(),
540            Some(bundle(1)),
541            "create must never overwrite an existing bundle"
542        );
543    }
544
545    #[test]
546    fn mock_bundle_store_write_overwrites() {
547        let store = MockBundleStore::seeded(bundle(1));
548        store.write(&bundle(2)).unwrap();
549        assert_eq!(store.read().unwrap(), Some(bundle(2)));
550    }
551
552    #[test]
553    fn file_bundle_store_create_then_read_round_trips() {
554        let dir = tempfile::tempdir().unwrap();
555        let store = FileBundleStore::new(dir.path().join("credentials.json"));
556
557        assert!(store.read().unwrap().is_none());
558        let outcome = store.create(&bundle(7)).unwrap();
559        assert_eq!(outcome, BundleCreateOutcome::Created);
560        assert_eq!(store.read().unwrap(), Some(bundle(7)));
561
562        #[cfg(unix)]
563        {
564            use std::os::unix::fs::PermissionsExt;
565            let mode = std::fs::metadata(dir.path().join("credentials.json"))
566                .unwrap()
567                .permissions()
568                .mode()
569                & 0o777;
570            assert_eq!(mode, 0o600, "credential file must be 0600");
571        }
572    }
573
574    #[test]
575    fn file_bundle_store_create_preserves_an_existing_bundle() {
576        let dir = tempfile::tempdir().unwrap();
577        let store = FileBundleStore::new(dir.path().join("credentials.json"));
578        store.write(&bundle(1)).unwrap();
579
580        let outcome = store.create(&bundle(2)).unwrap();
581        assert_eq!(outcome, BundleCreateOutcome::AlreadyExists);
582        assert_eq!(store.read().unwrap(), Some(bundle(1)));
583    }
584
585    #[test]
586    fn file_bundle_store_write_overwrites() {
587        let dir = tempfile::tempdir().unwrap();
588        let store = FileBundleStore::new(dir.path().join("credentials.json"));
589        store.write(&bundle(1)).unwrap();
590        store.write(&bundle(2)).unwrap();
591        assert_eq!(store.read().unwrap(), Some(bundle(2)));
592    }
593}