use std::time::{Duration, SystemTime};
use isothrum_runner::ProcessSpec;
use super::{CLI_TIMEOUT, line, run, says, unreadable};
use crate::context::Context;
use crate::failure::{Failure, Refusal};
pub const CLI: &str = "aws";
pub const CLI_IMAGE: &str = "amazon/aws-cli:2.37.9";
pub const IMAGE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
pub const WHO_AM_I: [&str; 6] = ["sts", "get-caller-identity", "--query", "Arn", "--output", "text"];
pub const PROBE_INSTANCE_TYPE: &str = "t3.micro";
pub const LATEST_AMAZON_LINUX: &str = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64";
pub const UNKNOWN_IMAGE: &str = "ami-12345678";
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Credentials {
Cli {
profile: Option<String>,
},
Keys {
id: String,
secret: String,
},
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Credentials::Cli { profile } => f.debug_struct("Cli").field("profile", profile).finish(),
Credentials::Keys { id, .. } => f.debug_struct("Keys").field("id", id).field("secret", &"<masked>").finish(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Account {
pub credentials: Credentials,
pub region: Option<String>,
}
impl Account {
#[must_use]
pub fn new(credentials: Credentials, region: Option<String>) -> Account {
Account { credentials, region }
}
#[must_use]
pub fn invocation(&self, args: &[&str]) -> (&'static str, Vec<String>, Vec<(String, String)>) {
let mut env: Vec<(String, String)> = Vec::new();
let region = self.region.iter().map(|r| ("AWS_REGION".to_owned(), r.clone()));
match &self.credentials {
Credentials::Cli { profile } => {
env.extend(region);
env.extend(profile.iter().map(|p| ("AWS_PROFILE".to_owned(), p.clone())));
(CLI, args.iter().map(|a| (*a).to_owned()).collect(), env)
}
Credentials::Keys { id, secret } => {
env.push(("AWS_ACCESS_KEY_ID".to_owned(), id.clone()));
env.push(("AWS_SECRET_ACCESS_KEY".to_owned(), secret.clone()));
env.extend(region);
let mut docker: Vec<String> = [
"run",
"--rm",
"-e",
"AWS_ACCESS_KEY_ID",
"-e",
"AWS_SECRET_ACCESS_KEY",
"-e",
"AWS_REGION",
CLI_IMAGE,
]
.map(str::to_owned)
.to_vec();
docker.extend(args.iter().map(|a| (*a).to_owned()));
("docker", docker, env)
}
}
}
async fn ask(&self, cx: &Context, args: &[&str]) -> Result<String, Failure> {
let (program, invoked, env) = self.invocation(args);
let limit = if program == CLI { CLI_TIMEOUT } else { IMAGE_TIMEOUT };
let mut spec = ProcessSpec::new(program, invoked);
spec.env = env;
run(cx, limit, &spec, refusal).await
}
}
#[must_use]
pub fn refusal(said: &str) -> Refusal {
const SIGNED_OUT: [&str; 7] = [
"InvalidClientTokenId",
"SignatureDoesNotMatch",
"Unable to locate credentials",
"sso",
"not logged in",
"TokenRefresh",
"credentials",
];
if isothrum_runner::sign_in_expired(said) || says(said, &SIGNED_OUT) {
Refusal::CredentialsExpired
} else if says(said, &["Cost Explorer", "not enabled", "OptInRequired"]) {
Refusal::NotEnabled
} else if says(said, &["AccessDenied", "UnauthorizedOperation", "not authorized"]) {
Refusal::Denied
} else {
Refusal::Other
}
}
pub async fn identity(cx: &Context, account: &Account) -> Result<String, Failure> {
account.ask(cx, &WHO_AM_I).await.map(|out| line(&out))
}
pub async fn profiles(cx: &Context) -> Result<Vec<String>, Failure> {
super::ask(cx, CLI, &["configure", "list-profiles"], refusal).await.map(|out| lines(&out))
}
fn lines(out: &str) -> Vec<String> {
out.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()
}
pub async fn month_to_date_cost(cx: &Context, account: &Account) -> Result<f64, Failure> {
let period = month_period(SystemTime::now());
let out = account.ask(cx, &cost_args(&period)).await?;
spend(&out)
}
fn cost_args(period: &str) -> [&str; 12] {
[
"ce",
"get-cost-and-usage",
"--time-period",
period,
"--granularity",
"MONTHLY",
"--metrics",
"UnblendedCost",
"--query",
"ResultsByTime[0].Total.UnblendedCost.Amount",
"--output",
"text",
]
}
fn spend(out: &str) -> Result<f64, Failure> {
out.trim()
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| unreadable(CLI, format!("the spend isn't a number: {:?}", out.trim())))
}
fn month_period(now: SystemTime) -> String {
let day = |at: SystemTime| {
isothrum_runner::rfc3339(at)
.split_once('T')
.map(|(date, _)| date.to_owned())
.unwrap_or_default()
};
let today = day(now);
let month = today.rsplit_once('-').map_or(today.as_str(), |(month, _)| month);
format!("Start={month}-01,End={}", day(now + Duration::from_secs(86_400)))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LaunchPermission {
Allowed,
AllowedThen {
code: String,
},
Denied,
Unconfirmed(Failure),
NoAnswer,
}
pub async fn launch_permission(cx: &Context, account: &Account) -> LaunchPermission {
let latest = account
.ask(
cx,
&[
"ssm",
"get-parameter",
"--name",
LATEST_AMAZON_LINUX,
"--query",
"Parameter.Value",
"--output",
"text",
],
)
.await;
let image = probe_image(latest.ok().as_deref());
let dry = account
.ask(
cx,
&[
"ec2",
"run-instances",
"--dry-run",
"--instance-type",
PROBE_INSTANCE_TYPE,
"--image-id",
&image,
"--output",
"text",
],
)
.await;
match dry {
Ok(_) => LaunchPermission::NoAnswer,
Err(failure) => permission(failure),
}
}
fn probe_image(latest: Option<&str>) -> String {
match latest.map(str::trim) {
Some(id) if id.starts_with("ami-") && id.len() > 4 && !id.contains(char::is_whitespace) => id.to_owned(),
_ => UNKNOWN_IMAGE.to_owned(),
}
}
fn permission(failure: Failure) -> LaunchPermission {
let code = match &failure {
Failure::Refused { said, .. } => error_code(said).map(str::to_owned),
_ => None,
};
match code.as_deref() {
Some("DryRunOperation") => LaunchPermission::Allowed,
Some("UnauthorizedOperation") => LaunchPermission::Denied,
Some(code) if !before_authorization(code) => LaunchPermission::AllowedThen { code: code.to_owned() },
_ => LaunchPermission::Unconfirmed(failure),
}
}
#[must_use]
pub fn error_code(said: &str) -> Option<&str> {
let (_, after) = said.split_once("An error occurred (")?;
after.split_once(')').map(|(code, _)| code)
}
#[must_use]
pub fn before_authorization(code: &str) -> bool {
const BEFORE: &[&str] = &[
"AuthFailure",
"ExpiredToken",
"InvalidClientTokenId",
"SignatureDoesNotMatch",
"IncompleteSignature",
"RequestExpired",
"RequestLimitExceeded",
"Throttling",
"ServiceUnavailable",
"InternalError",
"InternalFailure",
"Unavailable",
"ValidationError",
"MissingParameter",
"InvalidParameter",
"UnknownParameter",
"OptInRequired",
"PendingVerification",
"AccessDenied",
"Blocked",
];
BEFORE.iter().any(|b| code.starts_with(b)) || code.ends_with(".Malformed")
}
#[cfg(test)]
mod tests;