aws_runtime/env_config/
source.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Code for handling in-memory sources of profile data

use super::error::{CouldNotReadConfigFile, EnvConfigFileLoadError};
use crate::env_config::file::{EnvConfigFile, EnvConfigFileKind, EnvConfigFiles};
use crate::fs_util::{home_dir, Os};
use aws_smithy_types::error::display::DisplayErrorContext;
use aws_types::os_shim_internal;
use std::borrow::Cow;
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use tracing::{warn, Instrument};
const HOME_EXPANSION_FAILURE_WARNING: &str =
    "home directory expansion was requested (via `~` character) for the profile \
     config file path, but no home directory could be determined";

#[derive(Debug)]
/// In-memory source of profile data
pub struct Source {
    /// Profile file sources
    pub(crate) files: Vec<File>,

    /// Profile to use
    ///
    /// Overridden via `$AWS_PROFILE`, defaults to `default`
    pub profile: Cow<'static, str>,
}

#[derive(Debug)]
/// In-memory configuration file
pub struct File {
    pub(crate) kind: EnvConfigFileKind,
    pub(crate) path: Option<String>,
    pub(crate) contents: String,
}

/// Load a [`Source`] from a given environment and filesystem.
pub async fn load(
    proc_env: &os_shim_internal::Env,
    fs: &os_shim_internal::Fs,
    profile_files: &EnvConfigFiles,
) -> Result<Source, EnvConfigFileLoadError> {
    let home = home_dir(proc_env, Os::real());

    let mut files = Vec::new();
    for file in &profile_files.files {
        let file = load_config_file(file, &home, fs, proc_env)
            .instrument(tracing::debug_span!("load_config_file", file = ?file))
            .await?;
        files.push(file);
    }

    Ok(Source {
        files,
        profile: proc_env
            .get("AWS_PROFILE")
            .map(Cow::Owned)
            .unwrap_or(Cow::Borrowed("default")),
    })
}

fn file_contents_to_string(path: &Path, contents: Vec<u8>) -> String {
    // if the file is not valid utf-8, log a warning and use an empty file instead
    match String::from_utf8(contents) {
        Ok(contents) => contents,
        Err(e) => {
            tracing::warn!(path = ?path, error = %DisplayErrorContext(&e), "config file did not contain utf-8 encoded data");
            Default::default()
        }
    }
}

/// Loads an AWS Config file
///
/// Both the default & the overriding patterns may contain `~/` which MUST be expanded to the users
/// home directory in a platform-aware way (see [`expand_home`]).
///
/// Arguments:
/// * `kind`: The type of config file to load
/// * `home_directory`: Home directory to use during home directory expansion
/// * `fs`: Filesystem abstraction
/// * `environment`: Process environment abstraction
async fn load_config_file(
    source: &EnvConfigFile,
    home_directory: &Option<String>,
    fs: &os_shim_internal::Fs,
    environment: &os_shim_internal::Env,
) -> Result<File, EnvConfigFileLoadError> {
    let (path, kind, contents) = match source {
        EnvConfigFile::Default(kind) => {
            let (path_is_default, path) = environment
                .get(kind.override_environment_variable())
                .map(|p| (false, Cow::Owned(p)))
                .ok()
                .unwrap_or_else(|| (true, kind.default_path().into()));
            let expanded = expand_home(path.as_ref(), path_is_default, home_directory);
            if path != expanded.to_string_lossy() {
                tracing::debug!(before = ?path, after = ?expanded, "home directory expanded");
            }
            // read the data at the specified path
            // if the path does not exist, log a warning but pretend it was actually an empty file
            let data = match fs.read_to_end(&expanded).await {
                Ok(data) => data,
                Err(e) => {
                    // Important: The default config/credentials files MUST NOT return an error
                    match e.kind() {
                        ErrorKind::NotFound if path == kind.default_path() => {
                            tracing::debug!(path = %path, "config file not found")
                        }
                        ErrorKind::NotFound if path != kind.default_path() => {
                            // in the case where the user overrode the path with an environment variable,
                            // log more loudly than the case where the default path was missing
                            tracing::warn!(path = %path, env = %kind.override_environment_variable(), "config file overridden via environment variable not found")
                        }
                        _other => {
                            tracing::warn!(path = %path, error = %DisplayErrorContext(&e), "failed to read config file")
                        }
                    };
                    Default::default()
                }
            };
            let contents = file_contents_to_string(&expanded, data);
            (Some(Cow::Owned(expanded)), kind, contents)
        }
        EnvConfigFile::FilePath { kind, path } => {
            let data = match fs.read_to_end(&path).await {
                Ok(data) => data,
                Err(e) => {
                    return Err(EnvConfigFileLoadError::CouldNotReadFile(
                        CouldNotReadConfigFile {
                            path: path.clone(),
                            cause: Arc::new(e),
                        },
                    ))
                }
            };
            (
                Some(Cow::Borrowed(path)),
                kind,
                file_contents_to_string(path, data),
            )
        }
        EnvConfigFile::FileContents { kind, contents } => (None, kind, contents.clone()),
    };
    tracing::debug!(path = ?path, size = ?contents.len(), "config file loaded");
    Ok(File {
        kind: *kind,
        // lossy is OK here, the name of this file is just for debugging purposes
        path: path.map(|p| p.to_string_lossy().into()),
        contents,
    })
}

