Skip to main content

isothrum_machine/cloud/
aws.rs

1//! AWS, through the AWS CLI: who an account's credentials are, the CLI's profiles, this month's
2//! spend (Cost Explorer), and whether the account may create EC2 instances (a dry run, which
3//! creates nothing). An account signs in with the CLI's own credentials (its default chain, or a
4//! profile), or with an access key, given to the CLI's official container (Docker is all that
5//! needs).
6
7use std::time::{Duration, SystemTime};
8
9use isothrum_runner::ProcessSpec;
10
11use super::{CLI_TIMEOUT, line, run, says, unreadable};
12use crate::context::Context;
13use crate::failure::{Failure, Refusal};
14
15/// The AWS CLI.
16pub const CLI: &str = "aws";
17
18/// The AWS CLI's official image, which runs a call made with an access key.
19pub const CLI_IMAGE: &str = "amazon/aws-cli:2.37.9";
20
21/// How long a call in [`CLI_IMAGE`] may take: the first one pulls the image.
22pub const IMAGE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
23
24/// The question whose answer is who an account's credentials are, the identity's ARN: the one
25/// that tells its sign-in still holds.
26pub const WHO_AM_I: [&str; 6] = ["sts", "get-caller-identity", "--query", "Arn", "--output", "text"];
27
28/// The instance type the launch permission is dry-run with.
29pub const PROBE_INSTANCE_TYPE: &str = "t3.micro";
30
31/// The SSM public parameter naming the latest Amazon Linux 2023 image (`x86_64`, for
32/// [`PROBE_INSTANCE_TYPE`]) in the account's region: a real, public image the dry run is checked
33/// against.
34pub const LATEST_AMAZON_LINUX: &str = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64";
35
36/// A well-formed image id no account has: AWS answers it with `InvalidAMIID.NotFound`, which it
37/// only says once the request is authorized. Used when the public parameter can't be read
38/// (`ssm:GetParameter` denied, SSM unreachable). Not a 17-character made-up id: AWS reads those as
39/// malformed before it looks at the permission at all.
40pub const UNKNOWN_IMAGE: &str = "ami-12345678";
41
42/// Where an account's credentials come from.
43#[derive(Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum Credentials {
46    /// The AWS CLI's own: its default chain, or `profile`.
47    Cli {
48        /// The profile, when not the default.
49        profile: Option<String>,
50    },
51    /// An access key: the CLI runs in [`CLI_IMAGE`], the key in its environment.
52    Keys {
53        /// The access key id.
54        id: String,
55        /// The secret access key.
56        secret: String,
57    },
58}
59
60impl std::fmt::Debug for Credentials {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        match self {
63            Credentials::Cli { profile } => f.debug_struct("Cli").field("profile", profile).finish(),
64            Credentials::Keys { id, .. } => f.debug_struct("Keys").field("id", id).field("secret", &"<masked>").finish(),
65        }
66    }
67}
68
69/// An AWS account: its credentials, and the region asked.
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct Account {
73    /// Where its credentials come from.
74    pub credentials: Credentials,
75    /// The region its calls go to (`AWS_REGION`), when one is set.
76    pub region: Option<String>,
77}
78
79impl Account {
80    /// An account with `credentials`, its calls to `region`.
81    #[must_use]
82    pub fn new(credentials: Credentials, region: Option<String>) -> Account {
83        Account { credentials, region }
84    }
85
86    /// The program, arguments and environment of `aws args` the way this account's credentials
87    /// run: the host CLI (its profile in `AWS_PROFILE`), or the CLI's container with the key in
88    /// its environment.
89    #[must_use]
90    pub fn invocation(&self, args: &[&str]) -> (&'static str, Vec<String>, Vec<(String, String)>) {
91        let mut env: Vec<(String, String)> = Vec::new();
92        let region = self.region.iter().map(|r| ("AWS_REGION".to_owned(), r.clone()));
93        match &self.credentials {
94            Credentials::Cli { profile } => {
95                env.extend(region);
96                env.extend(profile.iter().map(|p| ("AWS_PROFILE".to_owned(), p.clone())));
97                (CLI, args.iter().map(|a| (*a).to_owned()).collect(), env)
98            }
99            Credentials::Keys { id, secret } => {
100                env.push(("AWS_ACCESS_KEY_ID".to_owned(), id.clone()));
101                env.push(("AWS_SECRET_ACCESS_KEY".to_owned(), secret.clone()));
102                env.extend(region);
103                let mut docker: Vec<String> = [
104                    "run",
105                    "--rm",
106                    "-e",
107                    "AWS_ACCESS_KEY_ID",
108                    "-e",
109                    "AWS_SECRET_ACCESS_KEY",
110                    "-e",
111                    "AWS_REGION",
112                    CLI_IMAGE,
113                ]
114                .map(str::to_owned)
115                .to_vec();
116                docker.extend(args.iter().map(|a| (*a).to_owned()));
117                ("docker", docker, env)
118            }
119        }
120    }
121
122    /// `aws args` as this account: its standard output, else why not.
123    async fn ask(&self, cx: &Context, args: &[&str]) -> Result<String, Failure> {
124        let (program, invoked, env) = self.invocation(args);
125        let limit = if program == CLI { CLI_TIMEOUT } else { IMAGE_TIMEOUT };
126        let mut spec = ProcessSpec::new(program, invoked);
127        spec.env = env;
128        run(cx, limit, &spec, refusal).await
129    }
130}
131
132/// How the AWS CLI refused, read from what it said: a sign-in run out or missing, or keys
133/// rejected (the runner's reading of an expired sign-in, and the CLI's own words), Cost Explorer
134/// not enabled, a permission denied.
135#[must_use]
136pub fn refusal(said: &str) -> Refusal {
137    const SIGNED_OUT: [&str; 7] = [
138        "InvalidClientTokenId",
139        "SignatureDoesNotMatch",
140        "Unable to locate credentials",
141        "sso",
142        "not logged in",
143        "TokenRefresh",
144        "credentials",
145    ];
146    if isothrum_runner::sign_in_expired(said) || says(said, &SIGNED_OUT) {
147        Refusal::CredentialsExpired
148    } else if says(said, &["Cost Explorer", "not enabled", "OptInRequired"]) {
149        // Before a denial: Cost Explorer off is refused as `AccessDeniedException`.
150        Refusal::NotEnabled
151    } else if says(said, &["AccessDenied", "UnauthorizedOperation", "not authorized"]) {
152        Refusal::Denied
153    } else {
154        Refusal::Other
155    }
156}
157
158/// Who `account`'s credentials are ([`WHO_AM_I`]): the identity's ARN.
159///
160/// # Errors
161///
162/// [`Failure`]: the CLI (or Docker) isn't there, or AWS refused ([`Refusal::CredentialsExpired`]
163/// for a sign-in run out or missing, or keys rejected).
164pub async fn identity(cx: &Context, account: &Account) -> Result<String, Failure> {
165    account.ask(cx, &WHO_AM_I).await.map(|out| line(&out))
166}
167
168/// The profiles the host's AWS CLI has (`aws configure list-profiles`), in its order.
169///
170/// # Errors
171///
172/// [`Failure`]: the CLI isn't installed, or failed.
173pub async fn profiles(cx: &Context) -> Result<Vec<String>, Failure> {
174    super::ask(cx, CLI, &["configure", "list-profiles"], refusal).await.map(|out| lines(&out))
175}
176
177/// The non-blank lines of an answer, trimmed.
178fn lines(out: &str) -> Vec<String> {
179    out.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()
180}
181
182/// `account`'s spend this month so far, in USD, as Cost Explorer has it (unblended).
183///
184/// # Errors
185///
186/// [`Failure`]: the CLI isn't there, AWS refused ([`Refusal::NotEnabled`]: Cost Explorer isn't
187/// enabled), or its answer isn't a finite number.
188pub async fn month_to_date_cost(cx: &Context, account: &Account) -> Result<f64, Failure> {
189    let period = month_period(SystemTime::now());
190    let out = account.ask(cx, &cost_args(&period)).await?;
191    spend(&out)
192}
193
194/// `aws ce get-cost-and-usage` for `period`, printing just the amount.
195fn cost_args(period: &str) -> [&str; 12] {
196    [
197        "ce",
198        "get-cost-and-usage",
199        "--time-period",
200        period,
201        "--granularity",
202        "MONTHLY",
203        "--metrics",
204        "UnblendedCost",
205        "--query",
206        "ResultsByTime[0].Total.UnblendedCost.Amount",
207        "--output",
208        "text",
209    ]
210}
211
212/// Cost Explorer's amount (its text output) as a number: a finite one (`f64::from_str` reads
213/// `NaN` and `inf` too, neither a spend).
214fn spend(out: &str) -> Result<f64, Failure> {
215    out.trim()
216        .parse::<f64>()
217        .ok()
218        .filter(|v| v.is_finite())
219        .ok_or_else(|| unreadable(CLI, format!("the spend isn't a number: {:?}", out.trim())))
220}
221
222/// Cost Explorer's period for the month of `now` so far: `Start` the 1st, `End` tomorrow (an
223/// exclusive end, so today's spend is in), UTC.
224fn month_period(now: SystemTime) -> String {
225    let day = |at: SystemTime| {
226        isothrum_runner::rfc3339(at)
227            .split_once('T')
228            .map(|(date, _)| date.to_owned())
229            .unwrap_or_default()
230    };
231    let today = day(now);
232    let month = today.rsplit_once('-').map_or(today.as_str(), |(month, _)| month);
233    format!("Start={month}-01,End={}", day(now + Duration::from_secs(86_400)))
234}
235
236/// Whether the account may create EC2 instances, as a dry run of one said.
237#[derive(Debug, Clone, PartialEq, Eq)]
238#[non_exhaustive]
239pub enum LaunchPermission {
240    /// AWS said the instance would have been created (`DryRunOperation`).
241    Allowed,
242    /// AWS checked the permission, then stopped at an error about the probe itself (its image,
243    /// the account's network): the permission is there.
244    AllowedThen {
245        /// The error AWS stopped at (`InvalidAMIID.NotFound`, `VPCIdNotSpecified`...).
246        code: String,
247    },
248    /// `ec2:RunInstances` is denied (`UnauthorizedOperation`).
249    Denied,
250    /// AWS stopped before it looked at the permission (throttled, a sign-in run out, a malformed
251    /// parameter, AWS itself), or gave no answer: what it said.
252    Unconfirmed(Failure),
253    /// The dry run printed nothing and exited 0: it says nothing.
254    NoAnswer,
255}
256
257/// Dry-runs creating a [`PROBE_INSTANCE_TYPE`] from the region's latest Amazon Linux image
258/// ([`LATEST_AMAZON_LINUX`], else [`UNKNOWN_IMAGE`]): creates nothing, and tells whether the
259/// account may create instances.
260pub async fn launch_permission(cx: &Context, account: &Account) -> LaunchPermission {
261    let latest = account
262        .ask(
263            cx,
264            &[
265                "ssm",
266                "get-parameter",
267                "--name",
268                LATEST_AMAZON_LINUX,
269                "--query",
270                "Parameter.Value",
271                "--output",
272                "text",
273            ],
274        )
275        .await;
276    let image = probe_image(latest.ok().as_deref());
277    let dry = account
278        .ask(
279            cx,
280            &[
281                "ec2",
282                "run-instances",
283                "--dry-run",
284                "--instance-type",
285                PROBE_INSTANCE_TYPE,
286                "--image-id",
287                &image,
288                "--output",
289                "text",
290            ],
291        )
292        .await;
293    match dry {
294        Ok(_) => LaunchPermission::NoAnswer,
295        Err(failure) => permission(failure),
296    }
297}
298
299/// The image a dry run uses: the one SSM printed when it is an image id, else [`UNKNOWN_IMAGE`].
300fn probe_image(latest: Option<&str>) -> String {
301    match latest.map(str::trim) {
302        Some(id) if id.starts_with("ami-") && id.len() > 4 && !id.contains(char::is_whitespace) => id.to_owned(),
303        _ => UNKNOWN_IMAGE.to_owned(),
304    }
305}
306
307/// What a refused dry run says of the permission, by AWS's error code.
308fn permission(failure: Failure) -> LaunchPermission {
309    let code = match &failure {
310        Failure::Refused { said, .. } => error_code(said).map(str::to_owned),
311        _ => None,
312    };
313    match code.as_deref() {
314        Some("DryRunOperation") => LaunchPermission::Allowed,
315        Some("UnauthorizedOperation") => LaunchPermission::Denied,
316        Some(code) if !before_authorization(code) => LaunchPermission::AllowedThen { code: code.to_owned() },
317        _ => LaunchPermission::Unconfirmed(failure),
318    }
319}
320
321/// The error code of a failed AWS CLI call: `Code` in "An error occurred (Code) when calling…".
322#[must_use]
323pub fn error_code(said: &str) -> Option<&str> {
324    let (_, after) = said.split_once("An error occurred (")?;
325    after.split_once(')').map(|(code, _)| code)
326}
327
328/// Whether AWS raises error `code` before it authorizes a request, so it says nothing of the
329/// permission: bad or expired credentials, throttling, a malformed or missing parameter, AWS
330/// itself, an account not yet usable. Every other code comes after authorization.
331#[must_use]
332pub fn before_authorization(code: &str) -> bool {
333    const BEFORE: &[&str] = &[
334        "AuthFailure",
335        "ExpiredToken",
336        "InvalidClientTokenId",
337        "SignatureDoesNotMatch",
338        "IncompleteSignature",
339        "RequestExpired",
340        "RequestLimitExceeded",
341        "Throttling",
342        "ServiceUnavailable",
343        "InternalError",
344        "InternalFailure",
345        "Unavailable",
346        "ValidationError",
347        "MissingParameter",
348        "InvalidParameter",
349        "UnknownParameter",
350        "OptInRequired",
351        "PendingVerification",
352        "AccessDenied",
353        "Blocked",
354    ];
355    BEFORE.iter().any(|b| code.starts_with(b)) || code.ends_with(".Malformed")
356}
357
358#[cfg(test)]
359mod tests;