-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
integration_test.go
373 lines (312 loc) · 10.3 KB
/
integration_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
//go:build integration || vm_integration || module_integration || k8s_integration
package integration
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"time"
cdx "github.com/CycloneDX/cyclonedx-go"
"github.com/samber/lo"
spdxjson "github.com/spdx/tools-golang/json"
"github.com/spdx/tools-golang/spdx"
"github.com/spdx/tools-golang/spdxlib"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xeipuuv/gojsonschema"
"github.com/aquasecurity/trivy-db/pkg/metadata"
"github.com/aquasecurity/trivy/internal/dbtest"
"github.com/aquasecurity/trivy/internal/testutil"
"github.com/aquasecurity/trivy/pkg/clock"
"github.com/aquasecurity/trivy/pkg/commands"
"github.com/aquasecurity/trivy/pkg/db"
"github.com/aquasecurity/trivy/pkg/types"
"github.com/aquasecurity/trivy/pkg/uuid"
"github.com/aquasecurity/trivy/pkg/vex/repo"
_ "modernc.org/sqlite"
)
var update = flag.Bool("update", false, "update golden files")
const SPDXSchema = "https://raw.githubusercontent.com/spdx/spdx-spec/development/v%s/schemas/spdx-schema.json"
func initDB(t *testing.T) string {
fixtureDir := filepath.Join("testdata", "fixtures", "db")
entries, err := os.ReadDir(fixtureDir)
require.NoError(t, err)
var fixtures []string
for _, entry := range entries {
if entry.IsDir() {
continue
}
fixtures = append(fixtures, filepath.Join(fixtureDir, entry.Name()))
}
cacheDir := dbtest.InitDB(t, fixtures)
defer dbtest.Close()
err = metadata.NewClient(db.Dir(cacheDir)).Update(metadata.Metadata{
Version: db.SchemaVersion,
NextUpdate: time.Now().Add(24 * time.Hour),
UpdatedAt: time.Now(),
})
require.NoError(t, err)
dbtest.InitJavaDB(t, cacheDir)
return cacheDir
}
func initVEXRepository(t *testing.T, homeDir, cacheDir string) {
t.Helper()
// Copy config directory
configSrc := "testdata/fixtures/vex/config/repository.yaml"
configDst := filepath.Join(homeDir, ".trivy", "vex", "repository.yaml")
testutil.CopyFile(t, configSrc, configDst)
// Copy repository directory
repoSrc := "testdata/fixtures/vex/repositories"
repoDst := filepath.Join(cacheDir, "vex", "repositories")
testutil.CopyDir(t, repoSrc, repoDst)
// Copy VEX file
vexSrc := "testdata/fixtures/vex/file/openvex.json"
repoDir := filepath.Join(repoDst, "default")
vexDst := filepath.Join(repoDir, "0.1", "openvex.json")
testutil.CopyFile(t, vexSrc, vexDst)
// Write a dummy cache metadata
testutil.MustWriteJSON(t, filepath.Join(repoDir, "cache.json"), repo.CacheMetadata{
UpdatedAt: time.Now(),
})
// Verify that necessary files exist
requiredFiles := []string{
configDst,
filepath.Join(repoDir, "vex-repository.json"),
filepath.Join(repoDir, "0.1", "index.json"),
filepath.Join(repoDir, "0.1", "openvex.json"),
}
for _, file := range requiredFiles {
require.FileExists(t, file)
}
}
func getFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}
func waitPort(ctx context.Context, addr string) error {
for {
conn, err := net.Dial("tcp", addr)
if err == nil && conn != nil {
return nil
}
select {
case <-ctx.Done():
return err
default:
time.Sleep(1 * time.Second)
}
}
}
func readReport(t *testing.T, filePath string) types.Report {
t.Helper()
f, err := os.Open(filePath)
require.NoError(t, err, filePath)
defer f.Close()
var report types.Report
err = json.NewDecoder(f).Decode(&report)
require.NoError(t, err, filePath)
// We don't compare history because the nano-seconds in "created" don't match
report.Metadata.ImageConfig.History = nil
// We don't compare repo tags because the archive doesn't support it
report.Metadata.RepoTags = nil
report.Metadata.RepoDigests = nil
for i, result := range report.Results {
for j := range result.Vulnerabilities {
report.Results[i].Vulnerabilities[j].Layer.Digest = ""
}
sort.Slice(result.CustomResources, func(i, j int) bool {
if result.CustomResources[i].Type != result.CustomResources[j].Type {
return result.CustomResources[i].Type < result.CustomResources[j].Type
}
return result.CustomResources[i].FilePath < result.CustomResources[j].FilePath
})
}
return report
}
func readCycloneDX(t *testing.T, filePath string) *cdx.BOM {
f, err := os.Open(filePath)
require.NoError(t, err)
defer f.Close()
bom := cdx.NewBOM()
decoder := cdx.NewBOMDecoder(f, cdx.BOMFileFormatJSON)
err = decoder.Decode(bom)
require.NoError(t, err)
// Sort components
if bom.Components != nil {
sort.Slice(*bom.Components, func(i, j int) bool {
return (*bom.Components)[i].Name < (*bom.Components)[j].Name
})
for i := range *bom.Components {
(*bom.Components)[i].BOMRef = ""
sort.Slice(*(*bom.Components)[i].Properties, func(ii, jj int) bool {
return (*(*bom.Components)[i].Properties)[ii].Name < (*(*bom.Components)[i].Properties)[jj].Name
})
}
sort.Slice(*bom.Vulnerabilities, func(i, j int) bool {
return (*bom.Vulnerabilities)[i].ID < (*bom.Vulnerabilities)[j].ID
})
}
return bom
}
func readSpdxJson(t *testing.T, filePath string) *spdx.Document {
f, err := os.Open(filePath)
require.NoError(t, err)
defer f.Close()
bom, err := spdxjson.Read(f)
require.NoError(t, err)
sort.Slice(bom.Relationships, func(i, j int) bool {
if bom.Relationships[i].RefA.ElementRefID != bom.Relationships[j].RefA.ElementRefID {
return bom.Relationships[i].RefA.ElementRefID < bom.Relationships[j].RefA.ElementRefID
}
return bom.Relationships[i].RefB.ElementRefID < bom.Relationships[j].RefB.ElementRefID
})
sort.Slice(bom.Files, func(i, j int) bool {
return bom.Files[i].FileSPDXIdentifier < bom.Files[j].FileSPDXIdentifier
})
// We don't compare values which change each time an SBOM is generated
bom.CreationInfo.Created = ""
bom.DocumentNamespace = ""
return bom
}
type OverrideFunc func(t *testing.T, want, got *types.Report)
type runOptions struct {
wantErr string
override OverrideFunc
fakeUUID string
}
// runTest runs Trivy with the given args and compares the output with the golden file.
// If outputFile is empty, the output file is created in a temporary directory.
// If update is true, the golden file is updated.
func runTest(t *testing.T, osArgs []string, wantFile, outputFile string, format types.Format, opts runOptions) {
if opts.fakeUUID != "" {
uuid.SetFakeUUID(t, opts.fakeUUID)
}
if outputFile == "" {
// Set up the output file
outputFile = filepath.Join(t.TempDir(), "output.json")
if *update && opts.override == nil {
outputFile = wantFile
}
}
osArgs = append(osArgs, "--output", outputFile)
// Run Trivy
err := execute(osArgs)
if opts.wantErr != "" {
require.ErrorContains(t, err, opts.wantErr)
return
}
require.NoError(t, err)
// Compare want and got
switch format {
case types.FormatCycloneDX:
compareCycloneDX(t, wantFile, outputFile)
case types.FormatSPDXJSON:
compareSPDXJson(t, wantFile, outputFile)
case types.FormatJSON:
compareReports(t, wantFile, outputFile, opts.override)
case types.FormatTemplate, types.FormatSarif, types.FormatGitHub:
compareRawFiles(t, wantFile, outputFile)
default:
require.Fail(t, "invalid format", "format: %s", format)
}
}
func execute(osArgs []string) error {
// viper.XXX() (e.g. viper.ReadInConfig()) affects the global state, so we need to reset it after each test.
defer viper.Reset()
// Set a fake time
ctx := clock.With(context.Background(), time.Date(2021, 8, 25, 12, 20, 30, 5, time.UTC))
// Setup CLI App
app := commands.NewApp()
app.SetOut(io.Discard)
app.SetArgs(osArgs)
// Run Trivy
return app.ExecuteContext(ctx)
}
func compareRawFiles(t *testing.T, wantFile, gotFile string) {
want, err := os.ReadFile(wantFile)
require.NoError(t, err)
got, err := os.ReadFile(gotFile)
require.NoError(t, err)
assert.EqualValues(t, string(want), string(got))
}
func compareReports(t *testing.T, wantFile, gotFile string, override func(t *testing.T, want, got *types.Report)) {
want := readReport(t, wantFile)
got := readReport(t, gotFile)
if override != nil {
override(t, &want, &got)
}
assert.Equal(t, want, got)
}
func compareCycloneDX(t *testing.T, wantFile, gotFile string) {
want := readCycloneDX(t, wantFile)
got := readCycloneDX(t, gotFile)
assert.Equal(t, want, got)
// Validate CycloneDX output against the JSON schema
validateReport(t, got.JSONSchema, got)
}
func compareSPDXJson(t *testing.T, wantFile, gotFile string) {
want := readSpdxJson(t, wantFile)
got := readSpdxJson(t, gotFile)
assert.Equal(t, want, got)
SPDXVersion, ok := strings.CutPrefix(want.SPDXVersion, "SPDX-")
assert.True(t, ok)
require.NoError(t, spdxlib.ValidateDocument(got))
// Validate SPDX output against the JSON schema
validateReport(t, fmt.Sprintf(SPDXSchema, SPDXVersion), got)
}
func validateReport(t *testing.T, schema string, report any) {
schemaLoader := gojsonschema.NewReferenceLoader(schema)
documentLoader := gojsonschema.NewGoLoader(report)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
require.NoError(t, err)
if valid := result.Valid(); !valid {
errs := lo.Map(result.Errors(), func(err gojsonschema.ResultError, _ int) string {
return err.String()
})
assert.True(t, valid, strings.Join(errs, "\n"))
}
}
func overrideFuncs(funcs ...OverrideFunc) OverrideFunc {
return func(t *testing.T, want, got *types.Report) {
for _, f := range funcs {
if f == nil {
continue
}
f(t, want, got)
}
}
}
// overrideUID only checks for the presence of the package UID and clears the UID;
// the UID is calculated from the package metadata, but the UID does not match
// as it varies slightly depending on the mode of scanning, e.g. the digest of the layer.
func overrideUID(t *testing.T, want, got *types.Report) {
for i, result := range got.Results {
for j, vuln := range result.Vulnerabilities {
assert.NotEmptyf(t, vuln.PkgIdentifier.UID, "UID is empty: %s", vuln.VulnerabilityID)
// Do not compare UID as the package metadata is slightly different between the tests,
// causing different UIDs.
got.Results[i].Vulnerabilities[j].PkgIdentifier.UID = ""
}
}
for i, result := range want.Results {
for j := range result.Vulnerabilities {
want.Results[i].Vulnerabilities[j].PkgIdentifier.UID = ""
}
}
}