-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminio_test.go
494 lines (441 loc) · 14.4 KB
/
minio_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
package minio
import (
"context"
"crypto/tls"
"fmt"
"net"
"reflect"
"strconv"
"testing"
"time"
backoff "github.com/cenkalti/backoff/v3"
"github.com/hashicorp/vault/sdk/helper/docker"
dbplugin "github.com/hashicorp/vault/sdk/database/dbplugin/v5"
dbtesting "github.com/hashicorp/vault/sdk/database/dbplugin/v5/testing"
api "github.com/minio/madmin-go/v3"
"github.com/stretchr/testify/require"
)
type (
checkFunc func(t testing.TB, address string, port int, username, password string, sslOpts *tls.Config) error
fixtureFunc func(t testing.TB, address string, port int, sslOpts *tls.Config)
)
const (
createUserDynamicStatements = `{"policy": {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ServerInfo"]}]}}`
staticPolicy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ServerInfo"]}]}`
createUserStaticStatements = `{"static_policies": ["test"]}`
createUserDynamicAndStaticStatements = `{"policy": {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ListUsers"]}]}, "static_policies": ["test"]}`
createUserGroupStatements = `{"groups": ["testgroup"], "policy": {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ServerInfo","admin:ListGroups","admin:ListUsers"]}]}}`
createUserAllStatements = `{"groups": ["testgroup"], "policy": {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["admin:ListUsers","admin:ListGroups"]}]}, "static_policies": ["test"]}`
createUserStaticMissingStatements = `{"static_policies": ["testmissing"]}`
)
func TestCreateUser(t *testing.T) {
type testCase struct {
usernameTemplate string
newUserReq dbplugin.NewUserRequest
expectErr bool
expectedUsernameRegex string
expectedErrRegex string
checkFuncs []checkFunc
fixtureFuncs []fixtureFunc
}
tests := map[string]testCase{
"default_username_template": {
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserDynamicStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
expectedUsernameRegex: `^v_token_mylongrolenamew_[a-z0-9]{20}_[0-9]{10}$`,
checkFuncs: []checkFunc{connect},
},
"custom_username_template": {
usernameTemplate: `foo_{{random 20}}_{{.RoleName | replace "e" "3"}}_{{unix_time}}`,
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserDynamicStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
expectedUsernameRegex: `^foo_[a-zA-Z0-9]{20}_mylongrol3nam3withmanycharact3rs_[0-9]{10}$`,
checkFuncs: []checkFunc{connect},
},
"static_policies": {
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserStaticStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
fixtureFuncs: []fixtureFunc{createPolicy},
checkFuncs: []checkFunc{connect},
},
"static_policies_missing": {
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserStaticMissingStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
expectErr: true,
expectedErrRegex: `Static policy [\w]+ does not exist`,
},
"static_and_dynamic_policies": {
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserDynamicAndStaticStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
fixtureFuncs: []fixtureFunc{createPolicy},
checkFuncs: []checkFunc{connect, checkUsers},
},
"groups": {
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserGroupStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
checkFuncs: []checkFunc{connect, checkGroups},
},
"static_and_dynamic_policies_with_groups": {
newUserReq: dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "token",
RoleName: "mylongrolenamewithmanycharacters",
},
Statements: dbplugin.Statements{
Commands: []string{createUserAllStatements},
},
Password: "newuserpass",
Expiration: time.Now().Add(1 * time.Minute),
},
fixtureFuncs: []fixtureFunc{createPolicy},
checkFuncs: []checkFunc{connect, checkGroups},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
db, cleanup := getMinio(t, test.usernameTemplate)
defer cleanup()
for _, fixtureFunc := range test.fixtureFuncs {
fixtureFunc(t, db.Host, db.Port, nil)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
newUserResp, err := db.NewUser(ctx, test.newUserReq)
if !test.expectErr && err != nil {
t.Fatalf("no error expected, got: %s", err)
}
if test.expectErr {
if err == nil {
t.Fatalf("err expected, got nil")
}
if test.expectedErrRegex != "" {
require.Regexp(t, test.expectedErrRegex, err.Error())
}
}
if test.expectedUsernameRegex != "" {
require.Regexp(t, test.expectedUsernameRegex, newUserResp.Username)
}
for _, checkFunc := range test.checkFuncs {
performAssert(t, db.Host, db.Port, newUserResp.Username, test.newUserReq.Password, nil, 5*time.Second, checkFunc)
}
})
}
}
func TestUpdateUserPassword(t *testing.T) {
db, cleanup := getMinio(t, "")
defer cleanup()
password := "myreallysecurepassword"
createReq := dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: dbplugin.Statements{
Commands: []string{createUserDynamicStatements},
},
Password: password,
Expiration: time.Now().Add(1 * time.Minute),
}
createResp := dbtesting.AssertNewUser(t, db, createReq)
performAssert(t, db.Host, db.Port, createResp.Username, password, nil, 5*time.Second, connect)
newPassword := "somenewpassword"
updateReq := dbplugin.UpdateUserRequest{
Username: createResp.Username,
Password: &dbplugin.ChangePassword{
NewPassword: newPassword,
Statements: dbplugin.Statements{},
},
Expiration: nil,
}
dbtesting.AssertUpdateUser(t, db, updateReq)
performAssert(t, db.Host, db.Port, createResp.Username, newPassword, nil, 5*time.Second, connect)
}
func TestDeleteUser(t *testing.T) {
db, cleanup := getMinio(t, "")
defer cleanup()
password := "myreallysecurepassword"
createReq := dbplugin.NewUserRequest{
UsernameConfig: dbplugin.UsernameMetadata{
DisplayName: "test",
RoleName: "test",
},
Statements: dbplugin.Statements{
Commands: []string{createUserDynamicStatements},
},
Password: password,
Expiration: time.Now().Add(1 * time.Minute),
}
createResp := dbtesting.AssertNewUser(t, db, createReq)
performAssert(t, db.Host, db.Port, createResp.Username, password, nil, 5*time.Second, connect)
deleteReq := dbplugin.DeleteUserRequest{
Username: createResp.Username,
}
dbtesting.AssertDeleteUser(t, db, deleteReq)
performAssert(t, db.Host, db.Port, createResp.Username, password, nil, 5*time.Second, noConnect)
}
func performAssert(t testing.TB, address string, port int, username, password string, sslOpts *tls.Config, timeout time.Duration, check checkFunc) {
t.Helper()
op := func() error {
return check(t, address, port, username, password, sslOpts)
}
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = timeout
bo.InitialInterval = 500 * time.Millisecond
bo.MaxInterval = bo.InitialInterval
bo.RandomizationFactor = 0.0
err := backoff.Retry(op, bo)
if err != nil {
t.Fatalf("failed after %s: %s", timeout, err)
}
}
func connect(t testing.TB, address string, port int, username, password string, sslOpts *tls.Config) error {
t.Helper()
client, err := api.New(net.JoinHostPort(address, strconv.Itoa(port)), username, password, sslOpts != nil)
if err != nil {
return err
}
_, err = client.ServerInfo(context.Background())
if err != nil {
return err
}
return nil
}
func noConnect(t testing.TB, address string, port int, username, password string, sslOpts *tls.Config) error {
err := connect(t, address, port, username, password, sslOpts)
if err != nil {
return nil
}
return fmt.Errorf("Connection succeeded")
}
func checkUsers(t testing.TB, address string, port int, username, password string, sslOpts *tls.Config) error {
client, err := api.New(net.JoinHostPort(address, strconv.Itoa(port)), username, password, sslOpts != nil)
if err != nil {
return err
}
_, err = client.ListUsers(context.Background())
if err != nil {
return err
}
return nil
}
func checkGroups(t testing.TB, address string, port int, username, password string, sslOpts *tls.Config) error {
client, err := api.New(net.JoinHostPort(address, strconv.Itoa(port)), username, password, sslOpts != nil)
if err != nil {
return err
}
groups, err := client.ListGroups(context.Background())
if err != nil {
return err
}
for _, group := range groups {
if group == "testgroup" {
users, err := client.ListUsers(context.Background())
if err != nil {
return err
}
for user, info := range users {
if user == username {
for _, memberOf := range info.MemberOf {
if memberOf == group {
return nil
}
}
return fmt.Errorf("User is not member of testgroup")
}
}
return fmt.Errorf("Could not find user")
}
}
return fmt.Errorf("Group `testgroup` not present")
}
func createPolicy(t testing.TB, address string, port int, sslOpts *tls.Config) {
client, err := api.New(net.JoinHostPort(address, strconv.Itoa(port)), "minioadmin", "minioadmin", false)
if err != nil {
t.Fatalf("%v", err)
}
err = client.AddCannedPolicy(context.Background(), "test", []byte(staticPolicy))
if err != nil {
t.Fatalf("%v", err)
}
}
type containerConfig struct {
containerName string
imageName string
version string
env []string
sslOpts *tls.Config
}
type ContainerOpt func(*containerConfig)
func ContainerName(name string) ContainerOpt {
return func(cfg *containerConfig) {
cfg.containerName = name
}
}
func Image(imageName string, version string) ContainerOpt {
return func(cfg *containerConfig) {
cfg.imageName = imageName
cfg.version = version
// Reset the environment because there's a very good chance the default environment doesn't apply to the
// non-default image being used
cfg.env = nil
}
}
func Version(version string) ContainerOpt {
return func(cfg *containerConfig) {
cfg.version = version
}
}
func Env(keyValue string) ContainerOpt {
return func(cfg *containerConfig) {
cfg.env = append(cfg.env, keyValue)
}
}
func SslOpts(sslOpts *tls.Config) ContainerOpt {
return func(cfg *containerConfig) {
cfg.sslOpts = sslOpts
}
}
type Host struct {
Name string
Port string
}
func (h Host) ConnectionURL() string {
return net.JoinHostPort(h.Name, h.Port)
}
func PrepareTestContainer(t *testing.T, opts ...ContainerOpt) (Host, func()) {
t.Helper()
containerCfg := &containerConfig{
imageName: "quay.io/minio/minio",
containerName: "minio",
version: "latest",
env: []string{},
}
for _, opt := range opts {
opt(containerCfg)
}
runOpts := docker.RunOptions{
ContainerName: containerCfg.containerName,
ImageRepo: containerCfg.imageName,
ImageTag: containerCfg.version,
Ports: []string{"9000/tcp"},
Env: containerCfg.env,
Cmd: []string{"server", "/data"},
}
runner, err := docker.NewServiceRunner(runOpts)
if err != nil {
t.Fatalf("Could not start docker minio: %s", err)
}
svc, err := runner.StartService(context.Background(), func(ctx context.Context, host string, port int) (docker.ServiceConfig, error) {
cfg := docker.NewServiceHostPort(host, port)
client, err := api.New(net.JoinHostPort(host, strconv.Itoa(port)), "minioadmin", "minioadmin", false)
if err != nil {
return nil, fmt.Errorf("error creating client: %s", err)
}
_, err = client.ServerInfo(ctx)
if err != nil {
return nil, fmt.Errorf("error checking serverinfo: %s", err)
}
return cfg, nil
})
if err != nil {
t.Fatalf("Could not start docker minio: %s", err)
}
host, port, err := net.SplitHostPort(svc.Config.Address())
if err != nil {
t.Fatalf("Failed to split host & port from address (%s): %s", svc.Config.Address(), err)
}
h := Host{
Name: host,
Port: port,
}
return h, svc.Cleanup
}
func getMinio(t *testing.T, usernameTemplate string) (*Minio, func()) {
host, cleanup := PrepareTestContainer(t,
Version("latest"),
)
db := new()
initReq := dbplugin.InitializeRequest{
Config: map[string]interface{}{
"host": host.Name,
"port": host.Port,
"username": "minioadmin",
"password": "minioadmin",
"connect_timeout": "20s",
},
VerifyConnection: true,
}
expectedConfig := map[string]interface{}{
"host": host.Name,
"port": host.Port,
"username": "minioadmin",
"password": "minioadmin",
"connect_timeout": "20s",
}
if usernameTemplate != "" {
initReq.Config["username_template"] = usernameTemplate
expectedConfig["username_template"] = usernameTemplate
}
initResp := dbtesting.AssertInitialize(t, db, initReq)
if !reflect.DeepEqual(initResp.Config, expectedConfig) {
t.Fatalf("Initialize response config actual: %#v\nExpected: %#v", initResp.Config, expectedConfig)
}
if !db.Initialized {
t.Fatal("Database should be initialized")
}
return db, cleanup
}