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 bond;
34pub mod cast;
35pub mod config;
36pub mod discover;
37pub mod dispute;
38pub mod escalate;
39pub mod escrow;
40pub mod events;
41pub mod fee;
42pub mod init;
43pub mod init_tui;
44pub mod me;
45pub mod message;
46pub mod payment;
47pub mod ping;
48pub mod platform;
49pub mod post;
50pub mod review;
51pub mod settle;
52pub mod skills;
53pub mod stake;
54pub mod task;
55pub mod wallet;
56pub mod wallet_args;
57pub mod webhook;
58
59#[derive(Clone)]
63pub struct Ctx {
64 pub api_key: Option<String>,
65 pub environment: Environment,
66 pub api_base: Option<String>,
70 pub config_path: PathBuf,
75 pub wallet_address: Option<String>,
78 pub keystore_path: Option<PathBuf>,
80 pub confirm_above_budget: Option<String>,
84 pub log_format: Option<String>,
87 pub receipt_timeout: Option<Duration>,
92 pub dry_run: bool,
93 pub quiet: bool,
94 pub allow_custom_endpoints: bool,
100}
101
102pub const DEFAULT_ENVIRONMENT: Environment = Environment::Prod;
104
105impl Default for Ctx {
106 fn default() -> Self {
107 Self {
108 api_key: None,
109 environment: DEFAULT_ENVIRONMENT,
110 api_base: None,
111 config_path: PathBuf::from("/dev/null"),
112 wallet_address: None,
113 keystore_path: None,
114 confirm_above_budget: None,
115 log_format: None,
116 receipt_timeout: None,
117 dry_run: false,
118 quiet: false,
119 allow_custom_endpoints: false,
120 }
121 }
122}
123
124impl Ctx {
125 pub fn state_store(&self) -> crate::state_store::StateStore {
127 crate::state_store::StateStore::from_config_path(&self.config_path)
128 }
129
130 pub fn from_parts(
142 cli_api_key: Option<String>,
143 cli_env: Option<Environment>,
144 cli_api_base: Option<String>,
145 cli_config_path: Option<PathBuf>,
146 cli_dry_run: bool,
147 cli_quiet: bool,
148 cli_allow_custom_endpoints: bool,
149 cfg: &Config,
150 ) -> Result<Self, CmdError> {
151 let receipt_timeout =
152 parse_duration_cfg(cfg.receipt_timeout.as_deref(), "receipt_timeout")?;
153 let environment = cli_env.or(cfg.environment).unwrap_or(DEFAULT_ENVIRONMENT);
154 let api_base = cli_api_base;
158 enforce_endpoint_guard(environment, api_base.as_deref(), cli_allow_custom_endpoints)?;
159 let config_path = cli_config_path.unwrap_or_else(Config::default_path);
160 Ok(Self {
161 api_key: cli_api_key.or_else(|| cfg.api_key.clone()),
162 environment,
163 api_base,
164 config_path,
165 wallet_address: cfg.wallet_address.clone(),
166 keystore_path: cfg.keystore_path.clone(),
167 confirm_above_budget: cfg.confirm_above_budget.clone(),
168 log_format: cfg.log_format.clone(),
169 receipt_timeout,
170 dry_run: cli_dry_run,
171 quiet: cli_quiet,
172 allow_custom_endpoints: cli_allow_custom_endpoints,
173 })
174 }
175
176 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_receipt_timeout_from_config() {
821 let cfg = Config {
822 receipt_timeout: Some("3min".into()),
823 ..Config::default()
824 };
825 let ctx =
826 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
827 assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
828 }
829
830 #[test]
831 fn from_parts_rejects_malformed_receipt_timeout() {
832 let cfg = Config {
833 receipt_timeout: Some("nope".into()),
834 ..Config::default()
835 };
836 let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
837 .err()
838 .expect("malformed timeout = startup error");
839 assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
840 }
841
842 #[test]
843 fn from_parts_duration_fields_none_when_config_absent() {
844 let ctx = Ctx::from_parts(
845 None,
846 None,
847 None,
848 None,
849 false,
850 false,
851 false,
852 &Config::default(),
853 )
854 .expect("default cfg is valid");
855 assert!(ctx.receipt_timeout.is_none());
856 }
857
858 #[test]
859 fn resolve_duration_flag_wins_over_ctx_and_default() {
860 let out = resolve_duration(
861 Some(Duration::from_secs(10)),
862 Some(Duration::from_secs(20)),
863 Duration::from_secs(30),
864 );
865 assert_eq!(out, Duration::from_secs(10));
866 }
867
868 #[test]
869 fn resolve_duration_ctx_wins_over_default_when_no_flag() {
870 let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
871 assert_eq!(out, Duration::from_secs(20));
872 }
873
874 #[test]
875 fn resolve_duration_falls_back_to_default() {
876 let out = resolve_duration(None, None, Duration::from_secs(30));
877 assert_eq!(out, Duration::from_secs(30));
878 }
879
880 fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
881 Ctx {
882 confirm_above_budget: threshold.map(str::to_string),
883 ..Default::default()
884 }
885 }
886
887 #[test]
888 fn budget_gate_no_op_when_threshold_unset() {
889 let ctx = ctx_with_threshold(None);
890 ctx.enforce_budget_gate(Some("99999"), false, "post a task")
891 .expect("no threshold = no gate");
892 }
893
894 #[test]
895 fn budget_gate_no_op_when_budget_absent() {
896 let ctx = ctx_with_threshold(Some("100"));
897 ctx.enforce_budget_gate(None, false, "post a task")
898 .expect("no budget = nothing to compare");
899 }
900
901 #[test]
902 fn budget_gate_passes_when_under_threshold() {
903 let ctx = ctx_with_threshold(Some("100"));
904 ctx.enforce_budget_gate(Some("50"), false, "post a task")
905 .expect("under threshold passes without --yes");
906 }
907
908 #[test]
909 fn budget_gate_passes_at_threshold_boundary() {
910 let ctx = ctx_with_threshold(Some("100"));
911 ctx.enforce_budget_gate(Some("100"), false, "post a task")
912 .expect("equal-to-threshold passes (gate is strict >)");
913 }
914
915 #[test]
916 fn budget_gate_blocks_above_threshold_without_yes() {
917 let ctx = ctx_with_threshold(Some("100"));
918 let err = ctx
919 .enforce_budget_gate(Some("100.01"), false, "post a task")
920 .expect_err("over threshold without --yes must fail");
921 match err {
922 CmdError::Usage(msg) => {
923 assert!(msg.contains("--yes"), "msg: {msg}");
924 assert!(msg.contains("post a task"), "msg: {msg}");
925 }
926 other => panic!("expected Usage, got {other:?}"),
927 }
928 }
929
930 #[test]
931 fn budget_gate_passes_above_threshold_with_yes() {
932 let ctx = ctx_with_threshold(Some("100"));
933 ctx.enforce_budget_gate(Some("9999"), true, "post a task")
934 .expect("--yes overrides the gate");
935 }
936
937 #[test]
938 fn budget_gate_uses_decimal_not_float_precision() {
939 let ctx = ctx_with_threshold(Some("0.3"));
943 ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
944 .expect_err("decimal compare must detect trailing precision");
945 }
946
947 #[test]
948 fn budget_gate_rejects_non_decimal_threshold() {
949 let ctx = ctx_with_threshold(Some("not-a-number"));
950 let err = ctx
951 .enforce_budget_gate(Some("50"), false, "post a task")
952 .expect_err("garbage threshold = usage error");
953 assert!(matches!(err, CmdError::Usage(_)));
954 }
955
956 #[test]
957 fn from_parts_flag_wins_over_config() {
958 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
959 let ctx = Ctx::from_parts(
960 Some("flag_key".into()),
961 Some(Environment::Local),
962 Some("http://flag".into()),
963 None,
964 false,
965 false,
966 false,
967 &cfg,
968 )
969 .expect("valid cfg");
970 assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
971 assert_eq!(ctx.environment, Environment::Local);
972 assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
975 }
976
977 #[test]
978 fn from_parts_config_fills_when_flags_absent() {
979 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
982 let ctx =
983 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
984 assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
985 assert_eq!(ctx.environment, Environment::Staging);
986 assert!(ctx.api_base.is_none());
989 assert_eq!(ctx.base_url(), Environment::Staging.api_base());
990 }
991
992 #[test]
993 fn from_parts_defaults_when_nothing_set() {
994 let ctx = Ctx::from_parts(
995 None,
996 None,
997 None,
998 None,
999 false,
1000 false,
1001 false,
1002 &Config::default(),
1003 )
1004 .expect("default cfg is valid");
1005 assert!(ctx.api_key.is_none());
1006 assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
1007 assert!(ctx.api_base.is_none());
1008 assert!(!ctx.dry_run);
1009 assert!(!ctx.quiet);
1010 }
1011
1012 #[test]
1013 fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
1014 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1018 let ctx = Ctx::from_parts(
1019 Some("flag_key".into()),
1020 None,
1021 None,
1022 None,
1023 false,
1024 false,
1025 false,
1026 &cfg,
1027 )
1028 .expect("valid cfg");
1029 assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1030 assert_eq!(ctx.environment, Environment::Staging);
1031 assert!(ctx.api_base.is_none());
1032 }
1033
1034 #[test]
1035 fn from_parts_rejects_custom_api_base_for_non_local_env() {
1036 let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
1039 let err = Ctx::from_parts(
1040 None,
1041 None,
1042 Some("https://evil.example".into()),
1043 None,
1044 false,
1045 false,
1046 false,
1047 &cfg,
1048 )
1049 .err()
1050 .expect("custom api_base on prod must be refused");
1051 match err {
1052 CmdError::Usage(msg) => {
1053 assert!(msg.contains("evil.example"), "msg: {msg}");
1054 assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
1055 }
1056 other => panic!("expected Usage, got {other:?}"),
1057 }
1058 }
1059
1060 #[test]
1061 fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
1062 let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1063 let ctx = Ctx::from_parts(
1064 None,
1065 None,
1066 Some("https://evil.example".into()),
1067 None,
1068 false,
1069 false,
1070 true,
1071 &cfg,
1072 )
1073 .expect("--allow-custom-endpoints must bypass the guard");
1074 assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
1075 }
1076
1077 #[test]
1078 fn from_parts_allows_custom_api_base_for_local_env() {
1079 let cfg = cfg_with(Some("k"), Some(Environment::Local));
1081 let ctx = Ctx::from_parts(
1082 None,
1083 None,
1084 Some("http://127.0.0.1:4001".into()),
1085 None,
1086 false,
1087 false,
1088 false,
1089 &cfg,
1090 )
1091 .expect("local env bypasses guard");
1092 assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
1093 }
1094
1095 #[test]
1096 fn from_parts_accepts_well_known_api_base_without_opt_in() {
1097 let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1098 let ctx = Ctx::from_parts(
1099 None,
1100 None,
1101 Some("https://api.taskfast.app".into()),
1102 None,
1103 false,
1104 false,
1105 false,
1106 &cfg,
1107 )
1108 .expect("well-known api_base passes without --allow-custom-endpoints");
1109 assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
1110 }
1111
1112 #[test]
1113 fn from_parts_guard_ignores_missing_api_base() {
1114 let ctx = Ctx::from_parts(
1116 None,
1117 None,
1118 None,
1119 None,
1120 false,
1121 false,
1122 false,
1123 &Config::default(),
1124 )
1125 .expect("no api_base = no guard");
1126 assert!(ctx.api_base.is_none());
1127 }
1128
1129 #[test]
1130 fn network_invariant_ok_when_single_advertised_matches() {
1131 let res = check_network_invariant(
1132 Environment::Prod,
1133 "https://api.taskfast.app",
1134 &["mainnet".into()],
1135 true,
1136 );
1137 assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
1138 }
1139
1140 #[test]
1141 fn network_invariant_strict_rejects_wrong_single_network() {
1142 let err = check_network_invariant(
1143 Environment::Prod,
1144 "https://api.taskfast.app",
1145 &["testnet".into()],
1146 true,
1147 )
1148 .expect_err("strict mode must reject wrong network");
1149 match err {
1150 CmdError::Server(msg) => {
1151 assert!(msg.contains("testnet"), "msg: {msg}");
1152 assert!(msg.contains("mainnet"), "msg: {msg}");
1153 assert!(msg.contains("issue #62"), "remediation hint: {msg}");
1154 }
1155 other => panic!("expected Server, got {other:?}"),
1156 }
1157 }
1158
1159 #[test]
1160 fn network_invariant_strict_rejects_extra_advertised() {
1161 let err = check_network_invariant(
1162 Environment::Prod,
1163 "https://api.taskfast.app",
1164 &["mainnet".into(), "testnet".into()],
1165 true,
1166 )
1167 .expect_err("strict mode must reject len != 1");
1168 assert!(matches!(err, CmdError::Server(_)));
1169 }
1170
1171 #[test]
1172 fn network_invariant_warn_passes_under_today_server_shape() {
1173 let res = check_network_invariant(
1176 Environment::Staging,
1177 "https://staging.api.taskfast.app",
1178 &["mainnet".into(), "testnet".into()],
1179 false,
1180 );
1181 assert!(
1182 res.is_ok(),
1183 "non-strict mode must let today's multi-network deployments through: {res:?}"
1184 );
1185 }
1186
1187 #[test]
1188 fn network_invariant_warn_passes_when_wrong_single_network() {
1189 let res = check_network_invariant(
1192 Environment::Prod,
1193 "https://api.taskfast.app",
1194 &["testnet".into()],
1195 false,
1196 );
1197 assert!(res.is_ok(), "non-strict mode warns rather than errors");
1198 }
1199
1200 #[test]
1201 fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
1202 let ctx = Ctx::from_parts(
1204 None,
1205 None,
1206 None,
1207 None,
1208 true,
1209 true,
1210 false,
1211 &Config::default(),
1212 )
1213 .expect("default cfg is valid");
1214 assert!(ctx.dry_run);
1215 assert!(ctx.quiet);
1216 }
1217}