use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
use rust_decimal::Decimal;
use thiserror::Error;
use crate::config::{Config, ConfigError};
use crate::envelope::Envelope;
use crate::exit::ExitCode;
use crate::{is_well_known_api_base, Environment, Network};
use taskfast_agent::keystore::KeystoreError;
use taskfast_chains::tempo::SigningError;
use taskfast_chains::tempo::TEMPO_MAINNET_CHAIN_ID;
use taskfast_client::{Error as ClientError, TaskFastClient};
pub mod agent;
pub mod artifact;
pub mod backer;
pub mod bid;
pub mod bond;
pub mod cast;
pub mod config;
pub mod discover;
pub mod dispute;
pub mod escalate;
pub mod escrow;
pub mod events;
pub mod fee;
pub mod init;
pub mod init_tui;
pub mod me;
pub mod message;
pub mod payment;
pub mod ping;
pub mod platform;
pub mod post;
pub mod review;
pub mod settle;
pub mod skills;
pub mod stake;
pub mod task;
pub mod wallet;
pub mod wallet_args;
pub mod webhook;
#[derive(Clone)]
pub struct Ctx {
pub api_key: Option<String>,
pub environment: Environment,
pub api_base: Option<String>,
pub config_path: PathBuf,
pub wallet_address: Option<String>,
pub keystore_path: Option<PathBuf>,
pub confirm_above_budget: Option<String>,
pub log_format: Option<String>,
pub receipt_timeout: Option<Duration>,
pub dry_run: bool,
pub quiet: bool,
pub allow_custom_endpoints: bool,
}
pub const DEFAULT_ENVIRONMENT: Environment = Environment::Prod;
impl Default for Ctx {
fn default() -> Self {
Self {
api_key: None,
environment: DEFAULT_ENVIRONMENT,
api_base: None,
config_path: PathBuf::from("/dev/null"),
wallet_address: None,
keystore_path: None,
confirm_above_budget: None,
log_format: None,
receipt_timeout: None,
dry_run: false,
quiet: false,
allow_custom_endpoints: false,
}
}
}
impl Ctx {
pub fn state_store(&self) -> crate::state_store::StateStore {
crate::state_store::StateStore::from_config_path(&self.config_path)
}
pub fn from_parts(
cli_api_key: Option<String>,
cli_env: Option<Environment>,
cli_api_base: Option<String>,
cli_config_path: Option<PathBuf>,
cli_dry_run: bool,
cli_quiet: bool,
cli_allow_custom_endpoints: bool,
cfg: &Config,
) -> Result<Self, CmdError> {
let receipt_timeout =
parse_duration_cfg(cfg.receipt_timeout.as_deref(), "receipt_timeout")?;
let environment = cli_env.or(cfg.environment).unwrap_or(DEFAULT_ENVIRONMENT);
let api_base = cli_api_base;
enforce_endpoint_guard(environment, api_base.as_deref(), cli_allow_custom_endpoints)?;
let config_path = cli_config_path.unwrap_or_else(Config::default_path);
Ok(Self {
api_key: cli_api_key.or_else(|| cfg.api_key.clone()),
environment,
api_base,
config_path,
wallet_address: cfg.wallet_address.clone(),
keystore_path: cfg.keystore_path.clone(),
confirm_above_budget: cfg.confirm_above_budget.clone(),
log_format: cfg.log_format.clone(),
receipt_timeout,
dry_run: cli_dry_run,
quiet: cli_quiet,
allow_custom_endpoints: cli_allow_custom_endpoints,
})
}
pub fn security_warnings(&self) -> Vec<crate::envelope::SecurityWarning> {
use crate::envelope::SecurityWarning;
let mut out = Vec::new();
if self.allow_custom_endpoints {
let detail = self.api_base.as_deref().unwrap_or("(env default)");
out.push(SecurityWarning {
code: "custom_endpoints_allowed",
message: format!(
"--allow-custom-endpoints is in effect; api_base={detail}. \
Traffic will go to a non-well-known host."
),
});
}
if std::env::var("TASKFAST_WALLET_PASSWORD").is_ok_and(|v| !v.is_empty()) {
out.push(SecurityWarning {
code: "password_env_var",
message: "TASKFAST_WALLET_PASSWORD is readable via /proc/<pid>/environ; \
prefer --wallet-password-file."
.into(),
});
}
out
}
pub fn base_url(&self) -> &str {
match self.api_base.as_deref() {
Some(u) => u,
None => self.environment.api_base(),
}
}
pub fn client(&self) -> Result<TaskFastClient, CmdError> {
let key = self.api_key.as_deref().ok_or(CmdError::MissingApiKey)?;
TaskFastClient::from_api_key(self.base_url(), key).map_err(CmdError::from)
}
pub fn rpc_http_client(&self, client: &TaskFastClient, rpc_url: &str) -> reqwest::Client {
if is_proxy_rpc_url(rpc_url, self.base_url()) {
client.http_client()
} else {
reqwest::Client::new()
}
}
pub fn enforce_budget_gate(
&self,
budget: Option<&str>,
yes: bool,
verb: &str,
) -> Result<(), CmdError> {
let threshold_str = match self.confirm_above_budget.as_deref() {
Some(t) => t,
None => return Ok(()),
};
let budget_str = match budget {
Some(b) => b,
None => return Ok(()),
};
let threshold = Decimal::from_str(threshold_str).map_err(|_| {
CmdError::Usage(format!(
"config `confirm_above_budget` is not a decimal: {threshold_str:?}"
))
})?;
let amount = Decimal::from_str(budget_str)
.map_err(|_| CmdError::Usage(format!("budget {budget_str:?} is not a decimal")))?;
if amount > threshold && !yes {
return Err(CmdError::Usage(format!(
"refusing to {verb}: budget {amount} exceeds confirm_above_budget \
{threshold} (pass --yes to override)"
)));
}
Ok(())
}
}
pub(crate) fn is_proxy_rpc_url(rpc_url: &str, base_url: &str) -> bool {
match (url::Url::parse(rpc_url), url::Url::parse(base_url)) {
(Ok(rpc), Ok(base)) => rpc.origin() == base.origin(),
_ => false,
}
}
fn is_loopback_url(url: &str) -> bool {
match url::Url::parse(url) {
Ok(u) => matches!(
u.host_str(),
Some("localhost" | "127.0.0.1" | "[::1]" | "::1")
),
Err(_) => false,
}
}
pub(crate) fn validate_override_rpc_url(
url: &str,
network: Network,
allow_custom: bool,
) -> Result<&str, CmdError> {
if !allow_custom {
return Err(CmdError::Usage(format!(
"refusing to use custom tempo_rpc_url {url:?}: pass \
--allow-custom-endpoints (or set \
TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) to override. The default \
path routes RPC through `{{api_base}}/rpc/{{network}}` \
which inherits the api_base endpoint guard."
)));
}
let is_plain_http_mainnet =
matches!(network, Network::Mainnet) && url.starts_with("http://") && !is_loopback_url(url);
if is_plain_http_mainnet {
return Err(CmdError::Usage(format!(
"refusing plain-HTTP mainnet tempo_rpc_url {url:?}: MITM on a \
mainnet RPC can observe the poster wallet and inflate gas \
price. Use HTTPS or point at loopback for local testing."
)));
}
Ok(url)
}
pub(crate) fn parse_wallet_address(raw: &str) -> Result<String, CmdError> {
let trimmed = raw.trim();
let _: alloy_primitives::Address = trimmed
.parse()
.map_err(|e| CmdError::Usage(format!("--wallet is not a valid EVM address: {e}")))?;
Ok(trimmed.to_string())
}
pub(crate) fn network_policy_for_chain_id(chain_id: u64) -> Network {
if chain_id == TEMPO_MAINNET_CHAIN_ID {
Network::Mainnet
} else {
Network::Testnet
}
}
fn enforce_endpoint_guard(
environment: Environment,
api_base: Option<&str>,
allow_custom: bool,
) -> Result<(), CmdError> {
if allow_custom || environment == Environment::Local {
return Ok(());
}
let Some(url) = api_base else { return Ok(()) };
if is_well_known_api_base(url) {
return Ok(());
}
Err(CmdError::Usage(format!(
"refusing to use custom api_base {url:?} for env {env}: \
pass --allow-custom-endpoints (or set TASKFAST_ALLOW_CUSTOM_ENDPOINTS=1) \
to override. This guard blocks a malicious .taskfast/config.json in \
a cloned repo from silently redirecting API traffic.",
env = environment.as_str()
)))
}
pub async fn enforce_server_network_invariant(
ctx: &Ctx,
client: &TaskFastClient,
) -> Result<(), CmdError> {
if ctx.allow_custom_endpoints || ctx.environment == Environment::Local {
return Ok(());
}
let cfg = client
.fetch_network_config()
.await
.map_err(CmdError::from)?;
let strict = std::env::var("TASKFAST_STRICT_ENV_NETWORK")
.is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
let advertised: Vec<String> = cfg.networks.keys().cloned().collect();
check_network_invariant(ctx.environment, ctx.base_url(), &advertised, strict)
}
fn check_network_invariant(
env: Environment,
api_base: &str,
advertised: &[String],
strict: bool,
) -> Result<(), CmdError> {
let expected = env.network().as_str();
if advertised.len() == 1 && advertised[0] == expected {
return Ok(());
}
if strict {
return Err(CmdError::Server(format!(
"deployment at {api_base} advertises networks {advertised:?}; env {} requires \
exactly [{expected}]. Server-side fix tracked in issue #62. Unset \
TASKFAST_STRICT_ENV_NETWORK or pass --allow-custom-endpoints to bypass.",
env.as_str(),
)));
}
tracing::warn!(
api_base = %api_base,
env = env.as_str(),
expected = expected,
advertised = ?advertised,
"deployment advertises a different network shape than env requires; \
server-side fix tracked in issue #62. Set TASKFAST_STRICT_ENV_NETWORK=1 \
to fail-closed."
);
Ok(())
}
fn parse_duration_cfg(
raw: Option<&str>,
field: &'static str,
) -> Result<Option<Duration>, CmdError> {
match raw {
None => Ok(None),
Some(s) => humantime::parse_duration(s).map(Some).map_err(|e| {
CmdError::Usage(format!("config `{field}` is not a duration: {s:?} ({e})"))
}),
}
}
pub fn resolve_duration(
flag: Option<Duration>,
ctx_field: Option<Duration>,
default: Duration,
) -> Duration {
flag.or(ctx_field).unwrap_or(default)
}
pub type CmdResult = Result<Envelope, CmdError>;
#[derive(Debug, Error)]
pub enum CmdError {
#[error("missing API key: set --api-key or TASKFAST_API_KEY")]
MissingApiKey,
#[error("usage: {0}")]
Usage(String),
#[error("auth: {0}")]
Auth(String),
#[error("rate limited (retry in {retry_after:?})")]
RateLimited { retry_after: Duration },
#[error("validation [{code}]: {message}")]
Validation { code: String, message: String },
#[error("server: {0}")]
Server(String),
#[error("network: {0}")]
Network(String),
#[error("decode: {0}")]
Decode(String),
#[error("keystore: {0}")]
Keystore(String),
#[error("signing: {0}")]
Signing(String),
#[error("not yet implemented: {0}")]
Unimplemented(&'static str),
#[error(transparent)]
Config(#[from] ConfigError),
}
impl CmdError {
pub fn code(&self) -> &'static str {
match self {
Self::MissingApiKey => "missing_api_key",
Self::Usage(_) => "usage",
Self::Auth(_) => "auth",
Self::RateLimited { .. } => "rate_limited",
Self::Validation { .. } => "validation",
Self::Server(_) => "server",
Self::Network(_) => "network",
Self::Decode(_) => "decode",
Self::Keystore(_) => "keystore",
Self::Signing(_) => "signing",
Self::Unimplemented(_) => "unimplemented",
Self::Config(_) => "config",
}
}
pub fn exit_code(&self) -> ExitCode {
match self {
Self::MissingApiKey | Self::Usage(_) | Self::Config(_) => ExitCode::Usage,
Self::Auth(_) => ExitCode::Auth,
Self::RateLimited { .. } => ExitCode::RateLimited,
Self::Validation { .. } => ExitCode::Validation,
Self::Server(_) | Self::Network(_) | Self::Decode(_) => ExitCode::Server,
Self::Keystore(_) | Self::Signing(_) => ExitCode::Wallet,
Self::Unimplemented(_) => ExitCode::Unimplemented,
}
}
pub fn retry_after(&self) -> Option<Duration> {
match self {
Self::RateLimited { retry_after } => Some(*retry_after),
_ => None,
}
}
}
impl From<ClientError> for CmdError {
fn from(e: ClientError) -> Self {
match e {
ClientError::Auth(m) => Self::Auth(m),
ClientError::Validation { code, message } => Self::Validation { code, message },
ClientError::RateLimited { retry_after } => Self::RateLimited { retry_after },
ClientError::Server(m) => Self::Server(m),
ClientError::Network(e) => Self::Network(e.to_string()),
ClientError::Decode(e) => Self::Decode(e.to_string()),
}
}
}
impl From<KeystoreError> for CmdError {
fn from(e: KeystoreError) -> Self {
Self::Keystore(e.to_string())
}
}
impl From<SigningError> for CmdError {
fn from(e: SigningError) -> Self {
Self::Signing(e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
fn sample(variant: &str) -> CmdError {
match variant {
"missing_api_key" => CmdError::MissingApiKey,
"usage" => CmdError::Usage("bad flag".into()),
"auth" => CmdError::Auth("401".into()),
"rate_limited" => CmdError::RateLimited {
retry_after: Duration::from_secs(30),
},
"validation" => CmdError::Validation {
code: "bad_field".into(),
message: "x".into(),
},
"server" => CmdError::Server("500".into()),
"network" => CmdError::Network("dns".into()),
"decode" => CmdError::Decode("json".into()),
"keystore" => CmdError::Keystore("bad pw".into()),
"signing" => CmdError::Signing("hsm".into()),
"unimplemented" => CmdError::Unimplemented("soon"),
"config" => CmdError::Config(ConfigError::Io {
path: PathBuf::from("/x"),
source: std::io::Error::other("boom"),
}),
_ => unreachable!(),
}
}
const ALL: &[&str] = &[
"missing_api_key",
"usage",
"auth",
"rate_limited",
"validation",
"server",
"network",
"decode",
"keystore",
"signing",
"unimplemented",
"config",
];
#[test]
fn every_variant_has_distinct_code() {
let codes: HashSet<&'static str> = ALL.iter().map(|v| sample(v).code()).collect();
assert_eq!(codes.len(), ALL.len(), "codes must be unique per variant");
for v in ALL {
assert_eq!(sample(v).code(), *v, "code() for {v} must match the label");
}
}
#[test]
fn exit_code_taxonomy_matches_plan() {
assert_eq!(CmdError::MissingApiKey.exit_code(), ExitCode::Usage);
assert_eq!(sample("usage").exit_code(), ExitCode::Usage);
assert_eq!(sample("auth").exit_code(), ExitCode::Auth);
assert_eq!(sample("rate_limited").exit_code(), ExitCode::RateLimited);
assert_eq!(sample("validation").exit_code(), ExitCode::Validation);
assert_eq!(sample("server").exit_code(), ExitCode::Server);
assert_eq!(sample("network").exit_code(), ExitCode::Server);
assert_eq!(sample("decode").exit_code(), ExitCode::Server);
assert_eq!(sample("keystore").exit_code(), ExitCode::Wallet);
assert_eq!(sample("signing").exit_code(), ExitCode::Wallet);
assert_eq!(sample("unimplemented").exit_code(), ExitCode::Unimplemented);
assert_eq!(sample("config").exit_code(), ExitCode::Usage);
}
#[test]
fn client_error_folds_retry_after_into_cmd_error() {
let ce = ClientError::RateLimited {
retry_after: Duration::from_secs(42),
};
let cmd: CmdError = ce.into();
match cmd {
CmdError::RateLimited { retry_after } => {
assert_eq!(retry_after, Duration::from_secs(42));
}
other => panic!("expected RateLimited, got {other:?}"),
}
assert_eq!(
sample("rate_limited").retry_after(),
Some(Duration::from_secs(30))
);
assert!(sample("auth").retry_after().is_none());
}
#[test]
fn is_proxy_rpc_url_matches_same_origin() {
let base = "https://staging.api.taskfast.app";
assert!(is_proxy_rpc_url(
"https://staging.api.taskfast.app/rpc/testnet",
base
));
assert!(is_proxy_rpc_url(
"https://staging.api.taskfast.app/api/rpc/testnet",
base
));
assert!(is_proxy_rpc_url(
"https://staging.api.taskfast.app/rpc/mainnet",
"https://staging.api.taskfast.app/"
));
assert!(!is_proxy_rpc_url("https://rpc.moderato.tempo.xyz", base));
assert!(!is_proxy_rpc_url(
"https://attacker.example/rpc/testnet",
base
));
assert!(!is_proxy_rpc_url(
"http://staging.api.taskfast.app/rpc/testnet",
base
));
}
#[test]
fn ctx_base_url_override_wins_over_environment_default() {
let ctx = Ctx {
api_key: None,
environment: Environment::Prod,
api_base: Some("http://localhost:9999".into()),
config_path: PathBuf::from("/dev/null"),
dry_run: false,
quiet: false,
..Default::default()
};
assert_eq!(ctx.base_url(), "http://localhost:9999");
}
#[test]
fn ctx_base_url_falls_back_to_environment_default() {
for (env, expected) in [
(Environment::Prod, "https://api.taskfast.app"),
(Environment::Staging, "https://staging.api.taskfast.app"),
(Environment::Local, "http://127.0.0.1:4000"),
] {
let ctx = Ctx {
api_key: None,
environment: env,
api_base: None,
config_path: PathBuf::from("/dev/null"),
dry_run: false,
quiet: false,
..Default::default()
};
assert_eq!(ctx.base_url(), expected);
}
}
#[test]
fn ctx_client_errors_when_api_key_missing() {
let ctx = Ctx {
api_key: None,
environment: Environment::Local,
api_base: None,
config_path: PathBuf::from("/dev/null"),
dry_run: false,
quiet: false,
..Default::default()
};
match ctx.client() {
Err(CmdError::MissingApiKey) => {}
Err(other) => panic!("expected MissingApiKey, got {other:?}"),
Ok(_) => panic!("expected MissingApiKey, got Ok(client)"),
}
}
#[test]
fn ctx_client_builds_when_api_key_present() {
let ctx = Ctx {
api_key: Some("tk_test_abc".into()),
environment: Environment::Local,
api_base: None,
config_path: PathBuf::from("/dev/null"),
dry_run: false,
quiet: false,
..Default::default()
};
ctx.client().expect("client should build with a valid key");
}
fn cfg_with(api_key: Option<&str>, environment: Option<Environment>) -> Config {
Config {
api_key: api_key.map(str::to_string),
environment,
..Config::default()
}
}
#[test]
fn from_parts_threads_wallet_keystore_confirm_log_format_from_config() {
let cfg = Config {
wallet_address: Some("0xfeed".into()),
keystore_path: Some(PathBuf::from("/tmp/k.json")),
confirm_above_budget: Some("500".into()),
log_format: Some("json".into()),
..Config::default()
};
let ctx =
Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
assert_eq!(ctx.wallet_address.as_deref(), Some("0xfeed"));
assert_eq!(
ctx.keystore_path.as_deref(),
Some(std::path::Path::new("/tmp/k.json"))
);
assert_eq!(ctx.confirm_above_budget.as_deref(), Some("500"));
assert_eq!(ctx.log_format.as_deref(), Some("json"));
}
#[test]
fn from_parts_parses_receipt_timeout_from_config() {
let cfg = Config {
receipt_timeout: Some("3min".into()),
..Config::default()
};
let ctx =
Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("parse 3min");
assert_eq!(ctx.receipt_timeout, Some(Duration::from_mins(3)));
}
#[test]
fn from_parts_rejects_malformed_receipt_timeout() {
let cfg = Config {
receipt_timeout: Some("nope".into()),
..Config::default()
};
let err = Ctx::from_parts(None, None, None, None, false, false, false, &cfg)
.err()
.expect("malformed timeout = startup error");
assert!(matches!(err, CmdError::Usage(msg) if msg.contains("receipt_timeout")));
}
#[test]
fn from_parts_duration_fields_none_when_config_absent() {
let ctx = Ctx::from_parts(
None,
None,
None,
None,
false,
false,
false,
&Config::default(),
)
.expect("default cfg is valid");
assert!(ctx.receipt_timeout.is_none());
}
#[test]
fn resolve_duration_flag_wins_over_ctx_and_default() {
let out = resolve_duration(
Some(Duration::from_secs(10)),
Some(Duration::from_secs(20)),
Duration::from_secs(30),
);
assert_eq!(out, Duration::from_secs(10));
}
#[test]
fn resolve_duration_ctx_wins_over_default_when_no_flag() {
let out = resolve_duration(None, Some(Duration::from_secs(20)), Duration::from_secs(30));
assert_eq!(out, Duration::from_secs(20));
}
#[test]
fn resolve_duration_falls_back_to_default() {
let out = resolve_duration(None, None, Duration::from_secs(30));
assert_eq!(out, Duration::from_secs(30));
}
fn ctx_with_threshold(threshold: Option<&str>) -> Ctx {
Ctx {
confirm_above_budget: threshold.map(str::to_string),
..Default::default()
}
}
#[test]
fn budget_gate_no_op_when_threshold_unset() {
let ctx = ctx_with_threshold(None);
ctx.enforce_budget_gate(Some("99999"), false, "post a task")
.expect("no threshold = no gate");
}
#[test]
fn budget_gate_no_op_when_budget_absent() {
let ctx = ctx_with_threshold(Some("100"));
ctx.enforce_budget_gate(None, false, "post a task")
.expect("no budget = nothing to compare");
}
#[test]
fn budget_gate_passes_when_under_threshold() {
let ctx = ctx_with_threshold(Some("100"));
ctx.enforce_budget_gate(Some("50"), false, "post a task")
.expect("under threshold passes without --yes");
}
#[test]
fn budget_gate_passes_at_threshold_boundary() {
let ctx = ctx_with_threshold(Some("100"));
ctx.enforce_budget_gate(Some("100"), false, "post a task")
.expect("equal-to-threshold passes (gate is strict >)");
}
#[test]
fn budget_gate_blocks_above_threshold_without_yes() {
let ctx = ctx_with_threshold(Some("100"));
let err = ctx
.enforce_budget_gate(Some("100.01"), false, "post a task")
.expect_err("over threshold without --yes must fail");
match err {
CmdError::Usage(msg) => {
assert!(msg.contains("--yes"), "msg: {msg}");
assert!(msg.contains("post a task"), "msg: {msg}");
}
other => panic!("expected Usage, got {other:?}"),
}
}
#[test]
fn budget_gate_passes_above_threshold_with_yes() {
let ctx = ctx_with_threshold(Some("100"));
ctx.enforce_budget_gate(Some("9999"), true, "post a task")
.expect("--yes overrides the gate");
}
#[test]
fn budget_gate_uses_decimal_not_float_precision() {
let ctx = ctx_with_threshold(Some("0.3"));
ctx.enforce_budget_gate(Some("0.30000000000000004"), false, "post a task")
.expect_err("decimal compare must detect trailing precision");
}
#[test]
fn budget_gate_rejects_non_decimal_threshold() {
let ctx = ctx_with_threshold(Some("not-a-number"));
let err = ctx
.enforce_budget_gate(Some("50"), false, "post a task")
.expect_err("garbage threshold = usage error");
assert!(matches!(err, CmdError::Usage(_)));
}
#[test]
fn from_parts_flag_wins_over_config() {
let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
let ctx = Ctx::from_parts(
Some("flag_key".into()),
Some(Environment::Local),
Some("http://flag".into()),
None,
false,
false,
false,
&cfg,
)
.expect("valid cfg");
assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
assert_eq!(ctx.environment, Environment::Local);
assert_eq!(ctx.api_base.as_deref(), Some("http://flag"));
}
#[test]
fn from_parts_config_fills_when_flags_absent() {
let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
let ctx =
Ctx::from_parts(None, None, None, None, false, false, false, &cfg).expect("valid cfg");
assert_eq!(ctx.api_key.as_deref(), Some("cfg_key"));
assert_eq!(ctx.environment, Environment::Staging);
assert!(ctx.api_base.is_none());
assert_eq!(ctx.base_url(), Environment::Staging.api_base());
}
#[test]
fn from_parts_defaults_when_nothing_set() {
let ctx = Ctx::from_parts(
None,
None,
None,
None,
false,
false,
false,
&Config::default(),
)
.expect("default cfg is valid");
assert!(ctx.api_key.is_none());
assert_eq!(ctx.environment, DEFAULT_ENVIRONMENT);
assert!(ctx.api_base.is_none());
assert!(!ctx.dry_run);
assert!(!ctx.quiet);
}
#[test]
fn from_parts_flag_partial_overrides_preserve_other_config_fields() {
let cfg = cfg_with(Some("cfg_key"), Some(Environment::Staging));
let ctx = Ctx::from_parts(
Some("flag_key".into()),
None,
None,
None,
false,
false,
false,
&cfg,
)
.expect("valid cfg");
assert_eq!(ctx.api_key.as_deref(), Some("flag_key"));
assert_eq!(ctx.environment, Environment::Staging);
assert!(ctx.api_base.is_none());
}
#[test]
fn from_parts_rejects_custom_api_base_for_non_local_env() {
let cfg = cfg_with(Some("stolen_pat"), Some(Environment::Prod));
let err = Ctx::from_parts(
None,
None,
Some("https://evil.example".into()),
None,
false,
false,
false,
&cfg,
)
.err()
.expect("custom api_base on prod must be refused");
match err {
CmdError::Usage(msg) => {
assert!(msg.contains("evil.example"), "msg: {msg}");
assert!(msg.contains("--allow-custom-endpoints"), "msg: {msg}");
}
other => panic!("expected Usage, got {other:?}"),
}
}
#[test]
fn from_parts_allows_custom_api_base_when_opt_in_flag_set() {
let cfg = cfg_with(Some("k"), Some(Environment::Prod));
let ctx = Ctx::from_parts(
None,
None,
Some("https://evil.example".into()),
None,
false,
false,
true,
&cfg,
)
.expect("--allow-custom-endpoints must bypass the guard");
assert_eq!(ctx.api_base.as_deref(), Some("https://evil.example"));
}
#[test]
fn from_parts_allows_custom_api_base_for_local_env() {
let cfg = cfg_with(Some("k"), Some(Environment::Local));
let ctx = Ctx::from_parts(
None,
None,
Some("http://127.0.0.1:4001".into()),
None,
false,
false,
false,
&cfg,
)
.expect("local env bypasses guard");
assert_eq!(ctx.api_base.as_deref(), Some("http://127.0.0.1:4001"));
}
#[test]
fn from_parts_accepts_well_known_api_base_without_opt_in() {
let cfg = cfg_with(Some("k"), Some(Environment::Prod));
let ctx = Ctx::from_parts(
None,
None,
Some("https://api.taskfast.app".into()),
None,
false,
false,
false,
&cfg,
)
.expect("well-known api_base passes without --allow-custom-endpoints");
assert_eq!(ctx.api_base.as_deref(), Some("https://api.taskfast.app"));
}
#[test]
fn from_parts_guard_ignores_missing_api_base() {
let ctx = Ctx::from_parts(
None,
None,
None,
None,
false,
false,
false,
&Config::default(),
)
.expect("no api_base = no guard");
assert!(ctx.api_base.is_none());
}
#[test]
fn network_invariant_ok_when_single_advertised_matches() {
let res = check_network_invariant(
Environment::Prod,
"https://api.taskfast.app",
&["mainnet".into()],
true,
);
assert!(res.is_ok(), "exact match passes strict mode: {res:?}");
}
#[test]
fn network_invariant_strict_rejects_wrong_single_network() {
let err = check_network_invariant(
Environment::Prod,
"https://api.taskfast.app",
&["testnet".into()],
true,
)
.expect_err("strict mode must reject wrong network");
match err {
CmdError::Server(msg) => {
assert!(msg.contains("testnet"), "msg: {msg}");
assert!(msg.contains("mainnet"), "msg: {msg}");
assert!(msg.contains("issue #62"), "remediation hint: {msg}");
}
other => panic!("expected Server, got {other:?}"),
}
}
#[test]
fn network_invariant_strict_rejects_extra_advertised() {
let err = check_network_invariant(
Environment::Prod,
"https://api.taskfast.app",
&["mainnet".into(), "testnet".into()],
true,
)
.expect_err("strict mode must reject len != 1");
assert!(matches!(err, CmdError::Server(_)));
}
#[test]
fn network_invariant_warn_passes_under_today_server_shape() {
let res = check_network_invariant(
Environment::Staging,
"https://staging.api.taskfast.app",
&["mainnet".into(), "testnet".into()],
false,
);
assert!(
res.is_ok(),
"non-strict mode must let today's multi-network deployments through: {res:?}"
);
}
#[test]
fn network_invariant_warn_passes_when_wrong_single_network() {
let res = check_network_invariant(
Environment::Prod,
"https://api.taskfast.app",
&["testnet".into()],
false,
);
assert!(res.is_ok(), "non-strict mode warns rather than errors");
}
#[test]
fn from_parts_dry_run_and_quiet_are_invocation_scoped() {
let ctx = Ctx::from_parts(
None,
None,
None,
None,
true,
true,
false,
&Config::default(),
)
.expect("default cfg is valid");
assert!(ctx.dry_run);
assert!(ctx.quiet);
}
}