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