Skip to main content

taskfast_cli/
config.rs

1// SPDX-License-Identifier: MIT
2//! JSON config file for the `taskfast` CLI.
3//!
4//! Persistent state written by `taskfast init` (and edited via
5//! `taskfast config set`) so subsequent subcommands work in a fresh
6//! shell without sourcing anything.
7//!
8//! # Layout
9//!
10//! Default path: `./.taskfast/config.json` (project-local). Override via
11//! the global `--config <path>` flag or `TASKFAST_CONFIG` env var.
12//!
13//! # Precedence
14//!
15//! `Ctx::from_cli_and_config` (see `cmd/mod.rs`) layers values as:
16//!
17//! ```text
18//! clap flag > env var > config file > default
19//! ```
20//!
21//! Clap already folds flag > env via `env = "..."`. The config file sits
22//! one rung under that, so omitting a field in JSON never surprises a
23//! caller who passed the flag.
24//!
25//! # Forward-compat
26//!
27//! `schema_version` is a `u32` that starts at `CURRENT_SCHEMA_VERSION`.
28//! Unknown fields are tolerated (default serde behaviour). A file with a
29//! newer `schema_version` logs a warning and loads what it recognises —
30//! it does not fail, so an older CLI doesn't brick a newer config dir.
31//!
32//! # Secrets
33//!
34//! `api_key` lives in this file. The file is written mode `0600` on unix
35//! (atomic temp + rename) and the containing `.taskfast/` directory is
36//! intended to be git-ignored.
37
38use std::fs;
39use std::io::Write;
40use std::path::{Path, PathBuf};
41
42use serde::{Deserialize, Serialize};
43use thiserror::Error;
44
45use crate::Environment;
46
47/// Default project-local path, relative to the CWD.
48pub const DEFAULT_CONFIG_PATH: &str = ".taskfast/config.json";
49
50/// Current on-disk schema version. Bump when a field changes shape in a
51/// way a reader needs to special-case; additive fields don't need a bump
52/// because serde `#[serde(default)]` already handles missing keys.
53///
54/// v2: dropped `api_base` and `network` — both derived from `environment`
55/// at runtime via [`crate::Environment::api_base`] and
56/// [`crate::Environment::network`]. Files at v1 with either key present
57/// hard-error in [`Config::load`] with a migration hint.
58pub const CURRENT_SCHEMA_VERSION: u32 = 2;
59
60/// Keys removed at schema v2. Loading a file that still carries any of
61/// these triggers [`ConfigError::LegacyFields`] so a stale config never
62/// silently misroutes traffic post-migration.
63const LEGACY_REMOVED_KEYS: &[&str] = &["api_base", "network"];
64
65#[derive(Debug, Error)]
66pub enum ConfigError {
67    #[error("I/O on {path}: {source}")]
68    Io {
69        path: PathBuf,
70        #[source]
71        source: std::io::Error,
72    },
73    #[error("parse {path}: {source}")]
74    Parse {
75        path: PathBuf,
76        #[source]
77        source: serde_json::Error,
78    },
79    #[error(
80        "config {path} carries removed key(s) {fields:?} — derived from `environment` since \
81         schema v2. Run `taskfast config migrate` (or remove the keys + bump `schema_version` \
82         to 2 manually) and re-run."
83    )]
84    LegacyFields { path: PathBuf, fields: Vec<String> },
85}
86
87/// On-disk config. Every runtime field is `Option` so the file stays
88/// small and a partially-configured project can still round-trip.
89#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
90#[serde(default)]
91pub struct Config {
92    /// On-disk schema version (`CURRENT_SCHEMA_VERSION` for fresh
93    /// writes). A `0` value means "not set" and is normalized to
94    /// `CURRENT_SCHEMA_VERSION` on save.
95    #[serde(skip_serializing_if = "is_zero")]
96    pub schema_version: u32,
97
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub environment: Option<Environment>,
100
101    /// Agent API key. Secret — the file is written `0600`.
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub api_key: Option<String>,
104
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub wallet_address: Option<String>,
107
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub keystore_path: Option<PathBuf>,
110
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub agent_id: Option<String>,
113
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub webhook_url: Option<String>,
116
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub webhook_secret_path: Option<PathBuf>,
119
120    /// Fail-closed confirmation gate for mutating commands. When the
121    /// requested budget on `post` (or task budget on `settle`) exceeds
122    /// this stablecoin-units threshold, the command refuses to proceed
123    /// without an explicit `--yes`. Decimal string in the same units
124    /// as `--budget` (e.g. `"1000"` = 1000 USDC). `None` = gate off.
125    #[serde(skip_serializing_if = "Option::is_none")]
126    pub confirm_above_budget: Option<String>,
127
128    /// Default `--verbose` log encoding. Accepts `"json"` or `"text"`.
129    /// `None` = `"text"`. CLI flag and env var (`TASKFAST_LOG_FORMAT`)
130    /// still win over this.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub log_format: Option<String>,
133
134    /// Receipt-polling ceiling for `escrow sign`. Human-readable
135    /// duration. `None` = network-aware default (3min mainnet,
136    /// 1min testnet). Flag `--receipt-timeout` and env var
137    /// `TASKFAST_RECEIPT_TIMEOUT` still win over this.
138    #[serde(skip_serializing_if = "Option::is_none")]
139    pub receipt_timeout: Option<String>,
140}
141
142// `skip_serializing_if` is required by serde to take `&T`, so clippy's
143// pass-by-value lint is a false positive here.
144#[allow(clippy::trivially_copy_pass_by_ref)]
145fn is_zero(v: &u32) -> bool {
146    *v == 0
147}
148
149/// Drop a `.gitignore` of `*` into the config dir so its plaintext secrets
150/// (`api_key`, keystore path, webhook secret) can't be committed by accident.
151/// `create_new` makes this idempotent and non-destructive: an existing
152/// `.gitignore` (user-customized) is left untouched. Best-effort — any other
153/// I/O error is logged, not propagated, so it never fails the config write.
154///
155/// Scoped to the conventional `.taskfast` secrets dir only: a caller who
156/// overrides `--config ./config.json` (or `TASKFAST_CONFIG`) must not have a
157/// `.gitignore` of `*` dropped into an arbitrary directory — into the repo
158/// root that would ignore the entire working tree.
159fn ensure_dir_gitignore(dir: &Path) {
160    let expected = Path::new(DEFAULT_CONFIG_PATH)
161        .parent()
162        .and_then(Path::file_name);
163    if dir.file_name() != expected {
164        return;
165    }
166    let gitignore = dir.join(".gitignore");
167    match fs::OpenOptions::new()
168        .write(true)
169        .create_new(true)
170        .open(&gitignore)
171    {
172        Ok(mut f) => {
173            if let Err(e) = f.write_all(b"*\n") {
174                tracing::warn!(path = %gitignore.display(), error = %e, "could not write .taskfast/.gitignore");
175            }
176        }
177        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
178        Err(e) => {
179            tracing::warn!(path = %gitignore.display(), error = %e, "could not create .taskfast/.gitignore");
180        }
181    }
182}
183
184impl Config {
185    /// Parse the JSON at `path`. Missing file → `Config::default()`
186    /// (callers treat absence the same as an empty config). Newer
187    /// `schema_version` values log a warning via `tracing::warn!` and
188    /// load what they recognise.
189    ///
190    /// Hard-errors with [`ConfigError::LegacyFields`] when the on-disk
191    /// JSON still carries any key removed at the current schema version
192    /// (currently `api_base` and `network`). Stale values would otherwise
193    /// silently outrank the `Environment`-derived defaults.
194    pub fn load(path: &Path) -> Result<Self, ConfigError> {
195        let src = match fs::read_to_string(path) {
196            Ok(s) => s,
197            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
198            Err(source) => {
199                return Err(ConfigError::Io {
200                    path: path.to_path_buf(),
201                    source,
202                });
203            }
204        };
205        // Peek raw JSON before strict deserialization so the migration error
206        // wins over a generic parse error and so removed-key detection does
207        // not depend on `Config` carrying the field.
208        let raw: serde_json::Value =
209            serde_json::from_str(&src).map_err(|source| ConfigError::Parse {
210                path: path.to_path_buf(),
211                source,
212            })?;
213        if let Some(obj) = raw.as_object() {
214            let legacy: Vec<String> = LEGACY_REMOVED_KEYS
215                .iter()
216                .filter(|k| obj.contains_key(**k))
217                .map(|k| (*k).to_string())
218                .collect();
219            if !legacy.is_empty() {
220                return Err(ConfigError::LegacyFields {
221                    path: path.to_path_buf(),
222                    fields: legacy,
223                });
224            }
225        }
226        let cfg: Config = serde_json::from_value(raw).map_err(|source| ConfigError::Parse {
227            path: path.to_path_buf(),
228            source,
229        })?;
230        if cfg.schema_version > CURRENT_SCHEMA_VERSION {
231            tracing::warn!(
232                file = %path.display(),
233                file_version = cfg.schema_version,
234                current_version = CURRENT_SCHEMA_VERSION,
235                "config schema_version is newer than this CLI — loading recognised fields only"
236            );
237        }
238        Ok(cfg)
239    }
240
241    /// Atomic(ish) write: JSON-serialize to a sibling `.tmp`, chmod
242    /// `0600` on unix, rename into place. Creates the parent directory
243    /// if it doesn't exist.
244    pub fn save(&self, path: &Path) -> Result<(), ConfigError> {
245        if let Some(parent) = path.parent() {
246            if !parent.as_os_str().is_empty() {
247                fs::create_dir_all(parent).map_err(|source| ConfigError::Io {
248                    path: parent.to_path_buf(),
249                    source,
250                })?;
251                // F4: tighten the `.taskfast/` dir to 0700. `create_dir_all`
252                // honors umask (typically 022 → 0755), leaving the keystore
253                // + webhook secret + API key config readable by anyone on
254                // the host. 0700 scopes them to the owning UID. Idempotent
255                // on subsequent saves.
256                #[cfg(unix)]
257                {
258                    use std::os::unix::fs::PermissionsExt;
259                    let perms = fs::Permissions::from_mode(0o700);
260                    fs::set_permissions(parent, perms).map_err(|source| ConfigError::Io {
261                        path: parent.to_path_buf(),
262                        source,
263                    })?;
264                }
265                // Git-ignore the whole config dir so the plaintext `api_key`
266                // can't be committed by accident from inside a repo (gh#78).
267                // Best-effort: a failure here must not fail the config write.
268                ensure_dir_gitignore(parent);
269            }
270        }
271        let mut to_write = self.clone();
272        if to_write.schema_version == 0 {
273            to_write.schema_version = CURRENT_SCHEMA_VERSION;
274        }
275        let body = serde_json::to_vec_pretty(&to_write).map_err(|source| ConfigError::Parse {
276            path: path.to_path_buf(),
277            source,
278        })?;
279
280        let tmp = path.with_extension("json.tmp");
281        {
282            // Create the temp at 0600 from the start (not umask-default then
283            // chmod) so the api_key is never momentarily world-readable
284            // before the rename. gh#78.
285            #[cfg(unix)]
286            let create = {
287                use std::os::unix::fs::OpenOptionsExt;
288                fs::OpenOptions::new()
289                    .write(true)
290                    .create(true)
291                    .truncate(true)
292                    .mode(0o600)
293                    .open(&tmp)
294            };
295            #[cfg(not(unix))]
296            let create = fs::File::create(&tmp);
297            let mut f = create.map_err(|source| ConfigError::Io {
298                path: tmp.clone(),
299                source,
300            })?;
301            f.write_all(&body).map_err(|source| ConfigError::Io {
302                path: tmp.clone(),
303                source,
304            })?;
305            f.write_all(b"\n").map_err(|source| ConfigError::Io {
306                path: tmp.clone(),
307                source,
308            })?;
309            f.flush().map_err(|source| ConfigError::Io {
310                path: tmp.clone(),
311                source,
312            })?;
313        }
314        #[cfg(unix)]
315        {
316            use std::os::unix::fs::PermissionsExt;
317            let perms = fs::Permissions::from_mode(0o600);
318            fs::set_permissions(&tmp, perms).map_err(|source| ConfigError::Io {
319                path: tmp.clone(),
320                source,
321            })?;
322        }
323        fs::rename(&tmp, path).map_err(|source| ConfigError::Io {
324            path: path.to_path_buf(),
325            source,
326        })?;
327        Ok(())
328    }
329
330    /// Default file path, rooted in the caller's current working
331    /// directory. Used when neither `--config` nor `TASKFAST_CONFIG`
332    /// is supplied.
333    pub fn default_path() -> PathBuf {
334        PathBuf::from(DEFAULT_CONFIG_PATH)
335    }
336}
337
338// Serde support for `Environment` — declared here (not in lib.rs) so the
339// config module owns its serialization contract. If the enum ever grows
340// a runtime variant that shouldn't be persisted, the mapping stays
341// local.
342impl Serialize for Environment {
343    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
344        ser.serialize_str(match self {
345            Self::Prod => "prod",
346            Self::Staging => "staging",
347            Self::Local => "local",
348        })
349    }
350}
351
352impl<'de> Deserialize<'de> for Environment {
353    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
354        let s = String::deserialize(de)?;
355        match s.as_str() {
356            "prod" | "production" => Ok(Self::Prod),
357            "staging" => Ok(Self::Staging),
358            "local" => Ok(Self::Local),
359            other => Err(serde::de::Error::custom(format!(
360                "unknown environment {other:?}; expected prod | staging | local"
361            ))),
362        }
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369    use tempfile::TempDir;
370
371    fn sample() -> Config {
372        Config {
373            schema_version: CURRENT_SCHEMA_VERSION,
374            environment: Some(Environment::Local),
375            api_key: Some("am_live_secret".into()),
376            wallet_address: Some("0xabc".into()),
377            keystore_path: Some(PathBuf::from("/tmp/keystore.json")),
378            agent_id: Some("agent_123".into()),
379            webhook_url: Some("https://example.com/hook".into()),
380            webhook_secret_path: Some(PathBuf::from("/tmp/hook.secret")),
381            confirm_above_budget: Some("1000".into()),
382            log_format: Some("json".into()),
383            receipt_timeout: Some("3min".into()),
384        }
385    }
386
387    #[test]
388    fn load_missing_file_returns_default() {
389        let tmp = TempDir::new().unwrap();
390        let missing = tmp.path().join("nope.json");
391        let cfg = Config::load(&missing).expect("missing file is default, not error");
392        assert_eq!(cfg, Config::default());
393    }
394
395    #[test]
396    fn roundtrip_preserves_every_field() {
397        let tmp = TempDir::new().unwrap();
398        let path = tmp.path().join("sub").join("config.json");
399        let original = sample();
400        original.save(&path).expect("save");
401        let loaded = Config::load(&path).expect("load");
402        assert_eq!(loaded, original);
403    }
404
405    #[test]
406    fn save_zero_schema_version_is_normalized_to_current() {
407        let tmp = TempDir::new().unwrap();
408        let path = tmp.path().join("config.json");
409        let cfg = Config {
410            wallet_address: Some("0xabc".into()),
411            ..Config::default()
412        };
413        assert_eq!(cfg.schema_version, 0);
414        cfg.save(&path).expect("save");
415        let loaded = Config::load(&path).expect("load");
416        assert_eq!(loaded.schema_version, CURRENT_SCHEMA_VERSION);
417    }
418
419    #[test]
420    fn save_creates_missing_parent_dir() {
421        let tmp = TempDir::new().unwrap();
422        let nested = tmp.path().join("a").join("b").join("config.json");
423        sample().save(&nested).expect("save into nested path");
424        assert!(nested.exists());
425    }
426
427    #[cfg(unix)]
428    #[test]
429    fn save_tightens_parent_directory_to_0700() {
430        use std::os::unix::fs::PermissionsExt;
431        let tmp = TempDir::new().unwrap();
432        let cfg_dir = tmp.path().join(".taskfast");
433        let path = cfg_dir.join("config.json");
434        sample().save(&path).expect("save");
435        let mode = fs::metadata(&cfg_dir).unwrap().permissions().mode() & 0o777;
436        assert_eq!(
437            mode, 0o700,
438            ".taskfast/ must be 0700 so other users on the host can't \
439             list the keystore + webhook secret + API key"
440        );
441    }
442
443    #[test]
444    fn save_writes_gitignore_star_in_config_dir() {
445        // gh#78: the dir holding the plaintext api_key must be git-ignored
446        // by default so a `taskfast init` inside a repo can't leak it.
447        let tmp = TempDir::new().unwrap();
448        let cfg_dir = tmp.path().join(".taskfast");
449        let path = cfg_dir.join("config.json");
450        sample().save(&path).expect("save");
451        let gi = fs::read_to_string(cfg_dir.join(".gitignore")).expect(".gitignore written");
452        assert_eq!(gi.trim(), "*");
453    }
454
455    #[test]
456    fn save_to_overridden_path_does_not_write_gitignore() {
457        // gh#78 review: `--config ./config.json` must NOT drop a `.gitignore`
458        // of `*` into an arbitrary dir (e.g. the repo root, which would
459        // ignore the whole tree). Only the conventional `.taskfast/` dir is
460        // auto-ignored.
461        let tmp = TempDir::new().unwrap();
462        let dir = tmp.path().join("some-project");
463        let path = dir.join("config.json");
464        sample().save(&path).expect("save");
465        assert!(path.exists(), "config still written");
466        assert!(
467            !dir.join(".gitignore").exists(),
468            "no .gitignore in a non-.taskfast dir"
469        );
470    }
471
472    #[test]
473    fn save_does_not_clobber_existing_gitignore() {
474        // A user who customized .gitignore keeps it — we only create when absent.
475        let tmp = TempDir::new().unwrap();
476        let cfg_dir = tmp.path().join(".taskfast");
477        fs::create_dir_all(&cfg_dir).unwrap();
478        fs::write(cfg_dir.join(".gitignore"), "# mine\nconfig.json\n").unwrap();
479        sample().save(&cfg_dir.join("config.json")).expect("save");
480        let gi = fs::read_to_string(cfg_dir.join(".gitignore")).unwrap();
481        assert_eq!(gi, "# mine\nconfig.json\n", "existing .gitignore preserved");
482    }
483
484    #[test]
485    fn unknown_fields_are_tolerated() {
486        let tmp = TempDir::new().unwrap();
487        let path = tmp.path().join("config.json");
488        let body = r#"{
489            "schema_version": 2,
490            "wallet_address": "0xabc",
491            "future_field": "ignored",
492            "another": {"nested": true}
493        }"#;
494        fs::write(&path, body).unwrap();
495        let cfg = Config::load(&path).expect("unknown fields should not fail load");
496        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
497    }
498
499    #[test]
500    fn newer_schema_version_loads_with_warning() {
501        let tmp = TempDir::new().unwrap();
502        let path = tmp.path().join("config.json");
503        let body = format!(
504            r#"{{ "schema_version": {}, "wallet_address": "0xabc" }}"#,
505            CURRENT_SCHEMA_VERSION + 5
506        );
507        fs::write(&path, body).unwrap();
508        let cfg = Config::load(&path).expect("newer version still loads");
509        assert_eq!(cfg.schema_version, CURRENT_SCHEMA_VERSION + 5);
510        assert_eq!(cfg.wallet_address.as_deref(), Some("0xabc"));
511    }
512
513    #[test]
514    fn legacy_api_base_field_hard_errors() {
515        let tmp = TempDir::new().unwrap();
516        let path = tmp.path().join("config.json");
517        let body = r#"{ "schema_version": 1, "api_base": "https://attacker.example" }"#;
518        fs::write(&path, body).unwrap();
519        let err = Config::load(&path).expect_err("legacy api_base must be rejected");
520        let ConfigError::LegacyFields { fields, .. } = err else {
521            panic!("expected LegacyFields, got {err:?}");
522        };
523        assert_eq!(fields, vec!["api_base".to_string()]);
524    }
525
526    #[test]
527    fn legacy_network_field_hard_errors() {
528        let tmp = TempDir::new().unwrap();
529        let path = tmp.path().join("config.json");
530        let body = r#"{ "schema_version": 1, "network": "mainnet" }"#;
531        fs::write(&path, body).unwrap();
532        let err = Config::load(&path).expect_err("legacy network must be rejected");
533        let ConfigError::LegacyFields { fields, .. } = err else {
534            panic!("expected LegacyFields, got {err:?}");
535        };
536        assert_eq!(fields, vec!["network".to_string()]);
537    }
538
539    #[test]
540    fn legacy_error_lists_both_fields_when_present() {
541        let tmp = TempDir::new().unwrap();
542        let path = tmp.path().join("config.json");
543        let body = r#"{ "api_base": "https://x", "network": "testnet" }"#;
544        fs::write(&path, body).unwrap();
545        let err = Config::load(&path).expect_err("both legacy fields must be flagged");
546        let ConfigError::LegacyFields { fields, .. } = err else {
547            panic!("expected LegacyFields, got {err:?}");
548        };
549        assert!(fields.contains(&"api_base".to_string()));
550        assert!(fields.contains(&"network".to_string()));
551    }
552
553    #[test]
554    fn legacy_error_message_names_migration_command() {
555        let tmp = TempDir::new().unwrap();
556        let path = tmp.path().join("config.json");
557        fs::write(&path, r#"{ "api_base": "https://x" }"#).unwrap();
558        let msg = Config::load(&path).unwrap_err().to_string();
559        assert!(
560            msg.contains("taskfast config migrate"),
561            "remediation hint must name the migrate command: {msg}"
562        );
563    }
564
565    #[test]
566    fn empty_config_serializes_compactly() {
567        // A default config has no runtime fields set — the JSON should
568        // be close to `{}` (just an empty object after skip_if).
569        let body = serde_json::to_string(&Config::default()).unwrap();
570        assert_eq!(body, "{}", "default config should serialize to {{}}");
571    }
572
573    #[test]
574    fn environment_roundtrip() {
575        for env in [Environment::Prod, Environment::Staging, Environment::Local] {
576            let cfg = Config {
577                environment: Some(env),
578                ..Config::default()
579            };
580            let body = serde_json::to_string(&cfg).unwrap();
581            let back: Config = serde_json::from_str(&body).unwrap();
582            assert_eq!(back.environment.map(|e| e.as_str()), Some(env.as_str()));
583        }
584    }
585
586    #[test]
587    fn environment_accepts_production_alias() {
588        let body = r#"{ "environment": "production" }"#;
589        let cfg: Config = serde_json::from_str(body).unwrap();
590        assert!(matches!(cfg.environment, Some(Environment::Prod)));
591    }
592
593    #[test]
594    fn environment_rejects_unknown() {
595        let body = r#"{ "environment": "moon" }"#;
596        let err = serde_json::from_str::<Config>(body).unwrap_err();
597        assert!(err.to_string().contains("moon"));
598    }
599
600    #[cfg(unix)]
601    #[test]
602    fn save_writes_mode_0600_on_unix() {
603        use std::os::unix::fs::PermissionsExt;
604        let tmp = TempDir::new().unwrap();
605        let path = tmp.path().join("config.json");
606        sample().save(&path).expect("save");
607        let meta = fs::metadata(&path).unwrap();
608        let mode = meta.permissions().mode() & 0o777;
609        assert_eq!(mode, 0o600, "expected mode 0600, got {mode:o}");
610    }
611
612    #[test]
613    fn parse_error_includes_path() {
614        let tmp = TempDir::new().unwrap();
615        let path = tmp.path().join("bad.json");
616        fs::write(&path, "{ not json").unwrap();
617        let err = Config::load(&path).unwrap_err();
618        let msg = err.to_string();
619        assert!(msg.contains("bad.json"), "error mentions path: {msg}");
620    }
621}