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