1use std::path::PathBuf;
18
19use anyhow::{Context, Result};
20use serde::{Deserialize, Serialize};
21
22pub const KEYRING_SERVICE: &str = "obsidianlog";
24pub const CREDENTIAL_BUNDLE_ACCOUNT: &str = "credentials";
26
27#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum BundleCreateOutcome {
50 Created,
51 AlreadyExists,
52}
53
54pub trait BundleStore {
58 fn read(&self) -> Result<Option<CredentialBundle>>;
60
61 fn write(&self, bundle: &CredentialBundle) -> Result<()>;
66
67 fn create(&self, bundle: &CredentialBundle) -> Result<BundleCreateOutcome>;
71
72 fn describe(&self) -> String;
75}
76
77pub 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 #[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#[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 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
167pub 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 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
257fn 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
274fn 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
294pub fn read_bundle() -> Result<(Option<CredentialBundle>, String)> {
297 with_bundle_fallback(|store| store.read())
298}
299
300pub 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
307pub fn create_bundle(bundle: &CredentialBundle) -> Result<(BundleCreateOutcome, String)> {
310 with_bundle_fallback(|store| store.create(bundle))
311}
312
313pub fn write_bundle(bundle: &CredentialBundle) -> Result<String> {
317 with_bundle_fallback(|store| store.write(bundle)).map(|(_, desc)| desc)
318}
319
320pub 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#[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 #[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 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}