1use 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 config;
34pub mod discover;
35pub mod dispute;
36pub mod escrow;
37pub mod events;
38pub mod init;
39pub mod init_tui;
40pub mod me;
41pub mod message;
42pub mod payment;
43pub mod ping;
44pub mod platform;
45pub mod post;
46pub mod review;
47pub mod settle;
48pub mod skills;
49pub mod stake;
50pub mod task;
51pub mod wallet;
52pub mod wallet_args;
53pub mod webhook;
54
55#[derive(Clone)]
59pub struct Ctx {
60 pub api_key: Option<String>,
61 pub environment: Environment,
62 pub api_base: Option<String>,
66 pub config_path: PathBuf,
71 pub wallet_address: Option<String>,
74 pub keystore_path: Option<PathBuf>,
76 pub confirm_above_budget: Option<String>,
80 pub log_format: Option<String>,
83 pub approval_horizon: Option<Duration>,
89 pub receipt_timeout: Option<Duration>,
94 pub dry_run: bool,
95 pub quiet: bool,
96 pub allow_custom_endpoints: bool,
102}
103
104pub const DEFAULT_ENVIRONMENT: Environment = Environment::Prod;
106
107impl Default for Ctx {
108 fn default() -> Self {
109 Self {
110 api_key: None,
111 environment: DEFAULT_ENVIRONMENT,
112 api_base: None,
113 config_path: PathBuf::from("/dev/null"),
114 wallet_address: None,
115 keystore_path: None,
116 confirm_above_budget: None,
117 log_format: None,
118 approval_horizon: None,
119 receipt_timeout: None,
120 dry_run: false,
121 quiet: false,
122 allow_custom_endpoints: false,
123 }
124 }
125}
126
127impl Ctx {
128 pub fn from_parts(
140 cli_api_key: Option<String>,
141 cli_env: Option<Environment>,
142 cli_api_base: Option<String>,
143 cli_config_path: Option<PathBuf>,
144 cli_dry_run: bool,
145 cli_quiet: bool,
146 cli_allow_custom_endpoints: bool,
147 cfg: &Config,
148 ) -> Result<Self, CmdError> {
149 let approval_horizon =
150 parse_duration_cfg(cfg.approval_horizon.as_deref(), "approval_horizon")?;
151 let receipt_timeout =
152 parse_duration_cfg(cfg.receipt_timeout.as_deref(), "receipt_timeout")?;
153 let environment = cli_env.or(cfg.environment).unwrap_or(DEFAULT_ENVIRONMENT);
154 let api_base = cli_api_base;
158 enforce_endpoint_guard(environment, api_base.as_deref(), cli_allow_custom_endpoints)?;
159 Ok(Self {
160 api_key: cli_api_key.or_else(|| cfg.api_key.clone()),
161 environment,
162 api_base,
163 config_path: cli_config_path.unwrap_or_else(Config::default_path),
164 wallet_address: cfg.wallet_address.clone(),
165 keystore_path: cfg.keystore_path.clone(),
166 confirm_above_budget: cfg.confirm_above_budget.clone(),
167 log_format: cfg.log_format.clone(),
168 approval_horizon,
169 receipt_timeout,
170 dry_run: cli_dry_run,
171 quiet: cli_quiet,
172 allow_custom_endpoints: cli_allow_custom_endpoints,
173 })
174 }
175
176 pub fn security_warnings(&self) -> Vec<crate::envelope::SecurityWarning> {
181 use crate::envelope::SecurityWarning;
182 let mut out = Vec::new();
183 if self.allow_custom_endpoints {
184 let detail = self.api_base.as_deref().unwrap_or("(env default)");
185 out.push(SecurityWarning {
186 code: "custom_endpoints_allowed",
187 message: format!(
188 "--allow-custom-endpoints is in effect; api_base={detail}. \
189 Traffic will go to a non-well-known host."
190 ),
191 });
192 }
193 if std::env::var("TASKFAST_WALLET_PASSWORD").is_ok_and(|v| !v.is_empty()) {
194 out.push(SecurityWarning {
195 code: "password_env_var",
196 message: "TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
197 prefer --wallet-password-file."
198 .into(),
199 });
200 }
201 out
202 }
203
204 pub fn base_url(&self) -> &str {
206 match self.api_base.as_deref() {
207 Some(u) => u,
208 None => self.environment.api_base(),
209 }
210 }
211
212 pub fn client(&self) -> Result<TaskFastClient, CmdError> {
215 let key = self.api_key.as_deref().ok_or(CmdError::MissingApiKey)?;
216 TaskFastClient::from_api_key(self.base_url(), key).map_err(CmdError::from)
217 }
218
219 pub fn rpc_http_client(&self, client: &TaskFastClient, rpc_url: &str) -> reqwest::Client {
232 if is_proxy_rpc_url(rpc_url, self.base_url()) {
233 client.http_client()
234 } else {
235 reqwest::Client::new()
236 }
237 }
238
239 pub fn enforce_budget_gate(
246 &self,
247 budget: Option<&str>,
248 yes: bool,
249 verb: &str,
250 ) -> Result<(), CmdError> {
251 let threshold_str = match self.confirm_above_budget.as_deref() {
252 Some(t) => t,
253 None => return Ok(()),
254 };
255 let budget_str = match budget {
256 Some(b) => b,
257 None => return Ok(()),
258 };
259 let threshold = Decimal::from_str(threshold_str).map_err(|_| {
264 CmdError::Usage(format!(
265 "config `confirm_above_budget` is not a decimal: {threshold_str:?}"
266 ))
267 })?;
268 let amount = Decimal::from_str(budget_str)
269 .map_err(|_| CmdError::Usage(format!("budget {budget_str:?} is not a decimal")))?;
270 if amount > threshold && !yes {
271 return Err(CmdError::Usage(format!(
272 "refusing to {verb}: budget {amount} exceeds confirm_above_budget \
273 {threshold} (pass --yes to override)"
274 )));
275 }
276 Ok(())
277 }
278}
279
280pub(crate) fn is_proxy_rpc_url(rpc_url: &str, base_url: &str) -> bool {
293 match (url::Url::parse(rpc_url), url::Url::parse(base_url)) {
294 (Ok(rpc), Ok(base)) => rpc.origin() == base.origin(),
297 _ => false,
298 }
299}
300
301fn is_loopback_url(url: &str) -> bool {
302 match url::Url::parse(url) {
303 Ok(u) => matches!(
304 u.host_str(),
305 Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
306 ),
307 Err(_) => false,
308 }
309}
310
311pub(crate) fn validate_override_rpc_url(
312 url: &str,
313 network: Network,
314 allow_custom: bool,
315) -> Result<&str, CmdError> {
316 if !allow_custom {
317 return Err(CmdError::Usage(format!(
318 "refusing to use custom tempo_rpc_url {url:?}: pass \
319 --allow-custom-endpoints (or set \
320 TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) to override. The default \
321 path routes RPC through `{{api_base}}/rpc/{{network}}` \
322 which inherits the api_base endpoint guard."
323 )));
324 }
325
326 let is_plain_http_mainnet =
327 matches!(network, Network::Mainnet) && url.starts_with("http://") && !is_loopback_url(url);
328 if is_plain_http_mainnet {
329 return Err(CmdError::Usage(format!(
330 "refusing plain-HTTP mainnet tempo_rpc_url {url:?}: MITM on a \
331 mainnet RPC can observe the poster wallet and inflate gas \
332 price. Use HTTPS or point at loopback for local testing."
333 )));
334 }
335
336 Ok(url)
337}
338
339pub(crate) fn parse_wallet_address(raw: &str) -> Result<String, CmdError> {
345 let trimmed = raw.trim();
346 let _: alloy_primitives::Address = trimmed
347 .parse()
348 .map_err(|e| CmdError::Usage(format!("--wallet is not a valid EVM address: {e}")))?;
349 Ok(trimmed.to_string())
350}
351
352pub(crate) fn network_policy_for_chain_id(chain_id: u64) -> Network {
353 if chain_id == TEMPO_MAINNET_CHAIN_ID {
354 Network::Mainnet
355 } else {
356 Network::Testnet
357 }
358}
359
360fn enforce_endpoint_guard(
372 environment: Environment,
373 api_base: Option<&str>,
374 allow_custom: bool,
375) -> Result<(), CmdError> {
376 if allow_custom || environment == Environment::Local {
377 return Ok(());
378 }
379 let Some(url) = api_base else { return Ok(()) };
380 if is_well_known_api_base(url) {
381 return Ok(());
382 }
383 Err(CmdError::Usage(format!(
384 "refusing to use custom api_base {url:?} for env {env}: \
385 pass --allow-custom-endpoints (or set TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) \
386 to override. This guard blocks a malicious .taskfast/config.json in \
387 a cloned repo from silently redirecting API traffic.",
388 env = environment.as_str()
389 )))
390}
391
392pub async fn enforce_server_network_invariant(
407 ctx: &Ctx,
408 client: &TaskFastClient,
409) -> Result<(), CmdError> {
410 if ctx.allow_custom_endpoints || ctx.environment == Environment::Local {
411 return Ok(());
412 }
413 let cfg = client
414 .fetch_network_config()
415 .await
416 .map_err(CmdError::from)?;
417 let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
418 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
419 let advertised: Vec<String> = cfg.networks.keys().cloned().collect();
420 check_network_invariant(ctx.environment, ctx.base_url(), &advertised, strict)
421}
422
423fn check_network_invariant(
427 env: Environment,
428 api_base: &str,
429 advertised: &[String],
430 strict: bool,
431) -> Result<(), CmdError> {
432 let expected = env.network().as_str();
433 if advertised.len() == 1 && advertised[0] == expected {
434 return Ok(());
435 }
436 if strict {
437 return Err(CmdError::Server(format!(
438 "deployment at {api_base} advertises networks {advertised:?}; env {} requires \
439 exactly [{expected}]. Server-side fix tracked in issue #62. Unset \
440 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
441 env.as_str(),
442 )));
443 }
444 tracing::warn!(
445 api_base = %api_base,
446 env = env.as_str(),
447 expected = expected,
448 advertised = ?advertised,
449 "deployment advertises a different network shape than env requires; \
450 server-side fix tracked in issue #62. Set TASKFAST_STRICT_ENV_NETWORK=1 \
451 to fail-closed."
452 );
453 Ok(())
454}
455
456fn parse_duration_cfg(
461 raw: Option<&str>,
462 field: &'static str,
463) -> Result<Option<Duration>, CmdError> {
464 match raw {
465 None => Ok(None),
466 Some(s) => humantime::parse_duration(s).map(Some).map_err(|e| {
467 CmdError::Usage(format!("config `{field}` is not a duration: {s:?} ({e})"))
468 }),
469 }
470}
471
472pub fn resolve_duration(
476 flag: Option<Duration>,
477 ctx_field: Option<Duration>,
478 default: Duration,
479) -> Duration {
480 flag.or(ctx_field).unwrap_or(default)
481}
482
483pub type CmdResult = Result<Envelope, CmdError>;
484
485#[derive(Debug, Error)]
489pub enum CmdError {
490 #[error("missing API key: set --api-key or TASKFAST_API_KEY")]
491 MissingApiKey,
492
493 #[error("usage: {0}")]
494 Usage(String),
495
496 #[error("auth: {0}")]
497 Auth(String),
498
499 #[error("rate limited (retry in {retry_after:?})")]
500 RateLimited { retry_after: Duration },
501
502 #[error("validation [{code}]: {message}")]
503 Validation { code: String, message: String },
504
505 #[error("server: {0}")]
506 Server(String),
507
508 #[error("network: {0}")]
509 Network(String),
510
511 #[error("decode: {0}")]
512 Decode(String),
513
514 #[error("keystore: {0}")]
515 Keystore(String),
516
517 #[error("signing: {0}")]
518 Signing(String),
519
520 #[error("not yet implemented: {0}")]
521 Unimplemented(&'static str),
522
523 #[error(transparent)]
524 Config(#[from] ConfigError),
525}
526
527impl CmdError {
528 pub fn code(&self) -> &'static str {
530 match self {
531 Self::MissingApiKey => "missing_api_key",
532 Self::Usage(_) => "usage",
533 Self::Auth(_) => "auth",
534 Self::RateLimited { .. } => "rate_limited",
535 Self::Validation { .. } => "validation",
536 Self::Server(_) => "server",
537 Self::Network(_) => "network",
538 Self::Decode(_) => "decode",
539 Self::Keystore(_) => "keystore",
540 Self::Signing(_) => "signing",
541 Self::Unimplemented(_) => "unimplemented",
542 Self::Config(_) => "config",
543 }
544 }
545
546 pub fn exit_code(&self) -> ExitCode {
548 match self {
549 Self::MissingApiKey | Self::Usage(_) | Self::Config(_) => ExitCode::Usage,
550 Self::Auth(_) => ExitCode::Auth,
551 Self::RateLimited { .. } => ExitCode::RateLimited,
552 Self::Validation { .. } => ExitCode::Validation,
553 Self::Server(_) | Self::Network(_) | Self::Decode(_) => ExitCode::Server,
554 Self::Keystore(_) | Self::Signing(_) => ExitCode::Wallet,
555 Self::Unimplemented(_) => ExitCode::Unimplemented,
556 }
557 }
558
559 pub fn retry_after(&self) -> Option<Duration> {
563 match self {
564 Self::RateLimited { retry_after } => Some(*retry_after),
565 _ => None,
566 }
567 }
568}
569
570impl From<ClientError> for CmdError {
571 fn from(e: ClientError) -> Self {
572 match e {
573 ClientError::Auth(m) => Self::Auth(m),
574 ClientError::Validation { code, message } => Self::Validation { code, message },
575 ClientError::RateLimited { retry_after } => Self::RateLimited { retry_after },
576 ClientError::Server(m) => Self::Server(m),
577 ClientError::Network(e) => Self::Network(e.to_string()),
578 ClientError::Decode(e) => Self::Decode(e.to_string()),
579 }
580 }
581}
582
583impl From<KeystoreError> for CmdError {
584 fn from(e: KeystoreError) -> Self {
585 Self::Keystore(e.to_string())
586 }
587}
588
589impl From<SigningError> for CmdError {
590 fn from(e: SigningError) -> Self {
591 Self::Signing(e.to_string())
592 }
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598 use std::collections::HashSet;
599
600 fn sample(variant: &str) -> CmdError {
601 match variant {
602 "missing_api_key" => CmdError::MissingApiKey,
603 "usage" => CmdError::Usage("bad flag".into()),
604 "auth" => CmdError::Auth("401".into()),
605 "rate_limited" => CmdError::RateLimited {
606 retry_after: Duration::from_secs(30),
607 },
608 "validation" => CmdError::Validation {
609 code: "bad_field".into(),
610 message: "x".into(),
611 },
612 "server" => CmdError::Server("500".into()),
613 "network" => CmdError::Network("dns".into()),
614 "decode" => CmdError::Decode("json".into()),
615 "keystore" => CmdError::Keystore("bad pw".into()),
616 "signing" => CmdError::Signing("hsm".into()),
617 "unimplemented" => CmdError::Unimplemented("soon"),
618 "config" => CmdError::Config(ConfigError::Io {
619 path: PathBuf::from("/x"),
620 source: std::io::Error::other("boom"),
621 }),
622 _ => unreachable!(),
623 }
624 }
625
626 const ALL: &[&str] = &[
627 "missing_api_key",
628 "usage",
629 "auth",
630 "rate_limited",
631 "validation",
632 "server",
633 "network",
634 "decode",
635 "keystore",
636 "signing",
637 "unimplemented",
638 "config",
639 ];
640
641 #[test]
642 fn every_variant_has_distinct_code() {
643 let codes: HashSet<&'static str> = ALL.iter().map(|v| sample(v).code()).collect();
644 assert_eq!(codes.len(), ALL.len(), "codes must be unique per variant");
645 for v in ALL {
646 assert_eq!(sample(v).code(), *v, "code() for {v} must match the label");
647 }
648 }
649
650 #[test]
651 fn exit_code_taxonomy_matches_plan() {
652 assert_eq!(CmdError::MissingApiKey.exit_code(), ExitCode::Usage);
655 assert_eq!(sample("usage").exit_code(), ExitCode::Usage);
656 assert_eq!(sample("auth").exit_code(), ExitCode::Auth);
657 assert_eq!(sample("rate_limited").exit_code(), ExitCode::RateLimited);
658 assert_eq!(sample("validation").exit_code(), ExitCode::Validation);
659 assert_eq!(sample("server").exit_code(), ExitCode::Server);
660 assert_eq!(sample("network").exit_code(), ExitCode::Server);
661 assert_eq!(sample("decode").exit_code(), ExitCode::Server);
662 assert_eq!(sample("keystore").exit_code(), ExitCode::Wallet);
663 assert_eq!(sample("signing").exit_code(), ExitCode::Wallet);
664 assert_eq!(sample("unimplemented").exit_code(), ExitCode::Unimplemented);
665 assert_eq!(sample("config").exit_code(), ExitCode::Usage);
666 }
667
668 #[test]
669 fn client_error_folds_retry_after_into_cmd_error() {
670 let ce = ClientError::RateLimited {
671 retry_after: Duration::from_secs(42),
672 };
673 let cmd: CmdError = ce.into();
674 match cmd {
675 CmdError::RateLimited { retry_after } => {
676 assert_eq!(retry_after, Duration::from_secs(42));
677 }
678 other => panic!("expected RateLimited, got {other:?}"),
679 }
680 assert_eq!(
682 sample("rate_limited").retry_after(),
683 Some(Duration::from_secs(30))
684 );
685 assert!(sample("auth").retry_after().is_none());
686 }
687
688 #[test]
689 fn is_proxy_rpc_url_matches_same_origin() {
690 let base = "https://staging.api.taskfast.app";
691 assert!(is_proxy_rpc_url(
693 "https://staging.api.taskfast.app/rpc/testnet",
694 base
695 ));
696 assert!(is_proxy_rpc_url(
700 "https://staging.api.taskfast.app/api/rpc/testnet",
701 base
702 ));
703 assert!(is_proxy_rpc_url(
705 "https://staging.api.taskfast.app/rpc/mainnet",
706 "https://staging.api.taskfast.app/"
707 ));
708 assert!(!is_proxy_rpc_url("https://rpc.moderato.tempo.xyz", base));
711 assert!(!is_proxy_rpc_url(
714 "https://attacker.example/rpc/testnet",
715 base
716 ));
717 assert!(!is_proxy_rpc_url(
720 "http://staging.api.taskfast.app/rpc/testnet",
721 base
722 ));
723 }
724
725 #[test]
726 fn ctx_base_url_override_wins_over_environment_default() {
727 let ctx = Ctx {
728 api_key: None,
729 environment: Environment::Prod,
730 api_base: Some("http://localhost:9999".into()),
731 config_path: PathBuf::from("/dev/null"),
732 dry_run: false,
733 quiet: false,
734 ..Default::default()
735 };
736 assert_eq!(ctx.base_url(), "http://localhost:9999");
737 }
738
739 #[test]
740 fn ctx_base_url_falls_back_to_environment_default() {
741 for (env, expected) in [
742 (Environment::Prod, "https://api.taskfast.app"),
743 (Environment::Staging, "https://staging.api.taskfast.app"),
744 (Environment::Local, "http://127.0.0.1:4000"),
745 ] {
746 let ctx = Ctx {
747 api_key: None,
748 environment: env,
749 api_base: None,
750 config_path: PathBuf::from("/dev/null"),
751 dry_run: false,
752 quiet: false,
753 ..Default::default()
754 };
755 assert_eq!(ctx.base_url(), expected);
756 }
757 }
758
759 #[test]
760 fn ctx_client_errors_when_api_key_missing() {
761 let ctx = Ctx {
762 api_key: None,
763 environment: Environment::Local,
764 api_base: None,
765 config_path: PathBuf::from("/dev/null"),
766 dry_run: false,
767 quiet: false,
768 ..Default::default()
769 };
770 match ctx.client() {
771 Err(CmdError::MissingApiKey) => {}
772 Err(other) => panic!("expected MissingApiKey, got {other:?}"),
773 Ok(_) => panic!("expected MissingApiKey, got Ok(client)"),
774 }
775 }
776
777 #[test]
778 fn ctx_client_builds_when_api_key_present() {
779 let ctx = Ctx {
780 api_key: Some("tk_test_abc".into()),
781 environment: Environment::Local,
782 api_base: None,
783 config_path: PathBuf::from("/dev/null"),
784 dry_run: false,
785 quiet: false,
786 ..Default::default()
787 };
788 ctx.client().expect("client should build with a valid key");
789 }
790
791 fn cfg_with(api_key: Option<&str>, environment: Option<Environment>) -> Config {
792 Config {
793 api_key: api_key.map(str::to_string),
794 environment,
795 ..Config::default()
796 }
797 }
798
799 #[test]
800 fn from_parts_threads_wallet_keystore_confirm_log_format_from_config() {
801 let cfg = Config {
802 wallet_address: Some("0xfeed".into()),
803 keystore_path: Some(PathBuf::from("/tmp/k.json")),
804 confirm_above_budget: Some("500".into()),
805 log_format: Some("json".into()),
806 ..Config::default()
807 };
808 let ctx =
809 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
810 assert_eq!(ctx.wallet_address.as_deref(), Some("0xfeed"));
811 assert_eq!(
812 ctx.keystore_path.as_deref(),
813 Some(std::path::Path::new("/tmp/k.json"))
814 );
815 assert_eq!(ctx.confirm_above_budget.as_deref(), Some("500"));
816 assert_eq!(ctx.log_format.as_deref(), Some("json"));
817 }
818
819 #[test]
820 fn from_parts_parses_approval_horizon_from_config() {
821 let cfg = Config {
822 approval_horizon: Some("7d".into()),
823 ..Config::default()
824 };
825 let ctx =
826 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 7d");
827 assert_eq!(ctx.approval_horizon, Some(Duration::from_hours(24 * 7)));
828 }
829
830 #[test]
831 fn from_parts_parses_receipt_timeout_from_config() {
832 let cfg = Config {
833 receipt_timeout: Some("3min".into()),
834 ..Config::default()
835 };
836 let ctx =
837 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
838 assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
839 }
840
841 #[test]
842 fn from_parts_rejects_malformed_approval_horizon() {
843 let cfg = Config {
844 approval_horizon: Some("7xyz".into()),
845 ..Config::default()
846 };
847 let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
848 .err()
849 .expect("malformed config must fail at startup");
850 match err {
851 CmdError::Usage(msg) => {
852 assert!(msg.contains("approval_horizon"), "msg: {msg}");
853 assert!(msg.contains("7xyz"), "msg: {msg}");
854 }
855 other => panic!("expected Usage, got {other:?}"),
856 }
857 }
858
859 #[test]
860 fn from_parts_rejects_malformed_receipt_timeout() {
861 let cfg = Config {
862 receipt_timeout: Some("nope".into()),
863 ..Config::default()
864 };
865 let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
866 .err()
867 .expect("malformed timeout = startup error");
868 assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
869 }
870
871 #[test]
872 fn from_parts_duration_fields_none_when_config_absent() {
873 let ctx = Ctx::from_parts(
874 None,
875 None,
876 None,
877 None,
878 false,
879 false,
880 false,
881 &Config::default(),
882 )
883 .expect("default cfg is valid");
884 assert!(ctx.approval_horizon.is_none());
885 assert!(ctx.receipt_timeout.is_none());
886 }
887
888 #[test]
889 fn resolve_duration_flag_wins_over_ctx_and_default() {
890 let out = resolve_duration(
891 Some(Duration::from_secs(10)),
892 Some(Duration::from_secs(20)),
893 Duration::from_secs(30),
894 );
895 assert_eq!(out, Duration::from_secs(10));
896 }
897
898 #[test]
899 fn resolve_duration_ctx_wins_over_default_when_no_flag() {
900 let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
901 assert_eq!(out, Duration::from_secs(20));
902 }
903
904 #[test]
905 fn resolve_duration_falls_back_to_default() {
906 let out = resolve_duration(None, None, Duration::from_secs(30));
907 assert_eq!(out, Duration::from_secs(30));
908 }
909
910 fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
911 Ctx {
912 confirm_above_budget: threshold.map(str::to_string),
913 ..Default::default()
914 }
915 }
916
917 #[test]
918 fn budget_gate_no_op_when_threshold_unset() {
919 let ctx = ctx_with_threshold(None);
920 ctx.enforce_budget_gate(Some("99999"), false, "post a task")
921 .expect("no threshold = no gate");
922 }
923
924 #[test]
925 fn budget_gate_no_op_when_budget_absent() {
926 let ctx = ctx_with_threshold(Some("100"));
927 ctx.enforce_budget_gate(None, false, "post a task")
928 .expect("no budget = nothing to compare");
929 }
930
931 #[test]
932 fn budget_gate_passes_when_under_threshold() {
933 let ctx = ctx_with_threshold(Some("100"));
934 ctx.enforce_budget_gate(Some("50"), false, "post a task")
935 .expect("under threshold passes without --yes");
936 }
937
938 #[test]
939 fn budget_gate_passes_at_threshold_boundary() {
940 let ctx = ctx_with_threshold(Some("100"));
941 ctx.enforce_budget_gate(Some("100"), false, "post a task")
942 .expect("equal-to-threshold passes (gate is strict >)");
943 }
944
945 #[test]
946 fn budget_gate_blocks_above_threshold_without_yes() {
947 let ctx = ctx_with_threshold(Some("100"));
948 let err = ctx
949 .enforce_budget_gate(Some("100.01"), false, "post a task")
950 .expect_err("over threshold without --yes must fail");
951 match err {
952 CmdError::Usage(msg) => {
953 assert!(msg.contains("--yes"), "msg: {msg}");
954 assert!(msg.contains("post a task"), "msg: {msg}");
955 }
956 other => panic!("expected Usage, got {other:?}"),
957 }
958 }
959
960 #[test]
961 fn budget_gate_passes_above_threshold_with_yes() {
962 let ctx = ctx_with_threshold(Some("100"));
963 ctx.enforce_budget_gate(Some("9999"), true, "post a task")
964 .expect("--yes overrides the gate");
965 }
966
967 #[test]
968 fn budget_gate_uses_decimal_not_float_precision() {
969 let ctx = ctx_with_threshold(Some("0.3"));
973 ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
974 .expect_err("decimal compare must detect trailing precision");
975 }
976
977 #[test]
978 fn budget_gate_rejects_non_decimal_threshold() {
979 let ctx = ctx_with_threshold(Some("not-a-number"));
980 let err = ctx
981 .enforce_budget_gate(Some("50"), false, "post a task")
982 .expect_err("garbage threshold = usage error");
983 assert!(matches!(err, CmdError::Usage(_)));
984 }
985
986 #[test]
987 fn from_parts_flag_wins_over_config() {
988 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
989 let ctx = Ctx::from_parts(
990 Some("flag_key".into()),
991 Some(Environment::Local),
992 Some("http://flag".into()),
993 None,
994 false,
995 false,
996 false,
997 &cfg,
998 )
999 .expect("valid cfg");
1000 assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1001 assert_eq!(ctx.environment, Environment::Local);
1002 assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
1005 }
1006
1007 #[test]
1008 fn from_parts_config_fills_when_flags_absent() {
1009 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1012 let ctx =
1013 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
1014 assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
1015 assert_eq!(ctx.environment, Environment::Staging);
1016 assert!(ctx.api_base.is_none());
1019 assert_eq!(ctx.base_url(), Environment::Staging.api_base());
1020 }
1021
1022 #[test]
1023 fn from_parts_defaults_when_nothing_set() {
1024 let ctx = Ctx::from_parts(
1025 None,
1026 None,
1027 None,
1028 None,
1029 false,
1030 false,
1031 false,
1032 &Config::default(),
1033 )
1034 .expect("default cfg is valid");
1035 assert!(ctx.api_key.is_none());
1036 assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
1037 assert!(ctx.api_base.is_none());
1038 assert!(!ctx.dry_run);
1039 assert!(!ctx.quiet);
1040 }
1041
1042 #[test]
1043 fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
1044 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1048 let ctx = Ctx::from_parts(
1049 Some("flag_key".into()),
1050 None,
1051 None,
1052 None,
1053 false,
1054 false,
1055 false,
1056 &cfg,
1057 )
1058 .expect("valid cfg");
1059 assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1060 assert_eq!(ctx.environment, Environment::Staging);
1061 assert!(ctx.api_base.is_none());
1062 }
1063
1064 #[test]
1065 fn from_parts_rejects_custom_api_base_for_non_local_env() {
1066 let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
1069 let err = Ctx::from_parts(
1070 None,
1071 None,
1072 Some("https://evil.example".into()),
1073 None,
1074 false,
1075 false,
1076 false,
1077 &cfg,
1078 )
1079 .err()
1080 .expect("custom api_base on prod must be refused");
1081 match err {
1082 CmdError::Usage(msg) => {
1083 assert!(msg.contains("evil.example"), "msg: {msg}");
1084 assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
1085 }
1086 other => panic!("expected Usage, got {other:?}"),
1087 }
1088 }
1089
1090 #[test]
1091 fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
1092 let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1093 let ctx = Ctx::from_parts(
1094 None,
1095 None,
1096 Some("https://evil.example".into()),
1097 None,
1098 false,
1099 false,
1100 true,
1101 &cfg,
1102 )
1103 .expect("--allow-custom-endpoints must bypass the guard");
1104 assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
1105 }
1106
1107 #[test]
1108 fn from_parts_allows_custom_api_base_for_local_env() {
1109 let cfg = cfg_with(Some("k"), Some(Environment::Local));
1111 let ctx = Ctx::from_parts(
1112 None,
1113 None,
1114 Some("http://127.0.0.1:4001".into()),
1115 None,
1116 false,
1117 false,
1118 false,
1119 &cfg,
1120 )
1121 .expect("local env bypasses guard");
1122 assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
1123 }
1124
1125 #[test]
1126 fn from_parts_accepts_well_known_api_base_without_opt_in() {
1127 let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1128 let ctx = Ctx::from_parts(
1129 None,
1130 None,
1131 Some("https://api.taskfast.app".into()),
1132 None,
1133 false,
1134 false,
1135 false,
1136 &cfg,
1137 )
1138 .expect("well-known api_base passes without --allow-custom-endpoints");
1139 assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
1140 }
1141
1142 #[test]
1143 fn from_parts_guard_ignores_missing_api_base() {
1144 let ctx = Ctx::from_parts(
1146 None,
1147 None,
1148 None,
1149 None,
1150 false,
1151 false,
1152 false,
1153 &Config::default(),
1154 )
1155 .expect("no api_base = no guard");
1156 assert!(ctx.api_base.is_none());
1157 }
1158
1159 #[test]
1160 fn network_invariant_ok_when_single_advertised_matches() {
1161 let res = check_network_invariant(
1162 Environment::Prod,
1163 "https://api.taskfast.app",
1164 &["mainnet".into()],
1165 true,
1166 );
1167 assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
1168 }
1169
1170 #[test]
1171 fn network_invariant_strict_rejects_wrong_single_network() {
1172 let err = check_network_invariant(
1173 Environment::Prod,
1174 "https://api.taskfast.app",
1175 &["testnet".into()],
1176 true,
1177 )
1178 .expect_err("strict mode must reject wrong network");
1179 match err {
1180 CmdError::Server(msg) => {
1181 assert!(msg.contains("testnet"), "msg: {msg}");
1182 assert!(msg.contains("mainnet"), "msg: {msg}");
1183 assert!(msg.contains("issue #62"), "remediation hint: {msg}");
1184 }
1185 other => panic!("expected Server, got {other:?}"),
1186 }
1187 }
1188
1189 #[test]
1190 fn network_invariant_strict_rejects_extra_advertised() {
1191 let err = check_network_invariant(
1192 Environment::Prod,
1193 "https://api.taskfast.app",
1194 &["mainnet".into(), "testnet".into()],
1195 true,
1196 )
1197 .expect_err("strict mode must reject len != 1");
1198 assert!(matches!(err, CmdError::Server(_)));
1199 }
1200
1201 #[test]
1202 fn network_invariant_warn_passes_under_today_server_shape() {
1203 let res = check_network_invariant(
1206 Environment::Staging,
1207 "https://staging.api.taskfast.app",
1208 &["mainnet".into(), "testnet".into()],
1209 false,
1210 );
1211 assert!(
1212 res.is_ok(),
1213 "non-strict mode must let today's multi-network deployments through: {res:?}"
1214 );
1215 }
1216
1217 #[test]
1218 fn network_invariant_warn_passes_when_wrong_single_network() {
1219 let res = check_network_invariant(
1222 Environment::Prod,
1223 "https://api.taskfast.app",
1224 &["testnet".into()],
1225 false,
1226 );
1227 assert!(res.is_ok(), "non-strict mode warns rather than errors");
1228 }
1229
1230 #[test]
1231 fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
1232 let ctx = Ctx::from_parts(
1234 None,
1235 None,
1236 None,
1237 None,
1238 true,
1239 true,
1240 false,
1241 &Config::default(),
1242 )
1243 .expect("default cfg is valid");
1244 assert!(ctx.dry_run);
1245 assert!(ctx.quiet);
1246 }
1247}