fn expand_home(
    path: impl AsRef<Path>,
    path_is_default: bool,
    home_dir: &Option<String>,
) -> PathBuf {
    let path = path.as_ref();
    let mut components = path.components();
    let start = components.next();
    match start {
        None => path.into(), // empty path,
        Some(Component::Normal(s)) if s == "~" => {
            // do homedir replacement
            let path = match home_dir {
                Some(dir) => {
                    tracing::debug!(home = ?dir, path = ?path, "performing home directory substitution");
                    dir.clone()
                }
                None => {
                    // Only log a warning if the path was explicitly set by the customer.
                    if !path_is_default {
                        warn!(HOME_EXPANSION_FAILURE_WARNING);
                    }
                    // if we can't determine the home directory, just leave it as `~`
                    "~".into()
                }
            };
            let mut path: PathBuf = path.into();
            // rewrite the path using system-specific path separators
            for component in components {
                path.push(component);
            }
            path
        }
        // Finally, handle the case where it doesn't begin with some version of `~/`:
        // NOTE: in this case we aren't performing path rewriting. This is correct because
        // this path comes from an environment variable on the target
        // platform, so in that case, the separators should already be correct.
        _other => path.into(),
    }
}

#[cfg(test)]
mod tests {
    use crate::env_config::error::EnvConfigFileLoadError;
    use crate::env_config::file::{EnvConfigFile, EnvConfigFileKind, EnvConfigFiles};
    use crate::env_config::source::{
        expand_home, load, load_config_file, HOME_EXPANSION_FAILURE_WARNING,
    };
    use aws_types::os_shim_internal::{Env, Fs};
    use futures_util::future::FutureExt;
    use serde::Deserialize;
    use std::collections::HashMap;
    use std::error::Error;
    use std::fs;
    use tracing_test::traced_test;

