1use 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
15pub const CLI: &str = "aws";
17
18pub const CLI_IMAGE: &str = "amazon/aws-cli:2.37.9";
20
21pub const IMAGE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
23
24pub const WHO_AM_I: [&str; 6] = ["sts", "get-caller-identity", "--query", "Arn", "--output", "text"];
27
28pub const PROBE_INSTANCE_TYPE: &str = "t3.micro";
30
31pub const LATEST_AMAZON_LINUX: &str = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64";
35
36pub const UNKNOWN_IMAGE: &str = "ami-12345678";
41
42#[derive(Clone, PartialEq, Eq)]
44#[non_exhaustive]
45pub enum Credentials {
46 Cli {
48 profile: Option<String>,
50 },
51 Keys {
53 id: String,
55 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#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct Account {
73 pub credentials: Credentials,
75 pub region: Option<String>,
77}
78
79impl Account {
80 #[must_use]
82 pub fn new(credentials: Credentials, region: Option<String>) -> Account {
83 Account { credentials, region }
84 }
85
86 #[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 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#[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 Refusal::NotEnabled
151 } else if says(said, &["AccessDenied", "UnauthorizedOperation", "not authorized"]) {
152 Refusal::Denied
153 } else {
154 Refusal::Other
155 }
156}
157
158pub async fn identity(cx: &Context, account: &Account) -> Result<String, Failure> {
165 account.ask(cx, &WHO_AM_I).await.map(|out| line(&out))
166}
167
168pub 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
177fn lines(out: &str) -> Vec<String> {
179 out.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()
180}
181
182pub 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
194fn 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
212fn 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
222fn 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#[derive(Debug, Clone, PartialEq, Eq)]
238#[non_exhaustive]
239pub enum LaunchPermission {
240 Allowed,
242 AllowedThen {
245 code: String,
247 },
248 Denied,
250 Unconfirmed(Failure),
253 NoAnswer,
255}
256
257pub 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
299fn 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
307fn 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#[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#[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;