1use std::ffi::{OsStr, OsString};
5use std::fmt;
6use std::io::Read;
7use std::path::{Path, PathBuf};
8
9use super::ini::{self, Entry, IniFile, Section};
10use super::sigv4::{region_refusal, valid_region};
11use super::{Credentials, DEFAULT_REGION};
12use crate::transport::without_userinfo;
13use crate::{Error, Result};
14
15const FILE_CAP: u64 = 1 << 20;
17
18const NAMES: [&str; 11] = [
21 "AWS_ACCESS_KEY_ID",
22 "AWS_SECRET_ACCESS_KEY",
23 "AWS_SESSION_TOKEN",
24 "AWS_REGION",
25 "AWS_DEFAULT_REGION",
26 "AWS_ENDPOINT_URL_S3",
27 "AWS_ENDPOINT_URL",
28 "AWS_PROFILE",
29 "AWS_SHARED_CREDENTIALS_FILE",
30 "AWS_CONFIG_FILE",
31 "HOME",
32];
33
34const OTHER_SOURCES: [&str; 4] = [
37 "role_arn",
38 "source_profile",
39 "credential_process",
40 "web_identity_token_file",
41];
42
43#[derive(Clone, Default, PartialEq, Eq)]
50pub struct Settings {
51 pub region: Option<String>,
53 pub endpoint: Option<String>,
55 pub addressing: Option<Addressing>,
57 pub profile: Option<String>,
62}
63
64impl fmt::Debug for Settings {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.debug_struct("Settings")
67 .field("region", &self.region)
68 .field("endpoint", &self.endpoint.as_deref().map(without_userinfo))
69 .field("addressing", &self.addressing)
70 .field("profile", &self.profile)
71 .finish()
72 }
73}
74
75#[derive(Clone, Default)]
80pub enum Environment {
81 #[default]
86 Process,
87 Variables(Vec<(String, String)>),
93}
94
95impl fmt::Debug for Environment {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 match self {
98 Environment::Process => f.write_str("Process"),
99 Environment::Variables(variables) => f
100 .debug_tuple("Variables")
101 .field(&RedactedVariables { variables })
102 .finish(),
103 }
104 }
105}
106
107struct RedactedVariables<'a> {
110 variables: &'a [(String, String)],
111}
112
113impl fmt::Debug for RedactedVariables<'_> {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.debug_list()
116 .entries(self.variables.iter().map(|(name, _)| (name, "<redacted>")))
117 .finish()
118 }
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub enum Addressing {
124 Path,
127 Virtual,
130}
131
132impl Addressing {
133 pub fn from_name(name: &str) -> Option<Addressing> {
143 match name {
144 "path" => Some(Addressing::Path),
145 "virtual" => Some(Addressing::Virtual),
146 _ => None,
147 }
148 }
149
150 pub fn as_str(self) -> &'static str {
152 match self {
153 Addressing::Path => "path",
154 Addressing::Virtual => "virtual",
155 }
156 }
157}
158
159#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct Setting<T> {
162 pub value: T,
164 pub origin: Origin,
166}
167
168#[derive(Clone, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum Origin {
174 Caller,
176 Environment(&'static str),
178 SharedFile {
180 path: PathBuf,
182 section: String,
184 key: &'static str,
186 },
187 Default,
189}
190
191impl fmt::Display for Origin {
192 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193 match self {
194 Origin::Caller => f.write_str("the caller"),
195 Origin::Environment(name) => write!(f, "the environment variable {name}"),
196 Origin::SharedFile { path, section, key } => write!(
197 f,
198 "the key {key} of the section [{section}] of '{}'",
199 path.display()
200 ),
201 Origin::Default => f.write_str("the default"),
202 }
203 }
204}
205
206#[derive(Clone)]
212#[non_exhaustive]
213pub struct Resolved {
214 pub profile: String,
216 pub region: Setting<String>,
218 pub endpoint: Option<Setting<String>>,
220 pub addressing: Option<Setting<Addressing>>,
222 pub credentials: Credentials,
224 pub credentials_origin: Origin,
228}
229
230impl fmt::Debug for Resolved {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 let endpoint = self.endpoint.as_ref().map(|endpoint| Setting {
233 value: without_userinfo(&endpoint.value),
234 origin: endpoint.origin.clone(),
235 });
236 f.debug_struct("Resolved")
237 .field("profile", &self.profile)
238 .field("region", &self.region)
239 .field("endpoint", &endpoint)
240 .field("addressing", &self.addressing)
241 .field("credentials", &self.credentials)
242 .field("credentials_origin", &self.credentials_origin)
243 .finish()
244 }
245}
246
247pub async fn resolve(settings: &Settings, environment: &Environment) -> Result<Resolved> {
373 let windows = cfg!(windows);
374 let vars = Vars::of(environment, windows);
375 let settings = settings.clone();
376 ostrya_rt::unblock(move || resolve_with(&settings, &vars, windows)).await
377}
378
379struct Vars {
381 values: Vec<(&'static str, OsString)>,
382}
383
384impl Vars {
385 fn of(environment: &Environment, windows: bool) -> Vars {
388 let names = NAMES.into_iter().chain(windows.then_some("USERPROFILE"));
389 let values = match environment {
390 Environment::Process => names
391 .filter_map(|name| Some((name, std::env::var_os(name)?)))
392 .collect(),
393 Environment::Variables(variables) => names
394 .filter_map(|name| {
395 variables
396 .iter()
397 .find(|(n, v)| n == name && !v.is_empty())
398 .map(|(_, v)| (name, OsString::from(v)))
399 })
400 .collect(),
401 };
402 Vars { values }
403 }
404
405 fn os(&self, name: &str) -> Option<&OsStr> {
407 self.values
408 .iter()
409 .find(|(n, v)| *n == name && !v.is_empty())
410 .map(|(_, v)| v.as_os_str())
411 }
412
413 fn text(&self, name: &str) -> Result<Option<&str>> {
415 self.os(name)
416 .map(|value| {
417 value.to_str().ok_or_else(|| {
418 Error::InvalidInput(format!("the environment variable {name} is not UTF-8"))
419 })
420 })
421 .transpose()
422 }
423}
424
425enum Shared {
427 NotLocated,
430 NoHome,
433 Absent(PathBuf),
435 Read(IniFile),
437}
438
439impl Shared {
440 fn file(&self) -> Option<&IniFile> {
441 match self {
442 Shared::Read(file) => Some(file),
443 _ => None,
444 }
445 }
446}
447
448fn resolve_with(settings: &Settings, vars: &Vars, windows: bool) -> Result<Resolved> {
452 let named = settings.profile.is_some();
453 if let Some(region) = &settings.region {
454 check_region(region, &Origin::Caller)?;
455 }
456 let profile = match &settings.profile {
457 Some(profile) => {
458 check_profile(profile, "the profile of the caller")?;
459 profile.clone()
460 }
461 None => match vars.text("AWS_PROFILE")? {
462 Some(profile) => {
463 check_profile(profile, "the environment variable AWS_PROFILE")?;
464 profile.to_owned()
465 }
466 None => "default".to_owned(),
467 },
468 };
469
470 let env_pair = if named { None } else { env_pair(vars)? };
471
472 let mut region = settings.region.clone().map(|value| Setting {
473 value,
474 origin: Origin::Caller,
475 });
476 let mut endpoint = settings.endpoint.clone().map(|value| Setting {
477 value,
478 origin: Origin::Caller,
479 });
480 let mut addressing = settings.addressing.map(|value| Setting {
481 value,
482 origin: Origin::Caller,
483 });
484 if !named {
485 if region.is_none() {
486 region = env_setting(vars, &["AWS_REGION", "AWS_DEFAULT_REGION"])?;
487 if let Some(region) = ®ion {
488 check_region(®ion.value, ®ion.origin)?;
489 }
490 }
491 if endpoint.is_none() {
492 endpoint = env_setting(vars, &["AWS_ENDPOINT_URL_S3", "AWS_ENDPOINT_URL"])?;
493 }
494 }
495
496 let home = vars
497 .os("HOME")
498 .or_else(|| {
499 if windows {
500 vars.os("USERPROFILE")
501 } else {
502 None
503 }
504 })
505 .map(PathBuf::from);
506 let need_config =
507 env_pair.is_none() || region.is_none() || endpoint.is_none() || addressing.is_none();
508 let config = if need_config {
509 let place = place(vars, "AWS_CONFIG_FILE", home.as_deref(), "config");
510 read_place(place, "shared config file")?
511 } else {
512 Shared::NotLocated
513 };
514 let config_section = match config.file() {
515 Some(file) => profile_section(file, &profile)?,
516 None => None,
517 };
518
519 if let (Some(file), Some(section)) = (config.file(), config_section) {
520 if region.is_none()
521 && let Some(entry) = section.value("region")
522 {
523 let origin = shared(file, section, "region");
524 check_region(&entry.value, &origin)?;
525 region = Some(Setting {
526 value: entry.value.clone(),
527 origin,
528 });
529 }
530 if endpoint.is_none() {
531 endpoint = file_endpoint(file, section)?;
532 }
533 if addressing.is_none() {
534 addressing = file_addressing(file, section)?;
535 }
536 }
537 let region = region.unwrap_or_else(|| Setting {
538 value: DEFAULT_REGION.to_owned(),
539 origin: Origin::Default,
540 });
541
542 let (credentials, credentials_origin) = match env_pair {
543 Some(pair) => pair,
544 None => {
545 let place = place(
546 vars,
547 "AWS_SHARED_CREDENTIALS_FILE",
548 home.as_deref(),
549 "credentials",
550 );
551 let creds = read_place(place, "shared credentials file")?;
552 let creds_section = creds.file().and_then(|file| file.section(&profile));
553 if let (Some(file), Some(section)) = (creds.file(), creds_section) {
554 check_static(file, section)?;
555 }
556 if let (Some(file), Some(section)) = (config.file(), config_section) {
557 check_static(file, section)?;
558 }
559 let from_creds = match (creds.file(), creds_section) {
560 (Some(file), Some(section)) => file_pair(file, section)?,
561 _ => None,
562 };
563 let from_config = match (from_creds.is_none(), config.file(), config_section) {
564 (true, Some(file), Some(section)) => file_pair(file, section)?,
565 _ => None,
566 };
567 match from_creds.or(from_config) {
568 Some(pair) => pair,
569 None => {
570 return Err(no_credentials(
571 &profile,
572 named,
573 windows,
574 (&creds, creds_section),
575 (&config, config_section),
576 ));
577 }
578 }
579 }
580 };
581
582 Ok(Resolved {
583 profile,
584 region,
585 endpoint,
586 addressing,
587 credentials,
588 credentials_origin,
589 })
590}
591
592fn check_region(region: &str, origin: &Origin) -> Result<()> {
595 if valid_region(region) {
596 Ok(())
597 } else {
598 Err(Error::InvalidInput(region_refusal(
599 region,
600 &origin.to_string(),
601 )))
602 }
603}
604
605fn check_profile(profile: &str, source: &str) -> Result<()> {
608 if profile.is_empty()
609 || profile
610 .chars()
611 .any(|c| c == '[' || c == ']' || c.is_control())
612 {
613 return Err(Error::InvalidInput(format!(
614 "{source}: the profile name {profile:?} is empty, or holds '[', ']', or a control character"
615 )));
616 }
617 Ok(())
618}
619
620fn env_pair(vars: &Vars) -> Result<Option<(Credentials, Origin)>> {
623 let id = vars.text("AWS_ACCESS_KEY_ID")?;
624 let secret = vars.text("AWS_SECRET_ACCESS_KEY")?;
625 let token = vars.text("AWS_SESSION_TOKEN")?;
626 match (id, secret) {
627 (Some(id), Some(secret)) => {
628 let credentials = Credentials::checked(id.into(), secret.into(), token.map(Into::into))
629 .map_err(|why| {
630 Error::InvalidInput(format!(
631 "the environment variables AWS_ACCESS_KEY_ID, \
632 AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN: {why}"
633 ))
634 })?;
635 Ok(Some((
636 credentials,
637 Origin::Environment("AWS_ACCESS_KEY_ID"),
638 )))
639 }
640 (Some(_), None) => Err(Error::InvalidInput(
641 "the environment variable AWS_ACCESS_KEY_ID is set, and \
642 AWS_SECRET_ACCESS_KEY is not"
643 .into(),
644 )),
645 (None, Some(_)) => Err(Error::InvalidInput(
646 "the environment variable AWS_SECRET_ACCESS_KEY is set, and \
647 AWS_ACCESS_KEY_ID is not"
648 .into(),
649 )),
650 (None, None) if token.is_some() => Err(Error::InvalidInput(
651 "the environment variable AWS_SESSION_TOKEN is set, and \
652 AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not"
653 .into(),
654 )),
655 (None, None) => Ok(None),
656 }
657}
658
659fn env_setting(vars: &Vars, names: &[&'static str]) -> Result<Option<Setting<String>>> {
662 for &name in names {
663 if let Some(value) = vars.text(name)? {
664 return Ok(Some(Setting {
665 value: value.to_owned(),
666 origin: Origin::Environment(name),
667 }));
668 }
669 }
670 Ok(None)
671}
672
673fn place(
680 vars: &Vars,
681 variable: &str,
682 home: Option<&Path>,
683 name: &str,
684) -> std::result::Result<PathBuf, Shared> {
685 match vars.os(variable) {
686 Some(value) => match value.to_str().and_then(|text| text.strip_prefix("~/")) {
687 Some(rest) => home.map(|home| home.join(rest)).ok_or(Shared::NoHome),
688 None => Ok(PathBuf::from(value)),
689 },
690 None => home
691 .map(|home| home.join(".aws").join(name))
692 .ok_or(Shared::NotLocated),
693 }
694}
695
696fn read_place(place: std::result::Result<PathBuf, Shared>, what: &str) -> Result<Shared> {
698 let path = match place {
699 Ok(path) => path,
700 Err(state) => return Ok(state),
701 };
702 match read_shared(&path, what)? {
703 Some(bytes) => Ok(Shared::Read(ini::parse(&path, &bytes)?)),
704 None => Ok(Shared::Absent(path)),
705 }
706}
707
708fn read_shared(path: &Path, what: &str) -> Result<Option<Vec<u8>>> {
715 let mut bytes = Vec::new();
716 let read =
717 std::fs::File::open(path).and_then(|file| file.take(FILE_CAP + 1).read_to_end(&mut bytes));
718 match read {
719 Ok(_) if bytes.len() as u64 > FILE_CAP => Err(Error::InvalidInput(format!(
720 "the {what} '{}' is over 1 MiB",
721 path.display()
722 ))),
723 Ok(_) => Ok(Some(bytes)),
724 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
725 Err(e) => Err(Error::Io(std::io::Error::new(
726 e.kind(),
727 format!("the {what} '{}': {e}", path.display()),
728 ))),
729 }
730}
731
732fn profile_section<'a>(file: &'a IniFile, profile: &str) -> Result<Option<&'a Section>> {
734 let named = file.section(&format!("profile {profile}"));
735 if profile != "default" {
736 return Ok(named);
737 }
738 match (file.section("default"), named) {
739 (Some(plain), Some(named)) => Err(Error::InvalidInput(format!(
740 "{}:{}: the profile default has the section [default] and the section \
741 [profile default]",
742 file.path.display(),
743 plain.line.max(named.line)
744 ))),
745 (plain, named) => Ok(plain.or(named)),
746 }
747}
748
749fn shared(file: &IniFile, section: &Section, key: &'static str) -> Origin {
751 Origin::SharedFile {
752 path: file.path.clone(),
753 section: section.name.clone(),
754 key,
755 }
756}
757
758fn refusal(file: &IniFile, section: &Section, line: usize, why: &str) -> Error {
761 Error::InvalidInput(format!(
762 "{}:{line}: the section [{}]: {why}",
763 file.path.display(),
764 section.name
765 ))
766}
767
768fn s3_entry<'a>(file: &IniFile, section: &'a Section) -> Result<Option<&'a Entry>> {
771 match section.entry("s3") {
772 Some(entry) if !entry.value.is_empty() => Err(refusal(
773 file,
774 section,
775 entry.line,
776 "the key s3 has a value, and it must open a sub-section",
777 )),
778 entry => Ok(entry),
779 }
780}
781
782fn file_endpoint(file: &IniFile, section: &Section) -> Result<Option<Setting<String>>> {
785 if let Some(services) = section.value("services") {
786 let name = format!("services {}", services.value);
787 let Some(target) = file.section(&name) else {
788 return Err(refusal(
789 file,
790 section,
791 services.line,
792 &format!("the key services names the section [{name}], which is absent"),
793 ));
794 };
795 if let Some((value, _)) =
796 s3_entry(file, target)?.and_then(|s3| s3.sub_value("endpoint_url"))
797 {
798 return Ok(Some(Setting {
799 value: value.to_owned(),
800 origin: shared(file, target, "s3.endpoint_url"),
801 }));
802 }
803 }
804 Ok(section.value("endpoint_url").map(|entry| Setting {
805 value: entry.value.clone(),
806 origin: shared(file, section, "endpoint_url"),
807 }))
808}
809
810fn file_addressing(file: &IniFile, section: &Section) -> Result<Option<Setting<Addressing>>> {
813 let Some((value, line)) =
814 s3_entry(file, section)?.and_then(|s3| s3.sub_value("addressing_style"))
815 else {
816 return Ok(None);
817 };
818 if value == "auto" {
819 return Ok(None);
820 }
821 match Addressing::from_name(value) {
822 Some(style) => Ok(Some(Setting {
823 value: style,
824 origin: shared(file, section, "s3.addressing_style"),
825 })),
826 None => Err(refusal(
827 file,
828 section,
829 line,
830 &format!("s3.addressing_style {value:?} is not path, virtual, or auto"),
831 )),
832 }
833}
834
835fn check_static(file: &IniFile, section: &Section) -> Result<()> {
838 let other = section
839 .entries
840 .iter()
841 .find(|entry| OTHER_SOURCES.contains(&entry.key.as_str()) || entry.key.starts_with("sso_"));
842 match other {
843 Some(entry) => Err(refusal(
844 file,
845 section,
846 entry.line,
847 &format!(
848 "the key {} names a credential source other than a static key pair, \
849 which is not read",
850 entry.key
851 ),
852 )),
853 None => Ok(()),
854 }
855}
856
857fn file_pair(file: &IniFile, section: &Section) -> Result<Option<(Credentials, Origin)>> {
860 let id = section.value("aws_access_key_id");
861 let secret = section.value("aws_secret_access_key");
862 let token = section.value("aws_session_token");
863 match (id, secret) {
864 (Some(id), Some(secret)) => {
865 let credentials = Credentials::checked(
866 id.value.clone(),
867 secret.value.clone(),
868 token.map(|token| token.value.clone()),
869 )
870 .map_err(|why| refusal(file, section, id.line, why))?;
871 Ok(Some((
872 credentials,
873 shared(file, section, "aws_access_key_id"),
874 )))
875 }
876 (Some(entry), None) => Err(refusal(
877 file,
878 section,
879 entry.line,
880 "the key aws_access_key_id is set, and aws_secret_access_key is not",
881 )),
882 (None, Some(entry)) => Err(refusal(
883 file,
884 section,
885 entry.line,
886 "the key aws_secret_access_key is set, and aws_access_key_id is not",
887 )),
888 (None, None) => match token {
889 Some(entry) => Err(refusal(
890 file,
891 section,
892 entry.line,
893 "the key aws_session_token is set, and aws_access_key_id and \
894 aws_secret_access_key are not",
895 )),
896 None => Ok(None),
897 },
898 }
899}
900
901fn no_credentials(
904 profile: &str,
905 named: bool,
906 windows: bool,
907 creds: (&Shared, Option<&Section>),
908 config: (&Shared, Option<&Section>),
909) -> Error {
910 let environment = if named {
911 "the environment: not read, because the caller names the profile"
912 } else {
913 "the environment: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not set"
914 };
915 let config_name = if profile == "default" {
916 "default".to_owned()
917 } else {
918 format!("profile {profile}")
919 };
920 Error::InvalidInput(format!(
921 "no S3 credentials for the profile '{profile}': {environment}; {}; {}",
922 file_state(
923 "shared credentials file",
924 "AWS_SHARED_CREDENTIALS_FILE",
925 windows,
926 creds,
927 profile
928 ),
929 file_state(
930 "shared config file",
931 "AWS_CONFIG_FILE",
932 windows,
933 config,
934 &config_name
935 ),
936 ))
937}
938
939fn file_state(
942 what: &str,
943 variable: &str,
944 windows: bool,
945 (shared, section): (&Shared, Option<&Section>),
946 name: &str,
947) -> String {
948 let home = if windows {
949 "HOME and USERPROFILE are"
950 } else {
951 "HOME is"
952 };
953 match (shared, section) {
954 (Shared::NotLocated, _) => {
955 format!("the {what}: not located, because {variable} gives no path and {home} not set")
956 }
957 (Shared::NoHome, _) => format!(
958 "the {what}: not located, because {variable} starts with '~/' and {home} not set"
959 ),
960 (Shared::Absent(path), _) => format!("the {what} '{}': absent", path.display()),
961 (Shared::Read(file), None) => {
962 format!("the {what} '{}': no section [{name}]", file.path.display())
963 }
964 (Shared::Read(file), Some(section)) => format!(
965 "the {what} '{}': the section [{}] has no key pair",
966 file.path.display(),
967 section.name
968 ),
969 }
970}
971
972#[cfg(test)]
973mod tests;