Skip to main content

taskfast_cli/cmd/
config.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast config` — inspect / edit the project-local JSON config.
3//!
4//! Three operations, each shaped around the orchestrator JSON envelope:
5//!
6//! * `show` — dump the config with `api_key` redacted to its last 4 chars.
7//!   `--reveal` prints the full value (e.g. for piping into an env var in
8//!   a one-shot).
9//! * `path` — print the resolved config path. Useful for `jq -r
10//!   .data.path` in a shell wrapper that needs to mount the file.
11//! * `set <key> <value>` — mutate a single field. Keys are allowlisted so
12//!   a typo can't smuggle garbage into the JSON; values are type-checked
13//!   against the field (enum for `environment`, path for
14//!   `keystore_path`, etc.).
15//!
16//! `taskfast init` and future writers share the same `Config::save` path,
17//! so edits from `set` interleave cleanly with a re-`init`.
18
19use std::path::PathBuf;
20
21use clap::{Args, Subcommand};
22use serde_json::json;
23
24use super::{CmdError, CmdResult, Ctx};
25use crate::config::Config;
26use crate::envelope::Envelope;
27use crate::Environment;
28
29#[derive(Debug, Subcommand)]
30pub enum Command {
31    /// Print the current config as JSON. `api_key` is redacted to
32    /// `***<last4>` unless `--reveal` is passed.
33    Show(ShowArgs),
34    /// Print the resolved config path (respects `--config` /
35    /// `TASKFAST_CONFIG`).
36    Path,
37    /// Set a single field in the config file. Allowlisted keys only.
38    Set(SetArgs),
39    /// Drop legacy keys (`api_base`, `network`) and bump `schema_version`
40    /// to the current value. Idempotent — no-op when nothing to migrate.
41    Migrate,
42}
43
44#[derive(Debug, Args)]
45pub struct ShowArgs {
46    /// Print `api_key` in full instead of the `***<last4>` redaction.
47    /// Consider piping to a file you `chmod 600` immediately rather than
48    /// letting the key sit in your shell history.
49    #[arg(long)]
50    pub reveal: bool,
51}
52
53#[derive(Debug, Args)]
54pub struct SetArgs {
55    /// Field name. One of: `environment`, `api_key`, `wallet_address`,
56    /// `keystore_path`, `agent_id`, `webhook_url`, `webhook_secret_path`.
57    pub key: String,
58    /// New value. Pass `--unset` (below) or an empty string to clear.
59    pub value: Option<String>,
60    /// Clear the field (equivalent to passing an empty value).
61    #[arg(long, conflicts_with = "value")]
62    pub unset: bool,
63}
64
65// Dispatch is sync (no HTTP / no I/O await) but the signature matches the
66// rest of the subcommands so `main.rs` can call `.await` uniformly.
67#[allow(clippy::unused_async)]
68pub async fn run(ctx: &Ctx, cmd: Command) -> CmdResult {
69    match cmd {
70        Command::Show(args) => show(ctx, args),
71        Command::Path => Ok(path(ctx)),
72        Command::Set(args) => set(ctx, args),
73        Command::Migrate => migrate(ctx),
74    }
75}
76
77fn show(ctx: &Ctx, args: ShowArgs) -> CmdResult {
78    let cfg = Config::load(&ctx.config_path)?;
79    let data = json!({
80        "path": ctx.config_path.display().to_string(),
81        "config": serialize_for_display(&cfg, args.reveal),
82    });
83    Ok(Envelope::success(ctx.environment, ctx.dry_run, data))
84}
85
86fn path(ctx: &Ctx) -> Envelope {
87    let data = json!({
88        "path": ctx.config_path.display().to_string(),
89        "exists": ctx.config_path.exists(),
90    });
91    Envelope::success(ctx.environment, ctx.dry_run, data)
92}
93
94fn set(ctx: &Ctx, args: SetArgs) -> CmdResult {
95    let value = if args.unset {
96        None
97    } else {
98        args.value
99            .as_deref()
100            .map(str::to_string)
101            .filter(|s| !s.is_empty())
102    };
103
104    let mut cfg = Config::load(&ctx.config_path)?;
105
106    let before = field_summary(&cfg, &args.key);
107    apply_set(&mut cfg, &args.key, value.as_deref())?;
108    let after = field_summary(&cfg, &args.key);
109
110    if ctx.dry_run {
111        return Ok(Envelope::success(
112            ctx.environment,
113            ctx.dry_run,
114            json!({
115                "key": args.key,
116                "before": before,
117                "after": after,
118                "written": false,
119                "would_write": true,
120                "path": ctx.config_path.display().to_string(),
121            }),
122        ));
123    }
124
125    cfg.save(&ctx.config_path)?;
126    Ok(Envelope::success(
127        ctx.environment,
128        ctx.dry_run,
129        json!({
130            "key": args.key,
131            "before": before,
132            "after": after,
133            "written": true,
134            "path": ctx.config_path.display().to_string(),
135        }),
136    ))
137}
138
139/// `config migrate` — strip removed-at-v2 keys (`api_base`, `network`)
140/// and re-save at the current schema version. Reads raw JSON to bypass
141/// the `Config::load` legacy-fields hard error, which is the whole point
142/// of this command. Idempotent.
143fn migrate(ctx: &Ctx) -> CmdResult {
144    let path = ctx.config_path.as_path();
145    let src = match std::fs::read_to_string(path) {
146        Ok(s) => s,
147        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
148            return Ok(Envelope::success(
149                ctx.environment,
150                ctx.dry_run,
151                json!({
152                    "path": path.display().to_string(),
153                    "removed": Vec::<String>::new(),
154                    "written": false,
155                    "reason": "no_config_file",
156                }),
157            ));
158        }
159        Err(e) => {
160            return Err(CmdError::Usage(format!(
161                "read config {}: {e}",
162                path.display()
163            )));
164        }
165    };
166    let mut raw: serde_json::Value = serde_json::from_str(&src)
167        .map_err(|e| CmdError::Usage(format!("parse config {}: {e}", path.display())))?;
168    let mut removed: Vec<String> = Vec::new();
169    if let Some(obj) = raw.as_object_mut() {
170        for k in ["api_base", "network"] {
171            if obj.remove(k).is_some() {
172                removed.push(k.to_string());
173            }
174        }
175        obj.insert(
176            "schema_version".to_string(),
177            serde_json::Value::from(crate::config::CURRENT_SCHEMA_VERSION),
178        );
179    }
180    // Round-trip through `Config` so any unrecognized-but-typed field that
181    // would have failed strict deserialization surfaces here, not on the
182    // next load.
183    let cfg: Config = serde_json::from_value(raw)
184        .map_err(|e| CmdError::Usage(format!("re-parse migrated config: {e}")))?;
185    let written = if ctx.dry_run {
186        false
187    } else {
188        cfg.save(path)?;
189        true
190    };
191    Ok(Envelope::success(
192        ctx.environment,
193        ctx.dry_run,
194        json!({
195            "path": path.display().to_string(),
196            "removed": removed,
197            "written": written,
198            "schema_version": crate::config::CURRENT_SCHEMA_VERSION,
199        }),
200    ))
201}
202
203/// Supported field names for `config set`. Kept as a constant so the
204/// error message lists exactly what's allowed without drifting from the
205/// match arm below.
206const ALLOWED_KEYS: &[&str] = &[
207    "environment",
208    "api_key",
209    "wallet_address",
210    "keystore_path",
211    "agent_id",
212    "webhook_url",
213    "webhook_secret_path",
214];
215
216fn apply_set(cfg: &mut Config, key: &str, value: Option<&str>) -> Result<(), CmdError> {
217    match key {
218        "environment" => {
219            cfg.environment = match value {
220                None => None,
221                Some(v) => Some(parse_environment(v)?),
222            };
223        }
224        "api_key" => cfg.api_key = value.map(str::to_string),
225        "wallet_address" => cfg.wallet_address = value.map(str::to_string),
226        "keystore_path" => cfg.keystore_path = value.map(PathBuf::from),
227        "agent_id" => cfg.agent_id = value.map(str::to_string),
228        "webhook_url" => cfg.webhook_url = value.map(str::to_string),
229        "webhook_secret_path" => cfg.webhook_secret_path = value.map(PathBuf::from),
230        _ => {
231            return Err(CmdError::Usage(format!(
232                "unknown config key `{key}`; allowed: {}",
233                ALLOWED_KEYS.join(", ")
234            )));
235        }
236    }
237    Ok(())
238}
239
240fn parse_environment(s: &str) -> Result<Environment, CmdError> {
241    match s {
242        "prod" | "production" => Ok(Environment::Prod),
243        "staging" => Ok(Environment::Staging),
244        "local" => Ok(Environment::Local),
245        other => Err(CmdError::Usage(format!(
246            "unknown environment `{other}`; expected prod | staging | local"
247        ))),
248    }
249}
250
251/// JSON projection of a single field — used by `set` to surface the
252/// before/after diff. Uses [`serialize_for_display`] under the hood so
253/// an `api_key` summary stays redacted.
254fn field_summary(cfg: &Config, key: &str) -> serde_json::Value {
255    let body = serialize_for_display(cfg, false);
256    body.get(key).cloned().unwrap_or(serde_json::Value::Null)
257}
258
259fn serialize_for_display(cfg: &Config, reveal: bool) -> serde_json::Value {
260    let mut v = serde_json::to_value(cfg).unwrap_or_else(|_| json!({}));
261    if !reveal {
262        if let Some(obj) = v.as_object_mut() {
263            if let Some(key) = obj.get_mut("api_key") {
264                if let Some(s) = key.as_str() {
265                    *key = serde_json::Value::String(redact(s));
266                }
267            }
268        }
269    }
270    v
271}
272
273/// Mask all but the last 4 chars: `am_live_abcd1234` → `***1234`. Short
274/// strings (≤4 chars) are fully masked so we don't leak the whole key.
275fn redact(s: &str) -> String {
276    let n = s.chars().count();
277    if n <= 4 {
278        return "***".to_string();
279    }
280    let tail: String = s.chars().skip(n - 4).collect();
281    format!("***{tail}")
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use std::path::PathBuf;
288    use tempfile::TempDir;
289
290    fn ctx_with(path: PathBuf, dry_run: bool) -> Ctx {
291        Ctx {
292            api_key: None,
293            environment: Environment::Local,
294            api_base: None,
295            config_path: path,
296            dry_run,
297            quiet: true,
298            ..Default::default()
299        }
300    }
301
302    #[test]
303    fn redact_masks_all_but_last_4() {
304        assert_eq!(redact("am_live_abcd1234"), "***1234");
305        assert_eq!(redact("12345"), "***2345");
306    }
307
308    #[test]
309    fn redact_short_strings_fully_masked() {
310        assert_eq!(redact("abcd"), "***");
311        assert_eq!(redact("xx"), "***");
312        assert_eq!(redact(""), "***");
313    }
314
315    #[test]
316    fn apply_set_unknown_key_errors_as_usage() {
317        let mut cfg = Config::default();
318        let err = apply_set(&mut cfg, "nope", Some("x")).unwrap_err();
319        match err {
320            CmdError::Usage(msg) => assert!(msg.contains("nope"), "{msg}"),
321            other => panic!("expected Usage, got {other:?}"),
322        }
323    }
324
325    #[test]
326    fn apply_set_environment_enum_is_validated() {
327        let mut cfg = Config::default();
328        assert!(apply_set(&mut cfg, "environment", Some("local")).is_ok());
329        assert_eq!(cfg.environment, Some(Environment::Local));
330        let err = apply_set(&mut cfg, "environment", Some("moon")).unwrap_err();
331        assert!(matches!(err, CmdError::Usage(_)));
332    }
333
334    #[test]
335    fn apply_set_empty_value_clears_field() {
336        let mut cfg = Config {
337            wallet_address: Some("0xabc".into()),
338            ..Config::default()
339        };
340        apply_set(&mut cfg, "wallet_address", None).unwrap();
341        assert!(cfg.wallet_address.is_none());
342    }
343
344    #[test]
345    fn apply_set_rejects_removed_keys_with_migration_hint() {
346        let mut cfg = Config::default();
347        for key in ["api_base", "network"] {
348            let err = apply_set(&mut cfg, key, Some("x")).unwrap_err();
349            match err {
350                CmdError::Usage(msg) => {
351                    assert!(
352                        msg.contains(key),
353                        "error must name the rejected key {key}: {msg}"
354                    );
355                }
356                other => panic!("expected Usage for {key}, got {other:?}"),
357            }
358        }
359    }
360
361    #[test]
362    fn apply_set_keystore_path_accepts_path() {
363        let mut cfg = Config::default();
364        apply_set(&mut cfg, "keystore_path", Some("/tmp/k.json")).unwrap();
365        assert_eq!(cfg.keystore_path, Some(PathBuf::from("/tmp/k.json")));
366    }
367
368    #[tokio::test]
369    async fn show_redacts_api_key_by_default() {
370        let tmp = TempDir::new().unwrap();
371        let path = tmp.path().join("config.json");
372        Config {
373            api_key: Some("am_live_secret0123".into()),
374            ..Config::default()
375        }
376        .save(&path)
377        .unwrap();
378
379        let env = run(
380            &ctx_with(path.clone(), false),
381            Command::Show(ShowArgs { reveal: false }),
382        )
383        .await
384        .unwrap();
385        let v = serde_json::to_value(&env).unwrap();
386        assert_eq!(v["data"]["config"]["api_key"], "***0123");
387    }
388
389    #[tokio::test]
390    async fn show_reveal_prints_api_key_in_full() {
391        let tmp = TempDir::new().unwrap();
392        let path = tmp.path().join("config.json");
393        Config {
394            api_key: Some("am_live_secret0123".into()),
395            ..Config::default()
396        }
397        .save(&path)
398        .unwrap();
399
400        let env = run(
401            &ctx_with(path, false),
402            Command::Show(ShowArgs { reveal: true }),
403        )
404        .await
405        .unwrap();
406        let v = serde_json::to_value(&env).unwrap();
407        assert_eq!(v["data"]["config"]["api_key"], "am_live_secret0123");
408    }
409
410    #[tokio::test]
411    async fn path_reports_existence() {
412        let tmp = TempDir::new().unwrap();
413        let missing = tmp.path().join("config.json");
414        let env = run(&ctx_with(missing.clone(), false), Command::Path)
415            .await
416            .unwrap();
417        let v = serde_json::to_value(&env).unwrap();
418        assert_eq!(v["data"]["exists"], false);
419
420        Config::default().save(&missing).unwrap();
421        let env = run(&ctx_with(missing, false), Command::Path).await.unwrap();
422        let v = serde_json::to_value(&env).unwrap();
423        assert_eq!(v["data"]["exists"], true);
424    }
425
426    #[tokio::test]
427    async fn set_writes_and_persists() {
428        let tmp = TempDir::new().unwrap();
429        let path = tmp.path().join(".taskfast").join("config.json");
430        let env = run(
431            &ctx_with(path.clone(), false),
432            Command::Set(SetArgs {
433                key: "wallet_address".into(),
434                value: Some("0xabc".into()),
435                unset: false,
436            }),
437        )
438        .await
439        .unwrap();
440        let v = serde_json::to_value(&env).unwrap();
441        assert_eq!(v["data"]["written"], true);
442        assert_eq!(v["data"]["after"], "0xabc");
443
444        let loaded = Config::load(&path).unwrap();
445        assert_eq!(loaded.wallet_address.as_deref(), Some("0xabc"));
446    }
447
448    #[tokio::test]
449    async fn set_dry_run_does_not_persist() {
450        let tmp = TempDir::new().unwrap();
451        let path = tmp.path().join(".taskfast").join("config.json");
452        let env = run(
453            &ctx_with(path.clone(), true),
454            Command::Set(SetArgs {
455                key: "wallet_address".into(),
456                value: Some("0xabc".into()),
457                unset: false,
458            }),
459        )
460        .await
461        .unwrap();
462        let v = serde_json::to_value(&env).unwrap();
463        assert_eq!(v["data"]["written"], false);
464        assert_eq!(v["data"]["would_write"], true);
465        assert!(!path.exists());
466    }
467
468    #[tokio::test]
469    async fn set_unset_clears_the_field() {
470        let tmp = TempDir::new().unwrap();
471        let path = tmp.path().join("config.json");
472        Config {
473            wallet_address: Some("0xabc".into()),
474            ..Config::default()
475        }
476        .save(&path)
477        .unwrap();
478
479        run(
480            &ctx_with(path.clone(), false),
481            Command::Set(SetArgs {
482                key: "wallet_address".into(),
483                value: None,
484                unset: true,
485            }),
486        )
487        .await
488        .unwrap();
489
490        let loaded = Config::load(&path).unwrap();
491        assert!(loaded.wallet_address.is_none());
492    }
493
494    #[tokio::test]
495    async fn migrate_strips_legacy_keys_and_bumps_schema() {
496        let tmp = TempDir::new().unwrap();
497        let path = tmp.path().join(".taskfast").join("config.json");
498        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
499        let body = r#"{
500            "schema_version": 1,
501            "api_base": "https://api.taskfast.app",
502            "network": "mainnet",
503            "wallet_address": "0xabc"
504        }"#;
505        std::fs::write(&path, body).unwrap();
506
507        let env = run(&ctx_with(path.clone(), false), Command::Migrate)
508            .await
509            .unwrap();
510        let v = serde_json::to_value(&env).unwrap();
511        assert_eq!(v["data"]["written"], true);
512        let removed: Vec<String> = serde_json::from_value(v["data"]["removed"].clone()).unwrap();
513        assert!(removed.contains(&"api_base".to_string()));
514        assert!(removed.contains(&"network".to_string()));
515
516        // Post-migration `Config::load` must succeed (no legacy fields).
517        let loaded = Config::load(&path).expect("post-migrate load succeeds");
518        assert_eq!(loaded.wallet_address.as_deref(), Some("0xabc"));
519    }
520
521    #[tokio::test]
522    async fn migrate_is_idempotent() {
523        let tmp = TempDir::new().unwrap();
524        let path = tmp.path().join("config.json");
525        Config {
526            wallet_address: Some("0xabc".into()),
527            ..Config::default()
528        }
529        .save(&path)
530        .unwrap();
531
532        let env = run(&ctx_with(path, false), Command::Migrate).await.unwrap();
533        let v = serde_json::to_value(&env).unwrap();
534        let removed: Vec<String> = serde_json::from_value(v["data"]["removed"].clone()).unwrap();
535        assert!(removed.is_empty(), "nothing to remove on a clean config");
536    }
537
538    #[tokio::test]
539    async fn migrate_no_config_file_is_noop() {
540        let tmp = TempDir::new().unwrap();
541        let path = tmp.path().join("nonexistent.json");
542        let env = run(&ctx_with(path, false), Command::Migrate).await.unwrap();
543        let v = serde_json::to_value(&env).unwrap();
544        assert_eq!(v["data"]["written"], false);
545        assert_eq!(v["data"]["reason"], "no_config_file");
546    }
547
548    #[tokio::test]
549    async fn set_api_key_shows_redacted_after_in_envelope() {
550        let tmp = TempDir::new().unwrap();
551        let path = tmp.path().join("config.json");
552        let env = run(
553            &ctx_with(path, false),
554            Command::Set(SetArgs {
555                key: "api_key".into(),
556                value: Some("am_live_supersecret1234".into()),
557                unset: false,
558            }),
559        )
560        .await
561        .unwrap();
562        let v = serde_json::to_value(&env).unwrap();
563        assert_eq!(v["data"]["after"], "***1234");
564    }
565}