-
Notifications
You must be signed in to change notification settings - Fork 37
/
credentials_test.go
336 lines (280 loc) · 9.84 KB
/
credentials_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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package awsbase
import (
"context"
"fmt"
"os"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/hashicorp/aws-sdk-go-base/v2/internal/test"
"github.com/hashicorp/aws-sdk-go-base/v2/servicemocks"
)
func TestAWSGetCredentials_static(t *testing.T) {
testCases := []struct {
Key, Secret, Token string
}{
{
Key: "test",
Secret: "secret",
}, {
Key: "test",
Secret: "secret",
Token: "token",
},
}
for _, testCase := range testCases {
ctx := test.Context(t)
c := testCase
cfg := Config{
AccessKey: c.Key,
SecretKey: c.Secret,
Token: c.Token,
}
creds, source, err := getCredentialsProvider(ctx, &cfg)
if err != nil {
t.Fatalf("unexpected '%[1]T' error getting credentials provider: %[1]s", err)
}
if a, e := source, credentials.StaticCredentialsName; a != e {
t.Errorf("Expected initial source to be %q, %q given", e, a)
}
validateCredentialsProvider(ctx, creds, c.Key, c.Secret, c.Token, credentials.StaticCredentialsName, t)
testCredentialsProviderWrappedWithCache(creds, t)
}
}
// TestAWSGetCredentials_ec2Imds is designed to test the scenario of running Terraform
// from an EC2 instance, without environment variables or manually supplied
// credentials.
func TestAWSGetCredentials_ec2Imds(t *testing.T) {
// clear AWS_* environment variables
resetEnv := servicemocks.UnsetEnv(t)
defer resetEnv()
ctx := test.Context(t)
// capture the test server's close method, to call after the test returns
ts := servicemocks.AwsMetadataApiMock(append(
servicemocks.Ec2metadata_securityCredentialsEndpoints,
servicemocks.Ec2metadata_instanceIdEndpoint,
servicemocks.Ec2metadata_iamInfoEndpoint,
))
defer ts()
// An empty config, no key supplied
cfg := Config{}
creds, source, err := getCredentialsProvider(ctx, &cfg)
if err != nil {
t.Fatalf("unexpected '%[1]T' error getting credentials provider: %[1]s", err)
}
if a, e := source, ec2rolecreds.ProviderName; a != e {
t.Errorf("Expected initial source to be %q, %q given", e, a)
}
validateCredentialsProvider(ctx, creds, "Ec2MetadataAccessKey", "Ec2MetadataSecretKey", "Ec2MetadataSessionToken", ec2rolecreds.ProviderName, t)
testCredentialsProviderWrappedWithCache(creds, t)
}
func TestAWSGetCredentials_configShouldOverrideEc2IMDS(t *testing.T) {
resetEnv := servicemocks.UnsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := servicemocks.AwsMetadataApiMock(append(
servicemocks.Ec2metadata_securityCredentialsEndpoints,
servicemocks.Ec2metadata_instanceIdEndpoint,
servicemocks.Ec2metadata_iamInfoEndpoint,
))
defer ts()
testCases := []struct {
Key, Secret, Token string
}{
{
Key: "test",
Secret: "secret",
}, {
Key: "test",
Secret: "secret",
Token: "token",
},
}
for _, testCase := range testCases {
ctx := test.Context(t)
c := testCase
cfg := Config{
AccessKey: c.Key,
SecretKey: c.Secret,
Token: c.Token,
}
creds, _, err := getCredentialsProvider(ctx, &cfg)
if err != nil {
t.Fatalf("unexpected '%[1]T' error: %[1]s", err)
}
validateCredentialsProvider(ctx, creds, c.Key, c.Secret, c.Token, credentials.StaticCredentialsName, t)
testCredentialsProviderWrappedWithCache(creds, t)
}
}
func TestAWSGetCredentials_shouldErrorWithInvalidEc2ImdsEndpoint(t *testing.T) {
ctx := test.Context(t)
resetEnv := servicemocks.UnsetEnv(t)
defer resetEnv()
// capture the test server's close method, to call after the test returns
ts := servicemocks.InvalidEC2MetadataEndpoint(t)
defer ts()
// An empty config, no key supplied
cfg := Config{}
_, _, err := getCredentialsProvider(ctx, &cfg)
if err == nil {
t.Fatal("expected error returned when getting creds w/ invalid EC2 IMDS endpoint")
}
if !IsNoValidCredentialSourcesError(err) {
t.Fatalf("expected NoValidCredentialSourcesError, got '%[1]T': %[1]s", err)
}
}
func TestAWSGetCredentials_sharedCredentialsFile(t *testing.T) {
ctx := test.Context(t)
resetEnv := servicemocks.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, source, err := getCredentialsProvider(ctx, &Config{
Profile: "myprofile",
})
if err != nil {
t.Fatalf("unexpected '%[1]T' error getting credentials provider from environment: %[1]s", err)
}
if a, e := source, sharedConfigCredentialsSource(fileEnvName); a != e {
t.Errorf("Expected initial source to be %q, %q given", e, a)
}
validateCredentialsProvider(ctx, credsEnv, "accesskey1", "secretkey1", "", sharedConfigCredentialsSource(fileEnvName), t)
// Confirm CredsFilename overrides AWS_SHARED_CREDENTIALS_FILE
credsParam, source, err := getCredentialsProvider(ctx, &Config{
Profile: "myprofile",
SharedCredentialsFiles: []string{fileParamName},
})
if err != nil {
t.Fatalf("unexpected '%[1]T' error getting credentials provider from configuration: %[1]s", err)
}
if a, e := source, sharedConfigCredentialsSource(fileParamName); a != e {
t.Errorf("Expected initial source to be %q, %q given", e, a)
}
validateCredentialsProvider(ctx, credsParam, "accesskey2", "secretkey2", "", sharedConfigCredentialsSource(fileParamName), t)
}
func TestAWSGetCredentials_webIdentityToken(t *testing.T) {
ctx := test.Context(t)
cfg := Config{
AssumeRoleWithWebIdentity: &AssumeRoleWithWebIdentity{
RoleARN: servicemocks.MockStsAssumeRoleWithWebIdentityArn,
SessionName: servicemocks.MockStsAssumeRoleWithWebIdentitySessionName,
WebIdentityToken: servicemocks.MockWebIdentityToken,
},
}
ts := servicemocks.MockAwsApiServer("STS", []*servicemocks.MockEndpoint{
servicemocks.MockStsAssumeRoleWithWebIdentityValidEndpoint,
servicemocks.MockStsGetCallerIdentityValidAssumedRoleEndpoint,
})
defer ts.Close()
cfg.StsEndpoint = ts.URL
creds, source, err := getCredentialsProvider(ctx, &cfg)
if err != nil {
t.Fatalf("unexpected '%[1]T' error getting credentials provider: %[1]s", err)
}
if a, e := source, stscreds.WebIdentityProviderName; a != e {
t.Errorf("Expected initial source to be %q, %q given", e, a)
}
validateCredentialsProvider(ctx, creds,
servicemocks.MockStsAssumeRoleWithWebIdentityAccessKey,
servicemocks.MockStsAssumeRoleWithWebIdentitySecretKey,
servicemocks.MockStsAssumeRoleWithWebIdentitySessionToken,
stscreds.WebIdentityProviderName, t)
testCredentialsProviderWrappedWithCache(creds, t)
}
func TestAWSGetCredentials_assumeRole(t *testing.T) {
ctx := test.Context(t)
key := "test"
secret := "secret"
cfg := Config{
AccessKey: key,
SecretKey: secret,
AssumeRole: &AssumeRole{
RoleARN: servicemocks.MockStsAssumeRoleArn,
SessionName: servicemocks.MockStsAssumeRoleSessionName,
},
}
ts := servicemocks.MockAwsApiServer("STS", []*servicemocks.MockEndpoint{
servicemocks.MockStsAssumeRoleValidEndpoint,
servicemocks.MockStsGetCallerIdentityValidAssumedRoleEndpoint,
})
defer ts.Close()
cfg.StsEndpoint = ts.URL
creds, source, err := getCredentialsProvider(ctx, &cfg)
if err != nil {
t.Fatalf("unexpected '%[1]T' error getting credentials provider: %[1]s", err)
}
if a, e := source, credentials.StaticCredentialsName; a != e {
t.Errorf("Expected initial source to be %q, %q given", e, a)
}
validateCredentialsProvider(ctx, creds,
servicemocks.MockStsAssumeRoleAccessKey,
servicemocks.MockStsAssumeRoleSecretKey,
servicemocks.MockStsAssumeRoleSessionToken,
stscreds.ProviderName, t)
testCredentialsProviderWrappedWithCache(creds, t)
}
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 := os.CreateTemp(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 validateCredentialsProvider(ctx context.Context, creds aws.CredentialsProvider, accesskey, secretkey, token, source string, t *testing.T) {
v, err := creds.Retrieve(ctx)
if err != nil {
t.Fatalf("Error retrieving credentials: %s", err)
}
if v.AccessKeyID != accesskey {
t.Errorf("AccessKeyID mismatch, expected: %q, got %q", accesskey, v.AccessKeyID)
}
if v.SecretAccessKey != secretkey {
t.Errorf("SecretAccessKey mismatch, expected: %q, got %q", secretkey, v.SecretAccessKey)
}
if v.SessionToken != token {
t.Errorf("SessionToken mismatch, expected: %q, got %q", token, v.SessionToken)
}
if v.Source != source {
t.Errorf("Expected provider name to be %q, %q given", source, v.Source)
}
}
func testCredentialsProviderWrappedWithCache(creds aws.CredentialsProvider, t *testing.T) {
switch creds.(type) {
case *aws.CredentialsCache:
break
default:
t.Error("expected credentials provider to be wrapped with aws.CredentialsCache")
}
}
func sharedConfigCredentialsSource(filename string) string {
return fmt.Sprintf(sharedConfigCredentialsProvider+": %s", filename)
}