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