reqsign-aws-core 3.2.0

Shared AWS credential and request canonicalization support for reqsign.
Documentation
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::Credential;
#[cfg(not(target_arch = "wasm32"))]
use crate::constants::*;
#[cfg(not(target_arch = "wasm32"))]
use ini::Ini;
#[cfg(not(target_arch = "wasm32"))]
use log::debug;
#[cfg(not(target_arch = "wasm32"))]
use reqsign_core::Error;
use reqsign_core::{Context, ProvideCredential, Result};

/// ProfileCredentialProvider loads AWS credentials from configuration files.
///
/// This provider loads credentials from:
/// - `~/.aws/credentials` (or the path specified by `AWS_SHARED_CREDENTIALS_FILE`)
/// - `~/.aws/config` (or the path specified by `AWS_CONFIG_FILE`)
///
/// The profile to use is determined by:
/// 1. The profile specified via `with_profile()`
/// 2. The `AWS_PROFILE` environment variable
/// 3. Default to "default"
#[derive(Debug, Clone)]
pub struct ProfileCredentialProvider {
    profile: Option<String>,
    config_file: Option<String>,
    credentials_file: Option<String>,
}

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

impl ProfileCredentialProvider {
    /// Create a new ProfileCredentialProvider with default settings.
    pub fn new() -> Self {
        Self {
            profile: None,
            config_file: None,
            credentials_file: None,
        }
    }

    /// Set the profile name to use.
    pub fn with_profile(mut self, profile: impl Into<String>) -> Self {
        self.profile = Some(profile.into());
        self
    }

    /// Set the path to the config file.
    pub fn with_config_file(mut self, path: impl Into<String>) -> Self {
        self.config_file = Some(path.into());
        self
    }

