use std::iter;
use chrono::{DateTime, SecondsFormat, Utc};
use clap::{Parser, ValueEnum};
use eyre::Result;
use serde::Serialize;
use sim_cli::ApiKeyArg;
use simulator_api::DatasetCredentialsResponse;
const CREDENTIAL_PROCESS_VERSION: u8 = 1;
const DOWNLOAD_EXAMPLES: &str = "\
Examples:
# Load the credentials into this shell, then list and download under the
# `# datasets:` or `# your datasets:` URI it prints.
eval \"$(sim datasets credentials)\" # fish: sim datasets credentials | source
aws s3 ls s3://<bucket>/datasets/
aws s3 sync s3://<bucket>/datasets/<dataset>/ ./<dataset>/
# Or keep a profile that renews itself when the hour-long credentials expire.
# SIMULATOR_API_KEY must be set wherever the profile is used.
# ~/.aws/config:
# [profile termina-datasets]
# credential_process = sim datasets credentials --format process
# region = <region>
aws s3 sync s3://<bucket>/datasets/<dataset>/ ./<dataset>/ --profile termina-datasets";
#[derive(Parser, Debug)]
#[command(after_help = DOWNLOAD_EXAMPLES)]
pub struct DatasetCredentialsArgs {
#[arg(long, value_enum, default_value_t = CredentialsFormat::Env)]
pub format: CredentialsFormat,
#[command(flatten)]
pub api_key: ApiKeyArg,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum CredentialsFormat {
Env,
Process,
Json,
}
pub async fn credentials(args: DatasetCredentialsArgs, url: String) -> Result<()> {
let client = sim_cli::client::new(&url, &args.api_key.get());
let resp = client.dataset_credentials().await?;
match args.format {
CredentialsFormat::Env => {
print!("{}", env_exports(&resp));
eprint!("{}", env_notes(&resp));
}
CredentialsFormat::Process => {
println!(
"{}",
serde_json::to_string(&CredentialProcess::from(&resp))?
);
}
CredentialsFormat::Json => println!("{}", serde_json::to_string_pretty(&resp)?),
}
Ok(())
}
#[derive(Serialize)]
#[serde(rename_all = "PascalCase")]
struct CredentialProcess<'a> {
version: u8,
access_key_id: &'a str,
secret_access_key: &'a str,
session_token: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
expiration: Option<DateTime<Utc>>,
}
impl<'a> From<&'a DatasetCredentialsResponse> for CredentialProcess<'a> {
fn from(resp: &'a DatasetCredentialsResponse) -> Self {
Self {
version: CREDENTIAL_PROCESS_VERSION,
access_key_id: &resp.access_key_id,
secret_access_key: &resp.secret_access_key,
session_token: &resp.session_token,
expiration: resp.expiration,
}
}
}
fn env_exports(resp: &DatasetCredentialsResponse) -> String {
[
("AWS_ACCESS_KEY_ID", Some(&resp.access_key_id)),
("AWS_SECRET_ACCESS_KEY", Some(&resp.secret_access_key)),
("AWS_SESSION_TOKEN", Some(&resp.session_token)),
("AWS_REGION", resp.region.as_ref()),
("AWS_DEFAULT_REGION", resp.region.as_ref()),
]
.into_iter()
.filter_map(|(name, value)| value.map(|value| format!("export {name}='{value}'\n")))
.collect()
}
fn env_notes(resp: &DatasetCredentialsResponse) -> String {
let own = resp
.user_s3_uri
.as_deref()
.map(|uri| format!("# your datasets: {uri}\n"));
let expires = resp.expiration.map(|at| {
format!(
"# expires: {}\n",
at.to_rfc3339_opts(SecondsFormat::Secs, true)
)
});
iter::once(format!("# datasets: {}\n", resp.s3_uri))
.chain(own)
.chain(expires)
.collect()
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
fn response(region: Option<&str>) -> DatasetCredentialsResponse {
DatasetCredentialsResponse {
access_key_id: "ASIAEXAMPLE".into(),
secret_access_key: "se/cr+et=".into(),
session_token: "tok".into(),
expiration: Some("2026-10-14T05:15:00Z".parse().expect("parse timestamp")),
s3_uri: "s3://bucket/datasets/".into(),
user_s3_uri: None,
region: region.map(Into::into),
}
}
#[rstest]
#[case::with_region(
Some("us-east-1"),
"export AWS_ACCESS_KEY_ID='ASIAEXAMPLE'\n\
export AWS_SECRET_ACCESS_KEY='se/cr+et='\n\
export AWS_SESSION_TOKEN='tok'\n\
export AWS_REGION='us-east-1'\n\
export AWS_DEFAULT_REGION='us-east-1'\n"
)]
#[case::without_region(
None,
"export AWS_ACCESS_KEY_ID='ASIAEXAMPLE'\n\
export AWS_SECRET_ACCESS_KEY='se/cr+et='\n\
export AWS_SESSION_TOKEN='tok'\n"
)]
fn env_exports_skip_an_unknown_region(#[case] region: Option<&str>, #[case] expected: &str) {
assert_eq!(env_exports(&response(region)), expected);
}
#[test]
fn credential_process_matches_the_aws_contract() {
let resp = response(None);
assert_eq!(
serde_json::to_value(CredentialProcess::from(&resp)).expect("serialize"),
serde_json::json!({
"Version": 1,
"AccessKeyId": "ASIAEXAMPLE",
"SecretAccessKey": "se/cr+et=",
"SessionToken": "tok",
"Expiration": "2026-10-14T05:15:00Z",
})
);
}
}