-
Notifications
You must be signed in to change notification settings - Fork 3
/
path_creds_test.go
508 lines (434 loc) · 18.2 KB
/
path_creds_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
package ibmcloudsecrets
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/logical"
)
func TestStaticServiceID(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Set up
callCount := map[string]int{
"CheckServiceIDAccount": 9,
"CreateAPIKey": 4,
}
b, s := getMockedBackendStaticServiceID(t, ctrl, callCount)
// Test successful Get
testRoleCreate(t, b, s, map[string]interface{}{nameField: "testRole", serviceIDField: "serviceID1"})
sec := testSuccessfulGet(t, b, s, map[string]string{apiKeyID: "apiKeyID"}, 0, 0)
// Test successful renew and revoke
testSuccessfulRenew(t, b, s, sec)
testSuccessfulRevoke(t, b, s, sec)
// Update role with TTLs set
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", serviceIDField: "serviceID1", ttlField: 1000, maxTTLField: 2000})
// Test successful Get, verify TTLs
sec = testSuccessfulGet(t, b, s, map[string]string{apiKeyID: "apiKeyID"}, 1000, 2000)
// Update role to different user
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", serviceIDField: "serviceID2"})
// Test failure to renew
testRenewFailureWithChangedBindings(t, b, s, sec)
// Test failure to get a credential
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", serviceIDField: "keyFailureGetUser"})
testFailedGet(t, b, s)
// Test failure to renew when the role has been deleted
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", serviceIDField: "serviceID1"})
sec = testSuccessfulGet(t, b, s, map[string]string{apiKeyID: "apiKeyID"}, 1000, 2000)
testRoleDelete(t, b, s, "testRole")
testRenewFailureWithDeletedRole(t, b, s, sec)
}
func TestDynamicServiceID(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Set up
callCount := map[string]int{
"CreateServiceID": 4,
"CreateAPIKey": 3,
"DeleteServiceID": 1,
"VerifyAccessGroupExists": 16,
"AddServiceIDToAccessGroup": 12,
}
b, s := getMockedBackendDynamicServiceID(t, ctrl, callCount)
// Test successful Get
accessGroups := []string{"a", "b", "c"}
testRoleCreate(t, b, s, map[string]interface{}{nameField: "testRole", accessGroupIDsField: accessGroups})
sec := testSuccessfulGet(t, b, s, map[string]string{serviceIDField: "createdServiceID"}, 0, 0)
// Test successful renew and revoke
testSuccessfulRenew(t, b, s, sec)
testSuccessfulRevoke(t, b, s, sec)
// Update role with TTLs set
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", accessGroupIDsField: accessGroups, ttlField: 1000, maxTTLField: 2000})
// Test successful Get, verify TTLs
sec = testSuccessfulGet(t, b, s, map[string]string{serviceIDField: "createdServiceID"}, 1000, 2000)
// Update role to add a group
accessGroups = append(accessGroups, "d")
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", accessGroupIDsField: accessGroups})
// Test failure to renew
testRenewFailureWithChangedBindings(t, b, s, sec)
// Test failure to get a credential
accessGroups = append(accessGroups, "groupToTriggerFailure")
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", accessGroupIDsField: accessGroups})
testFailedGet(t, b, s)
// Test failure to renew when the role has been deleted
accessGroups = []string{"a"}
testRoleUpdate(t, b, s, map[string]interface{}{nameField: "testRole", accessGroupIDsField: accessGroups})
sec = testSuccessfulGet(t, b, s, map[string]string{serviceIDField: "createdServiceID"}, 1000, 2000)
testRoleDelete(t, b, s, "testRole")
testRenewFailureWithDeletedRole(t, b, s, sec)
}
func TestStaticServiceIDDeleted(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
// Set up
b, s := getMockedBackendStaticServiceIDDeleteTest(t, ctrl)
testRoleCreate(t, b, s, map[string]interface{}{nameField: "testRole", serviceIDField: "serviceID1"})
// Test failed get
testFailedGet(t, b, s)
}
/*
Tests a successful Get (read) of a credential and validates the returned Secret.
The internalData parameter is used to pass in key-values that differ between static and dynamic service ID credentials.
If the ttl and maxTTL values are greater than 0 they will be used to check the Secret's lease.
*/
func testSuccessfulGet(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage, internalData map[string]string, ttl, maxTTL int) *logical.Secret {
t.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.ReadOperation,
Path: "creds/testRole",
Storage: s,
})
if err != nil {
t.Fatalf("\nunexpected error: %s", err.Error())
}
if resp.IsError() {
t.Fatalf("expected no response error, actual:%#v", resp.Error())
}
if resp == nil || resp.Secret == nil {
t.Fatalf("expected response with secret, got response: %v", resp)
}
// Verify the response
if resp.Data[apiKeyField].(string) != "theAPIKey" {
t.Fatalf("did not receive the exepcted API key")
}
for k, v := range internalData {
testV, ok := resp.Secret.InternalData[k]
if !ok {
t.Fatalf("did not find key %s in the Secret's InternalData", k)
}
if testV.(string) != v {
t.Fatalf("found %s=%s in the Secret's InternalData. expected %s=%s", k, testV, k, v)
}
}
if resp.Secret.InternalData[roleNameField].(string) != "testRole" {
t.Fatalf("the internal data does not contain the expected role name")
}
if _, ok := resp.Secret.InternalData[roleBindingHashField]; !ok {
t.Fatalf("the internal data does not contain the role binding hash")
}
if ttl > 0 && int(resp.Secret.LeaseTotal().Seconds()) != ttl {
t.Fatalf("expected lease duration %d, got %d", ttl, int(resp.Secret.LeaseTotal().Seconds()))
}
if maxTTL > 0 && int(resp.Secret.LeaseOptions.MaxTTL.Seconds()) != maxTTL {
t.Fatalf("expected max lease %d, got %d", maxTTL, int(resp.Secret.LeaseOptions.MaxTTL.Seconds()))
}
return resp.Secret
}
func testFailedGet(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage) {
t.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.ReadOperation,
Path: "creds/testRole",
Storage: s,
})
if (err == nil) && (resp == nil || !resp.IsError()) {
t.Fatalf("expected an error, or an error Response, actual returns: resp:%#v err:%#v", resp, err)
}
}
func testSuccessfulRenew(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage, sec *logical.Secret) {
t.Helper()
sec.IssueTime = time.Now()
sec.Increment = time.Hour
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.RenewOperation,
Secret: sec,
Storage: s,
})
if err != nil {
t.Fatalf("got error while trying to renew: %v", err)
} else if resp.IsError() {
t.Fatalf("got error while trying to renew: %v", resp.Error())
}
}
func testSuccessfulRevoke(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage, sec *logical.Secret) {
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.RevokeOperation,
Secret: sec,
Storage: s,
})
if err != nil {
t.Fatal(err)
}
if resp != nil && resp.IsError() {
t.Fatal(resp.Error())
}
}
func testRenewFailureWithChangedBindings(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage, sec *logical.Secret) {
t.Helper()
sec.IssueTime = time.Now()
sec.Increment = time.Hour
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.RenewOperation,
Secret: sec,
Storage: s,
})
if err != nil {
t.Fatal(err)
}
expectedMsg := "access group or service ID bindings were updated since secret was generated, cannot renew"
if resp == nil {
t.Fatalf("expected an error response on renew but did not receive one")
} else if !strings.Contains(resp.Error().Error(), expectedMsg) {
t.Fatalf("expected message \"%s\" to be in error: %v", expectedMsg, resp.Error())
}
}
func testRenewFailureWithDeletedRole(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage, sec *logical.Secret) {
t.Helper()
sec.IssueTime = time.Now()
sec.Increment = time.Hour
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.RenewOperation,
Secret: sec,
Storage: s,
})
if err != nil {
t.Fatal(err)
}
expectedMsg := "could not find role 'testRole' for secret"
if resp == nil {
t.Fatalf("expected an error response on renew but did not receive one")
} else if !strings.Contains(resp.Error().Error(), expectedMsg) {
t.Fatalf("expected message \"%s\" to be in error: %v", expectedMsg, resp.Error())
}
}
// TestServiceID_WAL_Cleanup tests that any service ID that gets created, but
// fails to have an API key created for it, gets cleaned up by the periodic WAL
// function.
func TestServiceID_WAL_Cleanup(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
callCount := map[string]int{
"VerifyAccessGroupExists": 1,
"CreateServiceID": 1,
"AddServiceIDToAccessGroup": 1,
"CreateAPIKey": 1,
"DeleteServiceID": 1,
}
b, s := getMockedBackendDynamicServiceID(t, ctrl, callCount)
wal, _ := framework.ListWAL(context.Background(), s)
if len(wal) != 0 {
t.Fatalf("The WAL is not empty at the start of the test.")
}
// Test successful Get
accessGroups := []string{"a"}
testRoleCreate(t, b, s, map[string]interface{}{nameField: "APIKeyErrorRole", accessGroupIDsField: accessGroups})
// create a short timeout to short-circuit the retry process and trigger the
// deadline error
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := b.HandleRequest(ctx, &logical.Request{
Operation: logical.ReadOperation,
Path: "creds/APIKeyErrorRole",
Storage: s,
})
if err == nil {
t.Fatalf("expected an error, but did not receive one")
}
if resp != nil {
t.Fatalf("expected no response, but received:%#v", resp)
}
if !strings.Contains(err.Error(), "intentional test error from mock CreateAPIKey") {
t.Fatalf("expected intentional error from mock, but got '%s'", err.Error())
}
assertEmptyWAL(t, b, s)
}
func assertEmptyWAL(t *testing.T, b *ibmCloudSecretBackend, s logical.Storage) {
t.Helper()
wal, err := framework.ListWAL(context.Background(), s)
if err != nil {
t.Fatalf("error listing wal: %s", err)
}
req := &logical.Request{
Storage: s,
}
// loop of WAL entries and trigger the rollback method for each, simulating
// Vault's rollback mechanism
for _, v := range wal {
ctx := context.Background()
entry, err := framework.GetWAL(ctx, s, v)
if err != nil {
t.Fatal(err)
}
err = b.walRollback(ctx, req, entry.Kind, entry.Data)
if err != nil {
t.Fatal(err)
}
if err := framework.DeleteWAL(ctx, s, v); err != nil {
t.Fatal(err)
}
}
}
func getMockedBackendStaticServiceID(t *testing.T, ctrl *gomock.Controller, callCount map[string]int) (*ibmCloudSecretBackend, logical.Storage) {
t.Helper()
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
adminToken := "AdminToken"
mockHelper := NewMockiamHelper(ctrl)
// For the adminKey we always return AdminToken, this lets enforce that the code is correctly using the admin token
// for the IBM Cloud API calls calls.
mockHelper.EXPECT().ObtainToken("adminKey").Return(adminToken, nil)
mockHelper.EXPECT().VerifyToken(gomock.Any(), adminToken).Return(&tokenInfo{Expiry: time.Now().Add(time.Hour)}, nil)
mockHelper.EXPECT().GetAPIKeyDetails("AdminToken", "adminKey").
Return(&APIKeyDetailsResponse{ID: "oldID", IAMID: "testIAMID", AccountID: "theAccountID"}, nil)
// Mock for create / update of the test role and the look up of the service ID's IAM ID
mockHelper.EXPECT().CheckServiceIDAccount(adminToken, gomock.Any(), "theAccountID").
Times(callCount["CheckServiceIDAccount"]).
DoAndReturn(func(iamToken, serviceID, accountID string) (*serviceIDv1Response, *logical.Response) {
if !strutil.StrListContains([]string{"serviceID1", "serviceID2", "keyFailureGetUser"}, serviceID) {
return nil, logical.ErrorResponse("CheckServiceIDAccount error with %s", serviceID)
}
return &serviceIDv1Response{ID: "serviceID1", IAMID: fmt.Sprintf("%s_iam", serviceID)}, nil
})
mockHelper.EXPECT().CreateAPIKey(adminToken, gomock.Any(), "theAccountID", gomock.Any(), gomock.Any()).
Times(callCount["CreateAPIKey"]).
DoAndReturn(func(iamToken, iamID, accountID, name, description string) (*APIKeyV1Response, error) {
roleName := "testRole"
if !strings.Contains(name, roleName) {
t.Fatalf("expected %s to be in the key name %s", roleName, name)
}
if !strings.Contains(description, roleName) {
t.Fatalf("expected %s to be in the key description %s", roleName, description)
}
if iamID == "keyFailureGetUser_iam" {
return nil, fmt.Errorf("intentional CreateAPIKey mock failure")
}
return &APIKeyV1Response{ID: "apiKeyID", APIKey: "theAPIKey"}, nil
})
mockHelper.EXPECT().DeleteAPIKey(adminToken, "apiKeyID").
Return(nil)
b, s := testBackend(t)
err := testConfigCreate(t, b, s, configData)
if err != nil {
t.Fatal("error configuring the backend")
}
b.iamHelper = mockHelper
return b, s
}
func getMockedBackendDynamicServiceID(t *testing.T, ctrl *gomock.Controller, callCount map[string]int) (*ibmCloudSecretBackend, logical.Storage) {
t.Helper()
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
adminToken := "AdminToken"
mockHelper := NewMockiamHelper(ctrl)
// For the adminKey we always return AdminToken, this lets enforce that the code is correctly using the admin token
// for the IBM Cloud API calls calls.
mockHelper.EXPECT().ObtainToken("adminKey").Return(adminToken, nil)
mockHelper.EXPECT().VerifyToken(gomock.Any(), adminToken).Return(&tokenInfo{Expiry: time.Now().Add(time.Hour)}, nil)
mockHelper.EXPECT().GetAPIKeyDetails("AdminToken", "adminKey").
Return(&APIKeyDetailsResponse{ID: "oldID", IAMID: "testIAMID", AccountID: "theAccountID"}, nil)
// Mock for create / update of the test role and the look up of the service ID's IAM ID
mockHelper.EXPECT().VerifyAccessGroupExists(adminToken, gomock.Any(), "theAccountID").
Times(callCount["VerifyAccessGroupExists"]).
DoAndReturn(func(iamToken, group, accountID string) (*logical.Response, error) {
if !strutil.StrListContains([]string{"a", "b", "c", "d", "groupToTriggerFailure"}, group) {
return logical.ErrorResponse("VerifyAccessGroupExists error with %s", group), nil
}
return nil, nil
})
// Mocks for getSecretDynamicServiceID
mockHelper.EXPECT().CreateServiceID(adminToken, "theAccountID", gomock.Any()).
Times(callCount["CreateServiceID"]).
DoAndReturn(func(iamToken, accountID, roleName string) (string, string, error) {
if roleName != "testRole" && roleName != "APIKeyErrorRole" {
return "", "", fmt.Errorf("unexpected role name in CreateServiceID: %s", roleName)
}
return "createdServiceID_iam", "createdServiceID", nil
})
mockHelper.EXPECT().AddServiceIDToAccessGroup(adminToken, "createdServiceID_iam", gomock.Any()).
Times(callCount["AddServiceIDToAccessGroup"]).
DoAndReturn(func(iamToken, iamID, group string) error {
if !strutil.StrListContains([]string{"a", "b", "c", "d"}, group) {
return fmt.Errorf("AddServiceIDToAccessGroup error with group %s", group)
}
return nil
})
mockHelper.EXPECT().CreateAPIKey(adminToken, "createdServiceID_iam", "theAccountID", gomock.Any(), gomock.Any()).
Times(callCount["CreateAPIKey"]).
DoAndReturn(func(iamToken, iamID, accountID, name, description string) (*APIKeyV1Response, error) {
if strings.Contains(name, "testRole") {
if !strings.Contains(description, "testRole") {
t.Fatalf("expected %s to be in the key description %s", "testRole", description)
}
return &APIKeyV1Response{ID: "apiKeyID", APIKey: "theAPIKey"}, nil
} else if strings.Contains(name, "APIKeyErrorRole") {
if !strings.Contains(description, "APIKeyErrorRole") {
t.Fatalf("expected %s to be in the key description %s", "APIKeyErrorRole", description)
}
return nil, fmt.Errorf("intentional test error from mock CreateAPIKey")
} else {
return nil, fmt.Errorf("unexpected key name in CreateAPIKey mock: %s", name)
}
})
// Mock for revoke
mockHelper.EXPECT().DeleteServiceID(adminToken, "createdServiceID").Times(callCount["DeleteServiceID"]).Return(nil)
b, s := testBackend(t)
err := testConfigCreate(t, b, s, configData)
if err != nil {
t.Fatal("error configuring the backend")
}
b.iamHelper = mockHelper
return b, s
}
func getMockedBackendStaticServiceIDDeleteTest(t *testing.T, ctrl *gomock.Controller) (*ibmCloudSecretBackend, logical.Storage) {
t.Helper()
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
adminToken := "AdminToken"
mockHelper := NewMockiamHelper(ctrl)
// For the adminKey we always return AdminToken, this lets enforce that the code is correctly using the admin token
// for the IBM Cloud API calls calls.
mockHelper.EXPECT().ObtainToken("adminKey").Return(adminToken, nil)
mockHelper.EXPECT().VerifyToken(gomock.Any(), adminToken).Return(&tokenInfo{Expiry: time.Now().Add(time.Hour)}, nil)
mockHelper.EXPECT().GetAPIKeyDetails("AdminToken", "adminKey").
Return(&APIKeyDetailsResponse{ID: "oldID", IAMID: "testIAMID", AccountID: "theAccountID"}, nil)
// Mock for create of the test role
mockHelper.EXPECT().CheckServiceIDAccount(adminToken, gomock.Any(), "theAccountID").
DoAndReturn(func(iamToken, serviceID, accountID string) (*serviceIDv1Response, *logical.Response) {
if !strutil.StrListContains([]string{"serviceID1"}, serviceID) {
return nil, logical.ErrorResponse("CheckServiceIDAccount error with %s", serviceID)
}
return &serviceIDv1Response{ID: "serviceID1", IAMID: fmt.Sprintf("%s_iam", serviceID)}, nil
})
// Mock to fail, simulating a service ID being deleted directly in IBM Cloud or other ID checking failure
mockHelper.EXPECT().CheckServiceIDAccount(adminToken, gomock.Any(), "theAccountID").
DoAndReturn(func(iamToken, serviceID, accountID string) (*serviceIDv1Response, *logical.Response) {
return nil, logical.ErrorResponse("CheckServiceIDAccount error with %s", serviceID)
})
b, s := testBackend(t)
err := testConfigCreate(t, b, s, configData)
if err != nil {
t.Fatal("error configuring the backend")
}
b.iamHelper = mockHelper
return b, s
}