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