Skip to main content

sandogasa_cli/
lib.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! Shared CLI utilities for sandogasa tools.
4
5pub mod date;
6pub mod defaults;
7#[cfg(feature = "http")]
8pub mod http;
9
10pub use defaults::parse_with_defaults;
11
12use std::process::{Command, Stdio};
13
14use url::{Host, Url};
15
16/// Standard process-wide initialization for sandogasa tools.
17///
18/// Call this once as the first statement of `main()` in every
19/// binary. It is the single place for cross-cutting startup work:
20/// anything added to this function is automatically picked up by
21/// every tool that calls it, so prefer extending `init` over
22/// scattering setup across mains.
23///
24/// Today it registers the rustls crypto provider that reqwest's
25/// TLS support needs (see [`install_crypto_provider`]). Idempotent
26/// and cheap, so calling it from a tool that does no networking is
27/// harmless.
28pub fn init() {
29    install_crypto_provider();
30}
31
32/// Install the ring-based rustls [`CryptoProvider`] as the process
33/// default.
34///
35/// We build reqwest with the `rustls-no-provider` feature to keep
36/// `aws-lc-rs` — reqwest 0.13's default provider, which is not
37/// packaged in Fedora — out of the dependency tree. That leaves
38/// rustls with no compiled-in default provider, so one must be
39/// registered at runtime before the first HTTPS request or reqwest
40/// panics with "No provider set". `ring` is statically linked into
41/// the binary (a build-time dependency only); this just points
42/// rustls at it.
43///
44/// Idempotent: the underlying `install_default` only takes effect
45/// on the first call and reports an error on subsequent ones, which
46/// we ignore so repeated calls (e.g. across tests) are harmless.
47///
48/// [`CryptoProvider`]: rustls::crypto::CryptoProvider
49pub fn install_crypto_provider() {
50    let _ = rustls::crypto::ring::default_provider().install_default();
51}
52
53/// Environment variable that, when set to a non-empty value,
54/// disables [`ensure_secure_url`]'s plaintext-credential guard.
55/// Intended for local testing against `http://` mock servers or a
56/// trusted internal proxy — never for production credentials.
57pub const ALLOW_INSECURE_URL_ENV: &str = "SANDOGASA_ALLOW_INSECURE_URL";
58
59/// Refuse to hand credentials to a base URL that would transmit
60/// them in cleartext.
61///
62/// Returns `Ok(())` when the URL is `https`, when its host is a
63/// loopback address (`localhost`, `127.0.0.0/8`, `::1` — so mock
64/// servers and local development keep working), or when
65/// [`ALLOW_INSECURE_URL_ENV`] is set to a non-empty value.
66/// Otherwise returns an error naming the URL and the override, so
67/// an API token is never put on the wire over plain `http`.
68///
69/// Call this wherever a client is built with a token, before any
70/// request is made.
71pub fn ensure_secure_url(base_url: &str) -> Result<(), String> {
72    let allow_insecure = std::env::var_os(ALLOW_INSECURE_URL_ENV).is_some_and(|v| !v.is_empty());
73    check_secure_url(base_url, allow_insecure)
74}
75
76/// Pure core of [`ensure_secure_url`], with the env override passed
77/// in so it can be unit-tested without mutating process state.
78fn check_secure_url(base_url: &str, allow_insecure: bool) -> Result<(), String> {
79    let parsed = Url::parse(base_url).map_err(|e| format!("invalid URL '{base_url}': {e}"))?;
80    if parsed.scheme() == "https" || host_is_loopback(&parsed) {
81        return Ok(());
82    }
83    if allow_insecure {
84        return Ok(());
85    }
86    Err(format!(
87        "refusing to send credentials to '{base_url}' over plaintext \
88         {}: use an https URL, or set {ALLOW_INSECURE_URL_ENV}=1 to \
89         override (e.g. for local testing against a mock server).",
90        parsed.scheme()
91    ))
92}
93
94/// Whether a URL's host is a loopback address.
95fn host_is_loopback(u: &Url) -> bool {
96    match u.host() {
97        Some(Host::Domain(d)) => d == "localhost" || d.ends_with(".localhost"),
98        Some(Host::Ipv4(ip)) => ip.is_loopback(),
99        Some(Host::Ipv6(ip)) => ip.is_loopback(),
100        None => false,
101    }
102}
103
104/// Whether an executable named `name` is on `$PATH` (a lightweight
105/// check that does **not** run the tool).
106pub fn tool_exists(name: &str) -> bool {
107    std::env::var_os("PATH")
108        .map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(name).is_file()))
109        .unwrap_or(false)
110}
111
112/// Whether `exe` is available, per its `probe`: `Some(arg)` runs
113/// `exe arg` and requires a zero exit (confirms it executes);
114/// `None` checks only `$PATH` existence.
115fn tool_available(exe: &str, probe: Option<&str>) -> bool {
116    match probe {
117        Some(arg) => Command::new(exe)
118            .arg(arg)
119            .stdout(Stdio::null())
120            .stderr(Stdio::null())
121            .status()
122            .is_ok_and(|s| s.success()),
123        None => tool_exists(exe),
124    }
125}
126
127/// Check that a batch of external tools is available, returning a
128/// single error that lists every missing one with its install hint.
129///
130/// Each entry is `(executable, install_hint, probe)`:
131/// - `probe = Some(arg)` *runs* `<executable> <arg>` (e.g.
132///   `Some("--version")`, or `Some("version")` for `koji`, or
133///   `Some("--help")` for `pbuilder-dist`) and requires a zero exit,
134///   confirming the tool actually executes.
135/// - `probe = None` checks only `$PATH` existence, for tools with no
136///   usable version/help flag.
137///
138/// All entries are checked, so the error names every missing tool
139/// rather than failing on the first.
140///
141/// # Example
142///
143/// ```no_run
144/// sandogasa_cli::require_tools(&[
145///     ("git", "sudo apt install git", Some("--version")),
146///     ("pbuilder-dist", "sudo apt install ubuntu-dev-tools", Some("--help")),
147/// ])
148/// .unwrap();
149/// ```
150pub fn require_tools(tools: &[(&str, &str, Option<&str>)]) -> Result<(), String> {
151    let missing: Vec<String> = tools
152        .iter()
153        .filter(|(exe, _, probe)| !tool_available(exe, *probe))
154        .map(|(exe, hint, _)| format!("{exe} (install: {hint})"))
155        .collect();
156    if missing.is_empty() {
157        Ok(())
158    } else {
159        Err(format!("missing required tool(s): {}", missing.join(", ")))
160    }
161}
162
163/// Word-wrap `text` to `width` columns and prefix every line with
164/// `prefix` (e.g. `"> "` for a Markdown blockquote, or the leading
165/// indent of a wrapped list item). Collapses runs of whitespace and
166/// never splits a word, so a single token longer than the width — a
167/// URL, typically — overflows rather than being broken. Such a token
168/// also stays on the line it started on: breaking before a word that
169/// won't fit on a fresh line either would only orphan whatever label
170/// introduces it (`LINK:`, `Minutes:`) while still overflowing.
171pub fn wrap_prefixed(text: &str, prefix: &str, width: usize) -> String {
172    let mut out = String::new();
173    let mut line = String::new();
174    for word in text.split_whitespace() {
175        if !line.is_empty()
176            && prefix.len() + line.len() + 1 + word.len() > width
177            && prefix.len() + word.len() <= width
178        {
179            out.push_str(prefix);
180            out.push_str(&line);
181            out.push('\n');
182            line.clear();
183        }
184        if !line.is_empty() {
185            line.push(' ');
186        }
187        line.push_str(word);
188    }
189    if !line.is_empty() {
190        out.push_str(prefix);
191        out.push_str(&line);
192    }
193    out
194}
195
196/// Ask a yes/no question on stderr (keeping stdout clean for piped
197/// or `--json` output) and read one line from stdin.
198///
199/// `y`/`yes` and `n`/`no` (any case) answer explicitly; anything
200/// else — including just Enter or EOF — takes the default. The
201/// prompt shows `[Y/n]` or `[y/N]` to match `default_yes`. Callers
202/// must not prompt when stdin isn't a terminal or in `--json` mode
203/// (see the CLI-behavior conventions).
204pub fn confirm(question: &str, default_yes: bool) -> std::io::Result<bool> {
205    use std::io::{BufRead, Write};
206    let hint = if default_yes { "[Y/n]" } else { "[y/N]" };
207    eprint!("{question} {hint}: ");
208    std::io::stderr().flush()?;
209    let mut line = String::new();
210    std::io::stdin().lock().read_line(&mut line)?;
211    Ok(parse_confirm(&line, default_yes))
212}
213
214/// Pure core of [`confirm`], unit-testable without stdin.
215fn parse_confirm(answer: &str, default_yes: bool) -> bool {
216    let answer = answer.trim();
217    if answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes") {
218        true
219    } else if answer.eq_ignore_ascii_case("n") || answer.eq_ignore_ascii_case("no") {
220        false
221    } else {
222        default_yes
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn tool_exists_detects_present_and_absent() {
232        assert!(tool_exists("sh"));
233        assert!(!tool_exists("nonexistent_tool_xyz_123"));
234    }
235
236    #[test]
237    fn require_tools_path_and_probe_modes() {
238        // PATH mode (probe None): present is OK, absent is missing.
239        assert!(require_tools(&[("sh", "present", None)]).is_ok());
240        assert!(require_tools(&[("nonexistent_zzz", "install zzz", None)]).is_err());
241
242        // Probe mode: `true` runs and exits 0; a missing executable
243        // fails the probe. The error lists every missing tool with its
244        // hint, and skips the present one.
245        assert!(require_tools(&[("true", "ok", Some("--version"))]).is_ok());
246        let err = require_tools(&[
247            ("true", "ok", Some("--version")),
248            ("nonexistent_aaa_111", "install aaa", Some("--version")),
249            ("nonexistent_bbb_222", "install bbb", None),
250        ])
251        .unwrap_err();
252        assert!(err.contains("nonexistent_aaa_111"));
253        assert!(err.contains("install aaa"));
254        assert!(err.contains("nonexistent_bbb_222"));
255        assert!(err.contains("install bbb"));
256        assert!(!err.contains("true ("));
257    }
258
259    #[test]
260    fn wrap_prefixed_wraps_and_prefixes() {
261        let text = "alpha beta gamma delta epsilon zeta eta theta iota";
262        let wrapped = wrap_prefixed(text, "> ", 20);
263        // Every line is prefixed and within width.
264        assert!(wrapped.lines().all(|l| l.starts_with("> ")));
265        assert!(wrapped.lines().all(|l| l.chars().count() <= 20));
266        // It actually wrapped (more than one line) and lost no words.
267        assert!(wrapped.lines().count() > 1);
268        assert_eq!(
269            wrapped.split_whitespace().count(),
270            9 + wrapped.lines().count()
271        );
272    }
273
274    #[test]
275    fn wrap_prefixed_keeps_a_long_word_whole_and_in_place() {
276        // A URL longer than the width overflows rather than breaking,
277        // and stays with the label that introduces it.
278        let url = "https://example.com/a/very/long/path/that/exceeds/the/width";
279        let wrapped = wrap_prefixed(&format!("LINK: {url} please"), "  ", 20);
280        assert!(wrapped.contains(url), "{wrapped}");
281        assert_eq!(wrapped.lines().next().unwrap(), format!("  LINK: {url}"));
282        // Wrapping resumes normally after the oversized word.
283        assert_eq!(wrapped.lines().nth(1).unwrap(), "  please");
284    }
285
286    #[test]
287    fn parse_confirm_answers_and_defaults() {
288        for yes in ["y", "Y", "yes", "YES", " y "] {
289            assert!(parse_confirm(yes, false));
290        }
291        for no in ["n", "N", "no", "NO"] {
292            assert!(!parse_confirm(no, true));
293        }
294        // Empty (Enter/EOF) and anything unrecognized take the default.
295        for other in ["", "\n", "maybe"] {
296            assert!(parse_confirm(other, true));
297            assert!(!parse_confirm(other, false));
298        }
299    }
300
301    #[test]
302    fn secure_url_allows_https() {
303        assert!(check_secure_url("https://bugzilla.redhat.com", false).is_ok());
304        assert!(check_secure_url("https://gitlab.com/api/v4", false).is_ok());
305    }
306
307    #[test]
308    fn secure_url_allows_loopback_over_http() {
309        // Mock servers / local dev: loopback is fine over http.
310        assert!(check_secure_url("http://127.0.0.1:8080", false).is_ok());
311        assert!(check_secure_url("http://localhost:3000/api", false).is_ok());
312        assert!(check_secure_url("http://[::1]:9999", false).is_ok());
313    }
314
315    #[test]
316    fn secure_url_rejects_plaintext_remote() {
317        let err = check_secure_url("http://gitlab.example.com", false).unwrap_err();
318        assert!(err.contains("gitlab.example.com"));
319        assert!(err.contains(ALLOW_INSECURE_URL_ENV));
320    }
321
322    #[test]
323    fn secure_url_override_allows_plaintext_remote() {
324        // With the override "set", plaintext to a remote host is allowed.
325        assert!(check_secure_url("http://gitlab.example.com", true).is_ok());
326    }
327
328    #[test]
329    fn secure_url_rejects_invalid() {
330        assert!(check_secure_url("not a url", false).is_err());
331    }
332}