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