Skip to main content

ostrya_remote/s3/
chain.rs

1//! The settings and the credentials of an S3 endpoint, from the caller, the
2//! environment, and the shared AWS files.
3
4use 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
15/// The largest shared file that [`resolve`] reads: 1 MiB.
16const FILE_CAP: u64 = 1 << 20;
17
18/// The environment variables that [`resolve`] reads, other than
19/// `USERPROFILE`.
20const 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
34/// The keys of a credential source other than a static key pair. A key that
35/// starts with `sso_` is also such a key.
36const OTHER_SOURCES: [&str; 4] = [
37    "role_arn",
38    "source_profile",
39    "credential_process",
40    "web_identity_token_file",
41];
42
43/// The settings of an S3 endpoint that the caller gives.
44///
45/// A field that is `None` comes from the environment or from the shared AWS
46/// files. [`resolve`] states the order of the sources.
47///
48/// The [`Debug`] output shows the endpoint with no userinfo.
49#[derive(Clone, Default, PartialEq, Eq)]
50pub struct Settings {
51    /// The region of the signature scope.
52    pub region: Option<String>,
53    /// The endpoint URL.
54    pub endpoint: Option<String>,
55    /// The addressing style of a bucket.
56    pub addressing: Option<Addressing>,
57    /// The profile of the shared AWS files.
58    ///
59    /// A profile that the caller names turns off the key pair, the region,
60    /// and the endpoint of the environment. [`resolve`] states the rule.
61    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/// The environment that [`resolve`] reads.
76///
77/// The [`Debug`] output shows the names of the variables, and shows each
78/// value as `<redacted>`.
79#[derive(Clone, Default)]
80pub enum Environment {
81    /// The variables of the process environment.
82    ///
83    /// [`resolve`] reads them once, before it reads a file. This is the
84    /// default.
85    #[default]
86    Process,
87    /// The variables, given as name and value pairs.
88    ///
89    /// [`resolve`] does not read the process environment. It ignores a name
90    /// that it does not read. Of two entries of one name, the first entry with
91    /// a value counts.
92    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
107/// The variables of [`Environment::Variables`] in a [`Debug`] output: a list
108/// of names and redacted values.
109struct 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/// The addressing style of a bucket.
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub enum Addressing {
124    /// The bucket is the first segment of the path:
125    /// `https://s3.example.com/bucket/key`.
126    Path,
127    /// The bucket is the first label of the host name:
128    /// `https://bucket.s3.example.com/key`.
129    Virtual,
130}
131
132impl Addressing {
133    /// Returns the style of the name `name`: `path` or `virtual`.
134    ///
135    /// # Examples
136    ///
137    /// ```
138    /// use ostrya_remote::s3::Addressing;
139    /// assert_eq!(Addressing::from_name("path"), Some(Addressing::Path));
140    /// assert_eq!(Addressing::from_name("auto"), None);
141    /// ```
142    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    /// Returns the name of the style: `path` or `virtual`.
151    pub fn as_str(self) -> &'static str {
152        match self {
153            Addressing::Path => "path",
154            Addressing::Virtual => "virtual",
155        }
156    }
157}
158
159/// A value of a setting, and the source that gives it.
160#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct Setting<T> {
162    /// The value.
163    pub value: T,
164    /// The source of the value.
165    pub origin: Origin,
166}
167
168/// The source of a setting or of the credentials.
169///
170/// The [`Display`](fmt::Display) output names the source for a message.
171#[derive(Clone, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum Origin {
174    /// A field of [`Settings`].
175    Caller,
176    /// The environment variable of this name.
177    Environment(&'static str),
178    /// A key of a shared AWS file.
179    SharedFile {
180        /// The path of the file.
181        path: PathBuf,
182        /// The name of the section, without the brackets.
183        section: String,
184        /// The key. A key of the `s3` sub-section has the prefix `s3.`.
185        key: &'static str,
186    },
187    /// The default of the setting.
188    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/// The settings and the credentials of an S3 endpoint that [`resolve`]
207/// gives.
208///
209/// The [`Debug`] output shows the endpoint with no userinfo, and shows the
210/// credentials as the [`Debug`] output of [`Credentials`] shows them.
211#[derive(Clone)]
212#[non_exhaustive]
213pub struct Resolved {
214    /// The profile of the shared AWS files.
215    pub profile: String,
216    /// The region of the signature scope.
217    pub region: Setting<String>,
218    /// The endpoint URL, or `None` if no source gives one.
219    pub endpoint: Option<Setting<String>>,
220    /// The addressing style, or `None` if no source gives one.
221    pub addressing: Option<Setting<Addressing>>,
222    /// The key pair.
223    pub credentials: Credentials,
224    /// The source of the key pair. For the environment, it names
225    /// `AWS_ACCESS_KEY_ID`. For a file, it names the key
226    /// `aws_access_key_id`.
227    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
247/// Returns the settings and the credentials of an S3 endpoint, from
248/// `settings`, from `environment`, and from the shared AWS files.
249///
250/// The call reads each file on the blocking pool of `ostrya-rt`.
251///
252/// # Profile
253///
254/// The profile is [`Settings::profile`], else `AWS_PROFILE`, else
255/// `default`. A profile that the caller names turns off `AWS_ACCESS_KEY_ID`,
256/// `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_REGION`,
257/// `AWS_DEFAULT_REGION`, `AWS_ENDPOINT_URL_S3`, and `AWS_ENDPOINT_URL`. A
258/// profile from `AWS_PROFILE` does not.
259///
260/// # Order of the sources
261///
262/// The first source that gives a value counts:
263///
264/// - The key pair: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and
265///   `AWS_SESSION_TOKEN`; then the keys `aws_access_key_id`,
266///   `aws_secret_access_key`, and `aws_session_token` of the section
267///   `[PROFILE]` of the credentials file; then the same keys of the profile
268///   section of the config file.
269/// - The region: [`Settings::region`], `AWS_REGION`, `AWS_DEFAULT_REGION`,
270///   the key `region` of the profile section of the config file, then
271///   [`DEFAULT_REGION`].
272/// - The endpoint: [`Settings::endpoint`], `AWS_ENDPOINT_URL_S3`,
273///   `AWS_ENDPOINT_URL`, the key `endpoint_url` of the `s3` sub-section of the
274///   section `[services NAME]` that the key `services` of the profile names,
275///   then the key `endpoint_url` of the profile section.
276/// - The addressing style: [`Settings::addressing`], then the key
277///   `addressing_style` of the `s3` sub-section of the profile section. The
278///   value `auto` gives no style.
279///
280/// A key pair comes from one source alone. The token goes with the pair of its
281/// source.
282///
283/// An empty variable and an empty value in a file count as unset.
284///
285/// # Files
286///
287/// The config file is `AWS_CONFIG_FILE`, else `HOME/.aws/config`. The
288/// credentials file is `AWS_SHARED_CREDENTIALS_FILE`, else
289/// `HOME/.aws/credentials`. On Windows, `USERPROFILE` takes the place of
290/// `HOME` when `HOME` is unset. A leading `~/` of `AWS_CONFIG_FILE` or of
291/// `AWS_SHARED_CREDENTIALS_FILE` is the home directory. These two variables
292/// apply also to a profile that the caller names.
293///
294/// The profile section of the config file is `[default]` or
295/// `[profile default]` for the profile `default`, and `[profile NAME]` for
296/// another profile. The section of the credentials file is `[NAME]`.
297///
298/// The call reads the credentials file if the environment gives no key pair.
299/// It reads the config file if the environment gives no key pair, or if a
300/// setting has no value from the caller or from the environment. An absent
301/// file is not an error. The call reads at most 1 MiB of each file.
302///
303/// The call reads static key pairs alone. A profile section that holds
304/// `role_arn`, `source_profile`, `credential_process`,
305/// `web_identity_token_file`, or a key that starts with `sso_` is refused,
306/// unless the environment gives the key pair.
307///
308/// The call does not read other variables, for example
309/// `AWS_IGNORE_CONFIGURED_ENDPOINT_URLS` and `AWS_USE_FIPS_ENDPOINT`.
310///
311/// # File syntax
312///
313/// - A file is UTF-8. A line ends with LF or CRLF.
314/// - A blank line is skipped. A line whose first non-blank character is `#`
315///   or `;` is a comment. A comment cannot follow a value on its line.
316/// - A line with no indent that starts with `[` opens a section. The name is
317///   the text between `[` and `]`, without the white space around it.
318/// - A line with no indent in a section is a key and a value. It splits at
319///   the first `=` or `:`. The key is lowercased. White space around the key
320///   and around the value is removed.
321/// - An indented line after a key with an empty value is a key and a value of
322///   a sub-section of that key, for example `addressing_style` under `s3`.
323/// - The call checks the syntax of each section, also of a section that it
324///   does not read.
325///
326/// These are refused: a key before the first section, an indented line that
327/// continues a value, an indented line with no key before it, a malformed
328/// section header, a line with no `=` and no `:`, a section twice in a file,
329/// and a key twice in a section or in a sub-section.
330///
331/// # Errors
332///
333/// - [`Error::InvalidInput`] if no source gives a key pair. The message names
334///   the profile, and states for each source why it gives none.
335/// - [`Error::InvalidInput`] if a value is refused. The message names the
336///   source, and holds no secret and no session token. These are refused:
337///   - a region that [`SigV4::new`](super::SigV4::new) refuses
338///   - an empty profile name, or a profile name with `[`, `]`, or a control
339///     character
340///   - one of `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` without the
341///     other, or `AWS_SESSION_TOKEN` without the two, and the same in a file
342///     section
343///   - a value of a key pair that [`Credentials::new`] refuses
344///   - a key of a credential source other than a static key pair
345///   - an `addressing_style` other than `path`, `virtual`, and `auto`
346///   - a key `services` that names no section, or an `s3` key with a value
347///     in place of a sub-section
348///   - a section of a profile in the config file as `[default]` and as
349///     `[profile default]`
350///   - a variable that is not UTF-8, other than a path
351///   - a file that is larger than 1 MiB. The message names the file.
352///   - a line that [File syntax](resolve#file-syntax) refuses. The message
353///     names the file and the line.
354/// - [`Error::Io`] if a file exists and cannot be read. The message names the
355///   file and its path.
356///
357/// # Examples
358///
359/// ```no_run
360/// use ostrya_remote::s3::{Environment, Settings, SigV4, resolve};
361/// # async fn run() -> ostrya_remote::Result<()> {
362/// let settings = Settings {
363///     profile: Some("backup".into()),
364///     ..Settings::default()
365/// };
366/// let resolved = resolve(&settings, &Environment::Process).await?;
367/// println!("region {} from {}", resolved.region.value, resolved.region.origin);
368/// let signer = SigV4::new(resolved.credentials, &resolved.region.value)?;
369/// # let _ = signer;
370/// # Ok(()) }
371/// ```
372pub 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
379/// The values of the variables that [`resolve`] reads.
380struct Vars {
381    values: Vec<(&'static str, OsString)>,
382}
383
384impl Vars {
385    /// Returns the variables of `environment`. `USERPROFILE` is read if
386    /// `windows` is `true`.
387    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    /// Returns the value of `name`, or `None` if it is unset or empty.
406    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    /// Returns the value of `name` as text, or `None` if it is unset or empty.
414    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
425/// The state of one shared file.
426enum Shared {
427    /// Neither a variable nor the home directory gives the path of the file,
428    /// or the call does not need the file.
429    NotLocated,
430    /// The variable gives a path that starts with `~/`, and no variable gives
431    /// the home directory.
432    NoHome,
433    /// No file is at the path.
434    Absent(PathBuf),
435    /// The file is read.
436    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
448/// Resolves the settings as [`resolve`] does, with the values of the
449/// variables in `vars`, and with the Windows rule of the home directory if
450/// `windows` is `true`.
451fn 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) = &region {
488                check_region(&region.value, &region.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
592/// Refuses `region` if [`SigV4::new`](super::SigV4::new) refuses it. The
593/// message names `origin`.
594fn 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
605/// Refuses the profile name `profile` if it is empty, or if it holds `[`,
606/// `]`, or a control character. The message names `source`.
607fn 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
620/// Returns the key pair of the environment, or `None` if the environment
621/// sets none of its variables.
622fn 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
659/// Returns the value of the first variable of `names` that is set, as a
660/// setting.
661fn 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
673/// Returns the path of the shared file that the variable `variable` names,
674/// else of the file `name` in the directory `.aws` of `home`.
675///
676/// A leading `~/` of the variable is `home`. An error is
677/// [`Shared::NoHome`] if the variable needs `home`, and [`Shared::NotLocated`]
678/// if the variable is not set. Each is for a `home` that is `None`.
679fn 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
696/// Reads and parses the shared file at `place`, which `what` names.
697fn 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
708/// Returns the bytes of the shared file at `path`, which `what` names, or
709/// `None` if no file is at the path.
710///
711/// The function reads at most 1 MiB and one byte of the file. A failure is an
712/// [`Error::Io`] with the kind of the failure. Its message names `what` and
713/// the path, and holds no byte of the file.
714fn 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
732/// Returns the section of the profile `profile` in the config file `file`.
733fn 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
749/// Returns the origin of `key` in `section` of `file`.
750fn 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
758/// Returns the refusal of the line `line` of `section` of `file`, for the
759/// reason `why`.
760fn 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
768/// Returns the `s3` sub-section of `section`, or `None` if the section has no
769/// key `s3`. A key `s3` with a value is refused.
770fn 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
782/// Returns the endpoint of the profile section `section` of the config file
783/// `file`.
784fn 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
810/// Returns the addressing style of the profile section `section` of the
811/// config file `file`.
812fn 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
835/// Refuses `section` of `file` if it holds a key of a credential source other
836/// than a static key pair.
837fn 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
857/// Returns the key pair of `section` of `file`, or `None` if the section
858/// holds none of its keys.
859fn 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
901/// Returns the refusal of a profile with no key pair. The message states for
902/// each source why it gives none.
903fn 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
939/// Returns why the shared file `what`, whose path the variable `variable`
940/// gives, gives no key pair. `name` is the section of the profile.
941fn 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;