-
Notifications
You must be signed in to change notification settings - Fork 3
/
path_roles_test.go
467 lines (390 loc) · 12.8 KB
/
path_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
package ibmcloudsecrets
import (
"context"
"fmt"
"math/rand"
"reflect"
"strings"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/logical"
)
// Defaults for verifying response data. If a value is not included here, it must be included in the
// 'expected' map param for a test.
var expectedDefaults = map[string]interface{}{
ttlField: int64(0),
maxTTLField: int64(0),
accessGroupIDsField: []string{},
serviceIDField: "",
}
// Test roles with access groups lists
func TestCRUDHappyPathAccessGroups(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
minCalls := map[string]int{
"VerifyAccessGroupExists": 4,
}
b, s := getMockedBackend(t, ctrl, minCalls)
roleName := testRole(t)
boundGroups := []string{"group1", "group2", "group3"}
testRoleCreate(t, b, s, map[string]interface{}{
nameField: roleName,
accessGroupIDsField: strings.Join(boundGroups, ","),
})
testRoleRead(t, b, s, roleName, map[string]interface{}{
nameField: roleName,
accessGroupIDsField: boundGroups,
})
boundGroups = append(boundGroups, "group4")
testRoleUpdate(t, b, s, map[string]interface{}{
nameField: roleName,
ttlField: 1000,
maxTTLField: 2000,
accessGroupIDsField: strings.Join(boundGroups, ","),
})
testRoleRead(t, b, s, roleName, map[string]interface{}{
ttlField: int64(1000),
maxTTLField: int64(2000),
accessGroupIDsField: boundGroups,
})
testRoleDelete(t, b, s, roleName)
}
// Test roles with access groups lists
func TestCRUDHappyPathServiceID(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
minCalls := map[string]int{
"CheckServiceIDAccount": 2,
}
b, s := getMockedBackend(t, ctrl, minCalls)
roleName := testRole(t)
boundID := "serviceID1"
testRoleCreate(t, b, s, map[string]interface{}{
nameField: roleName,
serviceIDField: boundID,
})
testRoleRead(t, b, s, roleName, map[string]interface{}{
nameField: roleName,
serviceIDField: boundID,
})
testRoleUpdate(t, b, s, map[string]interface{}{
nameField: roleName,
ttlField: 1000,
maxTTLField: 2000,
serviceIDField: "serviceID2",
})
testRoleRead(t, b, s, roleName, map[string]interface{}{
ttlField: int64(1000),
maxTTLField: int64(2000),
serviceIDField: "serviceID2",
})
testRoleDelete(t, b, s, roleName)
}
func TestAccessGroupVerifyError(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
minCalls := map[string]int{
"VerifyAccessGroupExists": 2,
}
b, s := getMockedBackend(t, ctrl, minCalls)
roleName := testRole(t)
boundGroups := []string{"group1", "problemGroup"}
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
accessGroupIDsField: boundGroups,
},
[]string{"VerifyAccessGroupExists error with problemGroup"})
}
func TestServiceIDVerifyError(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
defer ctrl.Finish()
minCalls := map[string]int{
"CheckServiceIDAccount": 1,
}
b, s := getMockedBackend(t, ctrl, minCalls)
roleName := testRole(t)
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
serviceIDField: "serviceIDNotThere",
},
[]string{"CheckServiceIDAccount error with serviceIDNotThere"})
}
func TestBindingSpecificationErrors(t *testing.T) {
t.Parallel()
b, s := testBackend(t)
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
err := testConfigCreate(t, b, s, configData)
if err != nil {
t.Fatal("error configuring the backend")
}
roleName := testRole(t)
// Test no bindings specified
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
},
[]string{"either a service ID or a non empty access group list are required"})
// Test both bindings specified
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
serviceIDField: "s1",
accessGroupIDsField: []string{"group1"},
},
[]string{"either an access group list or service ID should be provided, not both"})
}
func TestTTLError(t *testing.T) {
t.Parallel()
b, s := testBackend(t)
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
err := testConfigCreate(t, b, s, configData)
if err != nil {
t.Fatal("error configuring the backend")
}
roleName := testRole(t)
boundGroups := []string{"group1"}
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
accessGroupIDsField: boundGroups,
ttlField: 200,
maxTTLField: 100,
},
[]string{"ttl cannot be greater than max_ttl"})
}
func TestAccessGroupLimits(t *testing.T) {
t.Parallel()
b, s := testBackend(t)
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
err := testConfigCreate(t, b, s, configData)
if err != nil {
t.Fatal("error configuring the backend")
}
// Test more than the max num of access groups
//boundGroups := [maxGroupsPerRole + 1]string{}
boundGroups := make([]string, maxGroupsPerRole+1)
for index := range boundGroups {
boundGroups[index] = fmt.Sprintf("group%d", index)
}
roleName := testRole(t)
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
accessGroupIDsField: boundGroups,
},
[]string{fmt.Sprintf("the maximum number of access groups per role is: %d", maxGroupsPerRole)})
// Test the Public access group
roleName = testRole(t)
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
accessGroupIDsField: []string{"AccessGroupId-PublicAccess"},
},
[]string{"the AccessGroupId-PublicAccess access group is not allowed on roles"})
}
func TestNoConfig(t *testing.T) {
t.Parallel()
b, s := testBackend(t)
roleName := testRole(t)
testRoleCreateError(t, b, s, map[string]interface{}{
nameField: roleName,
},
[]string{"no API key was set in the configuration"})
}
// -- Utils --
func testRoleCreate(tb testing.TB, b logical.Backend, s logical.Storage, d map[string]interface{}) {
tb.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.CreateOperation,
Path: fmt.Sprintf("roles/%s", d[nameField]),
Data: d,
Storage: s,
})
if err != nil {
tb.Fatal(err)
}
if resp != nil && resp.IsError() {
tb.Fatal(resp.Error())
}
}
func testRoleUpdate(tb testing.TB, b logical.Backend, s logical.Storage, d map[string]interface{}) {
tb.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.UpdateOperation,
Path: fmt.Sprintf("roles/%s", d[nameField]),
Data: d,
Storage: s,
})
if err != nil {
tb.Fatal(err)
}
if resp != nil && resp.IsError() {
tb.Fatal(resp.Error())
}
}
func testRoleDelete(tb testing.TB, b logical.Backend, s logical.Storage, roleName string) {
tb.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.DeleteOperation,
Path: fmt.Sprintf("roles/%s", roleName),
Storage: s,
})
if err != nil {
tb.Fatalf("unable to delete role: %v", err)
} else if resp != nil {
if len(resp.Warnings) > 0 {
tb.Logf("warnings returned from role delete. Warnings:\n %s\n", strings.Join(resp.Warnings, ",\n"))
}
if resp.IsError() {
tb.Fatalf("unable to delete role: %v", resp.Error())
}
}
resp, err = b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.ReadOperation,
Path: fmt.Sprintf("roles/%s", roleName),
Storage: s,
})
if resp != nil || err != nil {
tb.Fatalf("expected nil response and error, actual:%#v and %#v", resp, err)
}
}
func testRoleCreateError(tb testing.TB, b logical.Backend, s logical.Storage, d map[string]interface{}, expected []string) {
tb.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.CreateOperation,
Path: fmt.Sprintf("roles/%s", d[nameField]),
Data: d,
Storage: s,
})
if err != nil {
tb.Fatal(err)
}
if resp == nil || !resp.IsError() {
tb.Fatalf("expected error containing: %s", strings.Join(expected, ", "))
}
for _, str := range expected {
if !strings.Contains(resp.Error().Error(), str) {
tb.Fatalf("expected %s to be in error %v", str, resp.Error())
}
}
}
func testRoleRead(tb testing.TB, b logical.Backend, s logical.Storage, roleName string, expected map[string]interface{}) {
tb.Helper()
resp, err := b.HandleRequest(context.Background(), &logical.Request{
Operation: logical.ReadOperation,
Path: fmt.Sprintf("roles/%s", roleName),
Storage: s,
})
if err != nil {
tb.Fatal(err)
}
if resp != nil && resp.IsError() {
tb.Fatal(resp.Error())
}
convertRespTypes(resp.Data)
if err := checkData(resp, expected, expectedDefaults); err != nil {
tb.Fatal(err)
}
}
func checkData(resp *logical.Response, expected map[string]interface{}, expectedDefault map[string]interface{}) error {
for k, actualVal := range resp.Data {
expectedVal, ok := expected[k]
if !ok {
expectedVal, ok = expectedDefault[k]
if !ok {
return fmt.Errorf("must provide expected value for %q for test", k)
}
}
var isEqual bool
switch actualVal.(type) {
case []string:
actual := actualVal.([]string)
expected, ok := expectedVal.([]string)
if !ok {
return fmt.Errorf("%s type mismatch: expected type %T, actual type %T", k, expectedVal, actualVal)
}
isEqual = (len(actual) == 0 && len(expected) == 0) ||
strutil.EquivalentSlices(actual, expected)
case map[string]string:
actual := actualVal.(map[string]string)
expected, ok := expectedVal.(map[string]string)
if !ok {
return fmt.Errorf("%s type mismatch: expected type %T, actual type %T", k, expectedVal, actualVal)
}
isEqual = (len(actual) == 0 && len(expected) == 0) ||
reflect.DeepEqual(actualVal, expectedVal)
default:
isEqual = actualVal == expectedVal
}
if !isEqual {
return fmt.Errorf("%s mismatch, expected: %v but got %v", k, expectedVal, actualVal)
}
}
return nil
}
// testRole generates a unique name for a role
func testRole(tb testing.TB) string {
tb.Helper()
r := rand.New(rand.NewSource(time.Now().UnixNano()))
suffix := fmt.Sprintf("%d", r.Intn(1000000))
roleName := "v-role-" + suffix
return roleName
}
/*
This function configures the mock iamHelper expectations for the test. It then creates a test Backend with
with the mock, and configures it.
The minCalls map is used to control the minimum number of times the functions of the iamHelper interface are
expected to be called. The keys are the function names (e.g. "ObtainToken", "VerifyAccessGroupExists", etc).
If unspecified 0 is used.
*/
func getMockedBackend(t *testing.T, ctrl *gomock.Controller, minCalls map[string]int) (*ibmCloudSecretBackend, logical.Storage) {
t.Helper()
var configData = map[string]interface{}{
apiKeyField: "adminKey",
accountIDField: "theAccountID",
}
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)
mockHelper.EXPECT().VerifyAccessGroupExists("AdminToken", gomock.Any(), "theAccountID").
MinTimes(minCalls["VerifyAccessGroupExists"]).DoAndReturn(func(iamToken, group, accountID string) *logical.Response {
if !strutil.StrListContains([]string{"group1", "group2", "group3", "group4"}, group) {
return logical.ErrorResponse("VerifyAccessGroupExists error with %s", group)
}
return nil
})
mockHelper.EXPECT().CheckServiceIDAccount("AdminToken", gomock.Any(), "theAccountID").
MinTimes(minCalls["CheckServiceIDAccount"]).DoAndReturn(func(iamToken, serviceID, accountID string) (*serviceIDv1Response, *logical.Response) {
if !strutil.StrListContains([]string{"serviceID1", "serviceID2"}, serviceID) {
return nil, logical.ErrorResponse("CheckServiceIDAccount error with %s", serviceID)
}
return nil, 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
}
// Utility function to convert response types back to the format that is used as
// input in order to streamline the comparison steps.
func convertRespTypes(data map[string]interface{}) {
data[ttlField] = int64(data[ttlField].(time.Duration))
data[maxTTLField] = int64(data[maxTTLField].(time.Duration))
}