forked from hashicorp/vault-testing-stepwise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stepwise_test.go
451 lines (406 loc) · 10.3 KB
/
stepwise_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
package stepwise
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"reflect"
"sync"
"testing"
"time"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
)
type testRun struct {
expectedTestT *mockT
environment *mockEnvironment
steps []Step
skipTeardown bool
requests *requestCounts
}
// TestStepwise_Run_SkipIfNotAcc tests if the Stepwise Run function skips tests
// if the VAULT_ACC environment variable is not set. This test is seperate from
// the table tests due to the unsetting/re-setting of the environment variable,
// which is assumed/needed for all other tests.
func TestStepwise_Run_SkipIfNotAcc(t *testing.T) {
if err := os.Setenv(TestEnvVar, ""); err != nil {
t.Fatalf("err: %s", err)
}
defer os.Setenv(TestEnvVar, "1")
skipCase := Case{
Environment: new(mockEnvironment),
Steps: []Step{{}},
}
expected := mockT{
SkipCalled: true,
}
testT := new(mockT)
Run(testT, skipCase)
if testT.SkipCalled != expected.SkipCalled {
t.Fatalf("expected SkipCalled (%t), got (%t)", expected.SkipCalled, testT.SkipCalled)
}
}
func TestStepwise_Run_Basic(t *testing.T) {
testRuns := map[string]testRun{
"basic_list": {
steps: []Step{
stepFunc("keys", ListOperation, false),
},
environment: new(mockEnvironment),
requests: &requestCounts{
listRequests: 1,
},
},
"basic_list_read": {
steps: []Step{
stepFunc("keys", ListOperation, false),
stepFunc("keys/name", ReadOperation, false),
},
environment: new(mockEnvironment),
requests: &requestCounts{
listRequests: 1,
readRequests: 1,
revokeRequests: 1,
},
},
"basic_unauth": {
steps: []Step{
stepFuncWithoutAuth("keys", ListOperation, true),
},
expectedTestT: &mockT{
ErrorCalled: true,
},
environment: new(mockEnvironment),
},
"error": {
steps: []Step{
stepFunc("keys", ListOperation, false),
stepFunc("keys/something", ReadOperation, true),
},
expectedTestT: &mockT{
ErrorCalled: true,
},
environment: new(mockEnvironment),
requests: &requestCounts{
listRequests: 1,
},
},
"nil-env": {
expectedTestT: &mockT{
FatalCalled: true,
},
steps: []Step{
stepFunc("keys", ListOperation, false),
},
},
"skipTeardown": {
steps: []Step{
stepFunc("keys", ListOperation, false),
stepFunc("keys/name", ReadOperation, false),
stepFunc("keys/name", ReadOperation, false),
stepFunc("keys/name", DeleteOperation, false),
},
skipTeardown: true,
environment: new(mockEnvironment),
requests: &requestCounts{
listRequests: 1,
readRequests: 2,
revokeRequests: 2,
deleteRequests: 1,
},
},
}
for name, tr := range testRuns {
t.Run(name, func(t *testing.T) {
testT := new(mockT)
expectedT := tr.expectedTestT
if expectedT == nil {
expectedT = new(mockT)
}
testCase := Case{
Steps: tr.steps,
SkipTeardown: tr.skipTeardown,
}
if tr.environment != nil {
testCase.Environment = tr.environment
}
Run(testT, testCase)
if tr.environment == nil && !testT.FatalCalled {
t.Fatal("expected FatalCalled with nil environment, but wasn't")
}
if tr.environment != nil {
if tr.skipTeardown && tr.environment.teardownCalled {
t.Fatal("SkipTeardown is true, but Teardown was called")
}
if !tr.skipTeardown && !tr.environment.teardownCalled {
t.Fatal("SkipTeardown is false, but Teardown was not called")
}
}
if expectedT.ErrorCalled != testT.ErrorCalled {
t.Fatalf("expected ErrorCalled (%t), got (%t)", expectedT.ErrorCalled, testT.ErrorCalled)
}
if tr.requests != nil {
if !reflect.DeepEqual(*tr.requests, tr.environment.requests) {
t.Fatalf("request counts do not match: %#v / %#v", tr.requests, tr.environment.requests)
}
}
})
}
}
type requestCounts struct {
writeRequests int
readRequests int
deleteRequests int
revokeRequests int
listRequests int
}
func TestStepwise_makeRequest(t *testing.T) {
me := new(mockEnvironment)
err := me.Setup()
if err != nil {
t.Error(err)
}
testT := new(mockT)
type testRequest struct {
Operation Operation
Path string
ExpectedRequestID string
ExpectErr bool
UnAuth bool
}
testRequests := map[string]testRequest{
"list": {
Operation: ListOperation,
Path: "keys",
ExpectedRequestID: "list-request",
},
"read": {
Operation: ReadOperation,
Path: "keys/name",
ExpectedRequestID: "read-request",
},
"write": {
Operation: WriteOperation,
Path: "keys/name",
ExpectedRequestID: "write-request",
},
"update": {
Operation: UpdateOperation,
Path: "keys/name",
ExpectedRequestID: "write-request",
},
"update_unauth": {
Operation: UpdateOperation,
Path: "keys/name",
UnAuth: true,
ExpectErr: true,
},
"delete": {
Operation: DeleteOperation,
Path: "keys/name",
ExpectedRequestID: "delete-request",
},
"error": {
Operation: ReadOperation,
Path: "error",
ExpectErr: true,
},
}
for name, tc := range testRequests {
t.Run(name, func(t *testing.T) {
step := Step{
Operation: tc.Operation,
Path: tc.Path,
}
if tc.UnAuth {
step.Unauthenticated = tc.UnAuth
}
secret, err := makeRequest(testT, me, step)
if err != nil && !tc.ExpectErr {
t.Fatalf("unexpected error: %s", err)
}
if err == nil && tc.ExpectErr {
t.Fatal("expected error but got none:")
}
if err != nil && tc.ExpectErr {
return
}
if secret.RequestID != tc.ExpectedRequestID {
t.Fatalf("expected (%s), got (%s)", tc.ExpectedRequestID, secret.RequestID)
}
})
}
}
type mockEnvironment struct {
ts *httptest.Server
client *api.Client
l sync.Mutex
teardownCalled bool
requests requestCounts
}
// Setup creates the mock environment, establishing a test HTTP server
func (m *mockEnvironment) Setup() error {
mux := http.NewServeMux()
// LIST
mux.HandleFunc("/v1/test/keys", func(w http.ResponseWriter, req *http.Request) {
checkAuth(w, req)
switch req.Method {
case "GET":
m.requests.listRequests++
respondCommon("list", true, w, req)
default:
w.WriteHeader(http.StatusBadRequest)
}
})
// lease revoke
mux.HandleFunc("/v1/sys/leases/revoke", func(w http.ResponseWriter, req *http.Request) {
checkAuth(w, req)
m.requests.revokeRequests++
w.WriteHeader(http.StatusOK)
})
// READ, DELETE, WRITE
mux.HandleFunc("/v1/test/keys/name", func(w http.ResponseWriter, req *http.Request) {
checkAuth(w, req)
var method string
// indicate if the common response should include a lease id
var excludeLease bool
switch req.Method {
case "GET":
m.requests.readRequests++
method = "read"
case "POST":
case "PUT":
m.requests.writeRequests++
method = "write"
case "DELETE":
m.requests.deleteRequests++
excludeLease = true
method = "delete"
default:
w.WriteHeader(http.StatusBadRequest)
}
respondCommon(method, excludeLease, w, req)
})
// fall through that rejects any other url than "/"
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/" {
http.NotFound(w, req)
return
}
fmt.Fprintf(w, "{}")
})
m.ts = httptest.NewServer(mux)
return nil
}
// respondCommon returns a mock secret with a request ID that matches the
// request method that was used to invoke it. A true Vault server would not
// respond with a request id / lease id for DELETE or REVOKE, but we do that
// here to verify that the makeRequest method translates the Step Operation
// and calls delete/revoke correctly
func respondCommon(id string, excludeLease bool, w http.ResponseWriter, req *http.Request) {
resp := api.Secret{
RequestID: id + "-request",
LeaseID: "lease-id",
}
if excludeLease {
resp.LeaseID = ""
}
out, err := jsonutil.EncodeJSON(resp)
if err != nil {
panic(err)
}
_, err = w.Write(out)
if err != nil {
panic(err)
}
}
// Client creates a Vault API client configured to the mock environment's test
// server
func (m *mockEnvironment) Client() (*api.Client, error) {
m.l.Lock()
defer m.l.Unlock()
if m.ts == nil {
return nil, errors.New("client() called but test server is nil")
}
if m.client != nil {
return m.client, nil
}
cfg := api.Config{
Address: m.ts.URL,
HttpClient: cleanhttp.DefaultPooledClient(),
Timeout: time.Second * 5,
MaxRetries: 2,
}
client, err := api.NewClient(&cfg)
if err != nil {
return nil, err
}
// need to set root token here to mimic an actual root token of a cluster
client.SetToken(m.RootToken())
m.client = client
return client, nil
}
func (m *mockEnvironment) Teardown() error {
m.teardownCalled = true
m.ts.Close()
return nil
}
func (m *mockEnvironment) Name() string { return "" }
func (m *mockEnvironment) MountPath() string {
return "/test/"
}
func (m *mockEnvironment) RootToken() string { return "root-token" }
func stepFuncWithoutAuth(path string, operation Operation, shouldError bool) Step {
return stepFuncCommon(path, operation, shouldError, true)
}
func stepFunc(path string, operation Operation, shouldError bool) Step {
return stepFuncCommon(path, operation, shouldError, false)
}
func stepFuncCommon(path string, operation Operation, shouldError bool, unauth bool) Step {
s := Step{
Operation: operation,
Path: path,
Unauthenticated: unauth,
}
if shouldError {
s.Assert = func(resp *api.Secret, err error) error {
return errors.New("some error")
}
}
return s
}
// mockT implements TestT for testing
type mockT struct {
ErrorCalled bool
ErrorArgs []interface{}
FatalCalled bool
FatalArgs []interface{}
SkipCalled bool
SkipArgs []interface{}
f bool
}
func (t *mockT) Error(args ...interface{}) {
t.ErrorCalled = true
t.ErrorArgs = args
t.f = true
}
func (t *mockT) Fatal(args ...interface{}) {
t.FatalCalled = true
t.FatalArgs = args
t.f = true
}
func (t *mockT) Skip(args ...interface{}) {
t.SkipCalled = true
t.SkipArgs = args
t.f = true
}
func (t *mockT) Helper() {}
// validates that X-Vault-Token is set on the requets to the mock endpoints
func checkAuth(w http.ResponseWriter, r *http.Request) {
if token := r.Header.Get("X-Vault-Token"); token == "" {
// not authenticated
w.WriteHeader(http.StatusForbidden)
}
}