forked from hashicorp/aws-sdk-go-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
awsauth_test.go
857 lines (771 loc) · 26.8 KB
/
awsauth_test.go
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
package awsbase
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
awsCredentials "github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
)
func TestGetAccountIDAndPartition(t *testing.T) {
var testCases = []struct {
Description string
AuthProviderName string
EC2MetadataEndpoints []*MetadataResponse
IAMEndpoints []*MockEndpoint
STSEndpoints []*MockEndpoint
ErrCount int
ExpectedAccountID string
ExpectedPartition string
}{
{
Description: "EC2 Metadata over iam:GetUser when using EC2 Instance Profile",
AuthProviderName: ec2rolecreds.ProviderName,
EC2MetadataEndpoints: append(ec2metadata_securityCredentialsEndpoints, ec2metadata_instanceIdEndpoint, ec2metadata_iamInfoEndpoint),
IAMEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{200, iamResponse_GetUser_valid, "text/xml"},
},
},
ExpectedAccountID: ec2metadata_iamInfoEndpoint_expectedAccountID,
ExpectedPartition: ec2metadata_iamInfoEndpoint_expectedPartition,
},
{
Description: "Mimic the metadata service mocked by Hologram (https://github.com/AdRoll/hologram)",
AuthProviderName: ec2rolecreds.ProviderName,
EC2MetadataEndpoints: ec2metadata_securityCredentialsEndpoints,
IAMEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{403, iamResponse_GetUser_unauthorized, "text/xml"},
},
},
STSEndpoints: []*MockEndpoint{
MockStsGetCallerIdentityValidEndpoint,
},
ExpectedAccountID: MockStsGetCallerIdentityAccountID,
ExpectedPartition: MockStsGetCallerIdentityPartition,
},
{
Description: "iam:ListRoles if iam:GetUser AccessDenied and sts:GetCallerIdentity fails",
IAMEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{403, iamResponse_GetUser_unauthorized, "text/xml"},
},
{
Request: &MockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
Response: &MockResponse{200, iamResponse_ListRoles_valid, "text/xml"},
},
},
STSEndpoints: []*MockEndpoint{
MockStsGetCallerIdentityInvalidEndpointAccessDenied,
},
ExpectedAccountID: iamResponse_ListRoles_valid_expectedAccountID,
ExpectedPartition: iamResponse_ListRoles_valid_expectedPartition,
},
{
Description: "iam:ListRoles if iam:GetUser ValidationError and sts:GetCallerIdentity fails",
IAMEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{400, iamResponse_GetUser_federatedFailure, "text/xml"},
},
{
Request: &MockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
Response: &MockResponse{200, iamResponse_ListRoles_valid, "text/xml"},
},
},
STSEndpoints: []*MockEndpoint{
MockStsGetCallerIdentityInvalidEndpointAccessDenied,
},
ExpectedAccountID: iamResponse_ListRoles_valid_expectedAccountID,
ExpectedPartition: iamResponse_ListRoles_valid_expectedPartition,
},
{
Description: "Error when all endpoints fail",
IAMEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{400, iamResponse_GetUser_federatedFailure, "text/xml"},
},
{
Request: &MockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
Response: &MockResponse{403, iamResponse_ListRoles_unauthorized, "text/xml"},
},
},
STSEndpoints: []*MockEndpoint{
MockStsGetCallerIdentityInvalidEndpointAccessDenied,
},
ErrCount: 1,
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.Description, func(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
awsTs := awsMetadataApiMock(testCase.EC2MetadataEndpoints)
defer awsTs()
closeIam, iamSess, err := GetMockedAwsApiSession("IAM", testCase.IAMEndpoints)
defer closeIam()
if err != nil {
t.Fatal(err)
}
closeSts, stsSess, err := GetMockedAwsApiSession("STS", testCase.STSEndpoints)
defer closeSts()
if err != nil {
t.Fatal(err)
}
iamConn := iam.New(iamSess)
stsConn := sts.New(stsSess)
accountID, partition, err := GetAccountIDAndPartition(iamConn, stsConn, testCase.AuthProviderName)
if err != nil && testCase.ErrCount == 0 {
t.Fatalf("Expected no error, received error: %s", err)
}
if err == nil && testCase.ErrCount > 0 {
t.Fatalf("Expected %d error(s), received none", testCase.ErrCount)
}
if accountID != testCase.ExpectedAccountID {
t.Fatalf("Parsed account ID doesn't match with expected (%q != %q)", accountID, testCase.ExpectedAccountID)
}
if partition != testCase.ExpectedPartition {
t.Fatalf("Parsed partition doesn't match with expected (%q != %q)", partition, testCase.ExpectedPartition)
}
})
}
}
func TestGetAccountIDAndPartitionFromEC2Metadata(t *testing.T) {
t.Run("EC2 metadata success", func(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
awsTs := awsMetadataApiMock(append(ec2metadata_securityCredentialsEndpoints, ec2metadata_instanceIdEndpoint, ec2metadata_iamInfoEndpoint))
defer awsTs()
id, partition, err := GetAccountIDAndPartitionFromEC2Metadata()
if err != nil {
t.Fatalf("Getting account ID from EC2 metadata API failed: %s", err)
}
if id != ec2metadata_iamInfoEndpoint_expectedAccountID {
t.Fatalf("Expected account ID: %s, given: %s", ec2metadata_iamInfoEndpoint_expectedAccountID, id)
}
if partition != ec2metadata_iamInfoEndpoint_expectedPartition {
t.Fatalf("Expected partition: %s, given: %s", ec2metadata_iamInfoEndpoint_expectedPartition, partition)
}
})
}
func TestGetAccountIDAndPartitionFromIAMGetUser(t *testing.T) {
var testCases = []struct {
Description string
MockEndpoints []*MockEndpoint
ErrCount int
ExpectedAccountID string
ExpectedPartition string
}{
{
Description: "Ignore iam:GetUser failure with federated user",
MockEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{400, iamResponse_GetUser_federatedFailure, "text/xml"},
},
},
ErrCount: 0,
},
{
Description: "Ignore iam:GetUser failure with unauthorized user",
MockEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{403, iamResponse_GetUser_unauthorized, "text/xml"},
},
},
ErrCount: 0,
},
{
Description: "iam:GetUser success",
MockEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=GetUser&Version=2010-05-08"},
Response: &MockResponse{200, iamResponse_GetUser_valid, "text/xml"},
},
},
ExpectedAccountID: iamResponse_GetUser_valid_expectedAccountID,
ExpectedPartition: iamResponse_GetUser_valid_expectedPartition,
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.Description, func(t *testing.T) {
closeIam, iamSess, err := GetMockedAwsApiSession("IAM", testCase.MockEndpoints)
defer closeIam()
if err != nil {
t.Fatal(err)
}
iamConn := iam.New(iamSess)
accountID, partition, err := GetAccountIDAndPartitionFromIAMGetUser(iamConn)
if err != nil && testCase.ErrCount == 0 {
t.Fatalf("Expected no error, received error: %s", err)
}
if err == nil && testCase.ErrCount > 0 {
t.Fatalf("Expected %d error(s), received none", testCase.ErrCount)
}
if accountID != testCase.ExpectedAccountID {
t.Fatalf("Parsed account ID doesn't match with expected (%q != %q)", accountID, testCase.ExpectedAccountID)
}
if partition != testCase.ExpectedPartition {
t.Fatalf("Parsed partition doesn't match with expected (%q != %q)", partition, testCase.ExpectedPartition)
}
})
}
}
func TestGetAccountIDAndPartitionFromIAMListRoles(t *testing.T) {
var testCases = []struct {
Description string
MockEndpoints []*MockEndpoint
ErrCount int
ExpectedAccountID string
ExpectedPartition string
}{
{
Description: "iam:ListRoles unauthorized",
MockEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
Response: &MockResponse{403, iamResponse_ListRoles_unauthorized, "text/xml"},
},
},
ErrCount: 1,
},
{
Description: "iam:ListRoles success",
MockEndpoints: []*MockEndpoint{
{
Request: &MockRequest{"POST", "/", "Action=ListRoles&MaxItems=1&Version=2010-05-08"},
Response: &MockResponse{200, iamResponse_ListRoles_valid, "text/xml"},
},
},
ExpectedAccountID: iamResponse_ListRoles_valid_expectedAccountID,
ExpectedPartition: iamResponse_ListRoles_valid_expectedPartition,
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.Description, func(t *testing.T) {
closeIam, iamSess, err := GetMockedAwsApiSession("IAM", testCase.MockEndpoints)
defer closeIam()
if err != nil {
t.Fatal(err)
}
iamConn := iam.New(iamSess)
accountID, partition, err := GetAccountIDAndPartitionFromIAMListRoles(iamConn)
if err != nil && testCase.ErrCount == 0 {
t.Fatalf("Expected no error, received error: %s", err)
}
if err == nil && testCase.ErrCount > 0 {
t.Fatalf("Expected %d error(s), received none", testCase.ErrCount)
}
if accountID != testCase.ExpectedAccountID {
t.Fatalf("Parsed account ID doesn't match with expected (%q != %q)", accountID, testCase.ExpectedAccountID)
}
if partition != testCase.ExpectedPartition {
t.Fatalf("Parsed partition doesn't match with expected (%q != %q)", partition, testCase.ExpectedPartition)
}
})
}
}
func TestGetAccountIDAndPartitionFromSTSGetCallerIdentity(t *testing.T) {
var testCases = []struct {
Description string
MockEndpoints []*MockEndpoint
ErrCount int
ExpectedAccountID string
ExpectedPartition string
}{
{
Description: "sts:GetCallerIdentity unauthorized",
MockEndpoints: []*MockEndpoint{
MockStsGetCallerIdentityInvalidEndpointAccessDenied,
},
ErrCount: 1,
},
{
Description: "sts:GetCallerIdentity success",
MockEndpoints: []*MockEndpoint{
MockStsGetCallerIdentityValidEndpoint,
},
ExpectedAccountID: MockStsGetCallerIdentityAccountID,
ExpectedPartition: MockStsGetCallerIdentityPartition,
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.Description, func(t *testing.T) {
closeSts, stsSess, err := GetMockedAwsApiSession("STS", testCase.MockEndpoints)
defer closeSts()
if err != nil {
t.Fatal(err)
}
stsConn := sts.New(stsSess)
accountID, partition, err := GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsConn)
if err != nil && testCase.ErrCount == 0 {
t.Fatalf("Expected no error, received error: %s", err)
}
if err == nil && testCase.ErrCount > 0 {
t.Fatalf("Expected %d error(s), received none", testCase.ErrCount)
}
if accountID != testCase.ExpectedAccountID {
t.Fatalf("Parsed account ID doesn't match with expected (%q != %q)", accountID, testCase.ExpectedAccountID)
}
if partition != testCase.ExpectedPartition {
t.Fatalf("Parsed partition doesn't match with expected (%q != %q)", partition, testCase.ExpectedPartition)
}
})
}
}
func TestAWSParseAccountIDAndPartitionFromARN(t *testing.T) {
var testCases = []struct {
InputARN string
ErrCount int
ExpectedAccountID string
ExpectedPartition string
}{
{
InputARN: "invalid-arn",
ErrCount: 1,
},
{
InputARN: "arn:aws:iam::123456789012:instance-profile/name",
ExpectedAccountID: "123456789012",
ExpectedPartition: "aws",
},
{
InputARN: "arn:aws:iam::123456789012:user/name",
ExpectedAccountID: "123456789012",
ExpectedPartition: "aws",
},
{
InputARN: "arn:aws:sts::123456789012:assumed-role/name",
ExpectedAccountID: "123456789012",
ExpectedPartition: "aws",
},
{
InputARN: "arn:aws-us-gov:sts::123456789012:assumed-role/name",
ExpectedAccountID: "123456789012",
ExpectedPartition: "aws-us-gov",
},
}
for _, testCase := range testCases {
testCase := testCase
t.Run(testCase.InputARN, func(t *testing.T) {
accountID, partition, err := parseAccountIDAndPartitionFromARN(testCase.InputARN)
if err != nil && testCase.ErrCount == 0 {
t.Fatalf("Expected no error when parsing ARN, received error: %s", err)
}
if err == nil && testCase.ErrCount > 0 {
t.Fatalf("Expected %d error(s) when parsing ARN, received none", testCase.ErrCount)
}
if accountID != testCase.ExpectedAccountID {
t.Fatalf("Parsed account ID doesn't match with expected (%q != %q)", accountID, testCase.ExpectedAccountID)
}
if partition != testCase.ExpectedPartition {
t.Fatalf("Parsed partition doesn't match with expected (%q != %q)", partition, testCase.ExpectedPartition)
}
})
}
}
func TestAWSGetCredentials_shouldErrorWhenBlank(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
cfg := Config{}
_, err := GetCredentials(&cfg)
if !IsNoValidCredentialSourcesError(err) {
t.Fatalf("Unexpected error: %s", err)
}
if err == nil {
t.Fatal("Expected an error given empty env, keys, and IAM in AWS Config")
}
}
func TestAWSGetCredentials_shouldBeStatic(t *testing.T) {
testCases := []struct {
Key, Secret, Token string
}{
{
Key: "test",
Secret: "secret",
}, {
Key: "test",
Secret: "test",
Token: "test",
},
}
for _, testCase := range testCases {
c := testCase
cfg := Config{
AccessKey: c.Key,
SecretKey: c.Secret,
Token: c.Token,
}
creds, err := GetCredentials(&cfg)
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if creds == nil {
t.Fatal("Expected a static creds provider to be returned")
}
v, err := creds.Get()
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if v.AccessKeyID != c.Key {
t.Fatalf("AccessKeyID mismatch, expected: (%s), got (%s)", c.Key, v.AccessKeyID)
}
if v.SecretAccessKey != c.Secret {
t.Fatalf("SecretAccessKey mismatch, expected: (%s), got (%s)", c.Secret, v.SecretAccessKey)
}
if v.SessionToken != c.Token {
t.Fatalf("SessionToken mismatch, expected: (%s), got (%s)", c.Token, v.SessionToken)
}
}
}
// TestAWSGetCredentials_shouldIAM is designed to test the scenario of running Terraform
// from an EC2 instance, without environment variables or manually supplied
// credentials.
func TestAWSGetCredentials_shouldIAM(t *testing.T) {
// clear AWS_* environment variables
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := awsMetadataApiMock(append(ec2metadata_securityCredentialsEndpoints, ec2metadata_instanceIdEndpoint, ec2metadata_iamInfoEndpoint))
defer ts()
// An empty config, no key supplied
cfg := Config{}
creds, err := GetCredentials(&cfg)
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if creds == nil {
t.Fatal("Expected a static creds provider to be returned")
}
v, err := creds.Get()
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if expected, actual := "Ec2MetadataAccessKey", v.AccessKeyID; expected != actual {
t.Fatalf("expected access key (%s), got: %s", expected, actual)
}
if expected, actual := "Ec2MetadataSecretKey", v.SecretAccessKey; expected != actual {
t.Fatalf("expected secret key (%s), got: %s", expected, actual)
}
if expected, actual := "Ec2MetadataSessionToken", v.SessionToken; expected != actual {
t.Fatalf("expected session token (%s), got: %s", expected, actual)
}
}
// TestAWSGetCredentials_shouldIAM is designed to test the scenario of running Terraform
// from an EC2 instance, without environment variables or manually supplied
// credentials.
func TestAWSGetCredentials_shouldIgnoreIAM(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := awsMetadataApiMock(append(ec2metadata_securityCredentialsEndpoints, ec2metadata_instanceIdEndpoint, ec2metadata_iamInfoEndpoint))
defer ts()
testCases := []struct {
Key, Secret, Token string
}{
{
Key: "test",
Secret: "secret",
}, {
Key: "test",
Secret: "test",
Token: "test",
},
}
for _, testCase := range testCases {
c := testCase
cfg := Config{
AccessKey: c.Key,
SecretKey: c.Secret,
Token: c.Token,
}
creds, err := GetCredentials(&cfg)
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if creds == nil {
t.Fatal("Expected a static creds provider to be returned")
}
v, err := creds.Get()
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if v.AccessKeyID != c.Key {
t.Fatalf("AccessKeyID mismatch, expected: (%s), got (%s)", c.Key, v.AccessKeyID)
}
if v.SecretAccessKey != c.Secret {
t.Fatalf("SecretAccessKey mismatch, expected: (%s), got (%s)", c.Secret, v.SecretAccessKey)
}
if v.SessionToken != c.Token {
t.Fatalf("SessionToken mismatch, expected: (%s), got (%s)", c.Token, v.SessionToken)
}
}
}
func TestAWSGetCredentials_shouldErrorWithInvalidEndpoint(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := invalidAwsEnv()
defer ts()
_, err := GetCredentials(&Config{})
if !IsNoValidCredentialSourcesError(err) {
t.Fatalf("Error gettings creds: %s", err)
}
if err == nil {
t.Fatal("Expected error returned when getting creds w/ invalid EC2 endpoint")
}
}
func TestAWSGetCredentials_shouldIgnoreInvalidEndpoint(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := invalidAwsEnv()
defer ts()
creds, err := GetCredentials(&Config{AccessKey: "accessKey", SecretKey: "secretKey"})
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
v, err := creds.Get()
if err != nil {
t.Fatalf("Getting static credentials w/ invalid EC2 endpoint failed: %s", err)
}
if creds == nil {
t.Fatal("Expected a static creds provider to be returned")
}
if v.ProviderName != "StaticProvider" {
t.Fatalf("Expected provider name to be %q, %q given", "StaticProvider", v.ProviderName)
}
if v.AccessKeyID != "accessKey" {
t.Fatalf("Static Access Key %q doesn't match: %s", "accessKey", v.AccessKeyID)
}
if v.SecretAccessKey != "secretKey" {
t.Fatalf("Static Secret Key %q doesn't match: %s", "secretKey", v.SecretAccessKey)
}
}
func TestAWSGetCredentials_shouldCatchEC2RoleProvider(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := awsMetadataApiMock(append(ec2metadata_securityCredentialsEndpoints, ec2metadata_instanceIdEndpoint, ec2metadata_iamInfoEndpoint))
defer ts()
creds, err := GetCredentials(&Config{})
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if creds == nil {
t.Fatal("Expected an EC2Role creds provider to be returned")
}
v, err := creds.Get()
if err != nil {
t.Fatalf("Expected no error when getting creds: %s", err)
}
expectedProvider := "EC2RoleProvider"
if v.ProviderName != expectedProvider {
t.Fatalf("Expected provider name to be %q, %q given",
expectedProvider, v.ProviderName)
}
}
var credentialsFileContentsEnv = `[myprofile]
aws_access_key_id = accesskey1
aws_secret_access_key = secretkey1
`
var credentialsFileContentsParam = `[myprofile]
aws_access_key_id = accesskey2
aws_secret_access_key = secretkey2
`
func writeCredentialsFile(credentialsFileContents string, t *testing.T) string {
file, err := ioutil.TempFile(os.TempDir(), "terraform_aws_cred")
if err != nil {
t.Fatalf("Error writing temporary credentials file: %s", err)
}
_, err = file.WriteString(credentialsFileContents)
if err != nil {
t.Fatalf("Error writing temporary credentials to file: %s", err)
}
err = file.Close()
if err != nil {
t.Fatalf("Error closing temporary credentials file: %s", err)
}
return file.Name()
}
func TestAWSGetCredentials_shouldBeShared(t *testing.T) {
resetEnv := unsetEnv(t)
defer resetEnv()
if err := os.Setenv("AWS_PROFILE", "myprofile"); err != nil {
t.Fatalf("Error resetting env var AWS_PROFILE: %s", err)
}
fileEnvName := writeCredentialsFile(credentialsFileContentsEnv, t)
defer os.Remove(fileEnvName)
fileParamName := writeCredentialsFile(credentialsFileContentsParam, t)
defer os.Remove(fileParamName)
if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", fileEnvName); err != nil {
t.Fatalf("Error resetting env var AWS_SHARED_CREDENTIALS_FILE: %s", err)
}
// Confirm AWS_SHARED_CREDENTIALS_FILE is working
credsEnv, err := GetCredentials(&Config{Profile: "myprofile"})
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
validateCredentials(credsEnv, "accesskey1", "secretkey1", "", t)
// Confirm CredsFilename overwrites AWS_SHARED_CREDENTIALS_FILE
credsParam, err := GetCredentials(&Config{Profile: "myprofile", CredsFilename: fileParamName})
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
validateCredentials(credsParam, "accesskey2", "secretkey2", "", t)
}
func TestAWSGetCredentials_shouldBeENV(t *testing.T) {
// need to set the environment variables to a dummy string, as we don't know
// what they may be at runtime without hardcoding here
s := "some_env"
resetEnv := setEnv(s, t)
defer resetEnv()
cfg := Config{}
creds, err := GetCredentials(&cfg)
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if creds == nil {
t.Fatalf("Expected a static creds provider to be returned")
}
validateCredentials(creds, s, s, s, t)
}
// invalidAwsEnv establishes a httptest server to simulate behaviour
// when endpoint doesn't respond as expected
func invalidAwsEnv() func() {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(400)
}))
os.Setenv("AWS_METADATA_URL", ts.URL+"/latest")
return ts.Close
}
// unsetEnv unsets environment variables for testing a "clean slate" with no
// credentials in the environment
func unsetEnv(t *testing.T) func() {
// Grab any existing AWS keys and preserve. In some tests we'll unset these, so
// we need to have them and restore them after
e := getEnv()
if err := os.Unsetenv("AWS_ACCESS_KEY_ID"); err != nil {
t.Fatalf("Error unsetting env var AWS_ACCESS_KEY_ID: %s", err)
}
if err := os.Unsetenv("AWS_SECRET_ACCESS_KEY"); err != nil {
t.Fatalf("Error unsetting env var AWS_SECRET_ACCESS_KEY: %s", err)
}
if err := os.Unsetenv("AWS_SESSION_TOKEN"); err != nil {
t.Fatalf("Error unsetting env var AWS_SESSION_TOKEN: %s", err)
}
if err := os.Unsetenv("AWS_PROFILE"); err != nil {
t.Fatalf("Error unsetting env var AWS_PROFILE: %s", err)
}
if err := os.Unsetenv("AWS_SHARED_CREDENTIALS_FILE"); err != nil {
t.Fatalf("Error unsetting env var AWS_SHARED_CREDENTIALS_FILE: %s", err)
}
// The Shared Credentials Provider has a very reasonable fallback option of
// checking the user's home directory for credentials, which may create
// unexpected results for users running these tests
os.Setenv("HOME", "/dev/null")
return func() {
// re-set all the envs we unset above
if err := os.Setenv("AWS_ACCESS_KEY_ID", e.Key); err != nil {
t.Fatalf("Error resetting env var AWS_ACCESS_KEY_ID: %s", err)
}
if err := os.Setenv("AWS_SECRET_ACCESS_KEY", e.Secret); err != nil {
t.Fatalf("Error resetting env var AWS_SECRET_ACCESS_KEY: %s", err)
}
if err := os.Setenv("AWS_SESSION_TOKEN", e.Token); err != nil {
t.Fatalf("Error resetting env var AWS_SESSION_TOKEN: %s", err)
}
if err := os.Setenv("AWS_PROFILE", e.Profile); err != nil {
t.Fatalf("Error resetting env var AWS_PROFILE: %s", err)
}
if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", e.CredsFilename); err != nil {
t.Fatalf("Error resetting env var AWS_SHARED_CREDENTIALS_FILE: %s", err)
}
if err := os.Setenv("HOME", e.Home); err != nil {
t.Fatalf("Error resetting env var HOME: %s", err)
}
}
}
func setEnv(s string, t *testing.T) func() {
e := getEnv()
// Set all the envs to a dummy value
if err := os.Setenv("AWS_ACCESS_KEY_ID", s); err != nil {
t.Fatalf("Error setting env var AWS_ACCESS_KEY_ID: %s", err)
}
if err := os.Setenv("AWS_SECRET_ACCESS_KEY", s); err != nil {
t.Fatalf("Error setting env var AWS_SECRET_ACCESS_KEY: %s", err)
}
if err := os.Setenv("AWS_SESSION_TOKEN", s); err != nil {
t.Fatalf("Error setting env var AWS_SESSION_TOKEN: %s", err)
}
if err := os.Setenv("AWS_PROFILE", s); err != nil {
t.Fatalf("Error setting env var AWS_PROFILE: %s", err)
}
if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", s); err != nil {
t.Fatalf("Error setting env var AWS_SHARED_CREDENTIALS_FLE: %s", err)
}
return func() {
// re-set all the envs we unset above
if err := os.Setenv("AWS_ACCESS_KEY_ID", e.Key); err != nil {
t.Fatalf("Error resetting env var AWS_ACCESS_KEY_ID: %s", err)
}
if err := os.Setenv("AWS_SECRET_ACCESS_KEY", e.Secret); err != nil {
t.Fatalf("Error resetting env var AWS_SECRET_ACCESS_KEY: %s", err)
}
if err := os.Setenv("AWS_SESSION_TOKEN", e.Token); err != nil {
t.Fatalf("Error resetting env var AWS_SESSION_TOKEN: %s", err)
}
if err := os.Setenv("AWS_PROFILE", e.Profile); err != nil {
t.Fatalf("Error setting env var AWS_PROFILE: %s", err)
}
if err := os.Setenv("AWS_SHARED_CREDENTIALS_FILE", s); err != nil {
t.Fatalf("Error setting env var AWS_SHARED_CREDENTIALS_FLE: %s", err)
}
}
}
func getEnv() *currentEnv {
// Grab any existing AWS keys and preserve. In some tests we'll unset these, so
// we need to have them and restore them after
return ¤tEnv{
Key: os.Getenv("AWS_ACCESS_KEY_ID"),
Secret: os.Getenv("AWS_SECRET_ACCESS_KEY"),
Token: os.Getenv("AWS_SESSION_TOKEN"),
Profile: os.Getenv("AWS_PROFILE"),
CredsFilename: os.Getenv("AWS_SHARED_CREDENTIALS_FILE"),
Home: os.Getenv("HOME"),
}
}
func validateCredentials(creds *awsCredentials.Credentials, accesskey string, secretkey string, token string, t *testing.T) {
v, err := creds.Get()
if err != nil {
t.Fatalf("Error gettings creds: %s", err)
}
if v.AccessKeyID != accesskey {
t.Fatalf("AccessKeyID mismatch, expected: (%s), got (%s)", accesskey, v.AccessKeyID)
}
if v.SecretAccessKey != secretkey {
t.Fatalf("SecretAccessKey mismatch, expected: (%s), got (%s)", secretkey, v.SecretAccessKey)
}
if v.SessionToken != token {
t.Fatalf("SessionToken mismatch, expected: (%s), got (%s)", token, v.SessionToken)
}
}
// struct to preserve the current environment
type currentEnv struct {
Key, Secret, Token, Profile, CredsFilename, Home string
}