forked from SAP/jenkins-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhitesourceExecuteScan_test.go
709 lines (655 loc) · 25.8 KB
/
whitesourceExecuteScan_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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
package cmd
import (
"fmt"
"path/filepath"
"testing"
"time"
piperGithub "github.com/SAP/jenkins-library/pkg/github"
"github.com/SAP/jenkins-library/pkg/mock"
"github.com/SAP/jenkins-library/pkg/piperenv"
"github.com/SAP/jenkins-library/pkg/piperutils"
"github.com/SAP/jenkins-library/pkg/reporting"
"github.com/SAP/jenkins-library/pkg/versioning"
ws "github.com/SAP/jenkins-library/pkg/whitesource"
"github.com/stretchr/testify/assert"
)
type whitesourceUtilsMock struct {
*ws.ScanUtilsMock
coordinates versioning.Coordinates
usedBuildTool string
usedBuildDescriptorFile string
usedOptions versioning.Options
}
func (w *whitesourceUtilsMock) GetArtifactCoordinates(buildTool, buildDescriptorFile string,
options *versioning.Options) (versioning.Coordinates, error) {
w.usedBuildTool = buildTool
w.usedBuildDescriptorFile = buildDescriptorFile
w.usedOptions = *options
return w.coordinates, nil
}
func (w *whitesourceUtilsMock) CreateIssue(ghCreateIssueOptions *piperGithub.CreateIssueOptions) error {
return nil
}
const wsTimeNow = "2010-05-10 00:15:42"
func (w *whitesourceUtilsMock) Now() time.Time {
now, _ := time.Parse("2006-01-02 15:04:05", wsTimeNow)
return now
}
func newWhitesourceUtilsMock() *whitesourceUtilsMock {
return &whitesourceUtilsMock{
ScanUtilsMock: &ws.ScanUtilsMock{
FilesMock: &mock.FilesMock{},
ExecMockRunner: &mock.ExecMockRunner{},
},
coordinates: versioning.Coordinates{
GroupID: "mock-group-id",
ArtifactID: "mock-artifact-id",
Version: "1.0.42",
},
}
}
func TestNewWhitesourceUtils(t *testing.T) {
t.Parallel()
config := ScanOptions{}
utils := newWhitesourceUtils(&config)
assert.NotNil(t, utils.Client)
assert.NotNil(t, utils.Command)
assert.NotNil(t, utils.Files)
}
func TestRunWhitesourceExecuteScan(t *testing.T) {
t.Parallel()
t.Run("fails for invalid configured project token", func(t *testing.T) {
// init
config := ScanOptions{
BuildDescriptorFile: "my-mta.yml",
VersioningModel: "major",
ProductName: "mock-product",
ProjectToken: "no-such-project-token",
AgentDownloadURL: "https://whitesource.com/agent.jar",
AgentFileName: "ua.jar",
}
utilsMock := newWhitesourceUtilsMock()
utilsMock.AddFile("wss-generated-file.config", []byte("key=value"))
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
cpe := whitesourceExecuteScanCommonPipelineEnvironment{}
influx := whitesourceExecuteScanInflux{}
// test
err := runWhitesourceExecuteScan(&config, scan, utilsMock, systemMock, &cpe, &influx)
// assert
assert.EqualError(t, err, "failed to resolve and aggregate project name: failed to get project by token: no project with token 'no-such-project-token' found in Whitesource")
assert.Equal(t, "", config.ProjectName)
assert.Equal(t, "", scan.AggregateProjectName)
})
t.Run("retrieves aggregate project name by configured token", func(t *testing.T) {
// init
config := ScanOptions{
BuildDescriptorFile: "my-mta.yml",
VersioningModel: "major",
AgentDownloadURL: "https://whitesource.com/agent.jar",
VulnerabilityReportFormat: "pdf",
Reporting: true,
AgentFileName: "ua.jar",
ProductName: "mock-product",
ProjectToken: "mock-project-token",
}
utilsMock := newWhitesourceUtilsMock()
utilsMock.AddFile("wss-generated-file.config", []byte("key=value"))
lastUpdatedDate := time.Now().Format(ws.DateTimeLayout)
systemMock := ws.NewSystemMock(lastUpdatedDate)
systemMock.Alerts = []ws.Alert{}
scan := newWhitesourceScan(&config)
cpe := whitesourceExecuteScanCommonPipelineEnvironment{}
influx := whitesourceExecuteScanInflux{}
// test
err := runWhitesourceExecuteScan(&config, scan, utilsMock, systemMock, &cpe, &influx)
// assert
assert.NoError(t, err)
// Retrieved project name is stored in scan.AggregateProjectName, but not in config.ProjectName
// in order to differentiate between aggregate-project scanning and multi-project scanning.
assert.Equal(t, "", config.ProjectName)
assert.Equal(t, "mock-project", scan.AggregateProjectName)
if assert.Len(t, utilsMock.DownloadedFiles, 1) {
assert.Equal(t, ws.DownloadedFile{
SourceURL: "https://whitesource.com/agent.jar",
FilePath: "ua.jar",
}, utilsMock.DownloadedFiles[0])
}
if assert.Len(t, cpe.custom.whitesourceProjectNames, 1) {
assert.Equal(t, []string{"mock-project - 1"}, cpe.custom.whitesourceProjectNames)
}
assert.True(t, utilsMock.HasWrittenFile(filepath.Join(ws.ReportsDirectory, "mock-project - 1-vulnerability-report.pdf")))
assert.True(t, utilsMock.HasWrittenFile(filepath.Join(ws.ReportsDirectory, "mock-project - 1-vulnerability-report.pdf")))
})
}
func TestCheckAndReportScanResults(t *testing.T) {
t.Parallel()
t.Run("no reports requested", func(t *testing.T) {
// init
config := &ScanOptions{
ProductToken: "mock-product-token",
ProjectToken: "mock-project-token",
Version: "1",
}
scan := newWhitesourceScan(config)
utils := newWhitesourceUtilsMock()
system := ws.NewSystemMock(time.Now().Format(ws.DateTimeLayout))
influx := whitesourceExecuteScanInflux{}
// test
_, err := checkAndReportScanResults(config, scan, utils, system, &influx)
// assert
assert.NoError(t, err)
vPath := filepath.Join(ws.ReportsDirectory, "mock-project-vulnerability-report.txt")
assert.False(t, utils.HasWrittenFile(vPath))
rPath := filepath.Join(ws.ReportsDirectory, "mock-project-risk-report.pdf")
assert.False(t, utils.HasWrittenFile(rPath))
})
t.Run("check vulnerabilities - invalid limit", func(t *testing.T) {
// init
config := &ScanOptions{
SecurityVulnerabilities: true,
CvssSeverityLimit: "invalid",
}
scan := newWhitesourceScan(config)
utils := newWhitesourceUtilsMock()
system := ws.NewSystemMock(time.Now().Format(ws.DateTimeLayout))
influx := whitesourceExecuteScanInflux{}
// test
_, err := checkAndReportScanResults(config, scan, utils, system, &influx)
// assert
assert.EqualError(t, err, "failed to parse parameter cvssSeverityLimit (invalid) as floating point number: strconv.ParseFloat: parsing \"invalid\": invalid syntax")
})
t.Run("check vulnerabilities - limit not hit", func(t *testing.T) {
// init
config := &ScanOptions{
ProductToken: "mock-product-token",
ProjectToken: "mock-project-token",
Version: "1",
SecurityVulnerabilities: true,
CvssSeverityLimit: "6.0",
}
scan := newWhitesourceScan(config)
utils := newWhitesourceUtilsMock()
system := ws.NewSystemMock(time.Now().Format(ws.DateTimeLayout))
influx := whitesourceExecuteScanInflux{}
// test
_, err := checkAndReportScanResults(config, scan, utils, system, &influx)
// assert
assert.NoError(t, err)
})
t.Run("check vulnerabilities - limit exceeded", func(t *testing.T) {
// init
config := &ScanOptions{
ProductToken: "mock-product-token",
ProjectName: "mock-project - 1",
ProjectToken: "mock-project-token",
Version: "1",
SecurityVulnerabilities: true,
CvssSeverityLimit: "4",
}
scan := newWhitesourceScan(config)
utils := newWhitesourceUtilsMock()
system := ws.NewSystemMock(time.Now().Format(ws.DateTimeLayout))
influx := whitesourceExecuteScanInflux{}
// test
_, err := checkAndReportScanResults(config, scan, utils, system, &influx)
// assert
assert.EqualError(t, err, "1 Open Source Software Security vulnerabilities with CVSS score greater or equal to 4.0 detected in project mock-project - 1")
})
}
func TestResolveProjectIdentifiers(t *testing.T) {
t.Parallel()
t.Run("success", func(t *testing.T) {
// init
config := ScanOptions{
BuildTool: "mta",
BuildDescriptorFile: "my-mta.yml",
VersioningModel: "major",
ProductName: "mock-product",
M2Path: "m2/path",
ProjectSettingsFile: "project-settings.xml",
GlobalSettingsFile: "global-settings.xml",
}
utilsMock := newWhitesourceUtilsMock()
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
// test
err := resolveProjectIdentifiers(&config, scan, utilsMock, systemMock)
// assert
if assert.NoError(t, err) {
assert.Equal(t, "mock-group-id-mock-artifact-id", scan.AggregateProjectName)
assert.Equal(t, "1", config.Version)
assert.Equal(t, "mock-product-token", config.ProductToken)
assert.Equal(t, "mta", utilsMock.usedBuildTool)
assert.Equal(t, "my-mta.yml", utilsMock.usedBuildDescriptorFile)
assert.Equal(t, "project-settings.xml", utilsMock.usedOptions.ProjectSettingsFile)
assert.Equal(t, "global-settings.xml", utilsMock.usedOptions.GlobalSettingsFile)
assert.Equal(t, "m2/path", utilsMock.usedOptions.M2Path)
}
})
t.Run("success - with version from default", func(t *testing.T) {
// init
config := ScanOptions{
BuildTool: "mta",
BuildDescriptorFile: "my-mta.yml",
Version: "1.2.3-20200101",
VersioningModel: "major",
ProductName: "mock-product",
M2Path: "m2/path",
ProjectSettingsFile: "project-settings.xml",
GlobalSettingsFile: "global-settings.xml",
}
utilsMock := newWhitesourceUtilsMock()
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
// test
err := resolveProjectIdentifiers(&config, scan, utilsMock, systemMock)
// assert
if assert.NoError(t, err) {
assert.Equal(t, "mock-group-id-mock-artifact-id", scan.AggregateProjectName)
assert.Equal(t, "1", config.Version)
assert.Equal(t, "mock-product-token", config.ProductToken)
assert.Equal(t, "mta", utilsMock.usedBuildTool)
assert.Equal(t, "my-mta.yml", utilsMock.usedBuildDescriptorFile)
assert.Equal(t, "project-settings.xml", utilsMock.usedOptions.ProjectSettingsFile)
assert.Equal(t, "global-settings.xml", utilsMock.usedOptions.GlobalSettingsFile)
assert.Equal(t, "m2/path", utilsMock.usedOptions.M2Path)
}
})
t.Run("success - with custom scan version", func(t *testing.T) {
// init
config := ScanOptions{
BuildTool: "mta",
BuildDescriptorFile: "my-mta.yml",
CustomScanVersion: "2.3.4",
VersioningModel: "major",
ProductName: "mock-product",
M2Path: "m2/path",
ProjectSettingsFile: "project-settings.xml",
GlobalSettingsFile: "global-settings.xml",
}
utilsMock := newWhitesourceUtilsMock()
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
// test
err := resolveProjectIdentifiers(&config, scan, utilsMock, systemMock)
// assert
if assert.NoError(t, err) {
assert.Equal(t, "mock-group-id-mock-artifact-id", scan.AggregateProjectName)
assert.Equal(t, "2.3.4", config.Version)
assert.Equal(t, "mock-product-token", config.ProductToken)
assert.Equal(t, "mta", utilsMock.usedBuildTool)
assert.Equal(t, "my-mta.yml", utilsMock.usedBuildDescriptorFile)
assert.Equal(t, "project-settings.xml", utilsMock.usedOptions.ProjectSettingsFile)
assert.Equal(t, "global-settings.xml", utilsMock.usedOptions.GlobalSettingsFile)
assert.Equal(t, "m2/path", utilsMock.usedOptions.M2Path)
}
})
t.Run("retrieves token for configured project name", func(t *testing.T) {
// init
config := ScanOptions{
BuildTool: "mta",
BuildDescriptorFile: "my-mta.yml",
VersioningModel: "major",
ProductName: "mock-product",
ProjectName: "mock-project",
}
utilsMock := newWhitesourceUtilsMock()
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
// test
err := resolveProjectIdentifiers(&config, scan, utilsMock, systemMock)
// assert
if assert.NoError(t, err) {
assert.Equal(t, "mock-project", scan.AggregateProjectName)
assert.Equal(t, "1", config.Version)
assert.Equal(t, "mock-product-token", config.ProductToken)
assert.Equal(t, "mta", utilsMock.usedBuildTool)
assert.Equal(t, "my-mta.yml", utilsMock.usedBuildDescriptorFile)
assert.Equal(t, "mock-project-token", config.ProjectToken)
}
})
t.Run("product not found", func(t *testing.T) {
// init
config := ScanOptions{
BuildTool: "mta",
VersioningModel: "major",
ProductName: "does-not-exist",
}
utilsMock := newWhitesourceUtilsMock()
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
// test
err := resolveProjectIdentifiers(&config, scan, utilsMock, systemMock)
// assert
assert.EqualError(t, err, "error resolving product token: failed to get product by name: no product with name 'does-not-exist' found in Whitesource")
})
t.Run("product not found, created from pipeline", func(t *testing.T) {
// init
config := ScanOptions{
BuildTool: "mta",
CreateProductFromPipeline: true,
EmailAddressesOfInitialProductAdmins: []string{"[email protected]", "[email protected]"},
VersioningModel: "major",
ProductName: "created-by-pipeline",
}
utilsMock := newWhitesourceUtilsMock()
systemMock := ws.NewSystemMock("ignored")
scan := newWhitesourceScan(&config)
// test
err := resolveProjectIdentifiers(&config, scan, utilsMock, systemMock)
// assert
assert.NoError(t, err)
assert.Len(t, systemMock.Products, 2)
assert.Equal(t, "created-by-pipeline", systemMock.Products[1].Name)
assert.Equal(t, "mock-product-token-1", config.ProductToken)
})
}
func TestCheckPolicyViolations(t *testing.T) {
t.Parallel()
t.Run("success - no violations", func(t *testing.T) {
config := ScanOptions{ProductName: "mock-product", Version: "1"}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{}
utilsMock := newWhitesourceUtilsMock()
reportPaths := []piperutils.Path{
{Target: filepath.Join("whitesource", "report1.pdf")},
{Target: filepath.Join("whitesource", "report2.pdf")},
}
influx := whitesourceExecuteScanInflux{}
path, err := checkPolicyViolations(&config, scan, systemMock, utilsMock, reportPaths, &influx)
assert.NoError(t, err)
assert.Equal(t, filepath.Join(ws.ReportsDirectory, "whitesource-ip.json"), path.Target)
fileContent, _ := utilsMock.FileRead(path.Target)
content := string(fileContent)
assert.Contains(t, content, `"policyViolations":0`)
assert.Contains(t, content, `"reports":["report1.pdf","report2.pdf"]`)
exists, err := utilsMock.FileExists(filepath.Join(reporting.StepReportDirectory, "whitesourceExecuteScan_ip_2d3120020f3f46393a54575a7f6f5675ad536721.json"))
assert.True(t, exists)
})
t.Run("success - no reports", func(t *testing.T) {
config := ScanOptions{}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{}
utilsMock := newWhitesourceUtilsMock()
reportPaths := []piperutils.Path{}
influx := whitesourceExecuteScanInflux{}
path, err := checkPolicyViolations(&config, scan, systemMock, utilsMock, reportPaths, &influx)
assert.NoError(t, err)
fileContent, _ := utilsMock.FileRead(path.Target)
content := string(fileContent)
assert.Contains(t, content, `reports":[]`)
})
t.Run("error - policy violations", func(t *testing.T) {
config := ScanOptions{}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{
{Vulnerability: ws.Vulnerability{Name: "policyVul1"}},
{Vulnerability: ws.Vulnerability{Name: "policyVul2"}},
}
utilsMock := newWhitesourceUtilsMock()
reportPaths := []piperutils.Path{
{Target: "report1.pdf"},
{Target: "report2.pdf"},
}
influx := whitesourceExecuteScanInflux{}
path, err := checkPolicyViolations(&config, scan, systemMock, utilsMock, reportPaths, &influx)
assert.Contains(t, fmt.Sprint(err), "2 policy violation(s) found")
fileContent, _ := utilsMock.FileRead(path.Target)
content := string(fileContent)
assert.Contains(t, content, `"policyViolations":2`)
assert.Contains(t, content, `"reports":["report1.pdf","report2.pdf"]`)
})
t.Run("error - get alerts", func(t *testing.T) {
config := ScanOptions{}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.AlertError = fmt.Errorf("failed to read alerts")
utilsMock := newWhitesourceUtilsMock()
reportPaths := []piperutils.Path{}
influx := whitesourceExecuteScanInflux{}
_, err := checkPolicyViolations(&config, scan, systemMock, utilsMock, reportPaths, &influx)
assert.Contains(t, fmt.Sprint(err), "failed to retrieve project policy alerts from WhiteSource")
})
t.Run("error - write file", func(t *testing.T) {
config := ScanOptions{}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{}
utilsMock := newWhitesourceUtilsMock()
utilsMock.FileWriteError = fmt.Errorf("failed to write file")
reportPaths := []piperutils.Path{}
influx := whitesourceExecuteScanInflux{}
_, err := checkPolicyViolations(&config, scan, systemMock, utilsMock, reportPaths, &influx)
assert.Contains(t, fmt.Sprint(err), "failed to write policy violation report:")
})
t.Run("failed to write json report", func(t *testing.T) {
config := ScanOptions{ProductName: "mock-product", Version: "1"}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{}
utilsMock := newWhitesourceUtilsMock()
utilsMock.FileWriteErrors = map[string]error{
filepath.Join(reporting.StepReportDirectory, "whitesourceExecuteScan_ip_2d3120020f3f46393a54575a7f6f5675ad536721.json"): fmt.Errorf("write error"),
}
reportPaths := []piperutils.Path{}
influx := whitesourceExecuteScanInflux{}
_, err := checkPolicyViolations(&config, scan, systemMock, utilsMock, reportPaths, &influx)
assert.Contains(t, fmt.Sprint(err), "failed to write json report")
})
}
func TestCheckSecurityViolations(t *testing.T) {
t.Parallel()
t.Run("success - non-aggregated", func(t *testing.T) {
config := ScanOptions{
CvssSeverityLimit: "7",
}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{
{Vulnerability: ws.Vulnerability{Name: "vul1", CVSS3Score: 6.0}},
}
utilsMock := newWhitesourceUtilsMock()
influx := whitesourceExecuteScanInflux{}
reportPaths, err := checkSecurityViolations(&config, scan, systemMock, utilsMock, &influx)
assert.NoError(t, err)
fileContent, err := utilsMock.FileRead(reportPaths[0].Target)
assert.NoError(t, err)
assert.True(t, len(fileContent) > 0)
})
t.Run("success - aggregated", func(t *testing.T) {
config := ScanOptions{
CvssSeverityLimit: "7",
ProjectToken: "theProjectToken",
}
scan := newWhitesourceScan(&config)
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{
{Vulnerability: ws.Vulnerability{Name: "vul1", CVSS3Score: 6.0}},
}
utilsMock := newWhitesourceUtilsMock()
influx := whitesourceExecuteScanInflux{}
reportPaths, err := checkSecurityViolations(&config, scan, systemMock, utilsMock, &influx)
assert.NoError(t, err)
assert.Equal(t, 0, len(reportPaths))
})
t.Run("error - wrong limit", func(t *testing.T) {
config := ScanOptions{CvssSeverityLimit: "x"}
scan := newWhitesourceScan(&config)
systemMock := ws.NewSystemMock("ignored")
utilsMock := newWhitesourceUtilsMock()
influx := whitesourceExecuteScanInflux{}
_, err := checkSecurityViolations(&config, scan, systemMock, utilsMock, &influx)
assert.Contains(t, fmt.Sprint(err), "failed to parse parameter cvssSeverityLimit")
})
t.Run("error - non-aggregated", func(t *testing.T) {
config := ScanOptions{
CvssSeverityLimit: "5",
}
scan := newWhitesourceScan(&config)
scan.AppendScannedProject("testProject1")
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{
{Vulnerability: ws.Vulnerability{Name: "vul1", CVSS3Score: 6.0}},
}
utilsMock := newWhitesourceUtilsMock()
influx := whitesourceExecuteScanInflux{}
reportPaths, err := checkSecurityViolations(&config, scan, systemMock, utilsMock, &influx)
assert.Contains(t, fmt.Sprint(err), "1 Open Source Software Security vulnerabilities")
fileContent, err := utilsMock.FileRead(reportPaths[0].Target)
assert.NoError(t, err)
assert.True(t, len(fileContent) > 0)
})
t.Run("error - aggregated", func(t *testing.T) {
config := ScanOptions{
CvssSeverityLimit: "5",
ProjectToken: "theProjectToken",
}
scan := newWhitesourceScan(&config)
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{
{Vulnerability: ws.Vulnerability{Name: "vul1", CVSS3Score: 6.0}},
}
utilsMock := newWhitesourceUtilsMock()
influx := whitesourceExecuteScanInflux{}
reportPaths, err := checkSecurityViolations(&config, scan, systemMock, utilsMock, &influx)
assert.Contains(t, fmt.Sprint(err), "1 Open Source Software Security vulnerabilities")
assert.Equal(t, 0, len(reportPaths))
})
}
func TestCheckProjectSecurityViolations(t *testing.T) {
project := ws.Project{Name: "testProject - 1", Token: "testToken"}
t.Run("success - no alerts", func(t *testing.T) {
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{}
influx := whitesourceExecuteScanInflux{}
severeVulnerabilities, alerts, err := checkProjectSecurityViolations(7.0, project, systemMock, &influx)
assert.NoError(t, err)
assert.Equal(t, 0, severeVulnerabilities)
assert.Equal(t, 0, len(alerts))
})
t.Run("error - some vulnerabilities", func(t *testing.T) {
systemMock := ws.NewSystemMock("ignored")
systemMock.Alerts = []ws.Alert{
{Vulnerability: ws.Vulnerability{CVSS3Score: 7}},
{Vulnerability: ws.Vulnerability{CVSS3Score: 6}},
}
influx := whitesourceExecuteScanInflux{}
severeVulnerabilities, alerts, err := checkProjectSecurityViolations(7.0, project, systemMock, &influx)
assert.Contains(t, fmt.Sprint(err), "1 Open Source Software Security vulnerabilities")
assert.Equal(t, 1, severeVulnerabilities)
assert.Equal(t, 2, len(alerts))
})
t.Run("error - WhiteSource failure", func(t *testing.T) {
systemMock := ws.NewSystemMock("ignored")
systemMock.AlertError = fmt.Errorf("failed to read alerts")
influx := whitesourceExecuteScanInflux{}
_, _, err := checkProjectSecurityViolations(7.0, project, systemMock, &influx)
assert.Contains(t, fmt.Sprint(err), "failed to retrieve project alerts from WhiteSource")
})
}
func TestAggregateVersionWideLibraries(t *testing.T) {
t.Parallel()
t.Run("happy path", func(t *testing.T) {
// init
config := &ScanOptions{
ProductToken: "mock-product-token",
Version: "1",
}
utils := newWhitesourceUtilsMock()
system := ws.NewSystemMock("2010-05-30 00:15:00 +0100")
// test
err := aggregateVersionWideLibraries(config, utils, system)
// assert
resource := filepath.Join(ws.ReportsDirectory, "libraries-20100510-001542.csv")
if assert.NoError(t, err) && assert.True(t, utils.HasWrittenFile(resource)) {
contents, _ := utils.FileRead(resource)
asString := string(contents)
assert.Equal(t, "Library Name, Project Name\nmock-library, mock-project\n", asString)
assert.NotEmpty(t, piperenv.GetParameter("", "whitesourceExecuteScan_reports.json"))
}
})
}
func TestAggregateVersionWideVulnerabilities(t *testing.T) {
t.Parallel()
t.Run("happy path", func(t *testing.T) {
// init
config := &ScanOptions{
ProductToken: "mock-product-token",
Version: "1",
}
utils := newWhitesourceUtilsMock()
system := ws.NewSystemMock("2010-05-30 00:15:00 +0100")
// test
err := aggregateVersionWideVulnerabilities(config, utils, system)
// assert
resource := filepath.Join(ws.ReportsDirectory, "project-names-aggregated.txt")
assert.NoError(t, err)
if assert.True(t, utils.HasWrittenFile(resource)) {
contents, _ := utils.FileRead(resource)
asString := string(contents)
assert.Equal(t, "mock-project - 1\n", asString)
}
reportSheet := filepath.Join(ws.ReportsDirectory, "vulnerabilities-20100510-001542.xlsx")
sheetContents, err := utils.FileRead(reportSheet)
assert.NoError(t, err)
assert.NotEmpty(t, sheetContents)
assert.NotEmpty(t, piperenv.GetParameter("", "whitesourceExecuteScan_reports.json"))
})
}
func TestPersistScannedProjects(t *testing.T) {
t.Parallel()
t.Run("write 1 scanned projects", func(t *testing.T) {
// init
cpe := whitesourceExecuteScanCommonPipelineEnvironment{}
config := &ScanOptions{Version: "1"}
scan := newWhitesourceScan(config)
_ = scan.AppendScannedProject("project")
// test
persistScannedProjects(config, scan, &cpe)
// assert
assert.Equal(t, []string{"project - 1"}, cpe.custom.whitesourceProjectNames)
})
t.Run("write 2 scanned projects", func(t *testing.T) {
// init
cpe := whitesourceExecuteScanCommonPipelineEnvironment{}
config := &ScanOptions{Version: "1"}
scan := newWhitesourceScan(config)
_ = scan.AppendScannedProject("project-app")
_ = scan.AppendScannedProject("project-db")
// test
persistScannedProjects(config, scan, &cpe)
// assert
assert.Equal(t, []string{"project-app - 1", "project-db - 1"}, cpe.custom.whitesourceProjectNames)
})
t.Run("write no projects", func(t *testing.T) {
// init
cpe := whitesourceExecuteScanCommonPipelineEnvironment{}
config := &ScanOptions{Version: "1"}
scan := newWhitesourceScan(config)
// test
persistScannedProjects(config, scan, &cpe)
// assert
assert.Equal(t, []string{}, cpe.custom.whitesourceProjectNames)
})
t.Run("write aggregated project", func(t *testing.T) {
// init
cpe := whitesourceExecuteScanCommonPipelineEnvironment{}
config := &ScanOptions{ProjectName: "project", Version: "1"}
scan := newWhitesourceScan(config)
// test
persistScannedProjects(config, scan, &cpe)
// assert
assert.Equal(t, []string{"project - 1"}, cpe.custom.whitesourceProjectNames)
})
}