Skip to main content

isothrum_machine/
cloud.rs

1//! The cloud accounts this computer's cloud CLIs are signed in to, asked through those CLIs:
2//! whether a sign-in still reaches its provider ([`Failure`] with [`Refusal::CredentialsExpired`]
3//! when it ran out or is missing), who it is, and what the account offers: AWS's profiles, its
4//! spend this month and whether it may create instances ([`aws`]), Azure's subscriptions, the VM
5//! sizes a region offers a subscription and its core quotas ([`azure`]), Google Cloud's billing
6//! accounts and organizations ([`gcp`]), and Oracle Cloud's compartments and config file
7//! ([`oci`]).
8//!
9//! Each CLI is one adapter here: its argument lists, its runs (through the context's runner, each
10//! within [`CLI_TIMEOUT`]) and the reading of its answers, a refusal read from its words (each
11//! wording backed by a fixture of the CLI's, under `cloud/fixtures/<cli>/`). What the answers mean
12//! to a user, and how a refusal is put to them, is the caller's.
13
14use std::time::Duration;
15
16use isothrum_runner::ProcessSpec;
17
18use crate::context::Context;
19use crate::failure::{self, Failure, Refusal};
20
21pub mod aws;
22pub mod azure;
23pub mod gcp;
24pub mod oci;
25pub mod token;
26
27pub use token::{TokenError, digitalocean, linode};
28
29pub use isothrum_runner::Cloud;
30
31/// How long a cloud CLI's answer may take: a call over the network to the provider, slower than a
32/// local probe.
33pub const CLI_TIMEOUT: Duration = Duration::from_secs(60);
34
35/// The CLI a cloud's account is signed in with on this computer: `aws`, `az`, `gcloud`, `oci`.
36/// None for a cloud whose credential is an API token alone (DigitalOcean, Linode).
37#[must_use]
38pub fn cli(cloud: Cloud) -> Option<&'static str> {
39    match cloud {
40        Cloud::Aws => Some(aws::CLI),
41        Cloud::Azure => Some(azure::CLI),
42        Cloud::Gcp => Some(gcp::CLI),
43        Cloud::Oci => Some(oci::CLI),
44        _ => None,
45    }
46}
47
48/// `spec` within `limit`: its standard output, else why not (a refusal read by `read`).
49async fn run(cx: &Context, limit: Duration, spec: &ProcessSpec, read: fn(&str) -> Refusal) -> Result<String, Failure> {
50    failure::answer(cx, limit, spec, read).await
51}
52
53/// `program args` within [`CLI_TIMEOUT`].
54async fn ask(cx: &Context, program: &str, args: &[&str], read: fn(&str) -> Refusal) -> Result<String, Failure> {
55    run(cx, CLI_TIMEOUT, &ProcessSpec::new(program, args.iter().copied()), read).await
56}
57
58/// An answer that isn't what `program` was asked for, said as [`Failure::Unreadable`].
59fn unreadable(program: &str, why: impl std::fmt::Display) -> Failure {
60    Failure::Unreadable {
61        program: program.to_owned(),
62        why: why.to_string(),
63    }
64}
65
66/// A JSON list a CLI answered, each entry as it is: an answer that isn't a list is unreadable
67/// (a changed format, or a warning printed instead).
68fn json_list(program: &str, out: &str) -> Result<Vec<serde_json::Value>, Failure> {
69    serde_json::from_str(out).map_err(|e| unreadable(program, format!("its answer isn't a JSON list ({e})")))
70}
71
72/// A one-line answer, trimmed.
73fn line(out: &str) -> String {
74    out.trim().to_owned()
75}
76
77/// Whether `said` holds any of `words`, in any case.
78fn says(said: &str, words: &[&str]) -> bool {
79    let lower = said.to_ascii_lowercase();
80    words.iter().any(|w| lower.contains(&w.to_ascii_lowercase()))
81}
82
83/// A browser sign-in to a cloud through its CLI ([`sign_in`]).
84#[derive(Debug, Clone, PartialEq, Eq)]
85#[non_exhaustive]
86pub enum SignIn {
87    /// `aws login` (AWS CLI 2.32 or later): console credentials for up to 12 hours, for the
88    /// CLI's default profile or `profile`.
89    Aws {
90        /// The profile signed in, when not the default.
91        profile: Option<String>,
92    },
93    /// `az login`.
94    Azure,
95    /// `gcloud auth login --update-adc`: the CLI's own sign-in and the application-default
96    /// credentials (what Terraform's Google provider reads) in one browser flow.
97    Gcp,
98}
99
100impl SignIn {
101    /// The CLI run, and its arguments.
102    #[must_use]
103    pub fn command(&self) -> ProcessSpec {
104        match self {
105            SignIn::Aws { profile } => {
106                let mut args = vec!["login".to_owned()];
107                if let Some(p) = profile {
108                    args.extend(["--profile".to_owned(), p.clone()]);
109                }
110                ProcessSpec::new(aws::CLI, args)
111            }
112            SignIn::Azure => ProcessSpec::new(azure::CLI, ["login"]),
113            SignIn::Gcp => ProcessSpec::new(gcp::CLI, ["auth", "login", "--update-adc"]),
114        }
115    }
116}
117
118/// Signs in to a cloud in the browser through its CLI ([`SignIn`]): `on_line` gets the command
119/// (`$ az login`), then each line the CLI prints, until it ends. No time limit: the browser waits
120/// for its user; dropping the future ends the CLI (the runner's), which is how a caller cancels it
121/// or gives it a limit.
122///
123/// # Errors
124///
125/// [`Failure`]: the CLI isn't installed or couldn't be started, or it failed (what it said last).
126pub async fn sign_in(cx: &Context, which: &SignIn, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<(), Failure> {
127    let spec = which.command();
128    on_line(&format!("$ {}", spec.line()));
129    let mut last = String::new();
130    let mut each = |_: isothrum_runner::Stream, l: &str| {
131        if !l.trim().is_empty() {
132            l.trim().clone_into(&mut last);
133        }
134        on_line(l);
135    };
136    let program = spec.program.clone();
137    match cx.runner.run(&spec, &mut each).await {
138        Ok(exit) if exit.success() => Ok(()),
139        Ok(exit) => Err(Failure::Refused {
140            refusal: Refusal::Other,
141            said: if last.is_empty() { exit.to_string() } else { last },
142            program,
143        }),
144        Err(isothrum_runner::ProcessError::Missing { .. }) => Err(Failure::Missing { program }),
145        Err(other) => Err(Failure::NotStarted {
146            program,
147            reason: other.to_string(),
148        }),
149    }
150}
151
152#[cfg(test)]
153mod tests;