Skip to main content

taskfast_cli/
lib.rs

1// SPDX-License-Identifier: MIT
2//! `taskfast-cli` library surface.
3//!
4//! The crate ships primarily as the `taskfast` binary (see `src/main.rs`),
5//! but every subcommand's `run` function and the shared envelope/exit/error
6//! types are re-exported here so integration tests (and, later, embedded
7//! callers) can drive the pipeline without spawning a process.
8
9// TODO: tighten doc coverage on public items + remove this allow.
10// Tracked under the rust-best-practices follow-up.
11#![allow(missing_docs)]
12
13pub mod cmd;
14pub mod config;
15pub mod envelope;
16pub mod exit;
17pub mod wallet_lock;
18
19pub use config::Config;
20pub use envelope::{Envelope, ErrorPayload};
21pub use exit::ExitCode;
22
23/// Re-exported from `main.rs` so tests can construct a [`cmd::Ctx`] with a
24/// named [`Environment`] without depending on the binary entry point.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, clap::ValueEnum)]
26pub enum Environment {
27    Prod,
28    Staging,
29    Local,
30}
31
32/// Tempo network selector. Derived from [`Environment`] — never persisted,
33/// never accepted as a CLI flag. The compile-time mapping in
34/// [`Environment::network`] is the single source of truth; the runtime
35/// invariant in `cmd::enforce_server_network_invariant` cross-checks it
36/// against `/config/network`.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Network {
39    Mainnet,
40    Testnet,
41}
42
43impl Network {
44    pub fn as_str(self) -> &'static str {
45        match self {
46            Self::Mainnet => "mainnet",
47            Self::Testnet => "testnet",
48        }
49    }
50}
51
52impl Environment {
53    /// Every variant. Drives table-driven tests and the well-known-base
54    /// iterator; touching [`Environment`] without updating this array
55    /// fails the `all_covers_every_variant` test.
56    pub const ALL: &'static [Environment] = &[Self::Prod, Self::Staging, Self::Local];
57
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Self::Prod => "production",
61            Self::Staging => "staging",
62            Self::Local => "local",
63        }
64    }
65
66    /// Sole TaskFast API base URL for this environment. Total function;
67    /// the F2 endpoint-override guard treats anything else as adversarial.
68    ///
69    /// `Local` uses the IPv4 literal `127.0.0.1` rather than `localhost`:
70    /// the well-known-base allowlist matches the bound string verbatim, and
71    /// some dev hosts resolve `localhost` to `::1` first, which then misses
72    /// an IPv4-only `mix phx.server` and confuses the endpoint guard.
73    pub fn api_base(self) -> &'static str {
74        match self {
75            Self::Prod => "https://api.taskfast.app",
76            Self::Staging => "https://staging.api.taskfast.app",
77            Self::Local => "http://127.0.0.1:4000",
78        }
79    }
80
81    /// Sole Tempo network for this environment. Prod runs mainnet; staging
82    /// and local both run testnet. The runtime invariant verifies the
83    /// deployment at [`api_base`](Self::api_base) advertises exactly this
84    /// network and no other.
85    pub fn network(self) -> Network {
86        match self {
87            Self::Prod => Network::Mainnet,
88            Self::Staging => Network::Testnet,
89            Self::Local => Network::Testnet,
90        }
91    }
92}
93
94/// Iterator over the well-known TaskFast API base URLs — one per
95/// [`Environment`] variant, derived from [`Environment::api_base`].
96///
97/// Used by the F2 endpoint-override guard: an `api_base` supplied via the
98/// `--api-base` flag is rejected unless it matches one of these or the
99/// caller passed `--allow-custom-endpoints`.
100pub fn well_known_api_bases() -> impl Iterator<Item = &'static str> {
101    Environment::ALL.iter().map(|e| e.api_base())
102}
103
104/// True when `url` exactly matches a known-good default from
105/// [`well_known_api_bases`]. Trailing `/` is tolerated so a value
106/// `https://api.taskfast.app/` isn't flagged as custom.
107pub fn is_well_known_api_base(url: &str) -> bool {
108    let trimmed = url.trim_end_matches('/');
109    well_known_api_bases().any(|w| w.trim_end_matches('/') == trimmed)
110}
111
112/// Derive the human-facing account-tokens URL from an API base URL.
113///
114/// Strips a leading `api.` from the host (so `api.taskfast.app` →
115/// `taskfast.app`) and appends `/account/tokens`. Hosts without the
116/// `api.` prefix (localhost, bare domains, IPs) are passed through.
117/// Scheme and port are preserved.
118pub fn accounts_url(api_base: &str) -> String {
119    match url::Url::parse(api_base) {
120        Ok(mut u) => {
121            let rewritten = u.host_str().and_then(strip_api_label);
122            if let Some(h) = rewritten {
123                let _ = u.set_host(Some(&h));
124            }
125            u.set_path("/account/tokens");
126            u.set_query(None);
127            u.set_fragment(None);
128            u.to_string()
129        }
130        // Fallback for a malformed base: best-effort string concat.
131        Err(_) => format!("{}/account/tokens", api_base.trim_end_matches('/')),
132    }
133}
134
135/// Drop the `api` label from a host so the URL points at the human-facing
136/// dashboard. `api.taskfast.app` → `taskfast.app`;
137/// `staging.api.taskfast.app` → `staging.taskfast.app`. Returns `None`
138/// when the host has no `api` label to strip.
139fn strip_api_label(host: &str) -> Option<String> {
140    if let Some(rest) = host.strip_prefix("api.") {
141        return Some(rest.to_owned());
142    }
143    // Middle label: collapse `.api.` into a single `.`.
144    if host.contains(".api.") {
145        return Some(host.replacen(".api.", ".", 1));
146    }
147    None
148}
149
150#[cfg(test)]
151mod tests {
152    use super::{accounts_url, is_well_known_api_base, well_known_api_bases, Environment, Network};
153    use std::collections::HashSet;
154
155    #[test]
156    fn all_covers_every_variant() {
157        // Drift trap: if someone adds an Environment variant without
158        // appending it to ::ALL, this test catches the gap that compile-
159        // time exhaustiveness can't (a new variant compiles fine if it's
160        // never read; ::ALL is a const array, not a match).
161        let n = Environment::ALL.len();
162        let unique: HashSet<_> = Environment::ALL.iter().copied().collect();
163        assert_eq!(unique.len(), n, "Environment::ALL has duplicates");
164        for env in Environment::ALL {
165            // Touch every method so adding a variant without updating one
166            // of these breaks the build via match exhaustiveness.
167            let _ = env.as_str();
168            let _ = env.api_base();
169            let _ = env.network();
170        }
171    }
172
173    #[test]
174    fn each_env_has_unique_api_base() {
175        let bases: HashSet<_> = Environment::ALL.iter().map(|e| e.api_base()).collect();
176        assert_eq!(
177            bases.len(),
178            Environment::ALL.len(),
179            "two envs share an api_base"
180        );
181    }
182
183    #[test]
184    fn env_api_base_table_is_frozen() {
185        // Pin the exact mapping. Touching this test = a deliberate decision.
186        assert_eq!(Environment::Prod.api_base(), "https://api.taskfast.app");
187        assert_eq!(
188            Environment::Staging.api_base(),
189            "https://staging.api.taskfast.app"
190        );
191        assert_eq!(Environment::Local.api_base(), "http://127.0.0.1:4000");
192    }
193
194    #[test]
195    fn env_network_table_is_frozen() {
196        assert_eq!(Environment::Prod.network(), Network::Mainnet);
197        assert_eq!(Environment::Staging.network(), Network::Testnet);
198        assert_eq!(Environment::Local.network(), Network::Testnet);
199    }
200
201    #[test]
202    fn well_known_api_bases_cover_every_environment_default() {
203        for env in Environment::ALL {
204            let url = env.api_base();
205            assert!(
206                is_well_known_api_base(url),
207                "api_base for {env:?} ({url}) must be in well_known_api_bases"
208            );
209        }
210    }
211
212    #[test]
213    fn is_well_known_api_base_accepts_exact_defaults() {
214        for url in well_known_api_bases() {
215            assert!(is_well_known_api_base(url), "expected well-known: {url}");
216        }
217    }
218
219    #[test]
220    fn is_well_known_api_base_tolerates_trailing_slash() {
221        assert!(is_well_known_api_base("https://api.taskfast.app/"));
222        assert!(is_well_known_api_base("http://127.0.0.1:4000/"));
223    }
224
225    #[test]
226    fn is_well_known_api_base_rejects_attacker_hosts() {
227        assert!(!is_well_known_api_base("https://evil.example"));
228        assert!(!is_well_known_api_base(
229            "https://api.taskfast.app.evil.example"
230        ));
231        assert!(!is_well_known_api_base("http://api.taskfast.app"));
232        assert!(!is_well_known_api_base("https://staging.taskfast.app"));
233    }
234
235    #[test]
236    fn accounts_url_strips_api_prefix_prod() {
237        assert_eq!(
238            accounts_url("https://api.taskfast.app"),
239            "https://taskfast.app/account/tokens"
240        );
241    }
242
243    #[test]
244    fn accounts_url_strips_api_prefix_staging() {
245        assert_eq!(
246            accounts_url("https://staging.api.taskfast.app"),
247            "https://staging.taskfast.app/account/tokens"
248        );
249    }
250
251    #[test]
252    fn accounts_url_passthrough_localhost_with_port() {
253        assert_eq!(
254            accounts_url("http://127.0.0.1:4000"),
255            "http://127.0.0.1:4000/account/tokens"
256        );
257    }
258
259    #[test]
260    fn accounts_url_passthrough_bare_domain() {
261        assert_eq!(
262            accounts_url("https://taskfast.app"),
263            "https://taskfast.app/account/tokens"
264        );
265    }
266
267    #[test]
268    fn accounts_url_drops_existing_path_and_query() {
269        assert_eq!(
270            accounts_url("https://api.taskfast.app/v1?x=1"),
271            "https://taskfast.app/account/tokens"
272        );
273    }
274
275    #[test]
276    fn accounts_url_malformed_falls_back_to_concat() {
277        assert_eq!(accounts_url("not a url"), "not a url/account/tokens");
278    }
279}