forked from googleapis/google-auth-library-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AwsCredentialsTest.java
755 lines (625 loc) · 31.2 KB
/
AwsCredentialsTest.java
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/*
* Copyright 2021 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.auth.oauth2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonParser;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.auth.TestUtils;
import com.google.auth.oauth2.AwsCredentials.AwsCredentialSource;
import com.google.auth.oauth2.ExternalAccountCredentialsTest.MockExternalAccountCredentialsTransportFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link AwsCredentials}. */
@RunWith(JUnit4.class)
public class AwsCredentialsTest {
private static final String STS_URL = "https://sts.googleapis.com";
private static final String AWS_CREDENTIALS_URL = "https://www.aws-credentials.com";
private static final String AWS_CREDENTIALS_URL_WITH_ROLE =
"https://www.aws-credentials.com/roleName";
private static final String AWS_REGION_URL = "https://www.aws-region.com";
private static final String AWS_IMDSV2_SESSION_TOKEN_URL = "https://www.aws-session-token.com";
private static final String AWS_IMDSV2_SESSION_TOKEN = "sessiontoken";
private static final String GET_CALLER_IDENTITY_URL =
"https://sts.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";
private static final String SERVICE_ACCOUNT_IMPERSONATION_URL =
"https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/testn@test.iam.gserviceaccount.com:generateAccessToken";
private static final Map<String, Object> AWS_CREDENTIAL_SOURCE_MAP =
new HashMap<String, Object>() {
{
put("environment_id", "aws1");
put("region_url", "regionUrl");
put("url", "url");
put("regional_cred_verification_url", "regionalCredVerificationUrl");
}
};
private static final Map<String, Object> EMPTY_METADATA_HEADERS = Collections.emptyMap();
private static final Map<String, String> EMPTY_STRING_HEADERS = Collections.emptyMap();
private static final AwsCredentialSource AWS_CREDENTIAL_SOURCE =
new AwsCredentialSource(AWS_CREDENTIAL_SOURCE_MAP);
private static final AwsCredentials AWS_CREDENTIAL =
(AwsCredentials)
AwsCredentials.newBuilder()
.setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY)
.setAudience("audience")
.setSubjectTokenType("subjectTokenType")
.setTokenUrl(STS_URL)
.setTokenInfoUrl("tokenInfoUrl")
.setCredentialSource(AWS_CREDENTIAL_SOURCE)
.build();
@Test
public void refreshAccessToken_withoutServiceAccountImpersonation() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setTokenUrl(transportFactory.transport.getStsUrl())
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
AccessToken accessToken = awsCredential.refreshAccessToken();
assertEquals(transportFactory.transport.getAccessToken(), accessToken.getTokenValue());
}
@Test
public void refreshAccessToken_withServiceAccountImpersonation() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime());
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setTokenUrl(transportFactory.transport.getStsUrl())
.setServiceAccountImpersonationUrl(
transportFactory.transport.getServiceAccountImpersonationUrl())
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
AccessToken accessToken = awsCredential.refreshAccessToken();
assertEquals(
transportFactory.transport.getServiceAccountAccessToken(), accessToken.getTokenValue());
}
@Test
public void refreshAccessToken_withServiceAccountImpersonationOptions() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
transportFactory.transport.setExpireTime(TestUtils.getDefaultExpireTime());
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setTokenUrl(transportFactory.transport.getStsUrl())
.setServiceAccountImpersonationUrl(
transportFactory.transport.getServiceAccountImpersonationUrl())
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.setServiceAccountImpersonationOptions(
ExternalAccountCredentialsTest.buildServiceAccountImpersonationOptions(2800))
.build();
AccessToken accessToken = awsCredential.refreshAccessToken();
assertEquals(
transportFactory.transport.getServiceAccountAccessToken(), accessToken.getTokenValue());
// Validate that default lifetime was set correctly on the request.
GenericJson query =
OAuth2Utils.JSON_FACTORY
.createJsonParser(transportFactory.transport.getLastRequest().getContentAsString())
.parseAndClose(GenericJson.class);
assertEquals("2800s", query.get("lifetime"));
}
@Test
public void retrieveSubjectToken() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
String subjectToken = URLDecoder.decode(awsCredential.retrieveSubjectToken(), "UTF-8");
JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(subjectToken);
GenericJson json = parser.parseAndClose(GenericJson.class);
List<Map<String, String>> headersList = (List<Map<String, String>>) json.get("headers");
Map<String, String> headers = new HashMap<>();
for (Map<String, String> header : headersList) {
headers.put(header.get("key"), header.get("value"));
}
assertEquals("POST", json.get("method"));
assertEquals(GET_CALLER_IDENTITY_URL, json.get("url"));
assertEquals(URI.create(GET_CALLER_IDENTITY_URL).getHost(), headers.get("host"));
assertEquals("token", headers.get("x-amz-security-token"));
assertEquals(awsCredential.getAudience(), headers.get("x-goog-cloud-target-resource"));
assertTrue(headers.containsKey("x-amz-date"));
assertNotNull(headers.get("Authorization"));
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(3, requests.size());
// Validate region request.
ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS);
// Validate role request.
ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL, EMPTY_STRING_HEADERS);
// Validate security credentials request.
ValidateRequest(requests.get(2), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS);
}
@Test
public void retrieveSubjectTokenWithSessionTokenUrl() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
Map<String, Object> credentialSourceMap = new HashMap<>();
credentialSourceMap.put("environment_id", "aws1");
credentialSourceMap.put("region_url", transportFactory.transport.getAwsRegionUrl());
credentialSourceMap.put("url", transportFactory.transport.getAwsCredentialsUrl());
credentialSourceMap.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
credentialSourceMap.put(
"imdsv2_session_token_url", transportFactory.transport.getAwsImdsv2SessionTokenUrl());
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(new AwsCredentialSource(credentialSourceMap))
.build();
String subjectToken = URLDecoder.decode(awsCredential.retrieveSubjectToken(), "UTF-8");
JsonParser parser = OAuth2Utils.JSON_FACTORY.createJsonParser(subjectToken);
GenericJson json = parser.parseAndClose(GenericJson.class);
List<Map<String, String>> headersList = (List<Map<String, String>>) json.get("headers");
Map<String, String> headers = new HashMap<>();
for (Map<String, String> header : headersList) {
headers.put(header.get("key"), header.get("value"));
}
assertEquals("POST", json.get("method"));
assertEquals(GET_CALLER_IDENTITY_URL, json.get("url"));
assertEquals(URI.create(GET_CALLER_IDENTITY_URL).getHost(), headers.get("host"));
assertEquals("token", headers.get("x-amz-security-token"));
assertEquals(awsCredential.getAudience(), headers.get("x-goog-cloud-target-resource"));
assertTrue(headers.containsKey("x-amz-date"));
assertNotNull(headers.get("Authorization"));
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(4, requests.size());
// Validate the session token request
ValidateRequest(
requests.get(0),
AWS_IMDSV2_SESSION_TOKEN_URL,
new HashMap<String, String>() {
{
put(
AwsCredentials.AWS_IMDSV2_SESSION_TOKEN_TTL_HEADER,
AwsCredentials.AWS_IMDSV2_SESSION_TOKEN_TTL);
}
});
Map<String, String> sessionTokenHeader =
new HashMap<String, String>() {
{
put(AwsCredentials.AWS_IMDSV2_SESSION_TOKEN_HEADER, AWS_IMDSV2_SESSION_TOKEN);
}
};
// Validate region request.
ValidateRequest(requests.get(1), AWS_REGION_URL, sessionTokenHeader);
// Validate role request.
ValidateRequest(requests.get(2), AWS_CREDENTIALS_URL, sessionTokenHeader);
// Validate security credentials request.
ValidateRequest(requests.get(3), AWS_CREDENTIALS_URL_WITH_ROLE, sessionTokenHeader);
}
@Test
public void retrieveSubjectToken_noRegion_expectThrows() {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
IOException response = new IOException();
transportFactory.transport.addResponseErrorSequence(response);
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
try {
awsCredential.retrieveSubjectToken();
fail("Should not be able to use credential without exception.");
} catch (IOException exception) {
assertEquals("Failed to retrieve AWS region.", exception.getMessage());
}
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(1, requests.size());
// Validate region request.
ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS);
}
@Test
public void retrieveSubjectToken_noRole_expectThrows() {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
IOException response = new IOException();
transportFactory.transport.addResponseErrorSequence(response);
transportFactory.transport.addResponseSequence(true, false);
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
try {
awsCredential.retrieveSubjectToken();
fail("Should not be able to use credential without exception.");
} catch (IOException exception) {
assertEquals("Failed to retrieve AWS IAM role.", exception.getMessage());
}
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(2, requests.size());
// Validate region request.
ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS);
// Validate role request.
ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL, EMPTY_STRING_HEADERS);
}
@Test
public void retrieveSubjectToken_noCredentials_expectThrows() {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
IOException response = new IOException();
transportFactory.transport.addResponseErrorSequence(response);
transportFactory.transport.addResponseSequence(true, true, false);
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
try {
awsCredential.retrieveSubjectToken();
fail("Should not be able to use credential without exception.");
} catch (IOException exception) {
assertEquals("Failed to retrieve AWS credentials.", exception.getMessage());
}
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(3, requests.size());
// Validate region request.
ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS);
// Validate role request.
ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL, EMPTY_STRING_HEADERS);
// Validate security credentials request.
ValidateRequest(requests.get(2), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS);
}
@Test
public void retrieveSubjectToken_noRegionUrlProvided() {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
Map<String, Object> credentialSource = new HashMap<>();
credentialSource.put("environment_id", "aws1");
credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(new AwsCredentialSource(credentialSource))
.build();
try {
awsCredential.retrieveSubjectToken();
fail("Should not be able to use credential without exception.");
} catch (IOException exception) {
assertEquals(
"Unable to determine the AWS region. The credential source does not "
+ "contain the region URL.",
exception.getMessage());
}
// No requests because the credential source does not contain region URL.
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertTrue(requests.isEmpty());
}
@Test
public void getAwsSecurityCredentials_fromEnvironmentVariablesNoToken() throws IOException {
TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider();
environmentProvider
.setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId")
.setEnv("AWS_SECRET_ACCESS_KEY", "awsSecretAccessKey");
AwsCredentials testAwsCredentials =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setEnvironmentProvider(environmentProvider)
.build();
AwsSecurityCredentials credentials =
testAwsCredentials.getAwsSecurityCredentials(EMPTY_METADATA_HEADERS);
assertEquals("awsAccessKeyId", credentials.getAccessKeyId());
assertEquals("awsSecretAccessKey", credentials.getSecretAccessKey());
assertNull(credentials.getToken());
}
@Test
public void getAwsSecurityCredentials_fromEnvironmentVariablesWithToken() throws IOException {
TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider();
environmentProvider
.setEnv("AWS_ACCESS_KEY_ID", "awsAccessKeyId")
.setEnv("AWS_SECRET_ACCESS_KEY", "awsSecretAccessKey")
.setEnv("AWS_SESSION_TOKEN", "awsSessionToken");
AwsCredentials testAwsCredentials =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setEnvironmentProvider(environmentProvider)
.build();
AwsSecurityCredentials credentials =
testAwsCredentials.getAwsSecurityCredentials(EMPTY_METADATA_HEADERS);
assertEquals("awsAccessKeyId", credentials.getAccessKeyId());
assertEquals("awsSecretAccessKey", credentials.getSecretAccessKey());
assertEquals("awsSessionToken", credentials.getToken());
}
@Test
public void getAwsSecurityCredentials_fromMetadataServer() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
AwsSecurityCredentials credentials =
awsCredential.getAwsSecurityCredentials(EMPTY_METADATA_HEADERS);
assertEquals("accessKeyId", credentials.getAccessKeyId());
assertEquals("secretAccessKey", credentials.getSecretAccessKey());
assertEquals("token", credentials.getToken());
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(2, requests.size());
// Validate role request.
ValidateRequest(requests.get(0), AWS_CREDENTIALS_URL, EMPTY_STRING_HEADERS);
// Validate security credentials request.
ValidateRequest(requests.get(1), AWS_CREDENTIALS_URL_WITH_ROLE, EMPTY_STRING_HEADERS);
}
@Test
public void getAwsSecurityCredentials_fromMetadataServer_noUrlProvided() {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
Map<String, Object> credentialSource = new HashMap<>();
credentialSource.put("environment_id", "aws1");
credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
AwsCredentials awsCredential =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(new AwsCredentialSource(credentialSource))
.build();
try {
awsCredential.getAwsSecurityCredentials(EMPTY_METADATA_HEADERS);
fail("Should not be able to use credential without exception.");
} catch (IOException exception) {
assertEquals(
"Unable to determine the AWS IAM role name. The credential source does not contain the url field.",
exception.getMessage());
}
// No requests because url field is not present in credential source.
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertTrue(requests.isEmpty());
}
@Test
public void getAwsRegion_awsRegionEnvironmentVariable() throws IOException {
TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider();
environmentProvider.setEnv("AWS_REGION", "region");
environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion");
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
AwsCredentials awsCredentials =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.setEnvironmentProvider(environmentProvider)
.build();
String region = awsCredentials.getAwsRegion(EMPTY_METADATA_HEADERS);
// Should attempt to retrieve the region from AWS_REGION env var first.
// Metadata server would return us-east-1b.
assertEquals("region", region);
// No requests because region is obtained from environment variables.
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertTrue(requests.isEmpty());
}
@Test
public void getAwsRegion_awsDefaultRegionEnvironmentVariable() throws IOException {
TestEnvironmentProvider environmentProvider = new TestEnvironmentProvider();
environmentProvider.setEnv("AWS_DEFAULT_REGION", "defaultRegion");
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
AwsCredentials awsCredentials =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.setEnvironmentProvider(environmentProvider)
.build();
String region = awsCredentials.getAwsRegion(EMPTY_METADATA_HEADERS);
// Should attempt to retrieve the region from DEFAULT_AWS_REGION before calling the metadata
// server. Metadata server would return us-east-1b.
assertEquals("defaultRegion", region);
// No requests because region is obtained from environment variables.
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertTrue(requests.isEmpty());
}
@Test
public void getAwsRegion_metadataServer() throws IOException {
MockExternalAccountCredentialsTransportFactory transportFactory =
new MockExternalAccountCredentialsTransportFactory();
AwsCredentials awsCredentials =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setHttpTransportFactory(transportFactory)
.setCredentialSource(buildAwsCredentialSource(transportFactory))
.build();
String region = awsCredentials.getAwsRegion(EMPTY_METADATA_HEADERS);
// Should retrieve the region from the Metadata server.
String expectedRegion =
transportFactory
.transport
.getAwsRegion()
.substring(0, transportFactory.transport.getAwsRegion().length() - 1);
assertEquals(expectedRegion, region);
List<MockLowLevelHttpRequest> requests = transportFactory.transport.getRequests();
assertEquals(1, requests.size());
// Validate region request.
ValidateRequest(requests.get(0), AWS_REGION_URL, EMPTY_STRING_HEADERS);
}
@Test
public void createdScoped_clonedCredentialWithAddedScopes() {
AwsCredentials credentials =
(AwsCredentials)
AwsCredentials.newBuilder(AWS_CREDENTIAL)
.setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL)
.setQuotaProjectId("quotaProjectId")
.setClientId("clientId")
.setClientSecret("clientSecret")
.build();
List<String> newScopes = Arrays.asList("scope1", "scope2");
AwsCredentials newCredentials = (AwsCredentials) credentials.createScoped(newScopes);
assertEquals(credentials.getAudience(), newCredentials.getAudience());
assertEquals(credentials.getSubjectTokenType(), newCredentials.getSubjectTokenType());
assertEquals(credentials.getTokenUrl(), newCredentials.getTokenUrl());
assertEquals(credentials.getTokenInfoUrl(), newCredentials.getTokenInfoUrl());
assertEquals(
credentials.getServiceAccountImpersonationUrl(),
newCredentials.getServiceAccountImpersonationUrl());
assertEquals(credentials.getCredentialSource(), newCredentials.getCredentialSource());
assertEquals(credentials.getQuotaProjectId(), newCredentials.getQuotaProjectId());
assertEquals(credentials.getClientId(), newCredentials.getClientId());
assertEquals(credentials.getClientSecret(), newCredentials.getClientSecret());
assertEquals(newScopes, newCredentials.getScopes());
}
@Test
public void credentialSource_invalidAwsEnvironmentId() {
Map<String, Object> credentialSource = new HashMap<>();
credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
credentialSource.put("environment_id", "azure1");
try {
new AwsCredentialSource(credentialSource);
fail("Exception should be thrown.");
} catch (IllegalArgumentException e) {
assertEquals("Invalid AWS environment ID.", e.getMessage());
}
}
@Test
public void credentialSource_invalidAwsEnvironmentVersion() {
Map<String, Object> credentialSource = new HashMap<>();
int environmentVersion = 2;
credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
credentialSource.put("environment_id", "aws" + environmentVersion);
try {
new AwsCredentialSource(credentialSource);
fail("Exception should be thrown.");
} catch (IllegalArgumentException e) {
assertEquals(
String.format(
"AWS version %s is not supported in the current build.", environmentVersion),
e.getMessage());
}
}
@Test
public void credentialSource_missingRegionalCredVerificationUrl() {
try {
new AwsCredentialSource(new HashMap<String, Object>());
fail("Exception should be thrown.");
} catch (IllegalArgumentException e) {
assertEquals(
"A regional_cred_verification_url representing the GetCallerIdentity action URL must be specified.",
e.getMessage());
}
}
@Test
public void builder() {
List<String> scopes = Arrays.asList("scope1", "scope2");
AwsCredentials credentials =
(AwsCredentials)
AwsCredentials.newBuilder()
.setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY)
.setAudience("audience")
.setSubjectTokenType("subjectTokenType")
.setTokenUrl(STS_URL)
.setTokenInfoUrl("tokenInfoUrl")
.setCredentialSource(AWS_CREDENTIAL_SOURCE)
.setTokenInfoUrl("tokenInfoUrl")
.setServiceAccountImpersonationUrl(SERVICE_ACCOUNT_IMPERSONATION_URL)
.setQuotaProjectId("quotaProjectId")
.setClientId("clientId")
.setClientSecret("clientSecret")
.setScopes(scopes)
.build();
assertEquals("audience", credentials.getAudience());
assertEquals("subjectTokenType", credentials.getSubjectTokenType());
assertEquals(credentials.getTokenUrl(), STS_URL);
assertEquals(credentials.getTokenInfoUrl(), "tokenInfoUrl");
assertEquals(
credentials.getServiceAccountImpersonationUrl(), SERVICE_ACCOUNT_IMPERSONATION_URL);
assertEquals(credentials.getCredentialSource(), AWS_CREDENTIAL_SOURCE);
assertEquals(credentials.getQuotaProjectId(), "quotaProjectId");
assertEquals(credentials.getClientId(), "clientId");
assertEquals(credentials.getClientSecret(), "clientSecret");
assertEquals(credentials.getScopes(), scopes);
assertEquals(credentials.getEnvironmentProvider(), SystemEnvironmentProvider.getInstance());
}
private static void ValidateRequest(
MockLowLevelHttpRequest request, String expectedUrl, Map<String, String> expectedHeaders) {
assertEquals(expectedUrl, request.getUrl());
Map<String, List<String>> actualHeaders = request.getHeaders();
for (Map.Entry<String, String> expectedHeader : expectedHeaders.entrySet()) {
assertTrue(actualHeaders.containsKey(expectedHeader.getKey()));
List<String> actualValues = actualHeaders.get(expectedHeader.getKey());
assertEquals(1, actualValues.size());
assertEquals(expectedHeader.getValue(), actualValues.get(0));
}
}
private static AwsCredentialSource buildAwsCredentialSource(
MockExternalAccountCredentialsTransportFactory transportFactory) {
Map<String, Object> credentialSourceMap = new HashMap<>();
credentialSourceMap.put("environment_id", "aws1");
credentialSourceMap.put("region_url", transportFactory.transport.getAwsRegionUrl());
credentialSourceMap.put("url", transportFactory.transport.getAwsCredentialsUrl());
credentialSourceMap.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
return new AwsCredentialSource(credentialSourceMap);
}
static InputStream writeAwsCredentialsStream(String stsUrl, String regionUrl, String metadataUrl)
throws IOException {
GenericJson json = new GenericJson();
json.put("audience", "audience");
json.put("subject_token_type", "subjectTokenType");
json.put("token_url", stsUrl);
json.put("token_info_url", "tokenInfoUrl");
json.put("type", ExternalAccountCredentials.EXTERNAL_ACCOUNT_FILE_TYPE);
GenericJson credentialSource = new GenericJson();
credentialSource.put("environment_id", "aws1");
credentialSource.put("region_url", regionUrl);
credentialSource.put("url", metadataUrl);
credentialSource.put("regional_cred_verification_url", GET_CALLER_IDENTITY_URL);
json.put("credential_source", credentialSource);
return TestUtils.jsonToInputStream(json);
}
}