    /// Set the path to the credentials file.
    pub fn with_credentials_file(mut self, path: impl Into<String>) -> Self {
        self.credentials_file = Some(path.into());
        self
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn load_from_credentials_file(
        &self,
        ctx: &Context,
        profile: &str,
    ) -> Result<Option<Credential>> {
        let path = if let Some(path) = &self.credentials_file {
            path.clone()
        } else if let Some(path) = ctx.env_var(AWS_SHARED_CREDENTIALS_FILE) {
            path
        } else {
            "~/.aws/credentials".to_string()
        };

        let expanded_path = if path.starts_with("~/") {
            match ctx.expand_home_dir(&path) {
                Some(expanded) => expanded,
                None => {
                    debug!("failed to expand homedir for path: {path}");
                    return Ok(None);
                }
            }
        } else {
            path.clone()
        };

        let content = match ctx.file_read(&expanded_path).await {
            Ok(content) => content,
            Err(err) => {
                debug!("failed to read credentials file {expanded_path}: {err:?}");
                return Ok(None);
            }
        };

        let conf = Ini::load_from_str(&String::from_utf8_lossy(&content)).map_err(|e| {
            Error::config_invalid("failed to parse credentials file").with_source(e)
        })?;

        let props = match conf.section(Some(profile)) {
            Some(props) => props,
            None => {
                debug!("profile {profile} not found in credentials file");
                return Ok(None);
            }
        };

        let access_key_id = props.get("aws_access_key_id");
        let secret_access_key = props.get("aws_secret_access_key");

        match (access_key_id, secret_access_key) {
            (Some(ak), Some(sk)) => Ok(Some(Credential {
                access_key_id: ak.to_string(),
                secret_access_key: sk.to_string(),
                session_token: props.get("aws_session_token").map(|s| s.to_string()),
                expires_in: None,
            })),
            _ => Ok(None),
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn load_from_config_file(
        &self,
        ctx: &Context,
        profile: &str,
    ) -> Result<Option<Credential>> {
        let path = if let Some(path) = &self.config_file {
            path.clone()
        } else if let Some(path) = ctx.env_var(AWS_CONFIG_FILE) {
            path
        } else {
            "~/.aws/config".to_string()
        };

        let expanded_path = if path.starts_with("~/") {
            match ctx.expand_home_dir(&path) {
                Some(expanded) => expanded,
                None => {
                    debug!("failed to expand homedir for path: {path}");
                    return Ok(None);
                }
            }
        } else {
            path.clone()
        };

        let content = match ctx.file_read(&expanded_path).await {
            Ok(content) => content,
            Err(err) => {
                debug!("failed to read config file {expanded_path}: {err:?}");
                return Ok(None);
            }
        };

        let conf = Ini::load_from_str(&String::from_utf8_lossy(&content))
            .map_err(|e| Error::config_invalid("failed to parse config file").with_source(e))?;

        let section = match profile {
            "default" => "default".to_string(),
            x => format!("profile {x}"),
        };

        let props = match conf.section(Some(&section)) {
            Some(props) => props,
            None => {
                debug!("section {profile} not found in config file");
                return Ok(None);
            }
        };

        let access_key_id = props.get("aws_access_key_id");
        let secret_access_key = props.get("aws_secret_access_key");

        match (access_key_id, secret_access_key) {
            (Some(ak), Some(sk)) => Ok(Some(Credential {
                access_key_id: ak.to_string(),
                secret_access_key: sk.to_string(),
                session_token: props.get("aws_session_token").map(|s| s.to_string()),
                expires_in: None,
            })),
            _ => Ok(None),
        }
    }
}
impl ProvideCredential for ProfileCredentialProvider {
    type Credential = Credential;

    async fn provide_credential(&self, ctx: &Context) -> Result<Option<Self::Credential>> {
        #[cfg(target_arch = "wasm32")]
        {
            let _ = ctx;
            Ok(None)
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let profile = self
                .profile
                .clone()
                .or_else(|| ctx.env_var(AWS_PROFILE))
                .unwrap_or_else(|| "default".to_string());

            // Try credentials file first
            if let Some(cred) = self.load_from_credentials_file(ctx, &profile).await? {
                return Ok(Some(cred));
            }

            // Then try config file
            self.load_from_config_file(ctx, &profile).await
        }
    }
}

#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use reqsign_core::StaticEnv;
    use reqsign_file_read_tokio::TokioFileRead;
    use reqsign_http_send_reqwest::ReqwestHttpSend;
    use std::collections::HashMap;
    use std::fs::File;
    use std::io::Write;
    use tempfile::tempdir;

    #[tokio::test]
    async fn test_profile_from_credentials_file() -> anyhow::Result<()> {
        let _ = env_logger::builder().is_test(true).try_init();

        let tmp_dir = tempdir()?;
        let file_path = tmp_dir.path().join("credentials");
        let mut tmp_file = File::create(&file_path)?;
        writeln!(tmp_file, "[default]")?;
        writeln!(tmp_file, "aws_access_key_id = DEFAULTACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = DEFAULTSECRETACCESSKEY")?;
        writeln!(tmp_file, "aws_session_token = DEFAULTSESSIONTOKEN")?;
        writeln!(tmp_file)?;
        writeln!(tmp_file, "[profile1]")?;
        writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?;
        writeln!(tmp_file, "aws_session_token = PROFILE1SESSIONTOKEN")?;

        let context = Context::new()
            .with_file_read(TokioFileRead)
            .with_http_send(ReqwestHttpSend::default())
            .with_env(StaticEnv {
                home_dir: None,
                envs: HashMap::new(),
            });

        // Test the final default fallback without an explicit profile or AWS_PROFILE
        let provider =
            ProfileCredentialProvider::new().with_credentials_file(file_path.to_str().unwrap());
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_some());
        let cred = cred.unwrap();
        assert_eq!(cred.access_key_id, "DEFAULTACCESSKEYID");
        assert_eq!(cred.secret_access_key, "DEFAULTSECRETACCESSKEY");
        assert_eq!(cred.session_token, Some("DEFAULTSESSIONTOKEN".to_string()));

        // Test specific profile
        let provider = ProfileCredentialProvider::new()
            .with_profile("profile1")
            .with_credentials_file(file_path.to_str().unwrap());
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_some());
        let cred = cred.unwrap();
        assert_eq!(cred.access_key_id, "PROFILE1ACCESSKEYID");
        assert_eq!(cred.secret_access_key, "PROFILE1SECRETACCESSKEY");
        assert_eq!(cred.session_token, Some("PROFILE1SESSIONTOKEN".to_string()));

        Ok(())
    }

