-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
k8s_test.go
109 lines (90 loc) · 2.34 KB
/
k8s_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
//go:build k8s_integration
package integration
import (
"encoding/json"
"os"
"path/filepath"
"testing"
cdx "github.com/CycloneDX/cyclonedx-go"
"github.com/aquasecurity/trivy/pkg/k8s/report"
"github.com/aquasecurity/trivy/pkg/types"
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Note: the test required k8s (kind) cluster installed.
// "mage test:k8s" will run this test.
func TestK8s(t *testing.T) {
// Set up testing DB
cacheDir := initDB(t)
t.Run("misconfig and vulnerability scan", func(t *testing.T) {
// Set up the output file
outputFile := filepath.Join(t.TempDir(), "output.json")
osArgs := []string{
"--cache-dir",
cacheDir,
"k8s",
"kind-kind-test",
"--report",
"summary",
"-q",
"--timeout",
"5m0s",
"--format",
"json",
"--output",
outputFile,
}
// Run Trivy
err := execute(osArgs)
require.NoError(t, err)
var got report.ConsolidatedReport
f, err := os.Open(outputFile)
require.NoError(t, err)
defer f.Close()
err = json.NewDecoder(f).Decode(&got)
require.NoError(t, err)
// Flatten findings
results := lo.FlatMap(got.Findings, func(resource report.Resource, _ int) []types.Result {
return resource.Results
})
// Has vulnerabilities
assert.True(t, lo.SomeBy(results, func(r types.Result) bool {
return len(r.Vulnerabilities) > 0
}))
// Has misconfigurations
assert.True(t, lo.SomeBy(results, func(r types.Result) bool {
return len(r.Misconfigurations) > 0
}))
})
t.Run("kbom cycloneDx", func(t *testing.T) {
// Set up the output file
outputFile := filepath.Join(t.TempDir(), "output.json")
osArgs := []string{
"k8s",
"kind-kind-test",
"--format",
"cyclonedx",
"-q",
"--output",
outputFile,
}
// Run Trivy
err := execute(osArgs)
require.NoError(t, err)
var got *cdx.BOM
f, err := os.Open(outputFile)
require.NoError(t, err)
defer f.Close()
err = json.NewDecoder(f).Decode(&got)
require.NoError(t, err)
assert.Equal(t, got.Metadata.Component.Name, "k8s.io/kubernetes")
assert.Equal(t, got.Metadata.Component.Type, cdx.ComponentType("platform"))
// Has components
assert.True(t, len(*got.Components) > 0)
// Has dependecies
assert.True(t, lo.SomeBy(*got.Dependencies, func(r cdx.Dependency) bool {
return len(*r.Dependencies) > 0
}))
})
}