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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use crate::credential_process::CommandWithSensitiveArgs;
use crate::profile::credentials::ProfileFileError;
use crate::profile::{Profile, ProfileSet};
use aws_credential_types::Credentials;
#[derive(Debug)]
pub(super) struct ProfileChain<'a> {
pub(super) base: BaseProvider<'a>,
pub(super) chain: Vec<RoleArn<'a>>,
}
impl<'a> ProfileChain<'a> {
pub(super) fn base(&self) -> &BaseProvider<'a> {
&self.base
}
pub(super) fn chain(&self) -> &[RoleArn<'a>] {
self.chain.as_slice()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub(super) enum BaseProvider<'a> {
NamedSource(&'a str),
AccessKey(Credentials),
WebIdentityTokenRole {
role_arn: &'a str,
web_identity_token_file: &'a str,
session_name: Option<&'a str>,
},
Sso {
sso_account_id: &'a str,
sso_region: &'a str,
sso_role_name: &'a str,
sso_start_url: &'a str,
},
CredentialProcess(CommandWithSensitiveArgs<&'a str>),
}
#[derive(Debug)]
pub(super) struct RoleArn<'a> {
pub(super) role_arn: &'a str,
pub(super) external_id: Option<&'a str>,
pub(super) session_name: Option<&'a str>,
}
pub(super) fn resolve_chain(
profile_set: &ProfileSet,
) -> Result<ProfileChain<'_>, ProfileFileError> {
if profile_set.is_empty() {
return Err(ProfileFileError::NoProfilesDefined);
}
if profile_set.selected_profile() == "default" && profile_set.get_profile("default").is_none() {
tracing::debug!("No default profile defined");
return Err(ProfileFileError::NoProfilesDefined);
}
let mut source_profile_name = profile_set.selected_profile();
let mut visited_profiles = vec![];
let mut chain = vec![];
let base = loop {
let profile = profile_set.get_profile(source_profile_name).ok_or(
ProfileFileError::MissingProfile {
profile: source_profile_name.into(),
message: format!(
"could not find source profile {} referenced from {}",
source_profile_name,
visited_profiles.last().unwrap_or(&"the root profile")
)
.into(),
},
)?;
if visited_profiles.contains(&source_profile_name) {
return Err(ProfileFileError::CredentialLoop {
profiles: visited_profiles
.into_iter()
.map(|s| s.to_string())
.collect(),
next: source_profile_name.to_string(),
});
}
visited_profiles.push(source_profile_name);
if visited_profiles.len() > 1 {
let try_static = static_creds_from_profile(profile);
if let Ok(static_credentials) = try_static {
break BaseProvider::AccessKey(static_credentials);
}
}
let next_profile = {
if let Some(role_provider) = role_arn_from_profile(profile) {
let next = chain_provider(profile)?;
chain.push(role_provider);
next
} else {
break base_provider(profile).map_err(|err| {
if visited_profiles.len() == 1 {
err
} else {
ProfileFileError::InvalidCredentialSource {
profile: profile.name().into(),
message: format!("could not load source profile: {}", err).into(),
}
}
})?;
}
};
match next_profile {
NextProfile::SelfReference => {
break base_provider(profile)?;
}
NextProfile::Named(name) => source_profile_name = name,
}
};
chain.reverse();
Ok(ProfileChain { base, chain })
}
mod role {
pub(super) const ROLE_ARN: &str = "role_arn";
pub(super) const EXTERNAL_ID: &str = "external_id";
pub(super) const SESSION_NAME: &str = "role_session_name";
pub(super) const CREDENTIAL_SOURCE: &str = "credential_source";
pub(super) const SOURCE_PROFILE: &str = "source_profile";
}
mod sso {
pub(super) const ACCOUNT_ID: &str = "sso_account_id";
pub(super) const REGION: &str = "sso_region";
pub(super) const ROLE_NAME: &str = "sso_role_name";
pub(super) const START_URL: &str = "sso_start_url";
}
mod web_identity_token {
pub(super) const TOKEN_FILE: &str = "web_identity_token_file";
}
mod static_credentials {
pub(super) const AWS_ACCESS_KEY_ID: &str = "aws_access_key_id";
pub(super) const AWS_SECRET_ACCESS_KEY: &str = "aws_secret_access_key";
pub(super) const AWS_SESSION_TOKEN: &str = "aws_session_token";
}
mod credential_process {
pub(super) const CREDENTIAL_PROCESS: &str = "credential_process";
}
const PROVIDER_NAME: &str = "ProfileFile";
fn base_provider(profile: &Profile) -> Result<BaseProvider<'_>, ProfileFileError> {
match profile.get(role::CREDENTIAL_SOURCE) {
Some(source) => Ok(BaseProvider::NamedSource(source)),
None => web_identity_token_from_profile(profile)
.or_else(|| sso_from_profile(profile))
.or_else(|| credential_process_from_profile(profile))
.unwrap_or_else(|| Ok(BaseProvider::AccessKey(static_creds_from_profile(profile)?))),
}
}
enum NextProfile<'a> {
SelfReference,
Named(&'a str),
}
fn chain_provider(profile: &Profile) -> Result<NextProfile<'_>, ProfileFileError> {
let (source_profile, credential_source) = (
profile.get(role::SOURCE_PROFILE),
profile.get(role::CREDENTIAL_SOURCE),
);
match (source_profile, credential_source) {
(Some(_), Some(_)) => Err(ProfileFileError::InvalidCredentialSource {
profile: profile.name().to_string(),
message: "profile contained both source_profile and credential_source. \
Only one or the other can be defined"
.into(),
}),
(None, None) => Err(ProfileFileError::InvalidCredentialSource {
profile: profile.name().to_string(),
message:
"profile must contain `source_profile` or `credential_source` but neither were defined"
.into(),
}),
(Some(source_profile), None) if source_profile == profile.name() => {
Ok(NextProfile::SelfReference)
}
(Some(source_profile), None) => Ok(NextProfile::Named(source_profile)),
(None, Some(_credential_source)) => Ok(NextProfile::SelfReference),
}
}
fn role_arn_from_profile(profile: &Profile) -> Option<RoleArn<'_>> {
if profile.get(web_identity_token::TOKEN_FILE).is_some() {
return None;
}
let role_arn = profile.get(role::ROLE_ARN)?;
let session_name = profile.get(role::SESSION_NAME);
let external_id = profile.get(role::EXTERNAL_ID);
Some(RoleArn {
role_arn,
external_id,
session_name,
})
}
fn sso_from_profile(profile: &Profile) -> Option<Result<BaseProvider<'_>, ProfileFileError>> {
let account_id = profile.get(sso::ACCOUNT_ID);
let region = profile.get(sso::REGION);
let role_name = profile.get(sso::ROLE_NAME);
let start_url = profile.get(sso::START_URL);
if [account_id, region, role_name, start_url]
.iter()
.all(|field| field.is_none())
{
return None;
}
let missing_field = |s| move || ProfileFileError::missing_field(profile, s);
let parse_profile = || {
let sso_account_id = account_id.ok_or_else(missing_field(sso::ACCOUNT_ID))?;
let sso_region = region.ok_or_else(missing_field(sso::REGION))?;
let sso_role_name = role_name.ok_or_else(missing_field(sso::ROLE_NAME))?;
let sso_start_url = start_url.ok_or_else(missing_field(sso::START_URL))?;
Ok(BaseProvider::Sso {
sso_account_id,
sso_region,
sso_role_name,
sso_start_url,
})
};
Some(parse_profile())
}
fn web_identity_token_from_profile(
profile: &Profile,
) -> Option<Result<BaseProvider<'_>, ProfileFileError>> {
let session_name = profile.get(role::SESSION_NAME);
match (
profile.get(role::ROLE_ARN),
profile.get(web_identity_token::TOKEN_FILE),
) {
(Some(role_arn), Some(token_file)) => Some(Ok(BaseProvider::WebIdentityTokenRole {
role_arn,
web_identity_token_file: token_file,
session_name,
})),
(None, None) => None,
(Some(_role_arn), None) => None,
(None, Some(_token_file)) => Some(Err(ProfileFileError::InvalidCredentialSource {
profile: profile.name().to_string(),
message: "`web_identity_token_file` was specified but `role_arn` was missing".into(),
})),
}
}
fn static_creds_from_profile(profile: &Profile) -> Result<Credentials, ProfileFileError> {
use static_credentials::*;
let access_key = profile.get(AWS_ACCESS_KEY_ID);
let secret_key = profile.get(AWS_SECRET_ACCESS_KEY);
let session_token = profile.get(AWS_SESSION_TOKEN);
if let (None, None, None) = (access_key, secret_key, session_token) {
return Err(ProfileFileError::ProfileDidNotContainCredentials {
profile: profile.name().to_string(),
});
}
let access_key = access_key.ok_or_else(|| ProfileFileError::InvalidCredentialSource {
profile: profile.name().to_string(),
message: "profile missing aws_access_key_id".into(),
})?;
let secret_key = secret_key.ok_or_else(|| ProfileFileError::InvalidCredentialSource {
profile: profile.name().to_string(),
message: "profile missing aws_secret_access_key".into(),
})?;
Ok(Credentials::new(
access_key,
secret_key,
session_token.map(|s| s.to_string()),
None,
PROVIDER_NAME,
))
}
fn credential_process_from_profile(
profile: &Profile,
) -> Option<Result<BaseProvider<'_>, ProfileFileError>> {
profile
.get(credential_process::CREDENTIAL_PROCESS)
.map(|credential_process| {
Ok(BaseProvider::CredentialProcess(
CommandWithSensitiveArgs::new(credential_process),
))
})
}
#[cfg(test)]
mod tests {
use crate::credential_process::CommandWithSensitiveArgs;
use crate::profile::credentials::repr::{resolve_chain, BaseProvider, ProfileChain};
use crate::profile::ProfileSet;
use serde::Deserialize;
use std::collections::HashMap;
use std::error::Error;
use std::fs;
#[test]
fn run_test_cases() -> Result<(), Box<dyn Error>> {
let test_cases: Vec<TestCase> =
serde_json::from_str(&fs::read_to_string("./test-data/assume-role-tests.json")?)?;
for test_case in test_cases {
print!("checking: {}...", test_case.docs);
check(test_case);
println!("ok")
}
Ok(())
}
fn check(test_case: TestCase) {
let source = ProfileSet::new(test_case.input.profile, test_case.input.selected_profile);
let actual = resolve_chain(&source);
let expected = test_case.output;
match (expected, actual) {
(TestOutput::Error(s), Err(e)) => assert!(
format!("{}", e).contains(&s),
"expected\n{}\nto contain\n{}\n",
e,
s
),
(TestOutput::ProfileChain(expected), Ok(actual)) => {
assert_eq!(to_test_output(actual), expected)
}
(expected, actual) => panic!(
"error/success mismatch. Expected:\n {:?}\nActual:\n {:?}",
&expected, actual
),
}
}
#[derive(Deserialize)]
struct TestCase {
docs: String,
input: TestInput,
output: TestOutput,
}
#[derive(Deserialize)]
struct TestInput {
profile: HashMap<String, HashMap<String, String>>,
selected_profile: String,
}
fn to_test_output(profile_chain: ProfileChain<'_>) -> Vec<Provider> {
let mut output = vec![];
match profile_chain.base {
BaseProvider::NamedSource(name) => output.push(Provider::NamedSource(name.into())),
BaseProvider::AccessKey(creds) => output.push(Provider::AccessKey {
access_key_id: creds.access_key_id().into(),
secret_access_key: creds.secret_access_key().into(),
session_token: creds.session_token().map(|tok| tok.to_string()),
}),
BaseProvider::CredentialProcess(credential_process) => output.push(
Provider::CredentialProcess(credential_process.unredacted().into()),
),
BaseProvider::WebIdentityTokenRole {
role_arn,
web_identity_token_file,
session_name,
} => output.push(Provider::WebIdentityToken {
role_arn: role_arn.into(),
web_identity_token_file: web_identity_token_file.into(),
role_session_name: session_name.map(|sess| sess.to_string()),
}),
BaseProvider::Sso {
sso_account_id,
sso_region,
sso_role_name,
sso_start_url,
} => output.push(Provider::Sso {
sso_account_id: sso_account_id.into(),
sso_region: sso_region.into(),
sso_role_name: sso_role_name.into(),
sso_start_url: sso_start_url.into(),
}),
};
for role in profile_chain.chain {
output.push(Provider::AssumeRole {
role_arn: role.role_arn.into(),
external_id: role.external_id.map(ToString::to_string),
role_session_name: role.session_name.map(ToString::to_string),
})
}
output
}
#[derive(Deserialize, Debug, PartialEq, Eq)]
enum TestOutput {
ProfileChain(Vec<Provider>),
Error(String),
}
#[derive(Deserialize, Debug, Eq, PartialEq)]
enum Provider {
AssumeRole {
role_arn: String,
external_id: Option<String>,
role_session_name: Option<String>,
},
AccessKey {
access_key_id: String,
secret_access_key: String,
session_token: Option<String>,
},
NamedSource(String),
CredentialProcess(String),
WebIdentityToken {
role_arn: String,
web_identity_token_file: String,
role_session_name: Option<String>,
},
Sso {
sso_account_id: String,
sso_region: String,
sso_role_name: String,
sso_start_url: String,
},
}
#[test]
fn base_provider_process_credentials_args_redaction() {
assert_eq!(
"CredentialProcess(\"program\")",
format!(
"{:?}",
BaseProvider::CredentialProcess(CommandWithSensitiveArgs::new("program"))
)
);
assert_eq!(
"CredentialProcess(\"program ** arguments redacted **\")",
format!(
"{:?}",
BaseProvider::CredentialProcess(CommandWithSensitiveArgs::new("program arg1 arg2"))
)
);
assert_eq!(
"CredentialProcess(\"program ** arguments redacted **\")",
format!(
"{:?}",
BaseProvider::CredentialProcess(CommandWithSensitiveArgs::new(
"program\targ1 arg2"
))
)
);
}
}