    #[tokio::test]
    async fn test_profile_from_config_file() -> anyhow::Result<()> {
        let _ = env_logger::builder().is_test(true).try_init();

        let tmp_dir = tempdir()?;
        let file_path = tmp_dir.path().join("config");
        let mut tmp_file = File::create(&file_path)?;
        writeln!(tmp_file, "[default]")?;
        writeln!(tmp_file, "aws_access_key_id = DEFAULTACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = DEFAULTSECRETACCESSKEY")?;
        writeln!(tmp_file)?;
        writeln!(tmp_file, "[profile profile1]")?;
        writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?;

        let context = Context::new()
            .with_file_read(TokioFileRead)
            .with_http_send(ReqwestHttpSend::default())
            .with_env(StaticEnv {
                home_dir: None,
                envs: HashMap::new(),
            });

        // Test default profile
        let provider =
            ProfileCredentialProvider::new().with_config_file(file_path.to_str().unwrap());
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_some());
        let cred = cred.unwrap();
        assert_eq!(cred.access_key_id, "DEFAULTACCESSKEYID");
        assert_eq!(cred.secret_access_key, "DEFAULTSECRETACCESSKEY");
        assert!(cred.session_token.is_none());

        // Test specific profile
        let provider = ProfileCredentialProvider::new()
            .with_profile("profile1")
            .with_config_file(file_path.to_str().unwrap());
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_some());
        let cred = cred.unwrap();
        assert_eq!(cred.access_key_id, "PROFILE1ACCESSKEYID");
        assert_eq!(cred.secret_access_key, "PROFILE1SECRETACCESSKEY");
        assert!(cred.session_token.is_none());

        Ok(())
    }

    #[tokio::test]
    async fn test_profile_env_fallback() -> anyhow::Result<()> {
        let _ = env_logger::builder().is_test(true).try_init();

        let tmp_dir = tempdir()?;
        let file_path = tmp_dir.path().join("credentials");
        let mut tmp_file = File::create(&file_path)?;
        writeln!(tmp_file, "[default]")?;
        writeln!(tmp_file, "aws_access_key_id = DEFAULTACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = DEFAULTSECRETACCESSKEY")?;
        writeln!(tmp_file)?;
        writeln!(tmp_file, "[profile1]")?;
        writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?;

        let context = Context::new()
            .with_file_read(TokioFileRead)
            .with_http_send(ReqwestHttpSend::default())
            .with_env(StaticEnv {
                home_dir: None,
                envs: HashMap::from([(AWS_PROFILE.to_string(), "profile1".to_string())]),
            });

        let provider =
            ProfileCredentialProvider::new().with_credentials_file(file_path.to_str().unwrap());
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_some());
        let cred = cred.unwrap();
        assert_eq!(cred.access_key_id, "PROFILE1ACCESSKEYID");
        assert_eq!(cred.secret_access_key, "PROFILE1SECRETACCESSKEY");

        Ok(())
    }

    #[tokio::test]
    async fn test_explicit_profile_overrides_env() -> anyhow::Result<()> {
        let _ = env_logger::builder().is_test(true).try_init();

        let tmp_dir = tempdir()?;
        let file_path = tmp_dir.path().join("credentials");
        let mut tmp_file = File::create(&file_path)?;
        writeln!(tmp_file, "[default]")?;
        writeln!(tmp_file, "aws_access_key_id = DEFAULTACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = DEFAULTSECRETACCESSKEY")?;
        writeln!(tmp_file)?;
        writeln!(tmp_file, "[profile1]")?;
        writeln!(tmp_file, "aws_access_key_id = PROFILE1ACCESSKEYID")?;
        writeln!(tmp_file, "aws_secret_access_key = PROFILE1SECRETACCESSKEY")?;

        let context = Context::new()
            .with_file_read(TokioFileRead)
            .with_http_send(ReqwestHttpSend::default())
            .with_env(StaticEnv {
                home_dir: None,
                envs: HashMap::from([(AWS_PROFILE.to_string(), "profile1".to_string())]),
            });

        let provider = ProfileCredentialProvider::new()
            .with_profile("default")
            .with_credentials_file(file_path.to_str().unwrap());
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_some());
        let cred = cred.unwrap();
        assert_eq!(cred.access_key_id, "DEFAULTACCESSKEYID");
        assert_eq!(cred.secret_access_key, "DEFAULTSECRETACCESSKEY");

        Ok(())
    }

    #[tokio::test]
    async fn test_profile_missing_credentials() -> anyhow::Result<()> {
        let context = Context::new()
            .with_file_read(TokioFileRead)
            .with_http_send(ReqwestHttpSend::default());

        let provider = ProfileCredentialProvider::new()
            .with_credentials_file("/non/existent/path")
            .with_config_file("/non/existent/path");
        let cred = provider.provide_credential(&context).await?;
        assert!(cred.is_none());

        Ok(())
    }
}