Skip to main content

taskfast_cli/cmd/
mod.rs

1// SPDX-License-Identifier: MIT
2//! Subcommand module tree + shared [`Ctx`] / [`CmdError`] types.
3//!
4//! The taxonomy here is the CLI's stable, orchestrator-visible surface:
5//!
6//!   * `CmdError` codes (the short strings in the JSON envelope)
7//!   * `ExitCode` bucket per variant
8//!
9//! Both are covered by tests at the bottom of this file so a refactor that
10//! silently re-homes a variant will break the build.
11
12use std::path::PathBuf;
13use std::str::FromStr;
14use std::time::Duration;
15
16use rust_decimal::Decimal;
17use thiserror::Error;
18
19use crate::config::{Config, ConfigError};
20use crate::envelope::Envelope;
21use crate::exit::ExitCode;
22use crate::{is_well_known_api_base, Environment, Network};
23
24use taskfast_agent::keystore::KeystoreError;
25use taskfast_chains::tempo::SigningError;
26use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
27use taskfast_client::{Error as ClientError, TaskFastClient};
28
29pub mod agent;
30pub mod artifact;
31pub mod backer;
32pub mod bid;
33pub mod bond;
34pub mod cast;
35pub mod config;
36pub mod discover;
37pub mod dispute;
38pub mod escrow;
39pub mod events;
40pub mod init;
41pub mod init_tui;
42pub mod me;
43pub mod message;
44pub mod payment;
45pub mod ping;
46pub mod platform;
47pub mod post;
48pub mod review;
49pub mod settle;
50pub mod skills;
51pub mod stake;
52pub mod task;
53pub mod wallet;
54pub mod wallet_args;
55pub mod webhook;
56
57/// Shared invocation context threaded through every subcommand.
58///
59/// Built once in `main` from parsed global flags; subcommands only read.
60#[derive(Clone)]
61pub struct Ctx {
62    pub api_key: Option<String>,
63    pub environment: Environment,
64    /// Explicit `--api-base` / `TASKFAST_API` override. Wins over
65    /// [`Environment::api_base`] when set. Never persisted — the in-memory
66    /// override is session-scoped only.
67    pub api_base: Option<String>,
68    /// Resolved path to the JSON config file (default
69    /// `./.taskfast/config.json`, override via `--config` /
70    /// `TASKFAST_CONFIG`). Subcommands that persist state (init,
71    /// `config set`, etc.) write here; tests construct this directly.
72    pub config_path: PathBuf,
73    /// Poster wallet address from config — fallback when no flag/env set
74    /// on `post`/`settle`/`escrow sign`. Persisted by `taskfast init`.
75    pub wallet_address: Option<String>,
76    /// Keystore path from config — fallback for the same trio.
77    pub keystore_path: Option<PathBuf>,
78    /// Stablecoin-units threshold above which mutating commands
79    /// (`post`, `settle`) require an explicit `--yes`. `None` = gate
80    /// disabled. Set via `confirm_above_budget` in the JSON config.
81    pub confirm_above_budget: Option<String>,
82    /// Default log format for `--verbose` output. `None` = text. Set
83    /// via `log_format` in the JSON config or `TASKFAST_LOG_FORMAT` env.
84    pub log_format: Option<String>,
85    /// Poster approval-deadline horizon for `escrow sign`. Parsed from
86    /// the config file's `approval_horizon` at startup (fail-fast on
87    /// malformed values). `None` = built-in default (7 days). The
88    /// `--approval-horizon` flag / `TASKFAST_APPROVAL_HORIZON` env
89    /// still win over this.
90    pub approval_horizon: Option<Duration>,
91    /// Receipt-polling ceiling for `escrow sign`. Parsed from the
92    /// config file's `receipt_timeout` at startup. `None` = network-aware
93    /// default (3min mainnet, 1min testnet). `--receipt-timeout` /
94    /// `TASKFAST_RECEIPT_TIMEOUT` still win over this.
95    pub receipt_timeout: Option<Duration>,
96    pub dry_run: bool,
97    pub quiet: bool,
98    /// F2 opt-in: allow a custom `api_base` or `tempo_rpc_url` that isn't
99    /// one of the well-known TaskFast defaults. Plumbed through to
100    /// subcommands (notably `post`) that construct their own network
101    /// clients outside the [`TaskFastClient`] covered by the Ctx-level
102    /// guard.
103    pub allow_custom_endpoints: bool,
104}
105
106/// Default environment when neither a flag nor the config file pins one.
107pub const DEFAULT_ENVIRONMENT: Environment = Environment::Prod;
108
109impl Default for Ctx {
110    fn default() -> Self {
111        Self {
112            api_key: None,
113            environment: DEFAULT_ENVIRONMENT,
114            api_base: None,
115            config_path: PathBuf::from("/dev/null"),
116            wallet_address: None,
117            keystore_path: None,
118            confirm_above_budget: None,
119            log_format: None,
120            approval_horizon: None,
121            receipt_timeout: None,
122            dry_run: false,
123            quiet: false,
124            allow_custom_endpoints: false,
125        }
126    }
127}
128
129impl Ctx {
130    /// Build a [`Ctx`] by layering CLI flags (including clap's
131    /// env-var folding) over the on-disk [`Config`]. Precedence:
132    ///
133    /// ```text
134    /// flag > env var > config file > default
135    /// ```
136    ///
137    /// Clap already folds `flag > env var` for each field (via
138    /// `#[arg(env = "…")]`), so the merge here is just "cli wins, else
139    /// config, else default". `dry_run` and `quiet` are never
140    /// persisted — they're invocation-scoped.
141    pub fn from_parts(
142        cli_api_key: Option<String>,
143        cli_env: Option<Environment>,
144        cli_api_base: Option<String>,
145        cli_config_path: Option<PathBuf>,
146        cli_dry_run: bool,
147        cli_quiet: bool,
148        cli_allow_custom_endpoints: bool,
149        cfg: &Config,
150    ) -> Result<Self, CmdError> {
151        let approval_horizon =
152            parse_duration_cfg(cfg.approval_horizon.as_deref(), "approval_horizon")?;
153        let receipt_timeout =
154            parse_duration_cfg(cfg.receipt_timeout.as_deref(), "receipt_timeout")?;
155        let environment = cli_env.or(cfg.environment).unwrap_or(DEFAULT_ENVIRONMENT);
156        // api_base is no longer persisted: only the CLI/env-supplied override
157        // can deviate from `environment.api_base()`. The endpoint guard still
158        // gates that override against the well-known set + opt-in flag.
159        let api_base = cli_api_base;
160        enforce_endpoint_guard(environment, api_base.as_deref(), cli_allow_custom_endpoints)?;
161        Ok(Self {
162            api_key: cli_api_key.or_else(|| cfg.api_key.clone()),
163            environment,
164            api_base,
165            config_path: cli_config_path.unwrap_or_else(Config::default_path),
166            wallet_address: cfg.wallet_address.clone(),
167            keystore_path: cfg.keystore_path.clone(),
168            confirm_above_budget: cfg.confirm_above_budget.clone(),
169            log_format: cfg.log_format.clone(),
170            approval_horizon,
171            receipt_timeout,
172            dry_run: cli_dry_run,
173            quiet: cli_quiet,
174            allow_custom_endpoints: cli_allow_custom_endpoints,
175        })
176    }
177
178    /// F15: gather non-fatal security warnings derived from the effective
179    /// runtime state. Computed at emit time (not at construction) so
180    /// subcommand-induced signals can be folded in here if needed later.
181    /// Always safe to call — never allocates for a healthy run.
182    pub fn security_warnings(&self) -> Vec<crate::envelope::SecurityWarning> {
183        use crate::envelope::SecurityWarning;
184        let mut out = Vec::new();
185        if self.allow_custom_endpoints {
186            let detail = self.api_base.as_deref().unwrap_or("(env default)");
187            out.push(SecurityWarning {
188                code: "custom_endpoints_allowed",
189                message: format!(
190                    "--allow-custom-endpoints is in effect; api_base={detail}. \
191                     Traffic will go to a non-well-known host."
192                ),
193            });
194        }
195        if std::env::var("TASKFAST_WALLET_PASSWORD").is_ok_and(|v| !v.is_empty()) {
196            out.push(SecurityWarning {
197                code: "password_env_var",
198                message: "TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
199                         prefer --wallet-password-file."
200                    .into(),
201            });
202        }
203        out
204    }
205
206    /// Resolved API base URL: override if set, else env default.
207    pub fn base_url(&self) -> &str {
208        match self.api_base.as_deref() {
209            Some(u) => u,
210            None => self.environment.api_base(),
211        }
212    }
213
214    /// Build an authenticated client, or fail with [`CmdError::MissingApiKey`]
215    /// if no key was supplied (via `--api-key` or `TASKFAST_API_KEY`).
216    pub fn client(&self) -> Result<TaskFastClient, CmdError> {
217        let key = self.api_key.as_deref().ok_or(CmdError::MissingApiKey)?;
218        TaskFastClient::from_api_key(self.base_url(), key).map_err(CmdError::from)
219    }
220
221    /// Pick the reqwest client to use for a JSON-RPC URL.
222    ///
223    /// Any URL whose prefix is `{api_base}/rpc/` is this deployment's
224    /// authenticated proxy and **must** be hit with the X-API-Key-bearing
225    /// client; otherwise the proxy short-circuits with 401 "missing API key"
226    /// before reaching the upstream RPC. Anything else (a bare upstream
227    /// Tempo gateway via `--rpc-url`/`TEMPO_RPC_URL`) gets a fresh client
228    /// with no TaskFast headers.
229    ///
230    /// This is selected by URL origin (same host as `api_base`), not by which
231    /// resolution branch the URL came from, so a user who points `--rpc-url` /
232    /// `TEMPO_RPC_URL` at the proxy still gets the authenticated client.
233    pub fn rpc_http_client(&self, client: &TaskFastClient, rpc_url: &str) -> reqwest::Client {
234        if is_proxy_rpc_url(rpc_url, self.base_url()) {
235            client.http_client()
236        } else {
237            reqwest::Client::new()
238        }
239    }
240
241    /// Fail-closed budget gate. When `confirm_above_budget` is set in the
242    /// config, any mutation whose budget exceeds it must be opted into via
243    /// `--yes`. By design there's no TTY prompt — automation-first stays
244    /// intact; the gate just stops a fat-finger script before it broadcasts
245    /// an oversized ERC-20 approve. `verb` is the action ("post a task",
246    /// "settle this task") for the error message.
247    pub fn enforce_budget_gate(
248        &self,
249        budget: Option<&str>,
250        yes: bool,
251        verb: &str,
252    ) -> Result<(), CmdError> {
253        let threshold_str = match self.confirm_above_budget.as_deref() {
254            Some(t) => t,
255            None => return Ok(()),
256        };
257        let budget_str = match budget {
258            Some(b) => b,
259            None => return Ok(()),
260        };
261        // Decimal (not f64): budget values are decimal strings like "0.1"
262        // that f64 cannot represent exactly. An f64 compare could flip the
263        // gate around an exact-boundary threshold, which defeats the whole
264        // point of a safety rail against oversized approvals.
265        let threshold = Decimal::from_str(threshold_str).map_err(|_| {
266            CmdError::Usage(format!(
267                "config `confirm_above_budget` is not a decimal: {threshold_str:?}"
268            ))
269        })?;
270        let amount = Decimal::from_str(budget_str)
271            .map_err(|_| CmdError::Usage(format!("budget {budget_str:?} is not a decimal")))?;
272        if amount > threshold && !yes {
273            return Err(CmdError::Usage(format!(
274                "refusing to {verb}: budget {amount} exceeds confirm_above_budget \
275                 {threshold} (pass --yes to override)"
276            )));
277        }
278        Ok(())
279    }
280}
281
282/// True when `rpc_url` is served from the same origin (scheme + host + port)
283/// as this deployment's `base_url` — i.e. it is this deployment's own
284/// authenticated proxy, whatever path it is mounted at (`/rpc/…` or
285/// `/api/rpc/…`). Used both to gate off-host RPC routing and to decide
286/// whether the authenticated reqwest client (with the `X-API-Key` default
287/// header) is required for the call.
288///
289/// The path is deliberately irrelevant: every route on `base_url` is a
290/// TaskFast route that already accepts the key, so the only boundary that
291/// matters is the host — we never leak the key off-host. `Url::origin()`
292/// folds in the scheme, so an `https`→`http` downgrade is a different origin
293/// and is correctly rejected.
294pub(crate) fn is_proxy_rpc_url(rpc_url: &str, base_url: &str) -> bool {
295    match (url::Url::parse(rpc_url), url::Url::parse(base_url)) {
296        // Two opaque origins are never equal, so a match here is always a
297        // genuine same-host tuple origin.
298        (Ok(rpc), Ok(base)) => rpc.origin() == base.origin(),
299        _ => false,
300    }
301}
302
303fn is_loopback_url(url: &str) -> bool {
304    match url::Url::parse(url) {
305        Ok(u) => matches!(
306            u.host_str(),
307            Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
308        ),
309        Err(_) => false,
310    }
311}
312
313pub(crate) fn validate_override_rpc_url(
314    url: &str,
315    network: Network,
316    allow_custom: bool,
317) -> Result<&str, CmdError> {
318    if !allow_custom {
319        return Err(CmdError::Usage(format!(
320            "refusing to use custom tempo_rpc_url {url:?}: pass \
321             --allow-custom-endpoints (or set \
322             TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) to override. The default \
323             path routes RPC through `{{api_base}}/rpc/{{network}}` \
324             which inherits the api_base endpoint guard."
325        )));
326    }
327
328    let is_plain_http_mainnet =
329        matches!(network, Network::Mainnet) && url.starts_with("http://") && !is_loopback_url(url);
330    if is_plain_http_mainnet {
331        return Err(CmdError::Usage(format!(
332            "refusing plain-HTTP mainnet tempo_rpc_url {url:?}: MITM on a \
333             mainnet RPC can observe the poster wallet and inflate gas \
334             price. Use HTTPS or point at loopback for local testing."
335        )));
336    }
337
338    Ok(url)
339}
340
341/// Trim and validate a user-supplied EVM wallet address, returning the
342/// trimmed form to forward to the server. Mirrors the `--wallet-address`
343/// preflight in `post`/`escrow`/`settle`: a malformed address is a
344/// never-retry [`CmdError::Usage`], and trimming keeps a copy-pasted
345/// trailing newline/space from turning into a server-side 422.
346pub(crate) fn parse_wallet_address(raw: &str) -> Result<String, CmdError> {
347    let trimmed = raw.trim();
348    let _: alloy_primitives::Address = trimmed
349        .parse()
350        .map_err(|e| CmdError::Usage(format!("--wallet is not a valid EVM address: {e}")))?;
351    Ok(trimmed.to_string())
352}
353
354pub(crate) fn network_policy_for_chain_id(chain_id: u64) -> Network {
355    if chain_id == TEMPO_MAINNET_CHAIN_ID {
356        Network::Mainnet
357    } else {
358        Network::Testnet
359    }
360}
361
362/// F2 endpoint-override guard. Refuses to run when the effective
363/// `api_base` deviates from [`well_known_api_bases`][crate::well_known_api_bases]
364/// unless the caller explicitly opts in via `--allow-custom-endpoints`
365/// (or env `TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1`) or the environment is
366/// [`Environment::Local`] (local dev is already network-sandboxed).
367///
368/// Threat: a malicious cloned repo ships `.taskfast/config.json` with an
369/// attacker `api_base`; `taskfast` loads config from CWD, so the next
370/// invocation silently exfiltrates the PAT (carried in `X-API-Key`) to
371/// the attacker host. The guard turns that silent redirect into a loud
372/// `Usage` error before any request fires.
373fn enforce_endpoint_guard(
374    environment: Environment,
375    api_base: Option<&str>,
376    allow_custom: bool,
377) -> Result<(), CmdError> {
378    if allow_custom || environment == Environment::Local {
379        return Ok(());
380    }
381    let Some(url) = api_base else { return Ok(()) };
382    if is_well_known_api_base(url) {
383        return Ok(());
384    }
385    Err(CmdError::Usage(format!(
386        "refusing to use custom api_base {url:?} for env {env}: \
387         pass --allow-custom-endpoints (or set TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) \
388         to override. This guard blocks a malicious .taskfast/config.json in \
389         a cloned repo from silently redirecting API traffic.",
390        env = environment.as_str()
391    )))
392}
393
394/// Runtime cross-system check for the env→network invariant. The
395/// compile-time table in [`Environment::network`] says each env runs
396/// exactly one Tempo network; this verifies that the deployment at
397/// `ctx.base_url()` agrees by inspecting `/config/network`.
398///
399/// **Default: warn-only.** Today's deployments still advertise multiple
400/// networks in one response (server-side one-network-per-deployment
401/// tracked in #62). Until that lands, a mismatch logs a `tracing::warn!`
402/// and continues. Set `TASKFAST_STRICT_ENV_NETWORK=1` to fail-closed
403/// instead. The default flips to strict in a follow-up CLI release once
404/// #62 is deployed across prod + staging.
405///
406/// Bypassed entirely for [`Environment::Local`] (sandboxed dev) and when
407/// `--allow-custom-endpoints` is set, matching the F2 endpoint guard.
408pub async fn enforce_server_network_invariant(
409    ctx: &Ctx,
410    client: &TaskFastClient,
411) -> Result<(), CmdError> {
412    if ctx.allow_custom_endpoints || ctx.environment == Environment::Local {
413        return Ok(());
414    }
415    let cfg = client
416        .fetch_network_config()
417        .await
418        .map_err(CmdError::from)?;
419    let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
420        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
421    let advertised: Vec<String> = cfg.networks.keys().cloned().collect();
422    check_network_invariant(ctx.environment, ctx.base_url(), &advertised, strict)
423}
424
425/// Pure-logic core of [`enforce_server_network_invariant`]. Split out so
426/// the strict / warn / bypass branches are unit-testable without spinning
427/// up a wiremock server.
428fn check_network_invariant(
429    env: Environment,
430    api_base: &str,
431    advertised: &[String],
432    strict: bool,
433) -> Result<(), CmdError> {
434    let expected = env.network().as_str();
435    if advertised.len() == 1 && advertised[0] == expected {
436        return Ok(());
437    }
438    if strict {
439        return Err(CmdError::Server(format!(
440            "deployment at {api_base} advertises networks {advertised:?}; env {} requires \
441             exactly [{expected}]. Server-side fix tracked in issue #62. Unset \
442             TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
443            env.as_str(),
444        )));
445    }
446    tracing::warn!(
447        api_base = %api_base,
448        env = env.as_str(),
449        expected = expected,
450        advertised = ?advertised,
451        "deployment advertises a different network shape than env requires; \
452         server-side fix tracked in issue #62. Set TASKFAST_STRICT_ENV_NETWORK=1 \
453         to fail-closed."
454    );
455    Ok(())
456}
457
458/// Parse a human-readable duration string from the config file,
459/// wrapping a malformed value in [`CmdError::Usage`] that names the
460/// field. Startup-time parsing lets a bad `approval_horizon: "7xyz"`
461/// surface before any on-chain operation instead of mid-`escrow sign`.
462fn parse_duration_cfg(
463    raw: Option<&str>,
464    field: &'static str,
465) -> Result<Option<Duration>, CmdError> {
466    match raw {
467        None => Ok(None),
468        Some(s) => humantime::parse_duration(s).map(Some).map_err(|e| {
469            CmdError::Usage(format!("config `{field}` is not a duration: {s:?} ({e})"))
470        }),
471    }
472}
473
474/// Resolve a duration with the CLI precedence: flag > Ctx (config) > default.
475/// Pulled out so #9 (`approval_horizon`) and #10 (`receipt_timeout`) share one
476/// pinning path — and tests exercise the precedence once, not per command.
477pub fn resolve_duration(
478    flag: Option<Duration>,
479    ctx_field: Option<Duration>,
480    default: Duration,
481) -> Duration {
482    flag.or(ctx_field).unwrap_or(default)
483}
484
485pub type CmdResult = Result<Envelope, CmdError>;
486
487/// CLI-layer error. Every variant maps to a stable `code` string (in the
488/// envelope) and a stable [`ExitCode`] bucket — both are part of the
489/// orchestrator contract.
490#[derive(Debug, Error)]
491pub enum CmdError {
492    #[error("missing API key: set --api-key or TASKFAST_API_KEY")]
493    MissingApiKey,
494
495    #[error("usage: {0}")]
496    Usage(String),
497
498    #[error("auth: {0}")]
499    Auth(String),
500
501    #[error("rate limited (retry in {retry_after:?})")]
502    RateLimited { retry_after: Duration },
503
504    #[error("validation [{code}]: {message}")]
505    Validation { code: String, message: String },
506
507    #[error("server: {0}")]
508    Server(String),
509
510    #[error("network: {0}")]
511    Network(String),
512
513    #[error("decode: {0}")]
514    Decode(String),
515
516    #[error("keystore: {0}")]
517    Keystore(String),
518
519    #[error("signing: {0}")]
520    Signing(String),
521
522    #[error("not yet implemented: {0}")]
523    Unimplemented(&'static str),
524
525    #[error(transparent)]
526    Config(#[from] ConfigError),
527}
528
529impl CmdError {
530    /// Short, stable code string for the JSON envelope's `error.code` field.
531    pub fn code(&self) -> &'static str {
532        match self {
533            Self::MissingApiKey => "missing_api_key",
534            Self::Usage(_) => "usage",
535            Self::Auth(_) => "auth",
536            Self::RateLimited { .. } => "rate_limited",
537            Self::Validation { .. } => "validation",
538            Self::Server(_) => "server",
539            Self::Network(_) => "network",
540            Self::Decode(_) => "decode",
541            Self::Keystore(_) => "keystore",
542            Self::Signing(_) => "signing",
543            Self::Unimplemented(_) => "unimplemented",
544            Self::Config(_) => "config",
545        }
546    }
547
548    /// Stable exit-code bucket — see [`ExitCode`] docstring for the taxonomy.
549    pub fn exit_code(&self) -> ExitCode {
550        match self {
551            Self::MissingApiKey | Self::Usage(_) | Self::Config(_) => ExitCode::Usage,
552            Self::Auth(_) => ExitCode::Auth,
553            Self::RateLimited { .. } => ExitCode::RateLimited,
554            Self::Validation { .. } => ExitCode::Validation,
555            Self::Server(_) | Self::Network(_) | Self::Decode(_) => ExitCode::Server,
556            Self::Keystore(_) | Self::Signing(_) => ExitCode::Wallet,
557            Self::Unimplemented(_) => ExitCode::Unimplemented,
558        }
559    }
560
561    /// Server-directed sleep hint, if any. Populated only for
562    /// [`Self::RateLimited`] so orchestrators can read it directly from the
563    /// envelope instead of parsing the message.
564    pub fn retry_after(&self) -> Option<Duration> {
565        match self {
566            Self::RateLimited { retry_after } => Some(*retry_after),
567            _ => None,
568        }
569    }
570}
571
572impl From<ClientError> for CmdError {
573    fn from(e: ClientError) -> Self {
574        match e {
575            ClientError::Auth(m) => Self::Auth(m),
576            ClientError::Validation { code, message } => Self::Validation { code, message },
577            ClientError::RateLimited { retry_after } => Self::RateLimited { retry_after },
578            ClientError::Server(m) => Self::Server(m),
579            ClientError::Network(e) => Self::Network(e.to_string()),
580            ClientError::Decode(e) => Self::Decode(e.to_string()),
581        }
582    }
583}
584
585impl From<KeystoreError> for CmdError {
586    fn from(e: KeystoreError) -> Self {
587        Self::Keystore(e.to_string())
588    }
589}
590
591impl From<SigningError> for CmdError {
592    fn from(e: SigningError) -> Self {
593        Self::Signing(e.to_string())
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600    use std::collections::HashSet;
601
602    fn sample(variant: &str) -> CmdError {
603        match variant {
604            "missing_api_key" => CmdError::MissingApiKey,
605            "usage" => CmdError::Usage("bad flag".into()),
606            "auth" => CmdError::Auth("401".into()),
607            "rate_limited" => CmdError::RateLimited {
608                retry_after: Duration::from_secs(30),
609            },
610            "validation" => CmdError::Validation {
611                code: "bad_field".into(),
612                message: "x".into(),
613            },
614            "server" => CmdError::Server("500".into()),
615            "network" => CmdError::Network("dns".into()),
616            "decode" => CmdError::Decode("json".into()),
617            "keystore" => CmdError::Keystore("bad pw".into()),
618            "signing" => CmdError::Signing("hsm".into()),
619            "unimplemented" => CmdError::Unimplemented("soon"),
620            "config" => CmdError::Config(ConfigError::Io {
621                path: PathBuf::from("/x"),
622                source: std::io::Error::other("boom"),
623            }),
624            _ => unreachable!(),
625        }
626    }
627
628    const ALL: &[&str] = &[
629        "missing_api_key",
630        "usage",
631        "auth",
632        "rate_limited",
633        "validation",
634        "server",
635        "network",
636        "decode",
637        "keystore",
638        "signing",
639        "unimplemented",
640        "config",
641    ];
642
643    #[test]
644    fn every_variant_has_distinct_code() {
645        let codes: HashSet<&'static str> = ALL.iter().map(|v| sample(v).code()).collect();
646        assert_eq!(codes.len(), ALL.len(), "codes must be unique per variant");
647        for v in ALL {
648            assert_eq!(sample(v).code(), *v, "code() for {v} must match the label");
649        }
650    }
651
652    #[test]
653    fn exit_code_taxonomy_matches_plan() {
654        // Pinning here is intentional: changing any of these is a breaking
655        // change to the orchestrator contract.
656        assert_eq!(CmdError::MissingApiKey.exit_code(), ExitCode::Usage);
657        assert_eq!(sample("usage").exit_code(), ExitCode::Usage);
658        assert_eq!(sample("auth").exit_code(), ExitCode::Auth);
659        assert_eq!(sample("rate_limited").exit_code(), ExitCode::RateLimited);
660        assert_eq!(sample("validation").exit_code(), ExitCode::Validation);
661        assert_eq!(sample("server").exit_code(), ExitCode::Server);
662        assert_eq!(sample("network").exit_code(), ExitCode::Server);
663        assert_eq!(sample("decode").exit_code(), ExitCode::Server);
664        assert_eq!(sample("keystore").exit_code(), ExitCode::Wallet);
665        assert_eq!(sample("signing").exit_code(), ExitCode::Wallet);
666        assert_eq!(sample("unimplemented").exit_code(), ExitCode::Unimplemented);
667        assert_eq!(sample("config").exit_code(), ExitCode::Usage);
668    }
669
670    #[test]
671    fn client_error_folds_retry_after_into_cmd_error() {
672        let ce = ClientError::RateLimited {
673            retry_after: Duration::from_secs(42),
674        };
675        let cmd: CmdError = ce.into();
676        match cmd {
677            CmdError::RateLimited { retry_after } => {
678                assert_eq!(retry_after, Duration::from_secs(42));
679            }
680            other => panic!("expected RateLimited, got {other:?}"),
681        }
682        // And the hint is available via the convenience accessor.
683        assert_eq!(
684            sample("rate_limited").retry_after(),
685            Some(Duration::from_secs(30))
686        );
687        assert!(sample("auth").retry_after().is_none());
688    }
689
690    #[test]
691    fn is_proxy_rpc_url_matches_same_origin() {
692        let base = "https://staging.api.taskfast.app";
693        // Proxy mounted at /rpc/ — same origin, authenticated client.
694        assert!(is_proxy_rpc_url(
695            "https://staging.api.taskfast.app/rpc/testnet",
696            base
697        ));
698        // Proxy mounted at /api/rpc/ (gh#79) — same origin, still ours.
699        // The path differs but the host is the one the endpoint-guard
700        // already approved, so the API key belongs here.
701        assert!(is_proxy_rpc_url(
702            "https://staging.api.taskfast.app/api/rpc/testnet",
703            base
704        ));
705        // Trailing slash on base must not break the match.
706        assert!(is_proxy_rpc_url(
707            "https://staging.api.taskfast.app/rpc/mainnet",
708            "https://staging.api.taskfast.app/"
709        ));
710        // Bare upstream Tempo gateway — different host, bare client is
711        // correct (no TaskFast auth header to leak off-host).
712        assert!(!is_proxy_rpc_url("https://rpc.moderato.tempo.xyz", base));
713        // Different host, even one that pretends to be a proxy path,
714        // must not pick up the authenticated client.
715        assert!(!is_proxy_rpc_url(
716            "https://attacker.example/rpc/testnet",
717            base
718        ));
719        // Scheme downgrade is a *different* origin — never send the key
720        // over plaintext, even to the same host.
721        assert!(!is_proxy_rpc_url(
722            "http://staging.api.taskfast.app/rpc/testnet",
723            base
724        ));
725    }
726
727    #[test]
728    fn ctx_base_url_override_wins_over_environment_default() {
729        let ctx = Ctx {
730            api_key: None,
731            environment: Environment::Prod,
732            api_base: Some("http://localhost:9999".into()),
733            config_path: PathBuf::from("/dev/null"),
734            dry_run: false,
735            quiet: false,
736            ..Default::default()
737        };
738        assert_eq!(ctx.base_url(), "http://localhost:9999");
739    }
740
741    #[test]
742    fn ctx_base_url_falls_back_to_environment_default() {
743        for (env, expected) in [
744            (Environment::Prod, "https://api.taskfast.app"),
745            (Environment::Staging, "https://staging.api.taskfast.app"),
746            (Environment::Local, "http://127.0.0.1:4000"),
747        ] {
748            let ctx = Ctx {
749                api_key: None,
750                environment: env,
751                api_base: None,
752                config_path: PathBuf::from("/dev/null"),
753                dry_run: false,
754                quiet: false,
755                ..Default::default()
756            };
757            assert_eq!(ctx.base_url(), expected);
758        }
759    }
760
761    #[test]
762    fn ctx_client_errors_when_api_key_missing() {
763        let ctx = Ctx {
764            api_key: None,
765            environment: Environment::Local,
766            api_base: None,
767            config_path: PathBuf::from("/dev/null"),
768            dry_run: false,
769            quiet: false,
770            ..Default::default()
771        };
772        match ctx.client() {
773            Err(CmdError::MissingApiKey) => {}
774            Err(other) => panic!("expected MissingApiKey, got {other:?}"),
775            Ok(_) => panic!("expected MissingApiKey, got Ok(client)"),
776        }
777    }
778
779    #[test]
780    fn ctx_client_builds_when_api_key_present() {
781        let ctx = Ctx {
782            api_key: Some("tk_test_abc".into()),
783            environment: Environment::Local,
784            api_base: None,
785            config_path: PathBuf::from("/dev/null"),
786            dry_run: false,
787            quiet: false,
788            ..Default::default()
789        };
790        ctx.client().expect("client should build with a valid key");
791    }
792
793    fn cfg_with(api_key: Option<&str>, environment: Option<Environment>) -> Config {
794        Config {
795            api_key: api_key.map(str::to_string),
796            environment,
797            ..Config::default()
798        }
799    }
800
801    #[test]
802    fn from_parts_threads_wallet_keystore_confirm_log_format_from_config() {
803        let cfg = Config {
804            wallet_address: Some("0xfeed".into()),
805            keystore_path: Some(PathBuf::from("/tmp/k.json")),
806            confirm_above_budget: Some("500".into()),
807            log_format: Some("json".into()),
808            ..Config::default()
809        };
810        let ctx =
811            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
812        assert_eq!(ctx.wallet_address.as_deref(), Some("0xfeed"));
813        assert_eq!(
814            ctx.keystore_path.as_deref(),
815            Some(std::path::Path::new("/tmp/k.json"))
816        );
817        assert_eq!(ctx.confirm_above_budget.as_deref(), Some("500"));
818        assert_eq!(ctx.log_format.as_deref(), Some("json"));
819    }
820
821    #[test]
822    fn from_parts_parses_approval_horizon_from_config() {
823        let cfg = Config {
824            approval_horizon: Some("7d".into()),
825            ..Config::default()
826        };
827        let ctx =
828            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 7d");
829        assert_eq!(ctx.approval_horizon, Some(Duration::from_hours(24 * 7)));
830    }
831
832    #[test]
833    fn from_parts_parses_receipt_timeout_from_config() {
834        let cfg = Config {
835            receipt_timeout: Some("3min".into()),
836            ..Config::default()
837        };
838        let ctx =
839            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
840        assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
841    }
842
843    #[test]
844    fn from_parts_rejects_malformed_approval_horizon() {
845        let cfg = Config {
846            approval_horizon: Some("7xyz".into()),
847            ..Config::default()
848        };
849        let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
850            .err()
851            .expect("malformed config must fail at startup");
852        match err {
853            CmdError::Usage(msg) => {
854                assert!(msg.contains("approval_horizon"), "msg: {msg}");
855                assert!(msg.contains("7xyz"), "msg: {msg}");
856            }
857            other => panic!("expected Usage, got {other:?}"),
858        }
859    }
860
861    #[test]
862    fn from_parts_rejects_malformed_receipt_timeout() {
863        let cfg = Config {
864            receipt_timeout: Some("nope".into()),
865            ..Config::default()
866        };
867        let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
868            .err()
869            .expect("malformed timeout = startup error");
870        assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
871    }
872
873    #[test]
874    fn from_parts_duration_fields_none_when_config_absent() {
875        let ctx = Ctx::from_parts(
876            None,
877            None,
878            None,
879            None,
880            false,
881            false,
882            false,
883            &Config::default(),
884        )
885        .expect("default cfg is valid");
886        assert!(ctx.approval_horizon.is_none());
887        assert!(ctx.receipt_timeout.is_none());
888    }
889
890    #[test]
891    fn resolve_duration_flag_wins_over_ctx_and_default() {
892        let out = resolve_duration(
893            Some(Duration::from_secs(10)),
894            Some(Duration::from_secs(20)),
895            Duration::from_secs(30),
896        );
897        assert_eq!(out, Duration::from_secs(10));
898    }
899
900    #[test]
901    fn resolve_duration_ctx_wins_over_default_when_no_flag() {
902        let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
903        assert_eq!(out, Duration::from_secs(20));
904    }
905
906    #[test]
907    fn resolve_duration_falls_back_to_default() {
908        let out = resolve_duration(None, None, Duration::from_secs(30));
909        assert_eq!(out, Duration::from_secs(30));
910    }
911
912    fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
913        Ctx {
914            confirm_above_budget: threshold.map(str::to_string),
915            ..Default::default()
916        }
917    }
918
919    #[test]
920    fn budget_gate_no_op_when_threshold_unset() {
921        let ctx = ctx_with_threshold(None);
922        ctx.enforce_budget_gate(Some("99999"), false, "post a task")
923            .expect("no threshold = no gate");
924    }
925
926    #[test]
927    fn budget_gate_no_op_when_budget_absent() {
928        let ctx = ctx_with_threshold(Some("100"));
929        ctx.enforce_budget_gate(None, false, "post a task")
930            .expect("no budget = nothing to compare");
931    }
932
933    #[test]
934    fn budget_gate_passes_when_under_threshold() {
935        let ctx = ctx_with_threshold(Some("100"));
936        ctx.enforce_budget_gate(Some("50"), false, "post a task")
937            .expect("under threshold passes without --yes");
938    }
939
940    #[test]
941    fn budget_gate_passes_at_threshold_boundary() {
942        let ctx = ctx_with_threshold(Some("100"));
943        ctx.enforce_budget_gate(Some("100"), false, "post a task")
944            .expect("equal-to-threshold passes (gate is strict >)");
945    }
946
947    #[test]
948    fn budget_gate_blocks_above_threshold_without_yes() {
949        let ctx = ctx_with_threshold(Some("100"));
950        let err = ctx
951            .enforce_budget_gate(Some("100.01"), false, "post a task")
952            .expect_err("over threshold without --yes must fail");
953        match err {
954            CmdError::Usage(msg) => {
955                assert!(msg.contains("--yes"), "msg: {msg}");
956                assert!(msg.contains("post a task"), "msg: {msg}");
957            }
958            other => panic!("expected Usage, got {other:?}"),
959        }
960    }
961
962    #[test]
963    fn budget_gate_passes_above_threshold_with_yes() {
964        let ctx = ctx_with_threshold(Some("100"));
965        ctx.enforce_budget_gate(Some("9999"), true, "post a task")
966            .expect("--yes overrides the gate");
967    }
968
969    #[test]
970    fn budget_gate_uses_decimal_not_float_precision() {
971        // f64 parsing would round "0.30000000000000004" to 0.3 and let it
972        // slip past a "0.3" threshold. Decimal preserves every digit so
973        // the gate correctly blocks.
974        let ctx = ctx_with_threshold(Some("0.3"));
975        ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
976            .expect_err("decimal compare must detect trailing precision");
977    }
978
979    #[test]
980    fn budget_gate_rejects_non_decimal_threshold() {
981        let ctx = ctx_with_threshold(Some("not-a-number"));
982        let err = ctx
983            .enforce_budget_gate(Some("50"), false, "post a task")
984            .expect_err("garbage threshold = usage error");
985        assert!(matches!(err, CmdError::Usage(_)));
986    }
987
988    #[test]
989    fn from_parts_flag_wins_over_config() {
990        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
991        let ctx = Ctx::from_parts(
992            Some("flag_key".into()),
993            Some(Environment::Local),
994            Some("http://flag".into()),
995            None,
996            false,
997            false,
998            false,
999            &cfg,
1000        )
1001        .expect("valid cfg");
1002        assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1003        assert_eq!(ctx.environment, Environment::Local);
1004        // `--api-base` is the only api_base source post-v2 — it should
1005        // round-trip into the in-memory Ctx field unchanged.
1006        assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
1007    }
1008
1009    #[test]
1010    fn from_parts_config_fills_when_flags_absent() {
1011        // Post-v2: `api_base` is no longer a config field, so the only
1012        // thing the config can supply here is api_key + environment.
1013        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1014        let ctx =
1015            Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
1016        assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
1017        assert_eq!(ctx.environment, Environment::Staging);
1018        // No CLI override and no persisted field → in-memory api_base
1019        // stays None; `base_url()` falls through to env default.
1020        assert!(ctx.api_base.is_none());
1021        assert_eq!(ctx.base_url(), Environment::Staging.api_base());
1022    }
1023
1024    #[test]
1025    fn from_parts_defaults_when_nothing_set() {
1026        let ctx = Ctx::from_parts(
1027            None,
1028            None,
1029            None,
1030            None,
1031            false,
1032            false,
1033            false,
1034            &Config::default(),
1035        )
1036        .expect("default cfg is valid");
1037        assert!(ctx.api_key.is_none());
1038        assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
1039        assert!(ctx.api_base.is_none());
1040        assert!(!ctx.dry_run);
1041        assert!(!ctx.quiet);
1042    }
1043
1044    #[test]
1045    fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
1046        // Only `api_key` passed on the CLI — environment should still come
1047        // from the config file. (api_base no longer persisted, so there's
1048        // nothing for the config to contribute on that axis.)
1049        let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1050        let ctx = Ctx::from_parts(
1051            Some("flag_key".into()),
1052            None,
1053            None,
1054            None,
1055            false,
1056            false,
1057            false,
1058            &cfg,
1059        )
1060        .expect("valid cfg");
1061        assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1062        assert_eq!(ctx.environment, Environment::Staging);
1063        assert!(ctx.api_base.is_none());
1064    }
1065
1066    #[test]
1067    fn from_parts_rejects_custom_api_base_for_non_local_env() {
1068        // Hostile invocation: --env prod with a CLI-supplied attacker
1069        // api_base. Guard must refuse before any request.
1070        let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
1071        let err = Ctx::from_parts(
1072            None,
1073            None,
1074            Some("https://evil.example".into()),
1075            None,
1076            false,
1077            false,
1078            false,
1079            &cfg,
1080        )
1081        .err()
1082        .expect("custom api_base on prod must be refused");
1083        match err {
1084            CmdError::Usage(msg) => {
1085                assert!(msg.contains("evil.example"), "msg: {msg}");
1086                assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
1087            }
1088            other => panic!("expected Usage, got {other:?}"),
1089        }
1090    }
1091
1092    #[test]
1093    fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
1094        let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1095        let ctx = Ctx::from_parts(
1096            None,
1097            None,
1098            Some("https://evil.example".into()),
1099            None,
1100            false,
1101            false,
1102            true,
1103            &cfg,
1104        )
1105        .expect("--allow-custom-endpoints must bypass the guard");
1106        assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
1107    }
1108
1109    #[test]
1110    fn from_parts_allows_custom_api_base_for_local_env() {
1111        // Local dev is sandboxed — no guard penalty.
1112        let cfg = cfg_with(Some("k"), Some(Environment::Local));
1113        let ctx = Ctx::from_parts(
1114            None,
1115            None,
1116            Some("http://127.0.0.1:4001".into()),
1117            None,
1118            false,
1119            false,
1120            false,
1121            &cfg,
1122        )
1123        .expect("local env bypasses guard");
1124        assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
1125    }
1126
1127    #[test]
1128    fn from_parts_accepts_well_known_api_base_without_opt_in() {
1129        let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1130        let ctx = Ctx::from_parts(
1131            None,
1132            None,
1133            Some("https://api.taskfast.app".into()),
1134            None,
1135            false,
1136            false,
1137            false,
1138            &cfg,
1139        )
1140        .expect("well-known api_base passes without --allow-custom-endpoints");
1141        assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
1142    }
1143
1144    #[test]
1145    fn from_parts_guard_ignores_missing_api_base() {
1146        // No override ⇒ we use the env default ⇒ nothing to guard against.
1147        let ctx = Ctx::from_parts(
1148            None,
1149            None,
1150            None,
1151            None,
1152            false,
1153            false,
1154            false,
1155            &Config::default(),
1156        )
1157        .expect("no api_base = no guard");
1158        assert!(ctx.api_base.is_none());
1159    }
1160
1161    #[test]
1162    fn network_invariant_ok_when_single_advertised_matches() {
1163        let res = check_network_invariant(
1164            Environment::Prod,
1165            "https://api.taskfast.app",
1166            &["mainnet".into()],
1167            true,
1168        );
1169        assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
1170    }
1171
1172    #[test]
1173    fn network_invariant_strict_rejects_wrong_single_network() {
1174        let err = check_network_invariant(
1175            Environment::Prod,
1176            "https://api.taskfast.app",
1177            &["testnet".into()],
1178            true,
1179        )
1180        .expect_err("strict mode must reject wrong network");
1181        match err {
1182            CmdError::Server(msg) => {
1183                assert!(msg.contains("testnet"), "msg: {msg}");
1184                assert!(msg.contains("mainnet"), "msg: {msg}");
1185                assert!(msg.contains("issue #62"), "remediation hint: {msg}");
1186            }
1187            other => panic!("expected Server, got {other:?}"),
1188        }
1189    }
1190
1191    #[test]
1192    fn network_invariant_strict_rejects_extra_advertised() {
1193        let err = check_network_invariant(
1194            Environment::Prod,
1195            "https://api.taskfast.app",
1196            &["mainnet".into(), "testnet".into()],
1197            true,
1198        )
1199        .expect_err("strict mode must reject len != 1");
1200        assert!(matches!(err, CmdError::Server(_)));
1201    }
1202
1203    #[test]
1204    fn network_invariant_warn_passes_under_today_server_shape() {
1205        // Today's deployments advertise both networks. Warn-only mode
1206        // (default) keeps the CLI usable until issue #62 closes.
1207        let res = check_network_invariant(
1208            Environment::Staging,
1209            "https://staging.api.taskfast.app",
1210            &["mainnet".into(), "testnet".into()],
1211            false,
1212        );
1213        assert!(
1214            res.is_ok(),
1215            "non-strict mode must let today's multi-network deployments through: {res:?}"
1216        );
1217    }
1218
1219    #[test]
1220    fn network_invariant_warn_passes_when_wrong_single_network() {
1221        // Even a wrong-single-network advertised should warn-only —
1222        // strict mode is opt-in.
1223        let res = check_network_invariant(
1224            Environment::Prod,
1225            "https://api.taskfast.app",
1226            &["testnet".into()],
1227            false,
1228        );
1229        assert!(res.is_ok(), "non-strict mode warns rather than errors");
1230    }
1231
1232    #[test]
1233    fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
1234        // These never come from config, only from the CLI.
1235        let ctx = Ctx::from_parts(
1236            None,
1237            None,
1238            None,
1239            None,
1240            true,
1241            true,
1242            false,
1243            &Config::default(),
1244        )
1245        .expect("default cfg is valid");
1246        assert!(ctx.dry_run);
1247        assert!(ctx.quiet);
1248    }
1249}