    #[test]
    fn only_expand_home_prefix() {
        // ~ is only expanded as a single component (currently)
        let path = "~aws/config";
        assert_eq!(
            expand_home(path, false, &None).to_str().unwrap(),
            "~aws/config"
        );
    }

    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "camelCase")]
    struct SourceTests {
        tests: Vec<TestCase>,
    }

    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "camelCase")]
    struct TestCase {
        name: String,
        environment: HashMap<String, String>,
        platform: String,
        profile: Option<String>,
        config_location: String,
        credentials_location: String,
    }

    /// Run all tests from file-location-tests.json
    #[test]
    fn run_tests() -> Result<(), Box<dyn Error>> {
        let tests = fs::read_to_string("test-data/file-location-tests.json")?;
        let tests: SourceTests = serde_json::from_str(&tests)?;
        for (i, test) in tests.tests.into_iter().enumerate() {
            eprintln!("test: {}", i);
            check(test)
                .now_or_never()
                .expect("these futures should never poll");
        }
        Ok(())
    }

    #[traced_test]
    #[test]
    fn logs_produced_default() {
        let env = Env::from_slice(&[("HOME", "/user/name")]);
        let mut fs = HashMap::new();
        fs.insert(
            "/user/name/.aws/config".to_string(),
            "[default]\nregion = us-east-1",
        );

        let fs = Fs::from_map(fs);

        let _src = load(&env, &fs, &Default::default()).now_or_never();
        assert!(logs_contain("config file loaded"));
        assert!(logs_contain("performing home directory substitution"));
    }

    #[traced_test]
    #[test]
    fn load_config_file_should_not_emit_warning_when_path_not_explicitly_set() {
        let env = Env::from_slice(&[]);
        let fs = Fs::from_slice(&[]);

        let _src = load_config_file(
            &EnvConfigFile::Default(EnvConfigFileKind::Config),
            &None,
            &fs,
            &env,
        )
        .now_or_never();
        assert!(!logs_contain(HOME_EXPANSION_FAILURE_WARNING));
    }

    #[traced_test]
    #[test]
    fn load_config_file_should_emit_warning_when_path_explicitly_set() {
        let env = Env::from_slice(&[("AWS_CONFIG_FILE", "~/some/path")]);
        let fs = Fs::from_slice(&[]);

        let _src = load_config_file(
            &EnvConfigFile::Default(EnvConfigFileKind::Config),
            &None,
            &fs,
            &env,
        )
        .now_or_never();
        assert!(logs_contain(HOME_EXPANSION_FAILURE_WARNING));
    }

    async fn check(test_case: TestCase) {
        let fs = Fs::real();
        let env = Env::from(test_case.environment);
        let platform_matches = (cfg!(windows) && test_case.platform == "windows")
            || (!cfg!(windows) && test_case.platform != "windows");
        if platform_matches {
            let source = load(&env, &fs, &Default::default()).await.unwrap();
            if let Some(expected_profile) = test_case.profile {
                assert_eq!(source.profile, expected_profile, "{}", &test_case.name);
            }
            assert_eq!(
                source.files[0].path,
                Some(test_case.config_location),
                "{}",
                &test_case.name
            );
            assert_eq!(
                source.files[1].path,
                Some(test_case.credentials_location),
                "{}",
                &test_case.name
            )
        } else {
            println!(
                "NOTE: ignoring test case for {} which does not apply to our platform: \n  {}",
                &test_case.platform, &test_case.name
            )
        }
    }

    #[test]
    #[cfg_attr(windows, ignore)]
    fn test_expand_home() {
        let path = "~/.aws/config";
        assert_eq!(
            expand_home(path, false, &Some("/user/foo".to_string()))
                .to_str()
                .unwrap(),
            "/user/foo/.aws/config"
        );
    }

    #[test]
    fn expand_home_no_home() {
        // there is an edge case around expansion when no home directory exists
        // if no home directory can be determined, leave the path as is
        if !cfg!(windows) {
            assert_eq!(
                expand_home("~/config", false, &None).to_str().unwrap(),
                "~/config"
            )
        } else {
            assert_eq!(
                expand_home("~/config", false, &None).to_str().unwrap(),
                "~\\config"
            )
        }
    }

    /// Test that a linux oriented path expands on windows
    #[test]
    #[cfg_attr(not(windows), ignore)]
    fn test_expand_home_windows() {
        let path = "~/.aws/config";
        assert_eq!(
            expand_home(path, true, &Some("C:\\Users\\name".to_string()),)
                .to_str()
                .unwrap(),
            "C:\\Users\\name\\.aws\\config"
        );
    }

    #[tokio::test]
    async fn programmatically_set_credentials_file_contents() {
        let contents = "[default]\n\
            aws_access_key_id = AKIAFAKE\n\
            aws_secret_access_key = FAKE\n\
            ";
        let env = Env::from_slice(&[]);
        let fs = Fs::from_slice(&[]);
        let profile_files = EnvConfigFiles::builder()
            .with_contents(EnvConfigFileKind::Credentials, contents)
            .build();
        let source = load(&env, &fs, &profile_files).await.unwrap();
        assert_eq!(1, source.files.len());
        assert_eq!("default", source.profile);
        assert_eq!(contents, source.files[0].contents);
    }

    #[tokio::test]
    async fn programmatically_set_credentials_file_path() {
        let contents = "[default]\n\
            aws_access_key_id = AKIAFAKE\n\
            aws_secret_access_key = FAKE\n\
            ";
        let mut fs = HashMap::new();
        fs.insert(
            "/custom/path/to/credentials".to_string(),
            contents.to_string(),
        );

        let fs = Fs::from_map(fs);
        let env = Env::from_slice(&[]);
        let profile_files = EnvConfigFiles::builder()
            .with_file(
                EnvConfigFileKind::Credentials,
                "/custom/path/to/credentials",
            )
            .build();
        let source = load(&env, &fs, &profile_files).await.unwrap();
        assert_eq!(1, source.files.len());
        assert_eq!("default", source.profile);
        assert_eq!(contents, source.files[0].contents);
    }

    // TODO(https://github.com/awslabs/aws-sdk-rust/issues/1117) This test is ignored on Windows because it uses Unix-style paths
    #[tokio::test]
    #[cfg_attr(windows, ignore)]
    async fn programmatically_include_default_files() {
        let config_contents = "[default]\nregion = us-east-1";
        let credentials_contents = "[default]\n\
            aws_access_key_id = AKIAFAKE\n\
            aws_secret_access_key = FAKE\n\
            ";
        let custom_contents = "[profile some-profile]\n\
            aws_access_key_id = AKIAFAKEOTHER\n\
            aws_secret_access_key = FAKEOTHER\n\
            ";
        let mut fs = HashMap::new();
        fs.insert(
            "/user/name/.aws/config".to_string(),
            config_contents.to_string(),
        );
        fs.insert(
            "/user/name/.aws/credentials".to_string(),
            credentials_contents.to_string(),
        );

        let fs = Fs::from_map(fs);
        let env = Env::from_slice(&[("HOME", "/user/name")]);
        let profile_files = EnvConfigFiles::builder()
            .with_contents(EnvConfigFileKind::Config, custom_contents)
            .include_default_credentials_file(true)
            .include_default_config_file(true)
            .build();
        let source = load(&env, &fs, &profile_files).await.unwrap();
        assert_eq!(3, source.files.len());
        assert_eq!("default", source.profile);
        assert_eq!(config_contents, source.files[0].contents);
        assert_eq!(credentials_contents, source.files[1].contents);
        assert_eq!(custom_contents, source.files[2].contents);
    }

    #[tokio::test]
    async fn default_files_must_not_error() {
        let custom_contents = "[profile some-profile]\n\
            aws_access_key_id = AKIAFAKEOTHER\n\
            aws_secret_access_key = FAKEOTHER\n\
            ";

        let fs = Fs::from_slice(&[]);
        let env = Env::from_slice(&[("HOME", "/user/name")]);
        let profile_files = EnvConfigFiles::builder()
            .with_contents(EnvConfigFileKind::Config, custom_contents)
            .include_default_credentials_file(true)
            .include_default_config_file(true)
            .build();
        let source = load(&env, &fs, &profile_files).await.unwrap();
        assert_eq!(3, source.files.len());
        assert_eq!("default", source.profile);
        assert_eq!("", source.files[0].contents);
        assert_eq!("", source.files[1].contents);
        assert_eq!(custom_contents, source.files[2].contents);
    }

    #[tokio::test]
    async fn misconfigured_programmatic_custom_profile_path_must_error() {
        let fs = Fs::from_slice(&[]);
        let env = Env::from_slice(&[]);
        let profile_files = EnvConfigFiles::builder()
            .with_file(EnvConfigFileKind::Config, "definitely-doesnt-exist")
            .build();
        assert!(matches!(
            load(&env, &fs, &profile_files).await,
            Err(EnvConfigFileLoadError::CouldNotReadFile(_))
        ));
    }
}