-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathpath_static_roles_test.go
612 lines (562 loc) · 18 KB
/
path_static_roles_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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package aws
import (
"context"
"errors"
"strconv"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/iam/iamiface"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-secure-stdlib/awsutil"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/hashicorp/vault/sdk/queue"
)
// TestStaticRolesValidation verifies that valid requests pass validation and that invalid requests fail validation.
// This includes the user already existing in IAM roles, and the rotation period being sufficiently long.
func TestStaticRolesValidation(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
bgCTX := context.Background() // for brevity
cases := []struct {
name string
opts []awsutil.MockIAMOption
requestData map[string]interface{}
isError bool
}{
{
name: "all good",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserOutput(&iam.GetUserOutput{User: &iam.User{UserName: aws.String("jane-doe"), UserId: aws.String("unique-id")}}),
awsutil.WithCreateAccessKeyOutput(&iam.CreateAccessKeyOutput{
AccessKey: &iam.AccessKey{
AccessKeyId: aws.String("abcdefghijklmnopqrstuvwxyz"),
SecretAccessKey: aws.String("zyxwvutsrqponmlkjihgfedcba"),
UserName: aws.String("jane-doe"),
},
}),
awsutil.WithListAccessKeysOutput(&iam.ListAccessKeysOutput{
AccessKeyMetadata: []*iam.AccessKeyMetadata{},
IsTruncated: aws.Bool(false),
}),
},
requestData: map[string]interface{}{
"name": "test",
"username": "jane-doe",
"rotation_period": "1d",
},
},
{
name: "bad user",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserError(errors.New("oh no")),
},
requestData: map[string]interface{}{
"name": "test",
"username": "jane-doe",
"rotation_period": "24h",
},
isError: true,
},
{
name: "user mismatch",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserOutput(&iam.GetUserOutput{User: &iam.User{UserName: aws.String("ms-impostor"), UserId: aws.String("fake-id")}}),
},
requestData: map[string]interface{}{
"name": "test",
"username": "jane-doe",
"rotation_period": "1d2h",
},
isError: true,
},
{
name: "bad rotation period",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserOutput(&iam.GetUserOutput{User: &iam.User{UserName: aws.String("jane-doe"), UserId: aws.String("unique-id")}}),
},
requestData: map[string]interface{}{
"name": "test",
"username": "jane-doe",
"rotation_period": "45s",
},
isError: true,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
b := Backend(config)
miam, err := awsutil.NewMockIAM(c.opts...)(nil)
if err != nil {
t.Fatal(err)
}
// Used to override the real IAM client creation to return the mocked client
b.nonCachedClientIAMFunc = func(ctx context.Context, s logical.Storage, logger hclog.Logger, entry *staticRoleEntry) (iamiface.IAMAPI, error) {
return miam, nil
}
if err := b.Setup(bgCTX, config); err != nil {
t.Fatal(err)
}
req := &logical.Request{
Operation: logical.UpdateOperation,
Storage: config.StorageView,
Data: c.requestData,
Path: "static-roles/test",
}
_, err = b.pathStaticRolesWrite(bgCTX, req, staticRoleFieldData(req.Data))
if c.isError && err == nil {
t.Fatal("expected an error but didn't get one")
} else if !c.isError && err != nil {
t.Fatalf("got an unexpected error: %s", err)
}
})
}
}
// TestStaticRolesWrite validates that we can write a new entry for a new static role, and that we correctly
// do not write if the request is invalid in some way.
func TestStaticRolesWrite(t *testing.T) {
bgCTX := context.Background()
cases := []struct {
name string
// objects to return from mock IAM.
// You'll need a GetUserOutput (to validate the existence of the user being written,
// the keys the user has already been assigned,
// and the new key vault requests.
opts []awsutil.MockIAMOption // objects to return from the mock IAM
// the name, username if updating, and rotation_period of the user. This is the inbound request the cod would get.
data map[string]interface{}
expectedError bool
findUser bool
// if data is sent the name "johnny", then we'll match an existing user with rotation period 24 hours.
isUpdate bool
newPriority int64 // update time of new item in queue, skip if isUpdate false. There is a wiggle room of 5 seconds
// so the deltas between the old and the new update time should be larger than that to ensure the difference
// can be detected.
}{
{
name: "happy path",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserOutput(&iam.GetUserOutput{User: &iam.User{UserName: aws.String("jane-doe"), UserId: aws.String("unique-id")}}),
awsutil.WithListAccessKeysOutput(&iam.ListAccessKeysOutput{
AccessKeyMetadata: []*iam.AccessKeyMetadata{},
IsTruncated: aws.Bool(false),
}),
awsutil.WithCreateAccessKeyOutput(&iam.CreateAccessKeyOutput{
AccessKey: &iam.AccessKey{
AccessKeyId: aws.String("abcdefghijklmnopqrstuvwxyz"),
SecretAccessKey: aws.String("zyxwvutsrqponmlkjihgfedcba"),
UserName: aws.String("jane-doe"),
},
}),
},
data: map[string]interface{}{
"name": "test",
"username": "jane-doe",
"rotation_period": "1d",
},
// writes role, writes cred
findUser: true,
},
{
name: "no aws user",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserError(errors.New("no such user, etc etc")),
},
data: map[string]interface{}{
"name": "test",
"username": "a-nony-mous",
"rotation_period": "15s",
},
expectedError: true,
},
{
name: "update existing user, decreased rotation duration",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserOutput(&iam.GetUserOutput{User: &iam.User{UserName: aws.String("john-doe"), UserId: aws.String("unique-id")}}),
awsutil.WithListAccessKeysOutput(&iam.ListAccessKeysOutput{
AccessKeyMetadata: []*iam.AccessKeyMetadata{},
IsTruncated: aws.Bool(false),
}),
awsutil.WithCreateAccessKeyOutput(&iam.CreateAccessKeyOutput{
AccessKey: &iam.AccessKey{
AccessKeyId: aws.String("abcdefghijklmnopqrstuvwxyz"),
SecretAccessKey: aws.String("zyxwvutsrqponmlkjihgfedcba"),
UserName: aws.String("john-doe"),
},
}),
},
data: map[string]interface{}{
"name": "johnny",
"rotation_period": "19m",
},
findUser: true,
isUpdate: true,
newPriority: time.Now().Add(19 * time.Minute).Unix(),
},
{
name: "update existing user, increased rotation duration",
opts: []awsutil.MockIAMOption{
awsutil.WithGetUserOutput(&iam.GetUserOutput{User: &iam.User{UserName: aws.String("john-doe"), UserId: aws.String("unique-id")}}),
awsutil.WithListAccessKeysOutput(&iam.ListAccessKeysOutput{
AccessKeyMetadata: []*iam.AccessKeyMetadata{},
IsTruncated: aws.Bool(false),
}),
awsutil.WithCreateAccessKeyOutput(&iam.CreateAccessKeyOutput{
AccessKey: &iam.AccessKey{
AccessKeyId: aws.String("abcdefghijklmnopqrstuvwxyz"),
SecretAccessKey: aws.String("zyxwvutsrqponmlkjihgfedcba"),
UserName: aws.String("john-doe"),
},
}),
},
data: map[string]interface{}{
"name": "johnny",
"rotation_period": "40h",
},
findUser: true,
isUpdate: true,
newPriority: time.Now().Add(40 * time.Hour).Unix(),
},
}
// if a user exists (user doesn't exist is tested in validation)
// we'll check how many keys the user has - if it's two, we delete one.
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
miam, err := awsutil.NewMockIAM(
c.opts...,
)(nil)
if err != nil {
t.Fatal(err)
}
b := Backend(config)
// Used to override the real IAM client creation to return the mocked client
b.nonCachedClientIAMFunc = func(ctx context.Context, s logical.Storage, logger hclog.Logger, entry *staticRoleEntry) (iamiface.IAMAPI, error) {
return miam, nil
}
if err := b.Setup(bgCTX, config); err != nil {
t.Fatal(err)
}
// put a role in storage for update tests
staticRole := staticRoleEntry{
Name: "johnny",
Username: "john-doe",
ID: "unique-id",
RotationPeriod: 24 * time.Hour,
}
entry, err := logical.StorageEntryJSON(formatRoleStoragePath(staticRole.Name), staticRole)
if err != nil {
t.Fatal(err)
}
err = config.StorageView.Put(bgCTX, entry)
if err != nil {
t.Fatal(err)
}
req := &logical.Request{
Operation: logical.UpdateOperation,
Storage: config.StorageView,
Data: c.data,
Path: "static-roles/" + c.data["name"].(string),
}
r, err := b.pathStaticRolesWrite(bgCTX, req, staticRoleFieldData(req.Data))
if c.expectedError && err == nil {
t.Fatal(err)
} else if c.expectedError {
return // save us some if statements
}
if err != nil {
t.Fatalf("got an error back unexpectedly: %s", err)
}
if c.findUser && r == nil {
t.Fatal("response was nil, but it shouldn't have been")
}
role, err := config.StorageView.Get(bgCTX, req.Path)
if c.findUser && (err != nil || role == nil) {
t.Fatalf("couldn't find the role we should have stored: %s", err)
}
var actualData staticRoleEntry
err = role.DecodeJSON(&actualData)
if err != nil {
t.Fatalf("couldn't convert storage data to role entry: %s", err)
}
// construct expected data
var expectedData staticRoleEntry
fieldData := staticRoleFieldData(c.data)
if c.isUpdate {
// data is johnny + c.data
expectedData = staticRole
}
var actualItem *queue.Item
if c.isUpdate {
actualItem, _ = b.credRotationQueue.PopByKey(expectedData.Name)
}
if u, ok := fieldData.GetOk("username"); ok {
expectedData.Username = u.(string)
}
if r, ok := fieldData.GetOk("rotation_period"); ok {
expectedData.RotationPeriod = time.Duration(r.(int)) * time.Second
}
if n, ok := fieldData.GetOk("name"); ok {
expectedData.Name = n.(string)
}
// validate fields
if eu, au := expectedData.Username, actualData.Username; eu != au {
t.Fatalf("mismatched username, expected %q but got %q", eu, au)
}
if er, ar := expectedData.RotationPeriod, actualData.RotationPeriod; er != ar {
t.Fatalf("mismatched rotation period, expected %q but got %q", er, ar)
}
if en, an := expectedData.Name, actualData.Name; en != an {
t.Fatalf("mismatched role name, expected %q, but got %q", en, an)
}
// one-off to avoid importing/casting
abs := func(x int64) int64 {
if x < 0 {
return -x
}
return x
}
if c.isUpdate {
if ep, ap := c.newPriority, actualItem.Priority; abs(ep-ap) > 5 { // 5 second wiggle room for how long the test takes
t.Fatalf("mismatched updated priority, expected %d but got %d", ep, ap)
}
}
})
}
}
// TestStaticRoleRead validates that we can read a configured role and correctly do not read anything if we
// request something that doesn't exist.
func TestStaticRoleRead(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
bgCTX := context.Background()
// test cases are run against an inmem storage holding a role called "test" attached to an IAM user called "jane-doe"
cases := []struct {
name string
roleName string
found bool
}{
{
name: "role name exists",
roleName: "test",
found: true,
},
{
name: "role name not found",
roleName: "toast",
found: false, // implied, but set for clarity
},
}
staticRole := staticRoleEntry{
Name: "test",
Username: "jane-doe",
RotationPeriod: 24 * time.Hour,
}
entry, err := logical.StorageEntryJSON(formatRoleStoragePath(staticRole.Name), staticRole)
if err != nil {
t.Fatal(err)
}
err = config.StorageView.Put(bgCTX, entry)
if err != nil {
t.Fatal(err)
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
req := &logical.Request{
Operation: logical.ReadOperation,
Storage: config.StorageView,
Data: map[string]interface{}{
"name": c.roleName,
},
Path: formatRoleStoragePath(c.roleName),
}
b := Backend(config)
r, err := b.pathStaticRolesRead(bgCTX, req, staticRoleFieldData(req.Data))
if err != nil {
t.Fatal(err)
}
if c.found {
if r == nil {
t.Fatal("response was nil, but it shouldn't have been")
}
} else {
if r != nil {
t.Fatal("response should have been nil on a non-existent role")
}
}
})
}
}
// TestStaticRoleDelete validates that we correctly remove a role on a delete request, and that we correctly do not
// remove anything if a role does not exist with that name.
func TestStaticRoleDelete(t *testing.T) {
bgCTX := context.Background()
// test cases are run against an inmem storage holding a role called "test" attached to an IAM user called "jane-doe"
cases := []struct {
name string
role string
found bool
}{
{
name: "role found",
role: "test",
found: true,
},
{
name: "role not found",
role: "tossed",
found: false,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
// fake an IAM
var iamfunc awsutil.IAMAPIFunc
if !c.found {
iamfunc = awsutil.NewMockIAM(awsutil.WithDeleteAccessKeyError(errors.New("shouldn't have called delete")))
} else {
iamfunc = awsutil.NewMockIAM()
}
miam, err := iamfunc(nil)
if err != nil {
t.Fatalf("couldn't initialize mockiam: %s", err)
}
b := Backend(config)
// Used to override the real IAM client creation to return the mocked client
b.nonCachedClientIAMFunc = func(ctx context.Context, s logical.Storage, logger hclog.Logger, entry *staticRoleEntry) (iamiface.IAMAPI, error) {
return miam, nil
}
// put in storage
staticRole := staticRoleEntry{
Name: "test",
Username: "jane-doe",
RotationPeriod: 24 * time.Hour,
}
entry, err := logical.StorageEntryJSON(formatRoleStoragePath(staticRole.Name), staticRole)
if err != nil {
t.Fatal(err)
}
err = config.StorageView.Put(bgCTX, entry)
if err != nil {
t.Fatal(err)
}
l, err := config.StorageView.List(bgCTX, "")
if err != nil || len(l) != 1 {
t.Fatalf("couldn't add an entry to storage during test setup: %s", err)
}
// put in queue
err = b.credRotationQueue.Push(&queue.Item{
Key: staticRole.Name,
Value: staticRole,
Priority: time.Now().Add(90 * time.Hour).Unix(),
})
if err != nil {
t.Fatalf("couldn't add items to pq")
}
req := &logical.Request{
Operation: logical.ReadOperation,
Storage: config.StorageView,
Data: map[string]interface{}{
"name": c.role,
},
Path: formatRoleStoragePath(c.role),
}
r, err := b.pathStaticRolesDelete(bgCTX, req, staticRoleFieldData(req.Data))
if err != nil {
t.Fatal(err)
}
if r != nil {
t.Fatal("response wasn't nil, but it should have been")
}
l, err = config.StorageView.List(bgCTX, "")
if err != nil {
t.Fatal(err)
}
if c.found && len(l) != 0 {
t.Fatal("size of role storage is non zero after delete")
} else if !c.found && len(l) != 1 {
t.Fatal("size of role storage changed after what should have been no deletion")
}
if c.found && b.credRotationQueue.Len() != 0 {
t.Fatal("size of queue is non-zero after delete")
} else if !c.found && b.credRotationQueue.Len() != 1 {
t.Fatal("size of queue changed after what should have been no deletion")
}
})
}
}
// TestStaticRolesList validates that we can list all the static roles in the storage backend.
func TestStaticRolesList(t *testing.T) {
config := logical.TestBackendConfig()
config.StorageView = &logical.InmemStorage{}
bgCTX := context.Background()
staticRoles := []staticRoleEntry{}
for i := 1; i <= 10; i++ {
roles := staticRoleEntry{
Name: "testrole" + strconv.Itoa(i),
Username: "jane-doe",
RotationPeriod: 24 * time.Hour,
}
staticRoles = append(staticRoles, roles)
}
for _, role := range staticRoles {
entry, err := logical.StorageEntryJSON(formatRoleStoragePath(role.Name), role)
if err != nil {
t.Fatalf("failed to create storage entry for %s: %v", role.Name, err)
}
err = config.StorageView.Put(bgCTX, entry)
if err != nil {
t.Fatalf("failed to store role %s: %v", role.Name, err)
}
}
b := Backend(config)
resp, err := b.HandleRequest(bgCTX, &logical.Request{
Operation: logical.ListOperation,
Path: "static-roles",
Storage: config.StorageView,
})
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("bad: listing roles failed. resp:%#v\n err:%v", resp, err)
}
if len(resp.Data["keys"].([]string)) != 10 {
t.Fatalf("failed to list all 10 roles")
}
resp, err = b.HandleRequest(bgCTX, &logical.Request{
Operation: logical.ListOperation,
Path: "static-roles/",
Storage: config.StorageView,
})
if err != nil || (resp != nil && resp.IsError()) {
t.Fatalf("bad: listing roles failed. resp:%#v\n err:%v", resp, err)
}
if len(resp.Data["keys"].([]string)) != 10 {
t.Fatalf("failed to list all 10 roles")
}
}
func staticRoleFieldData(data map[string]interface{}) *framework.FieldData {
schema := map[string]*framework.FieldSchema{
paramRoleName: {
Type: framework.TypeString,
Description: descRoleName,
},
paramUsername: {
Type: framework.TypeString,
Description: descUsername,
},
paramRotationPeriod: {
Type: framework.TypeDurationSecond,
Description: descRotationPeriod,
},
}
return &framework.FieldData{
Raw: data,
Schema: schema,
}
}