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 {
284 let prefix = format!("{}/rpc/", base_url.trim_end_matches('/'));
285 rpc_url.starts_with(&prefix)
286}
287
288fn is_loopback_url(url: &str) -> bool {
289 match url::Url::parse(url) {
290 Ok(u) => matches!(
291 u.host_str(),
292 Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
293 ),
294 Err(_) => false,
295 }
296}
297
298pub(crate) fn validate_override_rpc_url(
299 url: &str,
300 network: Network,
301 allow_custom: bool,
302) -> Result<&str, CmdError> {
303 if !allow_custom {
304 return Err(CmdError::Usage(format!(
305 "refusing to use custom tempo_rpc_url {url:?}: pass \
306 --allow-custom-endpoints (or set \
307 TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) to override. The default \
308 path routes RPC through `{{api_base}}/rpc/{{network}}` \
309 which inherits the api_base endpoint guard."
310 )));
311 }
312
313 let is_plain_http_mainnet =
314 matches!(network, Network::Mainnet) && url.starts_with("http://") && !is_loopback_url(url);
315 if is_plain_http_mainnet {
316 return Err(CmdError::Usage(format!(
317 "refusing plain-HTTP mainnet tempo_rpc_url {url:?}: MITM on a \
318 mainnet RPC can observe the poster wallet and inflate gas \
319 price. Use HTTPS or point at loopback for local testing."
320 )));
321 }
322
323 Ok(url)
324}
325
326pub(crate) fn parse_wallet_address(raw: &str) -> Result<String, CmdError> {
332 let trimmed = raw.trim();
333 let _: alloy_primitives::Address = trimmed
334 .parse()
335 .map_err(|e| CmdError::Usage(format!("--wallet is not a valid EVM address: {e}")))?;
336 Ok(trimmed.to_string())
337}
338
339pub(crate) fn network_policy_for_chain_id(chain_id: u64) -> Network {
340 if chain_id == TEMPO_MAINNET_CHAIN_ID {
341 Network::Mainnet
342 } else {
343 Network::Testnet
344 }
345}
346
347fn enforce_endpoint_guard(
359 environment: Environment,
360 api_base: Option<&str>,
361 allow_custom: bool,
362) -> Result<(), CmdError> {
363 if allow_custom || environment == Environment::Local {
364 return Ok(());
365 }
366 let Some(url) = api_base else { return Ok(()) };
367 if is_well_known_api_base(url) {
368 return Ok(());
369 }
370 Err(CmdError::Usage(format!(
371 "refusing to use custom api_base {url:?} for env {env}: \
372 pass --allow-custom-endpoints (or set TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) \
373 to override. This guard blocks a malicious .taskfast/config.json in \
374 a cloned repo from silently redirecting API traffic.",
375 env = environment.as_str()
376 )))
377}
378
379pub async fn enforce_server_network_invariant(
394 ctx: &Ctx,
395 client: &TaskFastClient,
396) -> Result<(), CmdError> {
397 if ctx.allow_custom_endpoints || ctx.environment == Environment::Local {
398 return Ok(());
399 }
400 let cfg = client
401 .fetch_network_config()
402 .await
403 .map_err(CmdError::from)?;
404 let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
405 .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
406 let advertised: Vec<String> = cfg.networks.keys().cloned().collect();
407 check_network_invariant(ctx.environment, ctx.base_url(), &advertised, strict)
408}
409
410fn check_network_invariant(
414 env: Environment,
415 api_base: &str,
416 advertised: &[String],
417 strict: bool,
418) -> Result<(), CmdError> {
419 let expected = env.network().as_str();
420 if advertised.len() == 1 && advertised[0] == expected {
421 return Ok(());
422 }
423 if strict {
424 return Err(CmdError::Server(format!(
425 "deployment at {api_base} advertises networks {advertised:?}; env {} requires \
426 exactly [{expected}]. Server-side fix tracked in issue #62. Unset \
427 TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
428 env.as_str(),
429 )));
430 }
431 tracing::warn!(
432 api_base = %api_base,
433 env = env.as_str(),
434 expected = expected,
435 advertised = ?advertised,
436 "deployment advertises a different network shape than env requires; \
437 server-side fix tracked in issue #62. Set TASKFAST_STRICT_ENV_NETWORK=1 \
438 to fail-closed."
439 );
440 Ok(())
441}
442
443fn parse_duration_cfg(
448 raw: Option<&str>,
449 field: &'static str,
450) -> Result<Option<Duration>, CmdError> {
451 match raw {
452 None => Ok(None),
453 Some(s) => humantime::parse_duration(s).map(Some).map_err(|e| {
454 CmdError::Usage(format!("config `{field}` is not a duration: {s:?} ({e})"))
455 }),
456 }
457}
458
459pub fn resolve_duration(
463 flag: Option<Duration>,
464 ctx_field: Option<Duration>,
465 default: Duration,
466) -> Duration {
467 flag.or(ctx_field).unwrap_or(default)
468}
469
470pub type CmdResult = Result<Envelope, CmdError>;
471
472#[derive(Debug, Error)]
476pub enum CmdError {
477 #[error("missing API key: set --api-key or TASKFAST_API_KEY")]
478 MissingApiKey,
479
480 #[error("usage: {0}")]
481 Usage(String),
482
483 #[error("auth: {0}")]
484 Auth(String),
485
486 #[error("rate limited (retry in {retry_after:?})")]
487 RateLimited { retry_after: Duration },
488
489 #[error("validation [{code}]: {message}")]
490 Validation { code: String, message: String },
491
492 #[error("server: {0}")]
493 Server(String),
494
495 #[error("network: {0}")]
496 Network(String),
497
498 #[error("decode: {0}")]
499 Decode(String),
500
501 #[error("keystore: {0}")]
502 Keystore(String),
503
504 #[error("signing: {0}")]
505 Signing(String),
506
507 #[error("not yet implemented: {0}")]
508 Unimplemented(&'static str),
509
510 #[error(transparent)]
511 Config(#[from] ConfigError),
512}
513
514impl CmdError {
515 pub fn code(&self) -> &'static str {
517 match self {
518 Self::MissingApiKey => "missing_api_key",
519 Self::Usage(_) => "usage",
520 Self::Auth(_) => "auth",
521 Self::RateLimited { .. } => "rate_limited",
522 Self::Validation { .. } => "validation",
523 Self::Server(_) => "server",
524 Self::Network(_) => "network",
525 Self::Decode(_) => "decode",
526 Self::Keystore(_) => "keystore",
527 Self::Signing(_) => "signing",
528 Self::Unimplemented(_) => "unimplemented",
529 Self::Config(_) => "config",
530 }
531 }
532
533 pub fn exit_code(&self) -> ExitCode {
535 match self {
536 Self::MissingApiKey | Self::Usage(_) | Self::Config(_) => ExitCode::Usage,
537 Self::Auth(_) => ExitCode::Auth,
538 Self::RateLimited { .. } => ExitCode::RateLimited,
539 Self::Validation { .. } => ExitCode::Validation,
540 Self::Server(_) | Self::Network(_) | Self::Decode(_) => ExitCode::Server,
541 Self::Keystore(_) | Self::Signing(_) => ExitCode::Wallet,
542 Self::Unimplemented(_) => ExitCode::Unimplemented,
543 }
544 }
545
546 pub fn retry_after(&self) -> Option<Duration> {
550 match self {
551 Self::RateLimited { retry_after } => Some(*retry_after),
552 _ => None,
553 }
554 }
555}
556
557impl From<ClientError> for CmdError {
558 fn from(e: ClientError) -> Self {
559 match e {
560 ClientError::Auth(m) => Self::Auth(m),
561 ClientError::Validation { code, message } => Self::Validation { code, message },
562 ClientError::RateLimited { retry_after } => Self::RateLimited { retry_after },
563 ClientError::Server(m) => Self::Server(m),
564 ClientError::Network(e) => Self::Network(e.to_string()),
565 ClientError::Decode(e) => Self::Decode(e.to_string()),
566 }
567 }
568}
569
570impl From<KeystoreError> for CmdError {
571 fn from(e: KeystoreError) -> Self {
572 Self::Keystore(e.to_string())
573 }
574}
575
576impl From<SigningError> for CmdError {
577 fn from(e: SigningError) -> Self {
578 Self::Signing(e.to_string())
579 }
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585 use std::collections::HashSet;
586
587 fn sample(variant: &str) -> CmdError {
588 match variant {
589 "missing_api_key" => CmdError::MissingApiKey,
590 "usage" => CmdError::Usage("bad flag".into()),
591 "auth" => CmdError::Auth("401".into()),
592 "rate_limited" => CmdError::RateLimited {
593 retry_after: Duration::from_secs(30),
594 },
595 "validation" => CmdError::Validation {
596 code: "bad_field".into(),
597 message: "x".into(),
598 },
599 "server" => CmdError::Server("500".into()),
600 "network" => CmdError::Network("dns".into()),
601 "decode" => CmdError::Decode("json".into()),
602 "keystore" => CmdError::Keystore("bad pw".into()),
603 "signing" => CmdError::Signing("hsm".into()),
604 "unimplemented" => CmdError::Unimplemented("soon"),
605 "config" => CmdError::Config(ConfigError::Io {
606 path: PathBuf::from("/x"),
607 source: std::io::Error::other("boom"),
608 }),
609 _ => unreachable!(),
610 }
611 }
612
613 const ALL: &[&str] = &[
614 "missing_api_key",
615 "usage",
616 "auth",
617 "rate_limited",
618 "validation",
619 "server",
620 "network",
621 "decode",
622 "keystore",
623 "signing",
624 "unimplemented",
625 "config",
626 ];
627
628 #[test]
629 fn every_variant_has_distinct_code() {
630 let codes: HashSet<&'static str> = ALL.iter().map(|v| sample(v).code()).collect();
631 assert_eq!(codes.len(), ALL.len(), "codes must be unique per variant");
632 for v in ALL {
633 assert_eq!(sample(v).code(), *v, "code() for {v} must match the label");
634 }
635 }
636
637 #[test]
638 fn exit_code_taxonomy_matches_plan() {
639 assert_eq!(CmdError::MissingApiKey.exit_code(), ExitCode::Usage);
642 assert_eq!(sample("usage").exit_code(), ExitCode::Usage);
643 assert_eq!(sample("auth").exit_code(), ExitCode::Auth);
644 assert_eq!(sample("rate_limited").exit_code(), ExitCode::RateLimited);
645 assert_eq!(sample("validation").exit_code(), ExitCode::Validation);
646 assert_eq!(sample("server").exit_code(), ExitCode::Server);
647 assert_eq!(sample("network").exit_code(), ExitCode::Server);
648 assert_eq!(sample("decode").exit_code(), ExitCode::Server);
649 assert_eq!(sample("keystore").exit_code(), ExitCode::Wallet);
650 assert_eq!(sample("signing").exit_code(), ExitCode::Wallet);
651 assert_eq!(sample("unimplemented").exit_code(), ExitCode::Unimplemented);
652 assert_eq!(sample("config").exit_code(), ExitCode::Usage);
653 }
654
655 #[test]
656 fn client_error_folds_retry_after_into_cmd_error() {
657 let ce = ClientError::RateLimited {
658 retry_after: Duration::from_secs(42),
659 };
660 let cmd: CmdError = ce.into();
661 match cmd {
662 CmdError::RateLimited { retry_after } => {
663 assert_eq!(retry_after, Duration::from_secs(42));
664 }
665 other => panic!("expected RateLimited, got {other:?}"),
666 }
667 assert_eq!(
669 sample("rate_limited").retry_after(),
670 Some(Duration::from_secs(30))
671 );
672 assert!(sample("auth").retry_after().is_none());
673 }
674
675 #[test]
676 fn is_proxy_rpc_url_recognises_authenticated_proxy() {
677 let base = "https://staging.api.taskfast.app";
678 assert!(is_proxy_rpc_url(
680 "https://staging.api.taskfast.app/rpc/testnet",
681 base
682 ));
683 assert!(is_proxy_rpc_url(
685 "https://staging.api.taskfast.app/rpc/mainnet",
686 "https://staging.api.taskfast.app/"
687 ));
688 assert!(!is_proxy_rpc_url("https://rpc.moderato.tempo.xyz", base));
691 assert!(!is_proxy_rpc_url(
694 "https://staging.api.taskfast.app/task_drafts",
695 base
696 ));
697 assert!(!is_proxy_rpc_url(
700 "https://attacker.example/rpc/testnet",
701 base
702 ));
703 }
704
705 #[test]
706 fn ctx_base_url_override_wins_over_environment_default() {
707 let ctx = Ctx {
708 api_key: None,
709 environment: Environment::Prod,
710 api_base: Some("http://localhost:9999".into()),
711 config_path: PathBuf::from("/dev/null"),
712 dry_run: false,
713 quiet: false,
714 ..Default::default()
715 };
716 assert_eq!(ctx.base_url(), "http://localhost:9999");
717 }
718
719 #[test]
720 fn ctx_base_url_falls_back_to_environment_default() {
721 for (env, expected) in [
722 (Environment::Prod, "https://api.taskfast.app"),
723 (Environment::Staging, "https://staging.api.taskfast.app"),
724 (Environment::Local, "http://127.0.0.1:4000"),
725 ] {
726 let ctx = Ctx {
727 api_key: None,
728 environment: env,
729 api_base: None,
730 config_path: PathBuf::from("/dev/null"),
731 dry_run: false,
732 quiet: false,
733 ..Default::default()
734 };
735 assert_eq!(ctx.base_url(), expected);
736 }
737 }
738
739 #[test]
740 fn ctx_client_errors_when_api_key_missing() {
741 let ctx = Ctx {
742 api_key: None,
743 environment: Environment::Local,
744 api_base: None,
745 config_path: PathBuf::from("/dev/null"),
746 dry_run: false,
747 quiet: false,
748 ..Default::default()
749 };
750 match ctx.client() {
751 Err(CmdError::MissingApiKey) => {}
752 Err(other) => panic!("expected MissingApiKey, got {other:?}"),
753 Ok(_) => panic!("expected MissingApiKey, got Ok(client)"),
754 }
755 }
756
757 #[test]
758 fn ctx_client_builds_when_api_key_present() {
759 let ctx = Ctx {
760 api_key: Some("tk_test_abc".into()),
761 environment: Environment::Local,
762 api_base: None,
763 config_path: PathBuf::from("/dev/null"),
764 dry_run: false,
765 quiet: false,
766 ..Default::default()
767 };
768 ctx.client().expect("client should build with a valid key");
769 }
770
771 fn cfg_with(api_key: Option<&str>, environment: Option<Environment>) -> Config {
772 Config {
773 api_key: api_key.map(str::to_string),
774 environment,
775 ..Config::default()
776 }
777 }
778
779 #[test]
780 fn from_parts_threads_wallet_keystore_confirm_log_format_from_config() {
781 let cfg = Config {
782 wallet_address: Some("0xfeed".into()),
783 keystore_path: Some(PathBuf::from("/tmp/k.json")),
784 confirm_above_budget: Some("500".into()),
785 log_format: Some("json".into()),
786 ..Config::default()
787 };
788 let ctx =
789 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
790 assert_eq!(ctx.wallet_address.as_deref(), Some("0xfeed"));
791 assert_eq!(
792 ctx.keystore_path.as_deref(),
793 Some(std::path::Path::new("/tmp/k.json"))
794 );
795 assert_eq!(ctx.confirm_above_budget.as_deref(), Some("500"));
796 assert_eq!(ctx.log_format.as_deref(), Some("json"));
797 }
798
799 #[test]
800 fn from_parts_parses_approval_horizon_from_config() {
801 let cfg = Config {
802 approval_horizon: Some("7d".into()),
803 ..Config::default()
804 };
805 let ctx =
806 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 7d");
807 assert_eq!(ctx.approval_horizon, Some(Duration::from_hours(24 * 7)));
808 }
809
810 #[test]
811 fn from_parts_parses_receipt_timeout_from_config() {
812 let cfg = Config {
813 receipt_timeout: Some("3min".into()),
814 ..Config::default()
815 };
816 let ctx =
817 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
818 assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
819 }
820
821 #[test]
822 fn from_parts_rejects_malformed_approval_horizon() {
823 let cfg = Config {
824 approval_horizon: Some("7xyz".into()),
825 ..Config::default()
826 };
827 let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
828 .err()
829 .expect("malformed config must fail at startup");
830 match err {
831 CmdError::Usage(msg) => {
832 assert!(msg.contains("approval_horizon"), "msg: {msg}");
833 assert!(msg.contains("7xyz"), "msg: {msg}");
834 }
835 other => panic!("expected Usage, got {other:?}"),
836 }
837 }
838
839 #[test]
840 fn from_parts_rejects_malformed_receipt_timeout() {
841 let cfg = Config {
842 receipt_timeout: Some("nope".into()),
843 ..Config::default()
844 };
845 let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
846 .err()
847 .expect("malformed timeout = startup error");
848 assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
849 }
850
851 #[test]
852 fn from_parts_duration_fields_none_when_config_absent() {
853 let ctx = Ctx::from_parts(
854 None,
855 None,
856 None,
857 None,
858 false,
859 false,
860 false,
861 &Config::default(),
862 )
863 .expect("default cfg is valid");
864 assert!(ctx.approval_horizon.is_none());
865 assert!(ctx.receipt_timeout.is_none());
866 }
867
868 #[test]
869 fn resolve_duration_flag_wins_over_ctx_and_default() {
870 let out = resolve_duration(
871 Some(Duration::from_secs(10)),
872 Some(Duration::from_secs(20)),
873 Duration::from_secs(30),
874 );
875 assert_eq!(out, Duration::from_secs(10));
876 }
877
878 #[test]
879 fn resolve_duration_ctx_wins_over_default_when_no_flag() {
880 let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
881 assert_eq!(out, Duration::from_secs(20));
882 }
883
884 #[test]
885 fn resolve_duration_falls_back_to_default() {
886 let out = resolve_duration(None, None, Duration::from_secs(30));
887 assert_eq!(out, Duration::from_secs(30));
888 }
889
890 fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
891 Ctx {
892 confirm_above_budget: threshold.map(str::to_string),
893 ..Default::default()
894 }
895 }
896
897 #[test]
898 fn budget_gate_no_op_when_threshold_unset() {
899 let ctx = ctx_with_threshold(None);
900 ctx.enforce_budget_gate(Some("99999"), false, "post a task")
901 .expect("no threshold = no gate");
902 }
903
904 #[test]
905 fn budget_gate_no_op_when_budget_absent() {
906 let ctx = ctx_with_threshold(Some("100"));
907 ctx.enforce_budget_gate(None, false, "post a task")
908 .expect("no budget = nothing to compare");
909 }
910
911 #[test]
912 fn budget_gate_passes_when_under_threshold() {
913 let ctx = ctx_with_threshold(Some("100"));
914 ctx.enforce_budget_gate(Some("50"), false, "post a task")
915 .expect("under threshold passes without --yes");
916 }
917
918 #[test]
919 fn budget_gate_passes_at_threshold_boundary() {
920 let ctx = ctx_with_threshold(Some("100"));
921 ctx.enforce_budget_gate(Some("100"), false, "post a task")
922 .expect("equal-to-threshold passes (gate is strict >)");
923 }
924
925 #[test]
926 fn budget_gate_blocks_above_threshold_without_yes() {
927 let ctx = ctx_with_threshold(Some("100"));
928 let err = ctx
929 .enforce_budget_gate(Some("100.01"), false, "post a task")
930 .expect_err("over threshold without --yes must fail");
931 match err {
932 CmdError::Usage(msg) => {
933 assert!(msg.contains("--yes"), "msg: {msg}");
934 assert!(msg.contains("post a task"), "msg: {msg}");
935 }
936 other => panic!("expected Usage, got {other:?}"),
937 }
938 }
939
940 #[test]
941 fn budget_gate_passes_above_threshold_with_yes() {
942 let ctx = ctx_with_threshold(Some("100"));
943 ctx.enforce_budget_gate(Some("9999"), true, "post a task")
944 .expect("--yes overrides the gate");
945 }
946
947 #[test]
948 fn budget_gate_uses_decimal_not_float_precision() {
949 let ctx = ctx_with_threshold(Some("0.3"));
953 ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
954 .expect_err("decimal compare must detect trailing precision");
955 }
956
957 #[test]
958 fn budget_gate_rejects_non_decimal_threshold() {
959 let ctx = ctx_with_threshold(Some("not-a-number"));
960 let err = ctx
961 .enforce_budget_gate(Some("50"), false, "post a task")
962 .expect_err("garbage threshold = usage error");
963 assert!(matches!(err, CmdError::Usage(_)));
964 }
965
966 #[test]
967 fn from_parts_flag_wins_over_config() {
968 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
969 let ctx = Ctx::from_parts(
970 Some("flag_key".into()),
971 Some(Environment::Local),
972 Some("http://flag".into()),
973 None,
974 false,
975 false,
976 false,
977 &cfg,
978 )
979 .expect("valid cfg");
980 assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
981 assert_eq!(ctx.environment, Environment::Local);
982 assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
985 }
986
987 #[test]
988 fn from_parts_config_fills_when_flags_absent() {
989 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
992 let ctx =
993 Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
994 assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
995 assert_eq!(ctx.environment, Environment::Staging);
996 assert!(ctx.api_base.is_none());
999 assert_eq!(ctx.base_url(), Environment::Staging.api_base());
1000 }
1001
1002 #[test]
1003 fn from_parts_defaults_when_nothing_set() {
1004 let ctx = Ctx::from_parts(
1005 None,
1006 None,
1007 None,
1008 None,
1009 false,
1010 false,
1011 false,
1012 &Config::default(),
1013 )
1014 .expect("default cfg is valid");
1015 assert!(ctx.api_key.is_none());
1016 assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
1017 assert!(ctx.api_base.is_none());
1018 assert!(!ctx.dry_run);
1019 assert!(!ctx.quiet);
1020 }
1021
1022 #[test]
1023 fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
1024 let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
1028 let ctx = Ctx::from_parts(
1029 Some("flag_key".into()),
1030 None,
1031 None,
1032 None,
1033 false,
1034 false,
1035 false,
1036 &cfg,
1037 )
1038 .expect("valid cfg");
1039 assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
1040 assert_eq!(ctx.environment, Environment::Staging);
1041 assert!(ctx.api_base.is_none());
1042 }
1043
1044 #[test]
1045 fn from_parts_rejects_custom_api_base_for_non_local_env() {
1046 let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
1049 let err = Ctx::from_parts(
1050 None,
1051 None,
1052 Some("https://evil.example".into()),
1053 None,
1054 false,
1055 false,
1056 false,
1057 &cfg,
1058 )
1059 .err()
1060 .expect("custom api_base on prod must be refused");
1061 match err {
1062 CmdError::Usage(msg) => {
1063 assert!(msg.contains("evil.example"), "msg: {msg}");
1064 assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
1065 }
1066 other => panic!("expected Usage, got {other:?}"),
1067 }
1068 }
1069
1070 #[test]
1071 fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
1072 let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1073 let ctx = Ctx::from_parts(
1074 None,
1075 None,
1076 Some("https://evil.example".into()),
1077 None,
1078 false,
1079 false,
1080 true,
1081 &cfg,
1082 )
1083 .expect("--allow-custom-endpoints must bypass the guard");
1084 assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
1085 }
1086
1087 #[test]
1088 fn from_parts_allows_custom_api_base_for_local_env() {
1089 let cfg = cfg_with(Some("k"), Some(Environment::Local));
1091 let ctx = Ctx::from_parts(
1092 None,
1093 None,
1094 Some("http://127.0.0.1:4001".into()),
1095 None,
1096 false,
1097 false,
1098 false,
1099 &cfg,
1100 )
1101 .expect("local env bypasses guard");
1102 assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
1103 }
1104
1105 #[test]
1106 fn from_parts_accepts_well_known_api_base_without_opt_in() {
1107 let cfg = cfg_with(Some("k"), Some(Environment::Prod));
1108 let ctx = Ctx::from_parts(
1109 None,
1110 None,
1111 Some("https://api.taskfast.app".into()),
1112 None,
1113 false,
1114 false,
1115 false,
1116 &cfg,
1117 )
1118 .expect("well-known api_base passes without --allow-custom-endpoints");
1119 assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
1120 }
1121
1122 #[test]
1123 fn from_parts_guard_ignores_missing_api_base() {
1124 let ctx = Ctx::from_parts(
1126 None,
1127 None,
1128 None,
1129 None,
1130 false,
1131 false,
1132 false,
1133 &Config::default(),
1134 )
1135 .expect("no api_base = no guard");
1136 assert!(ctx.api_base.is_none());
1137 }
1138
1139 #[test]
1140 fn network_invariant_ok_when_single_advertised_matches() {
1141 let res = check_network_invariant(
1142 Environment::Prod,
1143 "https://api.taskfast.app",
1144 &["mainnet".into()],
1145 true,
1146 );
1147 assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
1148 }
1149
1150 #[test]
1151 fn network_invariant_strict_rejects_wrong_single_network() {
1152 let err = check_network_invariant(
1153 Environment::Prod,
1154 "https://api.taskfast.app",
1155 &["testnet".into()],
1156 true,
1157 )
1158 .expect_err("strict mode must reject wrong network");
1159 match err {
1160 CmdError::Server(msg) => {
1161 assert!(msg.contains("testnet"), "msg: {msg}");
1162 assert!(msg.contains("mainnet"), "msg: {msg}");
1163 assert!(msg.contains("issue #62"), "remediation hint: {msg}");
1164 }
1165 other => panic!("expected Server, got {other:?}"),
1166 }
1167 }
1168
1169 #[test]
1170 fn network_invariant_strict_rejects_extra_advertised() {
1171 let err = check_network_invariant(
1172 Environment::Prod,
1173 "https://api.taskfast.app",
1174 &["mainnet".into(), "testnet".into()],
1175 true,
1176 )
1177 .expect_err("strict mode must reject len != 1");
1178 assert!(matches!(err, CmdError::Server(_)));
1179 }
1180
1181 #[test]
1182 fn network_invariant_warn_passes_under_today_server_shape() {
1183 let res = check_network_invariant(
1186 Environment::Staging,
1187 "https://staging.api.taskfast.app",
1188 &["mainnet".into(), "testnet".into()],
1189 false,
1190 );
1191 assert!(
1192 res.is_ok(),
1193 "non-strict mode must let today's multi-network deployments through: {res:?}"
1194 );
1195 }
1196
1197 #[test]
1198 fn network_invariant_warn_passes_when_wrong_single_network() {
1199 let res = check_network_invariant(
1202 Environment::Prod,
1203 "https://api.taskfast.app",
1204 &["testnet".into()],
1205 false,
1206 );
1207 assert!(res.is_ok(), "non-strict mode warns rather than errors");
1208 }
1209
1210 #[test]
1211 fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
1212 let ctx = Ctx::from_parts(
1214 None,
1215 None,
1216 None,
1217 None,
1218 true,
1219 true,
1220 false,
1221 &Config::default(),
1222 )
1223 .expect("default cfg is valid");
1224 assert!(ctx.dry_run);
1225 assert!(ctx.quiet);
1226 }
1227}