forked from kubescape/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkscloudapi_test.go
More file actions
571 lines (458 loc) · 14.7 KB
/
Copy pathkscloudapi_test.go
File metadata and controls
571 lines (458 loc) · 14.7 KB
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
package v1
import (
"context"
"encoding/json"
"errors"
"io"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
var (
testOptions = []KSCloudOption{
WithTrace(os.Getenv("DEBUG_TEST") != ""),
}
)
func TestFallBackGUID(t *testing.T) {
t.Run("should yield a GUID even though the account ID is not set", func(t *testing.T) {
ks := NewEmptyKSCloudAPI()
require.NotEmpty(t, ks.getCustomerGUIDFallBack())
})
}
func TestKSCloudAPI(t *testing.T) {
// NOTE:
// (i) mock handlers do not use "require" in order to let goroutines end normally upon failure.
// (ii) run with DEBUG_TEST=1 go test -v -run KSCloudAPI to get a trace of all HTTP traffic.
srv := MockAPIServer(t) // assert that a token is passed as header
t.Cleanup(srv.Close)
ks, err := NewKSCloudAPI(
srv.Root(),
srv.Root(),
"account",
"",
testOptions...,
)
require.NoError(t, err)
t.Run("with authenticated", func(t *testing.T) {
t.Run("should retrieve AttackTracks", func(t *testing.T) {
t.Parallel()
tracks, err := ks.GetAttackTracks()
require.NoError(t, err)
require.NotNil(t, tracks)
expected := mockAttackTracks()
// make sure controls don't leak
for i := range expected {
expected[i].Spec.Data.Controls = nil // doesn't pass the JSON marshal
for j := range expected[i].Spec.Data.SubSteps {
expected[i].Spec.Data.SubSteps[j].Controls = nil
}
}
require.EqualValues(t, expected, tracks)
})
t.Run("with frameworks", func(t *testing.T) {
t.Run("should retrieve Framework #1", func(t *testing.T) {
t.Parallel()
framework, err := ks.GetFramework("mock-1")
require.NoError(t, err)
require.NotNil(t, framework)
mocked := mockFrameworks()
expected := &mocked[0]
require.EqualValues(t, expected, framework)
})
t.Run("should retrieve Framework #2", func(t *testing.T) {
t.Parallel()
framework, err := ks.GetFramework("mock-2")
require.NoError(t, err)
require.NotNil(t, framework)
mocked := mockFrameworks()
expected := &mocked[1]
require.EqualValues(t, expected, framework)
})
t.Run("should retrieve native Framework", func(t *testing.T) {
t.Parallel()
const testFramework = "MITRE"
expected, err := os.ReadFile(TestFrameworkFile(testFramework))
require.NoError(t, err)
framework, err := ks.GetFramework("miTrE")
require.NoError(t, err)
require.NotNil(t, framework)
jazon, err := json.Marshal(framework)
require.NoError(t, err)
require.JSONEq(t, string(expected), string(jazon))
})
t.Run("should retrieve all Frameworks", func(t *testing.T) {
t.Parallel()
// NOTE: MITRE fixture is not part of the base mock
expected := mockFrameworks()
frameworks, err := ks.GetFrameworks()
require.NoError(t, err)
require.Len(t, frameworks, 3)
require.EqualValues(t, expected, frameworks)
})
t.Run("should list all Frameworks", func(t *testing.T) {
t.Parallel()
mocks := mockFrameworks()
expected := make([]string, 0, 3)
for _, fw := range mocks {
expected = append(expected, fw.Name)
}
frameworkNames, err := ks.ListFrameworks()
require.NoError(t, err)
require.Len(t, frameworkNames, 3)
require.ElementsMatch(t, expected, frameworkNames)
})
t.Run("should list custom Frameworks", func(t *testing.T) {
t.Parallel()
mocks := mockFrameworks()
expected := make([]string, 0, 2)
for _, fw := range mocks[:len(mocks)-1] {
expected = append(expected, fw.Name)
}
frameworkNames, err := ks.ListCustomFrameworks()
require.NoError(t, err)
require.Len(t, frameworkNames, 2)
require.ElementsMatch(t, expected, frameworkNames)
})
})
t.Run("with controls", func(t *testing.T) {
t.Run("should NOT retrieve Control (not a public API)", func(t *testing.T) {
t.Parallel()
const id = "control-1"
control, err := ks.GetControl(id)
require.Error(t, err)
require.Nil(t, control)
require.Contains(t, err.Error(), "is not public")
})
t.Run("should NOT list Controls (not a public API)", func(t *testing.T) {
t.Parallel()
control, err := ks.ListControls()
require.Error(t, err)
require.Nil(t, control)
require.Contains(t, err.Error(), "is not public")
})
})
t.Run("with exceptions", func(t *testing.T) {
t.Run("should retrieve Exceptions", func(t *testing.T) {
t.Parallel()
expected := mockExceptions()
exceptions, err := ks.GetExceptions("")
require.NoError(t, err)
require.Len(t, exceptions, 2)
require.EqualValues(t, expected, exceptions)
})
})
t.Run("with CustomerConfig", func(t *testing.T) {
t.Run("empty CustomerConfig", func(t *testing.T) {
t.Parallel()
kno, err := NewKSCloudAPI(
srv.Root(),
"",
"",
"",
)
require.NoError(t, err)
account, err := kno.GetAccountConfig("")
require.NoError(t, err)
require.NotNil(t, account)
require.Empty(t, *account)
})
t.Run("should retrieve CustomerConfig", func(t *testing.T) {
t.Parallel()
expected := mockCustomerConfig("", "")()
account, err := ks.GetAccountConfig("")
require.NoError(t, err)
require.NotNil(t, account)
require.EqualValues(t, expected, account)
})
t.Run("should retrieve CustomerConfig for cluster", func(t *testing.T) {
t.Parallel()
const cluster = "special-cluster"
expected := mockCustomerConfig(cluster, "")()
account, err := ks.GetAccountConfig(cluster)
require.NoError(t, err)
require.NotNil(t, account)
require.EqualValues(t, expected, account)
})
t.Run("should retrieve ControlInputs", func(t *testing.T) {
t.Parallel()
config := mockCustomerConfig("", "")()
expected := config.Settings.PostureControlInputs
inputs, err := ks.GetControlsInputs("")
require.NoError(t, err)
require.NotNil(t, inputs)
require.EqualValues(t, expected, inputs)
})
})
t.Run("should submit report", func(t *testing.T) {
t.Parallel()
const (
cluster = "special-cluster"
reportID = "5d817063-096f-4d91-b39b-8665240080af"
)
submitted := mockPostureReport(t, reportID, cluster)
_, err := ks.SubmitReport(submitted)
require.NoError(t, err)
})
})
t.Run("with getters & setters", func(t *testing.T) {
kno, err := NewKSCloudAPI(
srv.Root(),
"",
"",
"",
)
require.NoError(t, err)
pickString := func() string {
return strconv.Itoa(rand.Intn(10000)) //nolint:gosec
}
t.Run("should get&set account", func(t *testing.T) {
str := pickString()
kno.accountID = str
require.Equal(t, str, kno.GetAccountID())
})
t.Run("shouldn't set invalid report URL", func(t *testing.T) {
malformedUrl := "http://%41:8080/"
err := kno.SetCloudReportURL(malformedUrl)
require.Error(t, err)
require.Equal(t, "", kno.GetCloudReportURL())
})
t.Run("shouldn't set invalid API URL", func(t *testing.T) {
malformedUrl := "http://%41:8080/"
err := kno.SetCloudAPIURL(malformedUrl)
require.Error(t, err)
require.Equal(t, "", kno.GetCloudAPIURL())
})
t.Run("should get&set report URL", func(t *testing.T) {
str := "https://report.example.com"
err := kno.SetCloudReportURL(str)
require.NoError(t, err)
require.Equal(t, str, kno.GetCloudReportURL())
})
t.Run("should get&set API URL", func(t *testing.T) {
str := "https://api.example.com"
err := kno.SetCloudAPIURL(str)
require.NoError(t, err)
require.Equal(t, str, kno.GetCloudAPIURL())
})
})
t.Run("with API errors", func(t *testing.T) {
// exercise the client when the API returns errors
t.Parallel()
errAPI := errors.New("test error")
errSrv := MockAPIServer(t, withAPIError(errAPI))
t.Cleanup(errSrv.Close)
ke, err := NewKSCloudAPI(
errSrv.Root(),
"",
"account",
"",
)
require.NoError(t, err)
t.Run("API calls should error", func(t *testing.T) {
_, err = ke.GetExceptions("")
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.GetControlsInputs("")
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.GetAccountConfig("")
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.GetAttackTracks()
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.GetFramework("mock-1")
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.GetFrameworks()
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.ListFrameworks()
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
_, err = ke.ListCustomFrameworks()
require.Error(t, err)
require.Contains(t, err.Error(), errAPI.Error())
})
})
t.Run("with API returning invalid response", func(t *testing.T) {
// exercise the client when the API returns an invalid response
t.Parallel()
errSrv := MockAPIServer(t, withAPIGarbled(true))
t.Cleanup(errSrv.Close)
ke, err := NewKSCloudAPI(
errSrv.Root(),
"",
"account",
"",
)
require.NoError(t, err)
t.Run("API calls should return unmarshalling error", func(t *testing.T) {
// only API calls that return a typed response are checked
_, err := ke.GetExceptions("")
require.Error(t, err)
_, err = ke.GetAccountConfig("")
require.Error(t, err)
_, err = ke.GetControlsInputs("")
require.Error(t, err)
_, err = ke.GetAttackTracks()
require.Error(t, err)
_, err = ke.GetFramework("mock-1")
require.Error(t, err)
_, err = ke.GetFrameworks()
require.Error(t, err)
_, err = ke.ListFrameworks()
require.Error(t, err)
_, err = ke.ListCustomFrameworks()
require.Error(t, err)
})
})
}
func withAPIError(err error) mockAPIOption {
return func(o *mockAPIOptions) {
o.withError = err
}
}
func withAPIGarbled(enabled bool) mockAPIOption {
return func(o *mockAPIOptions) {
o.withGarbled = enabled
}
}
func TestGetExceptionsURL(t *testing.T) {
ks, err := NewKSCloudAPI("https://api.kubescape.com", "https://api.google.com/report", "00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000")
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
clusterName string
expectedURL string
}{
{
name: "should return correct URL with given cluster name",
clusterName: "testCluster",
expectedURL: "https://api.kubescape.com/api/v1/controlExceptions?customerGUID=00000000-0000-0000-0000-000000000000&gitRegoStoreVersion=v2",
},
{
name: "should return correct URL with different cluster name",
clusterName: "anotherTestCluster",
expectedURL: "https://api.kubescape.com/api/v1/controlExceptions?customerGUID=00000000-0000-0000-0000-000000000000&gitRegoStoreVersion=v2",
},
{
name: "should return correct URL when cluster name is empty",
clusterName: "",
expectedURL: "https://api.kubescape.com/api/v1/controlExceptions?customerGUID=00000000-0000-0000-0000-000000000000&gitRegoStoreVersion=v2",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resultURL := ks.getExceptionsURL(tt.clusterName)
require.Equal(t, tt.expectedURL, resultURL)
})
}
}
type contextTestKey struct{}
// recordingRoundTripper captures the outgoing request so a test can inspect what
// actually reached the transport. When blocking is set it waits for the request
// context to be done instead of answering, which simulates an upload that is
// already in flight.
type recordingRoundTripper struct {
requests chan *http.Request
blocking bool
}
func (rt *recordingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
rt.requests <- req
if rt.blocking {
<-req.Context().Done()
return nil, req.Context().Err()
}
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader("ok")),
Header: make(http.Header),
Request: req,
}, nil
}
func TestSubmitReportWithContext(t *testing.T) {
const (
cluster = "special-cluster"
reportID = "5d817063-096f-4d91-b39b-8665240080af"
)
newAPI := func(t *testing.T, rt http.RoundTripper) *KSCloudAPI {
t.Helper()
ks, err := NewKSCloudAPI(
"https://api.armo.cloud",
"https://report.armo.cloud",
"account",
"",
append(testOptions, WithHTTPClient(&http.Client{Transport: rt}))...,
)
require.NoError(t, err)
return ks
}
t.Run("should carry the caller context to the transport", func(t *testing.T) {
rt := &recordingRoundTripper{requests: make(chan *http.Request, 1)}
ks := newAPI(t, rt)
ctx := context.WithValue(context.Background(), contextTestKey{}, "value")
_, err := ks.SubmitReportWithContext(ctx, mockPostureReport(t, reportID, cluster))
require.NoError(t, err)
req := <-rt.requests
require.Equal(t, "value", req.Context().Value(contextTestKey{}))
})
t.Run("should cancel an upload that is already in flight", func(t *testing.T) {
rt := &recordingRoundTripper{requests: make(chan *http.Request, 1), blocking: true}
ks := newAPI(t, rt)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errCh := make(chan error, 1)
go func() {
_, err := ks.SubmitReportWithContext(ctx, mockPostureReport(t, reportID, cluster))
errCh <- err
}()
<-rt.requests // the request has reached the transport
cancel()
select {
case err := <-errCh:
require.Error(t, err)
require.ErrorIs(t, err, context.Canceled)
case <-time.After(5 * time.Second):
t.Fatal("cancelling the context did not stop the in-flight upload")
}
})
t.Run("should report an expired deadline as such", func(t *testing.T) {
rt := &recordingRoundTripper{requests: make(chan *http.Request, 1), blocking: true}
ks := newAPI(t, rt)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
_, err := ks.SubmitReportWithContext(ctx, mockPostureReport(t, reportID, cluster))
require.Error(t, err)
require.ErrorIs(t, err, context.DeadlineExceeded)
})
t.Run("should still apply request options", func(t *testing.T) {
rt := &recordingRoundTripper{requests: make(chan *http.Request, 1)}
ks := newAPI(t, rt)
_, err := ks.SubmitReportWithContext(
context.Background(),
mockPostureReport(t, reportID, cluster),
WithHeaders(map[string]string{"X-Test-Header": "set"}),
)
require.NoError(t, err)
req := <-rt.requests
require.Equal(t, "set", req.Header.Get("X-Test-Header"))
require.Equal(t, "application/json", req.Header.Get("Content-Type"))
})
t.Run("should keep SubmitReport working without a context", func(t *testing.T) {
rt := &recordingRoundTripper{requests: make(chan *http.Request, 1)}
ks := newAPI(t, rt)
body, err := ks.SubmitReport(mockPostureReport(t, reportID, cluster))
require.NoError(t, err)
require.Equal(t, "ok", body)
req := <-rt.requests
require.Equal(t, http.MethodPost, req.Method)
})
}