Skip to main content

obsidianlog_cli/
config.rs

1//! Configuration model and loading.
2//!
3//! ObsidianLog is self-hosted: configuration captures where logs are archived
4//! and how chunks are sized. It is **local-first** — the default backend writes
5//! to a local directory and needs no Sia node (mock-first invariant). The
6//! `indexd` section is optional and only consulted when the `sia` feature is
7//! built. Encryption keys are **not** stored here — they live in the OS keychain
8//! (see [`crate::keystore`]) or a `0600` secrets file, per the security model.
9//!
10//! # Discovery precedence
11//!
12//! 1. An explicit `--config PATH` (the file must exist).
13//! 2. `$XDG_CONFIG_HOME/obsidianlog/config.toml`, if `XDG_CONFIG_HOME` is set.
14//! 3. `~/.config/obsidianlog/config.toml` otherwise, where `~` is `$HOME`, or
15//!    `%USERPROFILE%` when `HOME` isn't set (the default on Windows).
16//!
17//! If neither `--config` nor a file at the resolved default path is present,
18//! [`Config::load`] falls back to [`Config::default`] rather than erroring —
19//! commands should work out of the box against the local backend.
20//!
21//! # Credential storage format (ADR-0015)
22//!
23//! `credential_store_version` records which local credential-storage layout
24//! the config expects. [`Config::load`] — used by every command except
25//! `init` — refuses to load a config whose version doesn't match
26//! [`CURRENT_CREDENTIAL_VERSION`], before any keychain access happens: a
27//! missing version (a pre-0.2 config) or an unrecognized future one both
28//! fail with a specific, actionable message rather than being silently
29//! reinterpreted. `init` alone uses [`Config::load_for_init`], which
30//! surfaces a legacy config as a distinct outcome instead of erroring, so it
31//! can offer a supported route back to a fresh setup. See ADR-0015.
32
33use std::path::{Path, PathBuf};
34
35use anyhow::{Context, Result};
36use serde::{Deserialize, Serialize};
37
38/// The credential-storage format this build of obsidianlog writes and
39/// expects: one bundled keychain item holding the encryption key and an
40/// optional Sia app key together (ADR-0015). A config missing this marker
41/// predates the bundled format (two independent keychain items); a config
42/// carrying a higher number is from a newer, unrecognized build.
43pub const CURRENT_CREDENTIAL_VERSION: u32 = 2;
44
45/// Top-level ObsidianLog configuration, persisted as TOML.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(default)]
48pub struct Config {
49    /// Storage bucket / namespace logs are archived under.
50    pub bucket: String,
51
52    /// Local (default) storage backend settings.
53    pub local: LocalConfig,
54
55    /// How to reach the user's indexd deployment. `None` (the default) uses the
56    /// local backend only; set this when archiving to Sia (`sia` feature).
57    #[serde(default)]
58    pub indexd: Option<IndexdConfig>,
59
60    /// Local HTTP ingest server settings.
61    pub serve: ServeConfig,
62
63    /// Chunking / time-window settings.
64    pub chunking: ChunkingConfig,
65
66    /// Which local credential-storage layout this config expects (see the
67    /// module docs and ADR-0015). `None` when parsed from a file that
68    /// predates this field — treated as the legacy, two-item layout.
69    /// Explicitly `#[serde(default)]` (defaulting to `None`) rather than
70    /// relying on the struct's blanket default, following the same pattern
71    /// already used for `indexd` above, so a missing field always means
72    /// "legacy" regardless of what `Config::default()`'s own value is.
73    #[serde(default)]
74    pub credential_store_version: Option<u32>,
75}
76
77/// Settings for the default, Sia-free local storage backend.
78#[derive(Debug, Clone, Serialize, Deserialize)]
79#[serde(default)]
80pub struct LocalConfig {
81    /// Directory the local backend stores chunks, indexes, and manifests under.
82    pub data_dir: PathBuf,
83}
84
85/// Connection details for the user's indexd gateway (Sia archival).
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct IndexdConfig {
88    /// Base URL of the indexd HTTP API.
89    pub url: String,
90    /// Sia bucket / namespace logs are archived under.
91    pub bucket: String,
92}
93
94/// Settings for the local Vector-compatible ingest endpoint.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96#[serde(default)]
97pub struct ServeConfig {
98    /// Address the ingest server binds to.
99    pub bind: String,
100}
101
102/// Controls how log batches are grouped into discrete chunk files.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104#[serde(default)]
105pub struct ChunkingConfig {
106    /// Length of each chunk's time window, in seconds (default: 1 hour).
107    pub window_secs: u64,
108}
109
110impl Default for Config {
111    fn default() -> Self {
112        Self {
113            bucket: "obsidianlog".to_string(),
114            local: LocalConfig {
115                data_dir: PathBuf::from("./obsidianlog-data"),
116            },
117            // Local-first: no Sia node required by default.
118            indexd: None,
119            serve: ServeConfig {
120                bind: "127.0.0.1:7080".to_string(),
121            },
122            chunking: ChunkingConfig { window_secs: 3600 },
123            // A freshly-created config always writes the current format, so
124            // it round-trips through Config::load cleanly from here on.
125            credential_store_version: Some(CURRENT_CREDENTIAL_VERSION),
126        }
127    }
128}
129
130impl Default for LocalConfig {
131    fn default() -> Self {
132        Config::default().local
133    }
134}
135
136impl Default for ServeConfig {
137    fn default() -> Self {
138        Config::default().serve
139    }
140}
141
142impl Default for ChunkingConfig {
143    fn default() -> Self {
144        Config::default().chunking
145    }
146}
147
148/// Resolve the default config path from XDG/home environment values.
149///
150/// Pure function over already-read env vars so it can be unit tested without
151/// mutating (or depending on) the real process environment. `userprofile` is
152/// the Windows fallback: PowerShell and cmd.exe don't set `HOME` by default
153/// (only `USERPROFILE`), so without it every fresh Windows install fails
154/// here before `init` gets a chance to run.
155fn resolve_default_path(
156    xdg_config_home: Option<&str>,
157    home: Option<&str>,
158    userprofile: Option<&str>,
159) -> Result<PathBuf> {
160    if let Some(xdg) = xdg_config_home.filter(|s| !s.is_empty()) {
161        return Ok(PathBuf::from(xdg).join("obsidianlog").join("config.toml"));
162    }
163    let home = home
164        .filter(|s| !s.is_empty())
165        .or_else(|| userprofile.filter(|s| !s.is_empty()))
166        .context(
167            "could not determine the config directory: none of XDG_CONFIG_HOME, HOME, or \
168             USERPROFILE is set (pass --config explicitly)",
169        )?;
170    Ok(PathBuf::from(home)
171        .join(".config")
172        .join("obsidianlog")
173        .join("config.toml"))
174}
175
176/// Parse `text` (read from `path`, used only for the error message) as a
177/// [`Config`], with no credential-format validation — shared by the strict
178/// [`Config::load`] and the permissive [`Config::load_for_init`], which
179/// apply different validation over the same underlying parse.
180fn parse(text: &str, path: &Path) -> Result<Config> {
181    toml::from_str(text).with_context(|| format!("parsing config file at {}", path.display()))
182}
183
184/// Outcome of [`Config::load_for_init`] — the one place in the codebase
185/// allowed to see a legacy config as something other than a hard failure.
186pub enum ConfigLoadOutcome {
187    /// No config file exists yet at the resolved path — a fresh install.
188    Missing,
189    /// A config file in the current credential-storage format.
190    Current(Config),
191    /// A config file predating the credential-storage format marker (no
192    /// `credential_store_version` field). Carries the parsed config so
193    /// `init` can still inspect its other fields if useful, but its
194    /// credential-bearing fields must not be trusted for keychain access.
195    Legacy(Config),
196}
197
198impl Config {
199    /// Resolve the default config path (`$XDG_CONFIG_HOME/obsidianlog/config.toml`,
200    /// falling back to `~/.config/obsidianlog/config.toml`, using `USERPROFILE`
201    /// in place of `HOME` on Windows when `HOME` itself isn't set).
202    pub fn default_path() -> Result<PathBuf> {
203        resolve_default_path(
204            std::env::var("XDG_CONFIG_HOME").ok().as_deref(),
205            std::env::var("HOME").ok().as_deref(),
206            std::env::var("USERPROFILE").ok().as_deref(),
207        )
208    }
209
210    /// Load configuration from `path`, or the default path when `None`.
211    ///
212    /// An explicit `path` must exist. With no `path`, a missing file at the
213    /// resolved default location is not an error — [`Config::default`] is used
214    /// instead, so commands work with zero setup against the local backend.
215    ///
216    /// Every command except `init` must use this function: a config whose
217    /// credential-storage format doesn't match [`CURRENT_CREDENTIAL_VERSION`]
218    /// (missing — legacy — or newer than this build understands) fails here,
219    /// before any keychain access happens. `init` alone uses
220    /// [`Config::load_for_init`] instead, since offering a route back to a
221    /// fresh setup is specifically its job (see ADR-0015); no other caller
222    /// should ever see a legacy config as anything but a hard failure.
223    pub fn load(path: Option<&Path>) -> Result<Self> {
224        match path {
225            Some(path) => {
226                let text = std::fs::read_to_string(path)
227                    .with_context(|| format!("reading config file at {}", path.display()))?;
228                let config = parse(&text, path)?;
229                config.require_supported_credential_store()?;
230                Ok(config)
231            }
232            None => {
233                let default_path = Self::default_path()?;
234                match std::fs::read_to_string(&default_path) {
235                    Ok(text) => {
236                        let config = parse(&text, &default_path)?;
237                        config.require_supported_credential_store()?;
238                        Ok(config)
239                    }
240                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
241                    Err(e) => Err(e).with_context(|| {
242                        format!("reading config file at {}", default_path.display())
243                    }),
244                }
245            }
246        }
247    }
248
249    /// Load configuration for `init`'s use only. Unlike [`Config::load`], a
250    /// missing config file resolves to [`ConfigLoadOutcome::Missing`]
251    /// (whether `path` was explicit or defaulted — `init` treats both the
252    /// same, since either way it means "nothing to reuse yet") and a legacy
253    /// config resolves to [`ConfigLoadOutcome::Legacy`] rather than erroring,
254    /// so `init` can print what continuing would abandon and offer a
255    /// supported route to a fresh setup. An unrecognized *future* format
256    /// still errors here exactly as it does in [`Config::load`] — there's no
257    /// reasonable repair action for a config written by a newer build.
258    pub fn load_for_init(path: Option<&Path>) -> Result<ConfigLoadOutcome> {
259        let resolved = match path {
260            Some(p) => p.to_path_buf(),
261            None => Self::default_path()?,
262        };
263        match std::fs::read_to_string(&resolved) {
264            Ok(text) => {
265                let config = parse(&text, &resolved)?;
266                match config.credential_store_version {
267                    Some(v) if v == CURRENT_CREDENTIAL_VERSION => {
268                        Ok(ConfigLoadOutcome::Current(config))
269                    }
270                    Some(v) if v > CURRENT_CREDENTIAL_VERSION => {
271                        Err(unsupported_future_version_error(v))
272                    }
273                    _ => Ok(ConfigLoadOutcome::Legacy(config)),
274                }
275            }
276            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ConfigLoadOutcome::Missing),
277            Err(e) => {
278                Err(e).with_context(|| format!("reading config file at {}", resolved.display()))
279            }
280        }
281    }
282
283    /// Persist configuration to `path`, or the default path when `None`.
284    pub fn save(&self, path: Option<&Path>) -> Result<()> {
285        let path = match path {
286            Some(path) => path.to_path_buf(),
287            None => Self::default_path()?,
288        };
289        if let Some(parent) = path.parent() {
290            std::fs::create_dir_all(parent)
291                .with_context(|| format!("creating config directory {}", parent.display()))?;
292        }
293        let text = toml::to_string_pretty(self).context("serializing config")?;
294        std::fs::write(&path, text)
295            .with_context(|| format!("writing config file at {}", path.display()))?;
296        Ok(())
297    }
298
299    /// The gate behind [`Config::load`]: errors unless
300    /// `credential_store_version` matches [`CURRENT_CREDENTIAL_VERSION`]
301    /// exactly. See the module docs and ADR-0015.
302    fn require_supported_credential_store(&self) -> Result<()> {
303        match self.credential_store_version {
304            Some(v) if v == CURRENT_CREDENTIAL_VERSION => Ok(()),
305            Some(v) if v > CURRENT_CREDENTIAL_VERSION => Err(unsupported_future_version_error(v)),
306            _ => anyhow::bail!(
307                "this config uses the pre-0.2 credential storage layout (one encryption key \
308                 and one Sia app key stored as two separate OS keychain items). obsidianlog \
309                 0.2 stores them as a single bundled item instead, and there is no automatic \
310                 migration. To keep reading archives created under the old layout, use \
311                 obsidianlog v0.1.1. To start fresh under the new layout — this rotates the \
312                 encryption key, and previously archived data will no longer be decryptable — \
313                 run `obsidianlog init --force`."
314            ),
315        }
316    }
317}
318
319fn unsupported_future_version_error(found: u32) -> anyhow::Error {
320    anyhow::anyhow!(
321        "this config was written by a newer version of obsidianlog (credential storage \
322         format {found}, this build only understands up to {CURRENT_CREDENTIAL_VERSION}) — \
323         upgrade obsidianlog to use it"
324    )
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn default_path_prefers_xdg_config_home() {
333        let path = resolve_default_path(Some("/xdg"), Some("/home/user"), None).unwrap();
334        assert_eq!(path, PathBuf::from("/xdg/obsidianlog/config.toml"));
335    }
336
337    #[test]
338    fn default_path_falls_back_to_home_when_xdg_unset() {
339        let path = resolve_default_path(None, Some("/home/user"), None).unwrap();
340        assert_eq!(
341            path,
342            PathBuf::from("/home/user/.config/obsidianlog/config.toml")
343        );
344    }
345
346    #[test]
347    fn default_path_falls_back_to_home_when_xdg_empty() {
348        let path = resolve_default_path(Some(""), Some("/home/user"), None).unwrap();
349        assert_eq!(
350            path,
351            PathBuf::from("/home/user/.config/obsidianlog/config.toml")
352        );
353    }
354
355    #[test]
356    fn default_path_falls_back_to_userprofile_when_home_unset() {
357        // The default state of a fresh Windows shell: HOME isn't set, only
358        // USERPROFILE is.
359        let path = resolve_default_path(None, None, Some(r"C:\Users\user")).unwrap();
360        assert_eq!(
361            path,
362            PathBuf::from(r"C:\Users\user").join(".config/obsidianlog/config.toml")
363        );
364    }
365
366    #[test]
367    fn default_path_prefers_home_over_userprofile_when_both_set() {
368        let path = resolve_default_path(None, Some("/home/user"), Some(r"C:\Users\user")).unwrap();
369        assert_eq!(
370            path,
371            PathBuf::from("/home/user/.config/obsidianlog/config.toml")
372        );
373    }
374
375    #[test]
376    fn default_path_errors_when_none_are_set() {
377        assert!(resolve_default_path(None, None, None).is_err());
378    }
379
380    #[test]
381    fn load_with_explicit_path_parses_the_file() {
382        let dir = tempfile::tempdir().unwrap();
383        let path = dir.path().join("config.toml");
384        std::fs::write(
385            &path,
386            r#"
387            bucket = "custom-bucket"
388            credential_store_version = 2
389
390            [local]
391            data_dir = "/data"
392
393            [serve]
394            bind = "0.0.0.0:9000"
395
396            [chunking]
397            window_secs = 60
398            "#,
399        )
400        .unwrap();
401
402        let config = Config::load(Some(&path)).unwrap();
403        assert_eq!(config.bucket, "custom-bucket");
404        assert_eq!(config.local.data_dir, PathBuf::from("/data"));
405        assert_eq!(config.serve.bind, "0.0.0.0:9000");
406        assert_eq!(config.chunking.window_secs, 60);
407        assert!(config.indexd.is_none());
408    }
409
410    #[test]
411    fn load_with_missing_explicit_path_errors() {
412        let dir = tempfile::tempdir().unwrap();
413        let missing = dir.path().join("does-not-exist.toml");
414        assert!(Config::load(Some(&missing)).is_err());
415    }
416
417    #[test]
418    fn load_with_partial_file_fills_in_defaults() {
419        let dir = tempfile::tempdir().unwrap();
420        let path = dir.path().join("config.toml");
421        std::fs::write(
422            &path,
423            "bucket = \"only-the-bucket\"\ncredential_store_version = 2\n",
424        )
425        .unwrap();
426
427        let config = Config::load(Some(&path)).unwrap();
428        assert_eq!(config.bucket, "only-the-bucket");
429        assert_eq!(config.serve.bind, Config::default().serve.bind);
430        assert_eq!(
431            config.chunking.window_secs,
432            Config::default().chunking.window_secs
433        );
434    }
435
436    #[test]
437    fn save_then_load_round_trips() {
438        let dir = tempfile::tempdir().unwrap();
439        let path = dir.path().join("nested").join("config.toml");
440        let config = Config {
441            bucket: "roundtrip".to_string(),
442            ..Config::default()
443        };
444
445        config.save(Some(&path)).unwrap();
446        let loaded = Config::load(Some(&path)).unwrap();
447        assert_eq!(loaded.bucket, "roundtrip");
448    }
449
450    #[test]
451    fn save_then_load_round_trips_an_indexd_config() {
452        let dir = tempfile::tempdir().unwrap();
453        let path = dir.path().join("config.toml");
454        let config = Config {
455            indexd: Some(IndexdConfig {
456                url: "https://indexd.example.com".to_string(),
457                bucket: "sia-bucket".to_string(),
458            }),
459            ..Config::default()
460        };
461
462        config.save(Some(&path)).unwrap();
463        let loaded = Config::load(Some(&path)).unwrap();
464        let indexd = loaded.indexd.expect("indexd section must round-trip");
465        assert_eq!(indexd.url, "https://indexd.example.com");
466        assert_eq!(indexd.bucket, "sia-bucket");
467    }
468
469    #[test]
470    fn save_writes_the_current_credential_version() {
471        let dir = tempfile::tempdir().unwrap();
472        let path = dir.path().join("config.toml");
473        Config::default().save(Some(&path)).unwrap();
474
475        let text = std::fs::read_to_string(&path).unwrap();
476        assert!(text.contains("credential_store_version = 2"));
477    }
478
479    #[test]
480    fn load_rejects_a_legacy_config_missing_the_version_field() {
481        let dir = tempfile::tempdir().unwrap();
482        let path = dir.path().join("config.toml");
483        std::fs::write(&path, "bucket = \"legacy\"\n").unwrap();
484
485        let err = Config::load(Some(&path)).unwrap_err();
486        let message = err.to_string();
487        assert!(message.contains("pre-0.2"), "{message}");
488        assert!(message.contains("v0.1.1"), "{message}");
489        assert!(message.contains("--force"), "{message}");
490    }
491
492    #[test]
493    fn load_rejects_an_unrecognized_future_version() {
494        let dir = tempfile::tempdir().unwrap();
495        let path = dir.path().join("config.toml");
496        std::fs::write(
497            &path,
498            "bucket = \"future\"\ncredential_store_version = 99\n",
499        )
500        .unwrap();
501
502        let err = Config::load(Some(&path)).unwrap_err();
503        let message = err.to_string();
504        assert!(message.contains("newer version"), "{message}");
505    }
506
507    #[test]
508    fn load_accepts_the_current_version() {
509        let dir = tempfile::tempdir().unwrap();
510        let path = dir.path().join("config.toml");
511        std::fs::write(&path, "bucket = \"ok\"\ncredential_store_version = 2\n").unwrap();
512
513        assert!(Config::load(Some(&path)).is_ok());
514    }
515
516    #[test]
517    fn load_for_init_reports_missing_when_no_file_exists() {
518        let dir = tempfile::tempdir().unwrap();
519        let path = dir.path().join("does-not-exist.toml");
520
521        assert!(matches!(
522            Config::load_for_init(Some(&path)).unwrap(),
523            ConfigLoadOutcome::Missing
524        ));
525    }
526
527    #[test]
528    fn load_for_init_reports_current_for_a_current_format_config() {
529        let dir = tempfile::tempdir().unwrap();
530        let path = dir.path().join("config.toml");
531        std::fs::write(&path, "bucket = \"ok\"\ncredential_store_version = 2\n").unwrap();
532
533        assert!(matches!(
534            Config::load_for_init(Some(&path)).unwrap(),
535            ConfigLoadOutcome::Current(_)
536        ));
537    }
538
539    #[test]
540    fn load_for_init_reports_legacy_for_a_config_missing_the_version_field() {
541        let dir = tempfile::tempdir().unwrap();
542        let path = dir.path().join("config.toml");
543        std::fs::write(&path, "bucket = \"legacy\"\n").unwrap();
544
545        match Config::load_for_init(Some(&path)).unwrap() {
546            ConfigLoadOutcome::Legacy(config) => assert_eq!(config.bucket, "legacy"),
547            _ => panic!("expected Legacy"),
548        }
549    }
550
551    #[test]
552    fn load_for_init_still_rejects_an_unrecognized_future_version() {
553        let dir = tempfile::tempdir().unwrap();
554        let path = dir.path().join("config.toml");
555        std::fs::write(
556            &path,
557            "bucket = \"future\"\ncredential_store_version = 99\n",
558        )
559        .unwrap();
560
561        assert!(Config::load_for_init(Some(&path)).is_err());
562    }
563}