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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use std::env::VarError;

use aws_credential_types::provider::{self, error::CredentialsError, future, ProvideCredentials};
use aws_credential_types::Credentials;
use aws_types::os_shim_internal::Env;

/// Load Credentials from Environment Variables
///
/// `EnvironmentVariableCredentialsProvider` uses the following variables:
/// - `AWS_ACCESS_KEY_ID`
/// - `AWS_SECRET_ACCESS_KEY` with fallback to `SECRET_ACCESS_KEY`
/// - `AWS_SESSION_TOKEN`
#[derive(Debug, Clone)]
pub struct EnvironmentVariableCredentialsProvider {
    env: Env,
}

impl EnvironmentVariableCredentialsProvider {
    fn credentials(&self) -> provider::Result {
        let access_key = self
            .env
            .get("AWS_ACCESS_KEY_ID")
            .and_then(err_if_blank)
            .map_err(to_cred_error)?;
        let secret_key = self
            .env
            .get("AWS_SECRET_ACCESS_KEY")
            .and_then(err_if_blank)
            .or_else(|_| self.env.get("SECRET_ACCESS_KEY"))
            .and_then(err_if_blank)
            .map_err(to_cred_error)?;
        let session_token =
            self.env
                .get("AWS_SESSION_TOKEN")
                .ok()
                .and_then(|token| match token.trim() {
                    "" => None,
                    s => Some(s.to_string()),
                });
        Ok(Credentials::new(
            access_key,
            secret_key,
            session_token,
            None,
            ENV_PROVIDER,
        ))
    }
}

impl EnvironmentVariableCredentialsProvider {
    /// Create a `EnvironmentVariableCredentialsProvider`
    pub fn new() -> Self {
        Self::new_with_env(Env::real())
    }

    /// Create a new `EnvironmentVariableCredentialsProvider` with `Env` overridden
    ///
    /// This function is intended for tests that mock out the process environment.
    pub(crate) fn new_with_env(env: Env) -> Self {
        Self { env }
    }
}

impl Default for EnvironmentVariableCredentialsProvider {
    fn default() -> Self {
        Self::new()
    }
}

const ENV_PROVIDER: &str = "EnvironmentVariable";

impl ProvideCredentials for EnvironmentVariableCredentialsProvider {
    fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
    where
        Self: 'a,
    {
        future::ProvideCredentials::ready(self.credentials())
    }
}

fn to_cred_error(err: VarError) -> CredentialsError {
    match err {
        VarError::NotPresent => CredentialsError::not_loaded("environment variable not set"),
        e @ VarError::NotUnicode(_) => CredentialsError::unhandled(e),
    }
}

fn err_if_blank(value: String) -> Result<String, VarError> {
    if value.trim().is_empty() {
        Err(VarError::NotPresent)
    } else {
        Ok(value)
    }
}

#[cfg(test)]
mod test {
    use aws_credential_types::provider::{error::CredentialsError, ProvideCredentials};
    use aws_types::os_shim_internal::Env;
    use futures_util::FutureExt;

    use super::EnvironmentVariableCredentialsProvider;

    fn make_provider(vars: &[(&str, &str)]) -> EnvironmentVariableCredentialsProvider {
        EnvironmentVariableCredentialsProvider {
            env: Env::from_slice(vars),
        }
    }

    #[test]
    fn valid_no_token() {
        let provider = make_provider(&[
            ("AWS_ACCESS_KEY_ID", "access"),
            ("AWS_SECRET_ACCESS_KEY", "secret"),
        ]);
        let creds = provider
            .provide_credentials()
            .now_or_never()
            .unwrap()
            .expect("valid credentials");
        assert_eq!(creds.session_token(), None);
        assert_eq!(creds.access_key_id(), "access");
        assert_eq!(creds.secret_access_key(), "secret");
    }

    #[test]
    fn valid_with_token() {
        let provider = make_provider(&[
            ("AWS_ACCESS_KEY_ID", "access"),
            ("AWS_SECRET_ACCESS_KEY", "secret"),
            ("AWS_SESSION_TOKEN", "token"),
        ]);

        let creds = provider
            .provide_credentials()
            .now_or_never()
            .unwrap()
            .expect("valid credentials");
        assert_eq!(creds.session_token().unwrap(), "token");
        assert_eq!(creds.access_key_id(), "access");
        assert_eq!(creds.secret_access_key(), "secret");
    }

    #[test]
    fn empty_token_env_var() {
        for token_value in &["", " "] {
            let provider = make_provider(&[
                ("AWS_ACCESS_KEY_ID", "access"),
                ("AWS_SECRET_ACCESS_KEY", "secret"),
                ("AWS_SESSION_TOKEN", token_value),
            ]);

            let creds = provider
                .provide_credentials()
                .now_or_never()
                .unwrap()
                .expect("valid credentials");
            assert_eq!(creds.access_key_id(), "access");
            assert_eq!(creds.secret_access_key(), "secret");
            assert_eq!(creds.session_token(), None);
        }
    }

    #[test]
    fn secret_key_fallback() {
        let provider = make_provider(&[
            ("AWS_ACCESS_KEY_ID", "access"),
            ("SECRET_ACCESS_KEY", "secret"),
            ("AWS_SESSION_TOKEN", "token"),
        ]);

        let creds = provider
            .provide_credentials()
            .now_or_never()
            .unwrap()
            .expect("valid credentials");
        assert_eq!(creds.session_token().unwrap(), "token");
        assert_eq!(creds.access_key_id(), "access");
        assert_eq!(creds.secret_access_key(), "secret");
    }

    #[test]
    fn secret_key_fallback_empty() {
        let provider = make_provider(&[
            ("AWS_ACCESS_KEY_ID", "access"),
            ("AWS_SECRET_ACCESS_KEY", " "),
            ("SECRET_ACCESS_KEY", "secret"),
            ("AWS_SESSION_TOKEN", "token"),
        ]);

        let creds = provider
            .provide_credentials()
            .now_or_never()
            .unwrap()
            .expect("valid credentials");
        assert_eq!(creds.session_token().unwrap(), "token");
        assert_eq!(creds.access_key_id(), "access");
        assert_eq!(creds.secret_access_key(), "secret");
    }

    #[test]
    fn missing() {
        let provider = make_provider(&[]);
        let err = provider
            .provide_credentials()
            .now_or_never()
            .unwrap()
            .expect_err("no credentials defined");
        assert!(matches!(err, CredentialsError::CredentialsNotLoaded { .. }));
    }

    #[test]
    fn empty_keys_env_vars() {
        for [access_key_value, secret_key_value] in &[
            &["", ""],
            &[" ", ""],
            &["access", ""],
            &["", " "],
            &[" ", " "],
            &["access", " "],
            &["", "secret"],
            &[" ", "secret"],
        ] {
            let provider = make_provider(&[
                ("AWS_ACCESS_KEY_ID", access_key_value),
                ("AWS_SECRET_ACCESS_KEY", secret_key_value),
            ]);

            let err = provider
                .provide_credentials()
                .now_or_never()
                .unwrap()
                .expect_err("no credentials defined");
            assert!(matches!(err, CredentialsError::CredentialsNotLoaded { .. }));
        }
    }

    #[test]
    fn real_environment() {
        let provider = EnvironmentVariableCredentialsProvider::new();
        // we don't know what's in the env, just make sure it doesn't crash.
        let _fut = provider.provide_credentials();
    }
}