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