-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackend_test.go
472 lines (442 loc) · 13.2 KB
/
backend_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
package vault_plugin_auth_tencentcloud
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"os"
"strings"
"testing"
"time"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault-plugin-auth-tencentcloud/clients"
"github.com/hashicorp/vault-plugin-auth-tencentcloud/tools"
"github.com/hashicorp/vault/sdk/logical"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
sts "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sts/v20180813"
)
const (
envVarRunAccTests = "VAULT_ACC"
// This role must have trusted actors enabled on it.
envVarAccTestRoleARN = "VAULT_ACC_TEST_ROLE_ARN"
// The secret id and kek and token given must be for someone who is a trusted actor
// and thus can assume the given role arn.
envVarAccTestSecretId = "VAULT_ACC_TEST_SECRET_ID"
envVarAccTestSecretKey = "VAULT_ACC_TEST_SECRET_KEY"
envVarAccTestToken = "VAULT_ACC_TEST_TOKEN"
envClientConfigTestSecretId = "CLIENT_CONFIG_TEST_SECRET_ID"
envClientConfigTestSecretKey = "CLIENT_CONFIG_TEST_SECRET_KEY"
)
var runAcceptanceTests = os.Getenv(envVarRunAccTests) == "1"
type testEnv struct {
ctx context.Context
storage logical.Storage
backend logical.Backend
isAccTest bool
arn *arn
secretId string
secretKey string
token string
clientConfigSecretId string
clientConfigSecretKey string
}
// This test doesn't make real API calls. It injects a fauxRoundTripper
// that intercepts outbound http calls and provides a mocked response.
func TestBackend_Integration(t *testing.T) {
ctx := context.Background()
arn, err := parseARN("qcs::cam::uin/1000215438890:roleName/elk")
if err != nil {
t.Fatal(err)
}
e := testEnv{
ctx: ctx,
storage: &logical.InmemStorage{},
backend: func() logical.Backend {
client := cleanhttp.DefaultClient()
client.Transport = &fauxRoundTripper{}
b := newBackend(client)
conf := &logical.BackendConfig{
System: &logical.StaticSystemView{
DefaultLeaseTTLVal: time.Hour,
MaxLeaseTTLVal: time.Hour,
},
}
if err := b.Setup(ctx, conf); err != nil {
panic(err)
}
return b
}(),
isAccTest: false,
arn: arn,
secretId: "someSecretId",
secretKey: "someSecretKey",
token: "someToken",
clientConfigSecretId: "someClientConfigSecretId",
clientConfigSecretKey: "someClientConfigSecretKey",
}
// Exercise all the role endpoints.
t.Run("AddClientConfig", e.AddClientConfig)
t.Run("EmptyList", e.EmptyList)
t.Run("CreateRole", e.CreateRole)
t.Run("ReadRole", e.ReadRole)
t.Run("ListOfOne", e.ListOfOne)
t.Run("UpdateRole", e.UpdateRole)
t.Run("ReadUpdatedRole", e.ReadUpdatedRole)
t.Run("ListOfOne", e.ListOfOne)
t.Run("DeleteRole", e.DeleteRole)
t.Run("EmptyList", e.EmptyList)
// Create the role again so we can test logging in.
t.Run("CreateRole", e.CreateRole)
t.Run("LoginSuccess", e.LoginSuccess)
}
// This test makes real API calls. It's intended for developers and a CI
// test runner.
func TestBackend_Acceptance(t *testing.T) {
if !runAcceptanceTests {
t.SkipNow()
}
ctx := context.Background()
arn, err := parseARN(os.Getenv(envVarAccTestRoleARN))
if err != nil {
t.Fatal(err)
}
e := testEnv{
ctx: ctx,
storage: &logical.InmemStorage{},
backend: func() logical.Backend {
client := cleanhttp.DefaultClient()
b := newBackend(client)
conf := &logical.BackendConfig{
System: &logical.StaticSystemView{
DefaultLeaseTTLVal: time.Hour,
MaxLeaseTTLVal: time.Hour,
},
}
if err := b.Setup(ctx, conf); err != nil {
panic(err)
}
return b
}(),
isAccTest: true,
arn: arn,
secretId: os.Getenv(envVarAccTestSecretId),
secretKey: os.Getenv(envVarAccTestSecretKey),
token: os.Getenv(envVarAccTestToken),
clientConfigSecretId: os.Getenv(envClientConfigTestSecretId),
clientConfigSecretKey: os.Getenv(envClientConfigTestSecretKey),
}
// Exercise all the role endpoints.
t.Run("AddClientConfig", e.AddClientConfig)
t.Run("EmptyList", e.EmptyList)
t.Run("CreateRole", e.CreateRole)
t.Run("ReadRole", e.ReadRole)
t.Run("ListOfOne", e.ListOfOne)
t.Run("UpdateRole", e.UpdateRole)
t.Run("ReadUpdatedRole", e.ReadUpdatedRole)
t.Run("ListOfOne", e.ListOfOne)
t.Run("DeleteRole", e.DeleteRole)
t.Run("EmptyList", e.EmptyList)
// Create the role again so we can test logging in.
t.Run("CreateRole", e.CreateRole)
t.Run("LoginSuccess", e.LoginSuccess)
}
func (e *testEnv) CreateRole(t *testing.T) {
req := &logical.Request{
Operation: logical.CreateOperation,
Path: "role/" + e.arn.RoleName,
Storage: e.storage,
Data: map[string]interface{}{
"arn": e.arn.String(),
"policies": "default",
"ttl": 10,
"max_ttl": 10,
"period": 1,
"bound_cidrs": []string{"127.0.0.1/24"},
},
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp != nil {
t.Fatal("expected nil response to represent a 204")
}
}
func (e *testEnv) ReadRole(t *testing.T) {
req := &logical.Request{
Operation: logical.ReadOperation,
Path: "role/" + e.arn.RoleName,
Storage: e.storage,
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("expected response containing data")
}
if resp.Data["arn"] != e.arn.String() {
t.Fatalf("expected arn of %s but received %s", e.arn, resp.Data["arn"])
}
if resp.Data["policies"].([]string)[0] != "default" {
t.Fatalf("expected policy of default but received %s", resp.Data["policies"].([]string)[0])
}
if resp.Data["ttl"].(int64) != 10 {
t.Fatalf("expected ttl of 10 but received %d", resp.Data["ttl"].(time.Duration))
}
if resp.Data["max_ttl"].(int64) != 10 {
t.Fatalf("expected max_ttl of 10 but received %d", resp.Data["max_ttl"].(time.Duration))
}
if resp.Data["period"].(int64) != 1 {
t.Fatalf("expected period of 1 but received %d", resp.Data["period"].(time.Duration))
}
}
func (e *testEnv) UpdateRole(t *testing.T) {
req := &logical.Request{
Operation: logical.UpdateOperation,
Path: "role/" + e.arn.RoleName,
Storage: e.storage,
Data: map[string]interface{}{
"max_ttl": 100,
},
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp != nil {
t.Fatal("expected nil response to represent a 204")
}
}
func (e *testEnv) ReadUpdatedRole(t *testing.T) {
req := &logical.Request{
Operation: logical.ReadOperation,
Path: "role/" + e.arn.RoleName,
Storage: e.storage,
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatalf("expected response containing data")
}
if resp.Data["arn"] != e.arn.String() {
t.Fatalf("expected arn of %s but received %s", e.arn, resp.Data["arn"])
}
if resp.Data["policies"].([]string)[0] != "default" {
t.Fatalf("expected policy of default but received %s", resp.Data["policies"].([]string)[0])
}
if resp.Data["ttl"].(int64) != 10 {
t.Fatalf("expected ttl of 10 but received %d", resp.Data["ttl"].(time.Duration))
}
if resp.Data["max_ttl"].(int64) != 100 {
t.Fatalf("expected max_ttl of 100 but received %d", resp.Data["max_ttl"].(time.Duration))
}
if resp.Data["period"].(int64) != 1 {
t.Fatalf("expected period of 1 but received %d", resp.Data["period"].(time.Duration))
}
}
func (e *testEnv) AddClientConfig(t *testing.T) {
req := &logical.Request{
Operation: logical.CreateOperation,
Path: "config/client",
Storage: e.storage,
Data: map[string]interface{}{
"secret_id": e.secretId,
"secret_key": e.secretKey,
},
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("bad: resp: %#v\nerr:%v", resp, err)
}
if resp != nil {
t.Fatal("expected nil response to represent a 204")
}
}
func (e *testEnv) DeleteRole(t *testing.T) {
req := &logical.Request{
Operation: logical.DeleteOperation,
Path: "role/" + e.arn.RoleName,
Storage: e.storage,
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp != nil {
t.Fatal("expected nil response to represent a 204")
}
}
func (e *testEnv) EmptyList(t *testing.T) {
req := &logical.Request{
Operation: logical.ListOperation,
Path: "role/",
Storage: e.storage,
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("expected response containing data")
}
if resp.Data["keys"] != nil {
t.Fatal("no keys should have been returned")
}
}
func (e *testEnv) ListOfOne(t *testing.T) {
req := &logical.Request{
Operation: logical.ListOperation,
Path: "role/",
Storage: e.storage,
}
resp, err := e.backend.HandleRequest(e.ctx, req)
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("expected response containing data")
}
if len(resp.Data["keys"].([]string)) != 1 {
t.Fatal("1 key should have been returned")
}
if resp.Data["keys"].([]string)[0] != e.arn.RoleName {
t.Fatalf("expected %s but received %s", e.arn.RoleName, resp.Data["keys"].([]string)[0])
}
}
func (e *testEnv) getIsAccTestCreds(t *testing.T) (creds common.CredentialIface) {
profile := profile.NewClientProfile()
profile.Language = "en-US"
profile.HttpProfile.ReqTimeout = 90
origCreds := common.NewCredential(e.secretId, e.secretKey)
client, err := sts.NewClient(origCreds, regions.Ashburn, profile)
if err != nil {
t.Fatal(err)
}
uid, err := uuid.GenerateUUID()
if err != nil {
t.Fatal(err)
}
req := sts.NewAssumeRoleRequest()
arnFull := e.arn.String()
req.RoleArn = &arnFull
sessionName := strings.Replace(uid, "-", "", -1)
req.RoleSessionName = &sessionName
resp, err := client.AssumeRole(req)
if err != nil {
t.Fatal(err)
}
creds, err = clients.NewConfigurationCredentialProvider(&clients.Configuration{
SecretId: *(resp.Response.Credentials.TmpSecretId),
SecretKey: *(resp.Response.Credentials.TmpSecretKey),
Token: *(resp.Response.Credentials.Token),
}).GetCredential()
return
}
func (e *testEnv) LoginSuccess(t *testing.T) {
data := tools.GenerateLoginDataV2(
e.arn.RoleName,
"na-ashburn",
e.clientConfigSecretId,
e.clientConfigSecretKey,
e.token,
)
req := &logical.Request{
Operation: logical.UpdateOperation,
Path: "login",
Storage: e.storage,
Data: data,
Connection: &logical.Connection{
RemoteAddr: "127.0.0.1/24",
},
}
resp, err := e.backend.HandleRequest(e.ctx, req)
e.checkResp(t, resp, err)
}
// checkResp
func (e *testEnv) checkResp(t *testing.T, resp *logical.Response, err error) {
if err != nil {
t.Fatal(err)
}
if resp == nil {
t.Fatal("expected response containing data")
}
if resp.Auth == nil {
t.Fatal("should have received an auth")
}
if resp.Auth.Period != time.Second {
t.Fatalf("expected period of 1 second but received %d", resp.Auth.Period)
}
if len(resp.Auth.Policies) != 1 {
t.Fatalf("expected 1 policy but received %d", len(resp.Auth.Policies))
}
if resp.Auth.Policies[0] != "default" {
t.Fatalf("expected default but received %s", resp.Auth.Policies[0])
}
if resp.Auth.Metadata["account_id"] != e.arn.Uin {
t.Fatalf("expected %s but received %s", e.arn.Uin, resp.Auth.Metadata["account_id"])
}
if resp.Auth.Metadata["role_id"] == "" {
t.Fatal("expected role_id but received none")
}
assumedRoleArn, err := parseARN(resp.Auth.Metadata["arn"])
if err != nil {
t.Fatal(err)
}
if !assumedRoleArn.IsMemberOf(e.arn) {
t.Fatalf("assumed role arn of %s is not a member of role arn of %s", assumedRoleArn, e.arn)
}
if resp.Auth.Metadata["principal_id"] == "" {
t.Fatal("expected principal_id but received none")
}
if resp.Auth.Metadata["request_id"] == "" {
t.Fatalf("expected request_id but received none")
}
if resp.Auth.Metadata["role_name"] != e.arn.RoleName {
t.Fatalf("expected %s but received %s", e.arn.RoleName, resp.Auth.Metadata["role_name"])
}
if resp.Auth.DisplayName == "" {
t.Fatal("expected displayname but received none")
}
if !resp.Auth.LeaseOptions.Renewable {
t.Fatal("auth should be renewable")
}
if resp.Auth.LeaseOptions.TTL != 10*time.Second {
t.Fatal("ttl should be 10 seconds")
}
if resp.Auth.LeaseOptions.MaxTTL != 10*time.Second {
t.Fatal("max ttl should be 10 seconds")
}
if resp.Auth.Alias.Name == "" {
t.Fatal("expected alias name but received none")
}
}
type fauxRoundTripper struct{}
// This simply returns a spoofed successful response from the GetCallerIdentity endpoint.
func (f *fauxRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
respBody := map[string]map[string]string{
"Response": {
"Type": "CAMRole",
"AccountId": "1000262888",
"UserId": "461168601842741888:roleSessionName",
"PrincipalId": "10002618888",
"Arn": "qcs::sts:1000262888:assumed-role/461168601842741***",
"RequestId": "1c875b55-128b-4152-9e73-0984fd489ba2",
},
}
b, err := json.Marshal(respBody)
if err != nil {
return nil, err
}
resp := &http.Response{
Body: ioutil.NopCloser(bytes.NewReader(b)),
StatusCode: 200,
}
return resp, nil
}