use std::ffi::{OsStr, OsString};
use std::fmt;
use std::io::Read;
use std::path::{Path, PathBuf};
use super::ini::{self, Entry, IniFile, Section};
use super::sigv4::{region_refusal, valid_region};
use super::{Credentials, DEFAULT_REGION};
use crate::transport::without_userinfo;
use crate::{Error, Result};
const FILE_CAP: u64 = 1 << 20;
const NAMES: [&str; 11] = [
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_REGION",
"AWS_DEFAULT_REGION",
"AWS_ENDPOINT_URL_S3",
"AWS_ENDPOINT_URL",
"AWS_PROFILE",
"AWS_SHARED_CREDENTIALS_FILE",
"AWS_CONFIG_FILE",
"HOME",
];
const OTHER_SOURCES: [&str; 4] = [
"role_arn",
"source_profile",
"credential_process",
"web_identity_token_file",
];
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Settings {
pub region: Option<String>,
pub endpoint: Option<String>,
pub addressing: Option<Addressing>,
pub profile: Option<String>,
}
impl fmt::Debug for Settings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Settings")
.field("region", &self.region)
.field("endpoint", &self.endpoint.as_deref().map(without_userinfo))
.field("addressing", &self.addressing)
.field("profile", &self.profile)
.finish()
}
}
#[derive(Clone, Default)]
pub enum Environment {
#[default]
Process,
Variables(Vec<(String, String)>),
}
impl fmt::Debug for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Environment::Process => f.write_str("Process"),
Environment::Variables(variables) => f
.debug_tuple("Variables")
.field(&RedactedVariables { variables })
.finish(),
}
}
}
struct RedactedVariables<'a> {
variables: &'a [(String, String)],
}
impl fmt::Debug for RedactedVariables<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.variables.iter().map(|(name, _)| (name, "<redacted>")))
.finish()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Addressing {
Path,
Virtual,
}
impl Addressing {
pub fn from_name(name: &str) -> Option<Addressing> {
match name {
"path" => Some(Addressing::Path),
"virtual" => Some(Addressing::Virtual),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Addressing::Path => "path",
Addressing::Virtual => "virtual",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Setting<T> {
pub value: T,
pub origin: Origin,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Origin {
Caller,
Environment(&'static str),
SharedFile {
path: PathBuf,
section: String,
key: &'static str,
},
Default,
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Origin::Caller => f.write_str("the caller"),
Origin::Environment(name) => write!(f, "the environment variable {name}"),
Origin::SharedFile { path, section, key } => write!(
f,
"the key {key} of the section [{section}] of '{}'",
path.display()
),
Origin::Default => f.write_str("the default"),
}
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct Resolved {
pub profile: String,
pub region: Setting<String>,
pub endpoint: Option<Setting<String>>,
pub addressing: Option<Setting<Addressing>>,
pub credentials: Credentials,
pub credentials_origin: Origin,
}
impl fmt::Debug for Resolved {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let endpoint = self.endpoint.as_ref().map(|endpoint| Setting {
value: without_userinfo(&endpoint.value),
origin: endpoint.origin.clone(),
});
f.debug_struct("Resolved")
.field("profile", &self.profile)
.field("region", &self.region)
.field("endpoint", &endpoint)
.field("addressing", &self.addressing)
.field("credentials", &self.credentials)
.field("credentials_origin", &self.credentials_origin)
.finish()
}
}
pub async fn resolve(settings: &Settings, environment: &Environment) -> Result<Resolved> {
let windows = cfg!(windows);
let vars = Vars::of(environment, windows);
let settings = settings.clone();
ostrya_rt::unblock(move || resolve_with(&settings, &vars, windows)).await
}
struct Vars {
values: Vec<(&'static str, OsString)>,
}
impl Vars {
fn of(environment: &Environment, windows: bool) -> Vars {
let names = NAMES.into_iter().chain(windows.then_some("USERPROFILE"));
let values = match environment {
Environment::Process => names
.filter_map(|name| Some((name, std::env::var_os(name)?)))
.collect(),
Environment::Variables(variables) => names
.filter_map(|name| {
variables
.iter()
.find(|(n, v)| n == name && !v.is_empty())
.map(|(_, v)| (name, OsString::from(v)))
})
.collect(),
};
Vars { values }
}
fn os(&self, name: &str) -> Option<&OsStr> {
self.values
.iter()
.find(|(n, v)| *n == name && !v.is_empty())
.map(|(_, v)| v.as_os_str())
}
fn text(&self, name: &str) -> Result<Option<&str>> {
self.os(name)
.map(|value| {
value.to_str().ok_or_else(|| {
Error::InvalidInput(format!("the environment variable {name} is not UTF-8"))
})
})
.transpose()
}
}
enum Shared {
NotLocated,
NoHome,
Absent(PathBuf),
Read(IniFile),
}
impl Shared {
fn file(&self) -> Option<&IniFile> {
match self {
Shared::Read(file) => Some(file),
_ => None,
}
}
}
fn resolve_with(settings: &Settings, vars: &Vars, windows: bool) -> Result<Resolved> {
let named = settings.profile.is_some();
if let Some(region) = &settings.region {
check_region(region, &Origin::Caller)?;
}
let profile = match &settings.profile {
Some(profile) => {
check_profile(profile, "the profile of the caller")?;
profile.clone()
}
None => match vars.text("AWS_PROFILE")? {
Some(profile) => {
check_profile(profile, "the environment variable AWS_PROFILE")?;
profile.to_owned()
}
None => "default".to_owned(),
},
};
let env_pair = if named { None } else { env_pair(vars)? };
let mut region = settings.region.clone().map(|value| Setting {
value,
origin: Origin::Caller,
});
let mut endpoint = settings.endpoint.clone().map(|value| Setting {
value,
origin: Origin::Caller,
});
let mut addressing = settings.addressing.map(|value| Setting {
value,
origin: Origin::Caller,
});
if !named {
if region.is_none() {
region = env_setting(vars, &["AWS_REGION", "AWS_DEFAULT_REGION"])?;
if let Some(region) = ®ion {
check_region(®ion.value, ®ion.origin)?;
}
}
if endpoint.is_none() {
endpoint = env_setting(vars, &["AWS_ENDPOINT_URL_S3", "AWS_ENDPOINT_URL"])?;
}
}
let home = vars
.os("HOME")
.or_else(|| {
if windows {
vars.os("USERPROFILE")
} else {
None
}
})
.map(PathBuf::from);
let need_config =
env_pair.is_none() || region.is_none() || endpoint.is_none() || addressing.is_none();
let config = if need_config {
let place = place(vars, "AWS_CONFIG_FILE", home.as_deref(), "config");
read_place(place, "shared config file")?
} else {
Shared::NotLocated
};
let config_section = match config.file() {
Some(file) => profile_section(file, &profile)?,
None => None,
};
if let (Some(file), Some(section)) = (config.file(), config_section) {
if region.is_none()
&& let Some(entry) = section.value("region")
{
let origin = shared(file, section, "region");
check_region(&entry.value, &origin)?;
region = Some(Setting {
value: entry.value.clone(),
origin,
});
}
if endpoint.is_none() {
endpoint = file_endpoint(file, section)?;
}
if addressing.is_none() {
addressing = file_addressing(file, section)?;
}
}
let region = region.unwrap_or_else(|| Setting {
value: DEFAULT_REGION.to_owned(),
origin: Origin::Default,
});
let (credentials, credentials_origin) = match env_pair {
Some(pair) => pair,
None => {
let place = place(
vars,
"AWS_SHARED_CREDENTIALS_FILE",
home.as_deref(),
"credentials",
);
let creds = read_place(place, "shared credentials file")?;
let creds_section = creds.file().and_then(|file| file.section(&profile));
if let (Some(file), Some(section)) = (creds.file(), creds_section) {
check_static(file, section)?;
}
if let (Some(file), Some(section)) = (config.file(), config_section) {
check_static(file, section)?;
}
let from_creds = match (creds.file(), creds_section) {
(Some(file), Some(section)) => file_pair(file, section)?,
_ => None,
};
let from_config = match (from_creds.is_none(), config.file(), config_section) {
(true, Some(file), Some(section)) => file_pair(file, section)?,
_ => None,
};
match from_creds.or(from_config) {
Some(pair) => pair,
None => {
return Err(no_credentials(
&profile,
named,
windows,
(&creds, creds_section),
(&config, config_section),
));
}
}
}
};
Ok(Resolved {
profile,
region,
endpoint,
addressing,
credentials,
credentials_origin,
})
}
fn check_region(region: &str, origin: &Origin) -> Result<()> {
if valid_region(region) {
Ok(())
} else {
Err(Error::InvalidInput(region_refusal(
region,
&origin.to_string(),
)))
}
}
fn check_profile(profile: &str, source: &str) -> Result<()> {
if profile.is_empty()
|| profile
.chars()
.any(|c| c == '[' || c == ']' || c.is_control())
{
return Err(Error::InvalidInput(format!(
"{source}: the profile name {profile:?} is empty, or holds '[', ']', or a control character"
)));
}
Ok(())
}
fn env_pair(vars: &Vars) -> Result<Option<(Credentials, Origin)>> {
let id = vars.text("AWS_ACCESS_KEY_ID")?;
let secret = vars.text("AWS_SECRET_ACCESS_KEY")?;
let token = vars.text("AWS_SESSION_TOKEN")?;
match (id, secret) {
(Some(id), Some(secret)) => {
let credentials = Credentials::checked(id.into(), secret.into(), token.map(Into::into))
.map_err(|why| {
Error::InvalidInput(format!(
"the environment variables AWS_ACCESS_KEY_ID, \
AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN: {why}"
))
})?;
Ok(Some((
credentials,
Origin::Environment("AWS_ACCESS_KEY_ID"),
)))
}
(Some(_), None) => Err(Error::InvalidInput(
"the environment variable AWS_ACCESS_KEY_ID is set, and \
AWS_SECRET_ACCESS_KEY is not"
.into(),
)),
(None, Some(_)) => Err(Error::InvalidInput(
"the environment variable AWS_SECRET_ACCESS_KEY is set, and \
AWS_ACCESS_KEY_ID is not"
.into(),
)),
(None, None) if token.is_some() => Err(Error::InvalidInput(
"the environment variable AWS_SESSION_TOKEN is set, and \
AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not"
.into(),
)),
(None, None) => Ok(None),
}
}
fn env_setting(vars: &Vars, names: &[&'static str]) -> Result<Option<Setting<String>>> {
for &name in names {
if let Some(value) = vars.text(name)? {
return Ok(Some(Setting {
value: value.to_owned(),
origin: Origin::Environment(name),
}));
}
}
Ok(None)
}
fn place(
vars: &Vars,
variable: &str,
home: Option<&Path>,
name: &str,
) -> std::result::Result<PathBuf, Shared> {
match vars.os(variable) {
Some(value) => match value.to_str().and_then(|text| text.strip_prefix("~/")) {
Some(rest) => home.map(|home| home.join(rest)).ok_or(Shared::NoHome),
None => Ok(PathBuf::from(value)),
},
None => home
.map(|home| home.join(".aws").join(name))
.ok_or(Shared::NotLocated),
}
}
fn read_place(place: std::result::Result<PathBuf, Shared>, what: &str) -> Result<Shared> {
let path = match place {
Ok(path) => path,
Err(state) => return Ok(state),
};
match read_shared(&path, what)? {
Some(bytes) => Ok(Shared::Read(ini::parse(&path, &bytes)?)),
None => Ok(Shared::Absent(path)),
}
}
fn read_shared(path: &Path, what: &str) -> Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
let read =
std::fs::File::open(path).and_then(|file| file.take(FILE_CAP + 1).read_to_end(&mut bytes));
match read {
Ok(_) if bytes.len() as u64 > FILE_CAP => Err(Error::InvalidInput(format!(
"the {what} '{}' is over 1 MiB",
path.display()
))),
Ok(_) => Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(Error::Io(std::io::Error::new(
e.kind(),
format!("the {what} '{}': {e}", path.display()),
))),
}
}
fn profile_section<'a>(file: &'a IniFile, profile: &str) -> Result<Option<&'a Section>> {
let named = file.section(&format!("profile {profile}"));
if profile != "default" {
return Ok(named);
}
match (file.section("default"), named) {
(Some(plain), Some(named)) => Err(Error::InvalidInput(format!(
"{}:{}: the profile default has the section [default] and the section \
[profile default]",
file.path.display(),
plain.line.max(named.line)
))),
(plain, named) => Ok(plain.or(named)),
}
}
fn shared(file: &IniFile, section: &Section, key: &'static str) -> Origin {
Origin::SharedFile {
path: file.path.clone(),
section: section.name.clone(),
key,
}
}
fn refusal(file: &IniFile, section: &Section, line: usize, why: &str) -> Error {
Error::InvalidInput(format!(
"{}:{line}: the section [{}]: {why}",
file.path.display(),
section.name
))
}
fn s3_entry<'a>(file: &IniFile, section: &'a Section) -> Result<Option<&'a Entry>> {
match section.entry("s3") {
Some(entry) if !entry.value.is_empty() => Err(refusal(
file,
section,
entry.line,
"the key s3 has a value, and it must open a sub-section",
)),
entry => Ok(entry),
}
}
fn file_endpoint(file: &IniFile, section: &Section) -> Result<Option<Setting<String>>> {
if let Some(services) = section.value("services") {
let name = format!("services {}", services.value);
let Some(target) = file.section(&name) else {
return Err(refusal(
file,
section,
services.line,
&format!("the key services names the section [{name}], which is absent"),
));
};
if let Some((value, _)) =
s3_entry(file, target)?.and_then(|s3| s3.sub_value("endpoint_url"))
{
return Ok(Some(Setting {
value: value.to_owned(),
origin: shared(file, target, "s3.endpoint_url"),
}));
}
}
Ok(section.value("endpoint_url").map(|entry| Setting {
value: entry.value.clone(),
origin: shared(file, section, "endpoint_url"),
}))
}
fn file_addressing(file: &IniFile, section: &Section) -> Result<Option<Setting<Addressing>>> {
let Some((value, line)) =
s3_entry(file, section)?.and_then(|s3| s3.sub_value("addressing_style"))
else {
return Ok(None);
};
if value == "auto" {
return Ok(None);
}
match Addressing::from_name(value) {
Some(style) => Ok(Some(Setting {
value: style,
origin: shared(file, section, "s3.addressing_style"),
})),
None => Err(refusal(
file,
section,
line,
&format!("s3.addressing_style {value:?} is not path, virtual, or auto"),
)),
}
}
fn check_static(file: &IniFile, section: &Section) -> Result<()> {
let other = section
.entries
.iter()
.find(|entry| OTHER_SOURCES.contains(&entry.key.as_str()) || entry.key.starts_with("sso_"));
match other {
Some(entry) => Err(refusal(
file,
section,
entry.line,
&format!(
"the key {} names a credential source other than a static key pair, \
which is not read",
entry.key
),
)),
None => Ok(()),
}
}
fn file_pair(file: &IniFile, section: &Section) -> Result<Option<(Credentials, Origin)>> {
let id = section.value("aws_access_key_id");
let secret = section.value("aws_secret_access_key");
let token = section.value("aws_session_token");
match (id, secret) {
(Some(id), Some(secret)) => {
let credentials = Credentials::checked(
id.value.clone(),
secret.value.clone(),
token.map(|token| token.value.clone()),
)
.map_err(|why| refusal(file, section, id.line, why))?;
Ok(Some((
credentials,
shared(file, section, "aws_access_key_id"),
)))
}
(Some(entry), None) => Err(refusal(
file,
section,
entry.line,
"the key aws_access_key_id is set, and aws_secret_access_key is not",
)),
(None, Some(entry)) => Err(refusal(
file,
section,
entry.line,
"the key aws_secret_access_key is set, and aws_access_key_id is not",
)),
(None, None) => match token {
Some(entry) => Err(refusal(
file,
section,
entry.line,
"the key aws_session_token is set, and aws_access_key_id and \
aws_secret_access_key are not",
)),
None => Ok(None),
},
}
}
fn no_credentials(
profile: &str,
named: bool,
windows: bool,
creds: (&Shared, Option<&Section>),
config: (&Shared, Option<&Section>),
) -> Error {
let environment = if named {
"the environment: not read, because the caller names the profile"
} else {
"the environment: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not set"
};
let config_name = if profile == "default" {
"default".to_owned()
} else {
format!("profile {profile}")
};
Error::InvalidInput(format!(
"no S3 credentials for the profile '{profile}': {environment}; {}; {}",
file_state(
"shared credentials file",
"AWS_SHARED_CREDENTIALS_FILE",
windows,
creds,
profile
),
file_state(
"shared config file",
"AWS_CONFIG_FILE",
windows,
config,
&config_name
),
))
}
fn file_state(
what: &str,
variable: &str,
windows: bool,
(shared, section): (&Shared, Option<&Section>),
name: &str,
) -> String {
let home = if windows {
"HOME and USERPROFILE are"
} else {
"HOME is"
};
match (shared, section) {
(Shared::NotLocated, _) => {
format!("the {what}: not located, because {variable} gives no path and {home} not set")
}
(Shared::NoHome, _) => format!(
"the {what}: not located, because {variable} starts with '~/' and {home} not set"
),
(Shared::Absent(path), _) => format!("the {what} '{}': absent", path.display()),
(Shared::Read(file), None) => {
format!("the {what} '{}': no section [{name}]", file.path.display())
}
(Shared::Read(file), Some(section)) => format!(
"the {what} '{}': the section [{}] has no key pair",
file.path.display(),
section.name
),
}
}
#[cfg(test)]
mod tests;