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