forked from SAP/jenkins-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfortifyExecuteScan.go
1116 lines (1001 loc) · 46.2 KB
/
fortifyExecuteScan.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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
piperhttp "github.com/SAP/jenkins-library/pkg/http"
"github.com/bmatcuk/doublestar"
"github.com/google/go-github/v32/github"
"github.com/google/uuid"
"github.com/piper-validation/fortify-client-go/models"
"github.com/SAP/jenkins-library/pkg/command"
"github.com/SAP/jenkins-library/pkg/fortify"
"github.com/SAP/jenkins-library/pkg/gradle"
"github.com/SAP/jenkins-library/pkg/log"
"github.com/SAP/jenkins-library/pkg/maven"
"github.com/SAP/jenkins-library/pkg/piperutils"
"github.com/SAP/jenkins-library/pkg/reporting"
"github.com/SAP/jenkins-library/pkg/telemetry"
"github.com/SAP/jenkins-library/pkg/toolrecord"
"github.com/SAP/jenkins-library/pkg/versioning"
piperGithub "github.com/SAP/jenkins-library/pkg/github"
"github.com/pkg/errors"
)
type pullRequestService interface {
ListPullRequestsWithCommit(ctx context.Context, owner, repo, sha string, opts *github.PullRequestListOptions) ([]*github.PullRequest, *github.Response, error)
}
type fortifyUtils interface {
maven.Utils
gradle.Utils
SetDir(d string)
GetArtifact(buildTool, buildDescriptorFile string, options *versioning.Options) (versioning.Artifact, error)
CreateIssue(ghCreateIssueOptions *piperGithub.CreateIssueOptions) error
}
type fortifyUtilsBundle struct {
*command.Command
*piperutils.Files
*piperhttp.Client
}
func (f *fortifyUtilsBundle) GetArtifact(buildTool, buildDescriptorFile string, options *versioning.Options) (versioning.Artifact, error) {
return versioning.GetArtifact(buildTool, buildDescriptorFile, options, f)
}
func (f *fortifyUtilsBundle) CreateIssue(ghCreateIssueOptions *piperGithub.CreateIssueOptions) error {
return piperGithub.CreateIssue(ghCreateIssueOptions)
}
func newFortifyUtilsBundle() fortifyUtils {
utils := fortifyUtilsBundle{
Command: &command.Command{},
Files: &piperutils.Files{},
Client: &piperhttp.Client{},
}
utils.Stdout(log.Writer())
utils.Stderr(log.Writer())
return &utils
}
const checkString = "<---CHECK FORTIFY---"
const classpathFileName = "fortify-execute-scan-cp.txt"
func fortifyExecuteScan(config fortifyExecuteScanOptions, telemetryData *telemetry.CustomData, influx *fortifyExecuteScanInflux) {
auditStatus := map[string]string{}
sys := fortify.NewSystemInstance(config.ServerURL, config.APIEndpoint, config.AuthToken, time.Minute*15)
utils := newFortifyUtilsBundle()
influx.step_data.fields.fortify = false
reports, err := runFortifyScan(config, sys, utils, telemetryData, influx, auditStatus)
piperutils.PersistReportsAndLinks("fortifyExecuteScan", config.ModulePath, reports, nil)
if err != nil {
log.Entry().WithError(err).Fatal("Fortify scan and check failed")
}
influx.step_data.fields.fortify = true
// make sure that no specific error category is set in success case
log.SetErrorCategory(log.ErrorUndefined)
}
func determineArtifact(config fortifyExecuteScanOptions, utils fortifyUtils) (versioning.Artifact, error) {
versioningOptions := versioning.Options{
M2Path: config.M2Path,
GlobalSettingsFile: config.GlobalSettingsFile,
ProjectSettingsFile: config.ProjectSettingsFile,
}
artifact, err := utils.GetArtifact(config.BuildTool, config.BuildDescriptorFile, &versioningOptions)
if err != nil {
return nil, fmt.Errorf("Unable to get artifact from descriptor %v: %w", config.BuildDescriptorFile, err)
}
return artifact, nil
}
func runFortifyScan(config fortifyExecuteScanOptions, sys fortify.System, utils fortifyUtils, telemetryData *telemetry.CustomData, influx *fortifyExecuteScanInflux, auditStatus map[string]string) ([]piperutils.Path, error) {
var reports []piperutils.Path
log.Entry().Debugf("Running Fortify scan against SSC at %v", config.ServerURL)
if config.BuildTool == "maven" && config.InstallArtifacts {
err := maven.InstallMavenArtifacts(&maven.EvaluateOptions{
M2Path: config.M2Path,
ProjectSettingsFile: config.ProjectSettingsFile,
GlobalSettingsFile: config.GlobalSettingsFile,
PomPath: config.BuildDescriptorFile,
}, utils)
if err != nil {
return reports, fmt.Errorf("Unable to install artifacts: %w", err)
}
}
artifact, err := determineArtifact(config, utils)
if err != nil {
log.Entry().WithError(err).Fatal()
}
coordinates, err := artifact.GetCoordinates()
if err != nil {
log.SetErrorCategory(log.ErrorConfiguration)
return reports, fmt.Errorf("unable to get project coordinates from descriptor %v: %w", config.BuildDescriptorFile, err)
}
log.Entry().Debugf("loaded project coordinates %v from descriptor", coordinates)
if len(config.Version) > 0 {
log.Entry().Infof("Resolving product version from default provided '%s' with versioning '%s'", config.Version, config.VersioningModel)
coordinates.Version = config.Version
}
fortifyProjectName, fortifyProjectVersion := versioning.DetermineProjectCoordinatesWithCustomVersion(config.ProjectName, config.VersioningModel, config.CustomScanVersion, coordinates)
project, err := sys.GetProjectByName(fortifyProjectName, config.AutoCreate, fortifyProjectVersion)
if err != nil {
classifyErrorOnLookup(err)
return reports, fmt.Errorf("Failed to load project %v: %w", fortifyProjectName, err)
}
projectVersion, err := sys.GetProjectVersionDetailsByProjectIDAndVersionName(project.ID, fortifyProjectVersion, config.AutoCreate, fortifyProjectName)
if err != nil {
classifyErrorOnLookup(err)
return reports, fmt.Errorf("Failed to load project version %v: %w", fortifyProjectVersion, err)
}
if len(config.PullRequestName) > 0 {
fortifyProjectVersion = config.PullRequestName
projectVersion, err = sys.LookupOrCreateProjectVersionDetailsForPullRequest(project.ID, projectVersion, fortifyProjectVersion)
if err != nil {
classifyErrorOnLookup(err)
return reports, fmt.Errorf("Failed to lookup / create project version for pull request %v: %w", fortifyProjectVersion, err)
}
log.Entry().Debugf("Looked up / created project version with ID %v for PR %v", projectVersion.ID, fortifyProjectVersion)
} else {
prID, prAuthor := determinePullRequestMerge(config)
if prID != "0" {
log.Entry().Debugf("Determined PR ID '%v' for merge check", prID)
if len(prAuthor) > 0 && !piperutils.ContainsString(config.Assignees, prAuthor) {
log.Entry().Debugf("Determined PR Author '%v' for result assignment", prAuthor)
config.Assignees = append(config.Assignees, prAuthor)
} else {
log.Entry().Debugf("Unable to determine PR Author, using assignees: %v", config.Assignees)
}
pullRequestProjectName := fmt.Sprintf("PR-%v", prID)
err = sys.MergeProjectVersionStateOfPRIntoMaster(config.FprDownloadEndpoint, config.FprUploadEndpoint, project.ID, projectVersion.ID, pullRequestProjectName)
if err != nil {
return reports, fmt.Errorf("Failed to merge project version state for pull request %v into project version %v of project %v: %w", pullRequestProjectName, fortifyProjectVersion, project.ID, err)
}
}
}
filterSet, err := sys.GetFilterSetOfProjectVersionByTitle(projectVersion.ID, config.FilterSetTitle)
if filterSet == nil || err != nil {
return reports, fmt.Errorf("Failed to load filter set with title %v", config.FilterSetTitle)
}
// create toolrecord file
// tbd - how to handle verifyOnly
toolRecordFileName, err := createToolRecordFortify("./", config, project.ID, fortifyProjectName, projectVersion.ID, fortifyProjectVersion)
if err != nil {
// do not fail until the framework is well established
log.Entry().Warning("TR_FORTIFY: Failed to create toolrecord file ...", err)
} else {
reports = append(reports, piperutils.Path{Target: toolRecordFileName})
}
if config.VerifyOnly {
log.Entry().Infof("Starting audit status check on project %v with version %v and project version ID %v", fortifyProjectName, fortifyProjectVersion, projectVersion.ID)
err, paths := verifyFFProjectCompliance(config, utils, sys, project, projectVersion, filterSet, influx, auditStatus)
reports = append(reports, paths...)
return reports, err
}
log.Entry().Infof("Scanning and uploading to project %v with version %v and projectVersionId %v", fortifyProjectName, fortifyProjectVersion, projectVersion.ID)
buildLabel := fmt.Sprintf("%v/repos/%v/%v/commits/%v", config.GithubAPIURL, config.Owner, config.Repository, config.CommitID)
// Create sourceanalyzer command based on configuration
buildID := uuid.New().String()
utils.SetDir(config.ModulePath)
os.MkdirAll(fmt.Sprintf("%v/%v", config.ModulePath, "target"), os.ModePerm)
if config.UpdateRulePack {
err := utils.RunExecutable("fortifyupdate", "-acceptKey", "-acceptSSLCertificate", "-url", config.ServerURL)
if err != nil {
return reports, fmt.Errorf("failed to update rule pack, serverUrl: %v", config.ServerURL)
}
err = utils.RunExecutable("fortifyupdate", "-acceptKey", "-acceptSSLCertificate", "-showInstalledRules")
if err != nil {
return reports, fmt.Errorf("failed to fetch details of installed rule pack, serverUrl: %v", config.ServerURL)
}
}
err = triggerFortifyScan(config, utils, buildID, buildLabel, fortifyProjectName)
reports = append(reports, piperutils.Path{Target: fmt.Sprintf("%vtarget/fortify-scan.*", config.ModulePath)})
reports = append(reports, piperutils.Path{Target: fmt.Sprintf("%vtarget/*.fpr", config.ModulePath)})
if err != nil {
return reports, errors.Wrapf(err, "failed to scan project")
}
var message string
if config.UploadResults {
log.Entry().Debug("Uploading results")
resultFilePath := fmt.Sprintf("%vtarget/result.fpr", config.ModulePath)
err = sys.UploadResultFile(config.FprUploadEndpoint, resultFilePath, projectVersion.ID)
message = fmt.Sprintf("Failed to upload result file %v to Fortify SSC at %v", resultFilePath, config.ServerURL)
} else {
log.Entry().Debug("Generating XML report")
xmlReportName := "fortify_result.xml"
err = utils.RunExecutable("ReportGenerator", "-format", "xml", "-f", xmlReportName, "-source", fmt.Sprintf("%vtarget/result.fpr", config.ModulePath))
message = fmt.Sprintf("Failed to generate XML report %v", xmlReportName)
if err != nil {
reports = append(reports, piperutils.Path{Target: fmt.Sprintf("%vfortify_result.xml", config.ModulePath)})
}
}
if err != nil {
return reports, fmt.Errorf(message+": %w", err)
}
//Place conversion beforehand, or audit will stop the pipeline and conversion will not take place?
if config.ConvertToSarif {
resultFilePath := fmt.Sprintf("%vtarget/result.fpr", config.ModulePath)
log.Entry().Info("Calling conversion to SARIF function.")
sarif, err := fortify.ConvertFprToSarif(sys, project, projectVersion, resultFilePath, filterSet)
if err != nil {
return reports, fmt.Errorf("failed to generate SARIF")
}
log.Entry().Debug("Writing sarif file to disk.")
paths, err := fortify.WriteSarif(sarif)
if err != nil {
return reports, fmt.Errorf("failed to write sarif")
}
reports = append(reports, paths...)
}
log.Entry().Infof("Starting audit status check on project %v with version %v and project version ID %v", fortifyProjectName, fortifyProjectVersion, projectVersion.ID)
// Ensure latest FPR is processed
err = verifyScanResultsFinishedUploading(config, sys, projectVersion.ID, buildLabel, filterSet,
10*time.Second, time.Duration(config.PollingMinutes)*time.Minute)
if err != nil {
return reports, err
}
err, paths := verifyFFProjectCompliance(config, utils, sys, project, projectVersion, filterSet, influx, auditStatus)
reports = append(reports, paths...)
return reports, err
}
func classifyErrorOnLookup(err error) {
if strings.Contains(err.Error(), "connect: connection refused") || strings.Contains(err.Error(), "net/http: TLS handshake timeout") {
log.SetErrorCategory(log.ErrorService)
}
}
func verifyFFProjectCompliance(config fortifyExecuteScanOptions, utils fortifyUtils, sys fortify.System, project *models.Project, projectVersion *models.ProjectVersion, filterSet *models.FilterSet, influx *fortifyExecuteScanInflux, auditStatus map[string]string) (error, []piperutils.Path) {
reports := []piperutils.Path{}
// Generate report
if config.Reporting {
resultURL := []byte(fmt.Sprintf("%v/html/ssc/version/%v/fix/null/", config.ServerURL, projectVersion.ID))
ioutil.WriteFile(fmt.Sprintf("%vtarget/%v-%v.%v", config.ModulePath, *project.Name, *projectVersion.Name, "txt"), resultURL, 0700)
data, err := generateAndDownloadQGateReport(config, sys, project, projectVersion)
if err != nil {
return err, reports
}
ioutil.WriteFile(fmt.Sprintf("%vtarget/%v-%v.%v", config.ModulePath, *project.Name, *projectVersion.Name, config.ReportType), data, 0700)
}
// Perform audit compliance checks
issueFilterSelectorSet, err := sys.GetIssueFilterSelectorOfProjectVersionByName(projectVersion.ID, []string{"Analysis", "Folder", "Category"}, nil)
if err != nil {
return errors.Wrapf(err, "failed to fetch project version issue filter selector for project version ID %v", projectVersion.ID), reports
}
log.Entry().Debugf("initial filter selector set: %v", issueFilterSelectorSet)
spotChecksCountByCategory := []fortify.SpotChecksAuditCount{}
numberOfViolations, issueGroups, err := analyseUnauditedIssues(config, sys, projectVersion, filterSet, issueFilterSelectorSet, influx, auditStatus, &spotChecksCountByCategory)
if err != nil {
return errors.Wrap(err, "failed to analyze unaudited issues"), reports
}
numberOfSuspiciousExploitable, issueGroupsSuspiciousExploitable := analyseSuspiciousExploitable(config, sys, projectVersion, filterSet, issueFilterSelectorSet, influx, auditStatus)
numberOfViolations += numberOfSuspiciousExploitable
issueGroups = append(issueGroups, issueGroupsSuspiciousExploitable...)
log.Entry().Infof("Counted %v violations, details: %v", numberOfViolations, auditStatus)
influx.fortify_data.fields.projectName = *project.Name
influx.fortify_data.fields.projectVersion = *projectVersion.Name
influx.fortify_data.fields.projectVersionID = projectVersion.ID
influx.fortify_data.fields.violations = numberOfViolations
fortifyReportingData := prepareReportData(influx)
scanReport := fortify.CreateCustomReport(fortifyReportingData, issueGroups)
paths, err := fortify.WriteCustomReports(scanReport)
if err != nil {
return errors.Wrap(err, "failed to write custom reports"), reports
}
reports = append(reports, paths...)
log.Entry().Debug("Checking whether GitHub issue creation/update is active")
log.Entry().Debugf("%v, %v, %v, %v, %v, %v", config.CreateResultIssue, numberOfViolations > 0, len(config.GithubToken) > 0, len(config.GithubAPIURL) > 0, len(config.Owner) > 0, len(config.Repository) > 0)
if config.CreateResultIssue && numberOfViolations > 0 && len(config.GithubToken) > 0 && len(config.GithubAPIURL) > 0 && len(config.Owner) > 0 && len(config.Repository) > 0 {
log.Entry().Debug("Creating/updating GitHub issue with scan results")
err = reporting.UploadSingleReportToGithub(scanReport, config.GithubToken, config.GithubAPIURL, config.Owner, config.Repository, config.Assignees, utils)
if err != nil {
return errors.Wrap(err, "failed to upload scan results into GitHub"), reports
}
}
jsonReport := fortify.CreateJSONReport(fortifyReportingData, spotChecksCountByCategory, config.ServerURL)
paths, err = fortify.WriteJSONReport(jsonReport)
if err != nil {
return errors.Wrap(err, "failed to write json report"), reports
}
reports = append(reports, paths...)
if numberOfViolations > 0 {
log.SetErrorCategory(log.ErrorCompliance)
return errors.New("fortify scan failed, the project is not compliant. For details check the archived report"), reports
}
return nil, reports
}
func prepareReportData(influx *fortifyExecuteScanInflux) fortify.FortifyReportData {
input := influx.fortify_data.fields
output := fortify.FortifyReportData{}
output.ProjectName = input.projectName
output.ProjectVersion = input.projectVersion
output.AuditAllAudited = input.auditAllAudited
output.AuditAllTotal = input.auditAllTotal
output.CorporateAudited = input.corporateAudited
output.CorporateTotal = input.corporateTotal
output.SpotChecksAudited = input.spotChecksAudited
output.SpotChecksGap = input.spotChecksGap
output.SpotChecksTotal = input.spotChecksTotal
output.Exploitable = input.exploitable
output.Suppressed = input.suppressed
output.Suspicious = input.suspicious
output.ProjectVersionID = input.projectVersionID
output.Violations = input.violations
return output
}
func analyseUnauditedIssues(config fortifyExecuteScanOptions, sys fortify.System, projectVersion *models.ProjectVersion, filterSet *models.FilterSet, issueFilterSelectorSet *models.IssueFilterSelectorSet, influx *fortifyExecuteScanInflux, auditStatus map[string]string, spotChecksCountByCategory *[]fortify.SpotChecksAuditCount) (int, []*models.ProjectVersionIssueGroup, error) {
log.Entry().Info("Analyzing unaudited issues")
reducedFilterSelectorSet := sys.ReduceIssueFilterSelectorSet(issueFilterSelectorSet, []string{"Folder"}, nil)
fetchedIssueGroups, err := sys.GetProjectIssuesByIDAndFilterSetGroupedBySelector(projectVersion.ID, "", filterSet.GUID, reducedFilterSelectorSet)
if err != nil {
return 0, fetchedIssueGroups, errors.Wrapf(err, "failed to fetch project version issue groups with filter set %v and selector %v for project version ID %v", filterSet, issueFilterSelectorSet, projectVersion.ID)
}
overallViolations := 0
for _, issueGroup := range fetchedIssueGroups {
issueDelta, err := getIssueDeltaFor(config, sys, issueGroup, projectVersion.ID, filterSet, issueFilterSelectorSet, influx, auditStatus, spotChecksCountByCategory)
if err != nil {
return overallViolations, fetchedIssueGroups, errors.Wrap(err, "failed to get issue delta")
}
overallViolations += issueDelta
}
return overallViolations, fetchedIssueGroups, nil
}
func getIssueDeltaFor(config fortifyExecuteScanOptions, sys fortify.System, issueGroup *models.ProjectVersionIssueGroup, projectVersionID int64, filterSet *models.FilterSet, issueFilterSelectorSet *models.IssueFilterSelectorSet, influx *fortifyExecuteScanInflux, auditStatus map[string]string, spotChecksCountByCategory *[]fortify.SpotChecksAuditCount) (int, error) {
totalMinusAuditedDelta := 0
group := ""
total := 0
audited := 0
if issueGroup != nil {
group = *issueGroup.ID
total = int(*issueGroup.TotalCount)
audited = int(*issueGroup.AuditedCount)
}
groupTotalMinusAuditedDelta := total - audited
if groupTotalMinusAuditedDelta > 0 {
reducedFilterSelectorSet := sys.ReduceIssueFilterSelectorSet(issueFilterSelectorSet, []string{"Folder", "Analysis"}, []string{group})
folderSelector := sys.GetFilterSetByDisplayName(reducedFilterSelectorSet, "Folder")
if folderSelector == nil {
return totalMinusAuditedDelta, fmt.Errorf("folder selector not found")
}
analysisSelector := sys.GetFilterSetByDisplayName(reducedFilterSelectorSet, "Analysis")
auditStatus[group] = fmt.Sprintf("%v total : %v audited", total, audited)
if strings.Contains(config.MustAuditIssueGroups, group) {
totalMinusAuditedDelta += groupTotalMinusAuditedDelta
if group == "Corporate Security Requirements" {
influx.fortify_data.fields.corporateTotal = total
influx.fortify_data.fields.corporateAudited = audited
}
if group == "Audit All" {
influx.fortify_data.fields.auditAllTotal = total
influx.fortify_data.fields.auditAllAudited = audited
}
log.Entry().Errorf("[projectVersionId %v]: Unaudited %v detected, count %v", projectVersionID, group, totalMinusAuditedDelta)
logIssueURL(config, projectVersionID, folderSelector, analysisSelector)
}
if strings.Contains(config.SpotAuditIssueGroups, group) {
log.Entry().Infof("Analyzing %v", config.SpotAuditIssueGroups)
filter := fmt.Sprintf("%v:%v", folderSelector.EntityType, folderSelector.SelectorOptions[0].Value)
fetchedIssueGroups, err := sys.GetProjectIssuesByIDAndFilterSetGroupedBySelector(projectVersionID, filter, filterSet.GUID, sys.ReduceIssueFilterSelectorSet(issueFilterSelectorSet, []string{"Category"}, nil))
if err != nil {
return totalMinusAuditedDelta, errors.Wrapf(err, "failed to fetch project version issue groups with filter %v, filter set %v and selector %v for project version ID %v", filter, filterSet, issueFilterSelectorSet, projectVersionID)
}
totalMinusAuditedDelta += getSpotIssueCount(config, sys, fetchedIssueGroups, projectVersionID, filterSet, reducedFilterSelectorSet, influx, auditStatus, spotChecksCountByCategory)
}
}
return totalMinusAuditedDelta, nil
}
func getSpotIssueCount(config fortifyExecuteScanOptions, sys fortify.System, spotCheckCategories []*models.ProjectVersionIssueGroup, projectVersionID int64, filterSet *models.FilterSet, issueFilterSelectorSet *models.IssueFilterSelectorSet, influx *fortifyExecuteScanInflux, auditStatus map[string]string, spotChecksCountByCategory *[]fortify.SpotChecksAuditCount) int {
overallDelta := 0
overallIssues := 0
overallIssuesAudited := 0
for _, issueGroup := range spotCheckCategories {
group := ""
total := 0
audited := 0
if issueGroup != nil {
group = *issueGroup.ID
total = int(*issueGroup.TotalCount)
audited = int(*issueGroup.AuditedCount)
}
flagOutput := ""
if ((total <= config.SpotCheckMinimum || config.SpotCheckMinimum < 0) && audited != total) || (total > config.SpotCheckMinimum && audited < config.SpotCheckMinimum) {
currentDelta := config.SpotCheckMinimum - audited
if config.SpotCheckMinimum < 0 || config.SpotCheckMinimum > total {
currentDelta = total - audited
}
if currentDelta > 0 {
filterSelectorFolder := sys.GetFilterSetByDisplayName(issueFilterSelectorSet, "Folder")
filterSelectorAnalysis := sys.GetFilterSetByDisplayName(issueFilterSelectorSet, "Analysis")
overallDelta += currentDelta
log.Entry().Errorf("[projectVersionId %v]: %v unaudited spot check issues detected in group %v", projectVersionID, currentDelta, group)
logIssueURL(config, projectVersionID, filterSelectorFolder, filterSelectorAnalysis)
flagOutput = checkString
}
}
overallIssues += total
overallIssuesAudited += audited
auditStatus[group] = fmt.Sprintf("%v total : %v audited %v", total, audited, flagOutput)
*spotChecksCountByCategory = append(*spotChecksCountByCategory, fortify.SpotChecksAuditCount{Audited: audited, Total: total, Type: group})
}
influx.fortify_data.fields.spotChecksTotal = overallIssues
influx.fortify_data.fields.spotChecksAudited = overallIssuesAudited
influx.fortify_data.fields.spotChecksGap = overallDelta
return overallDelta
}
func analyseSuspiciousExploitable(config fortifyExecuteScanOptions, sys fortify.System, projectVersion *models.ProjectVersion, filterSet *models.FilterSet, issueFilterSelectorSet *models.IssueFilterSelectorSet, influx *fortifyExecuteScanInflux, auditStatus map[string]string) (int, []*models.ProjectVersionIssueGroup) {
log.Entry().Info("Analyzing suspicious and exploitable issues")
reducedFilterSelectorSet := sys.ReduceIssueFilterSelectorSet(issueFilterSelectorSet, []string{"Analysis"}, []string{})
fetchedGroups, err := sys.GetProjectIssuesByIDAndFilterSetGroupedBySelector(projectVersion.ID, "", filterSet.GUID, reducedFilterSelectorSet)
suspiciousCount := 0
exploitableCount := 0
for _, issueGroup := range fetchedGroups {
if *issueGroup.ID == "3" {
suspiciousCount = int(*issueGroup.TotalCount)
} else if *issueGroup.ID == "4" {
exploitableCount = int(*issueGroup.TotalCount)
}
}
result := 0
if (suspiciousCount > 0 && config.ConsiderSuspicious) || exploitableCount > 0 {
result = result + suspiciousCount + exploitableCount
log.Entry().Errorf("[projectVersionId %v]: %v suspicious and %v exploitable issues detected", projectVersion.ID, suspiciousCount, exploitableCount)
log.Entry().Errorf("%v/html/ssc/index.jsp#!/version/%v/fix?issueGrouping=%v_%v&issueFilters=%v_%v", config.ServerURL, projectVersion.ID, reducedFilterSelectorSet.GroupBySet[0].EntityType, reducedFilterSelectorSet.GroupBySet[0].Value, reducedFilterSelectorSet.FilterBySet[0].EntityType, reducedFilterSelectorSet.FilterBySet[0].Value)
}
issueStatistics, err := sys.GetIssueStatisticsOfProjectVersion(projectVersion.ID)
if err != nil {
log.Entry().WithError(err).Errorf("Failed to fetch project version statistics for project version ID %v", projectVersion.ID)
}
auditStatus["Suspicious"] = fmt.Sprintf("%v", suspiciousCount)
auditStatus["Exploitable"] = fmt.Sprintf("%v", exploitableCount)
suppressedCount := *issueStatistics[0].SuppressedCount
if suppressedCount > 0 {
auditStatus["Suppressed"] = fmt.Sprintf("WARNING: Detected %v suppressed issues which could violate audit compliance!!!", suppressedCount)
}
influx.fortify_data.fields.suspicious = suspiciousCount
influx.fortify_data.fields.exploitable = exploitableCount
influx.fortify_data.fields.suppressed = int(suppressedCount)
return result, fetchedGroups
}
func logIssueURL(config fortifyExecuteScanOptions, projectVersionID int64, folderSelector, analysisSelector *models.IssueFilterSelector) {
url := fmt.Sprintf("%v/html/ssc/index.jsp#!/version/%v/fix", config.ServerURL, projectVersionID)
if len(folderSelector.SelectorOptions) > 0 {
url += fmt.Sprintf("?issueFilters=%v_%v:%v",
folderSelector.EntityType,
folderSelector.Value,
folderSelector.SelectorOptions[0].Value)
} else {
log.Entry().Debugf("no 'filter by set' array entries")
}
if analysisSelector != nil {
url += fmt.Sprintf("&issueFilters=%v_%v:",
analysisSelector.EntityType,
analysisSelector.Value)
} else {
log.Entry().Debugf("no second entry in 'filter by set' array")
}
log.Entry().Error(url)
}
func generateAndDownloadQGateReport(config fortifyExecuteScanOptions, sys fortify.System, project *models.Project, projectVersion *models.ProjectVersion) ([]byte, error) {
log.Entry().Infof("Generating report with template ID %v", config.ReportTemplateID)
report, err := sys.GenerateQGateReport(project.ID, projectVersion.ID, int64(config.ReportTemplateID), *project.Name, *projectVersion.Name, config.ReportType)
if err != nil {
return []byte{}, errors.Wrap(err, "failed to generate Q-Gate report")
}
log.Entry().Debugf("Triggered report generation of report ID %v", report.ID)
status := report.Status
for status == "PROCESSING" || status == "SCHED_PROCESSING" {
time.Sleep(10 * time.Second)
report, err = sys.GetReportDetails(report.ID)
if err != nil {
return []byte{}, fmt.Errorf("Failed to fetch Q-Gate report generation status: %w", err)
}
status = report.Status
}
data, err := sys.DownloadReportFile(config.ReportDownloadEndpoint, report.ID)
if err != nil {
return []byte{}, fmt.Errorf("Failed to download Q-Gate Report: %w", err)
}
return data, nil
}
var errProcessing = errors.New("artifact still processing")
func checkArtifactStatus(config fortifyExecuteScanOptions, projectVersionID int64, filterSet *models.FilterSet, artifact *models.Artifact, retries int, pollingDelay, timeout time.Duration) error {
if "PROCESSING" == artifact.Status || "SCHED_PROCESSING" == artifact.Status {
pollingTime := time.Duration(retries) * pollingDelay
if pollingTime >= timeout {
log.SetErrorCategory(log.ErrorService)
return fmt.Errorf("terminating after %v since artifact for Project Version %v is still in status %v", timeout, projectVersionID, artifact.Status)
}
log.Entry().Infof("Most recent artifact uploaded on %v of Project Version %v is still in status %v...", artifact.UploadDate, projectVersionID, artifact.Status)
time.Sleep(pollingDelay)
return errProcessing
}
if "REQUIRE_AUTH" == artifact.Status {
// verify no manual issue approval needed
log.SetErrorCategory(log.ErrorCompliance)
return fmt.Errorf("There are artifacts that require manual approval for Project Version %v, please visit Fortify SSC and approve them for processing\n%v/html/ssc/index.jsp#!/version/%v/artifacts?filterSet=%v", projectVersionID, config.ServerURL, projectVersionID, filterSet.GUID)
}
if "ERROR_PROCESSING" == artifact.Status {
log.SetErrorCategory(log.ErrorService)
return fmt.Errorf("There are artifacts that failed processing for Project Version %v\n%v/html/ssc/index.jsp#!/version/%v/artifacts?filterSet=%v", projectVersionID, config.ServerURL, projectVersionID, filterSet.GUID)
}
return nil
}
func verifyScanResultsFinishedUploading(config fortifyExecuteScanOptions, sys fortify.System, projectVersionID int64, buildLabel string, filterSet *models.FilterSet, pollingDelay, timeout time.Duration) error {
log.Entry().Debug("Verifying scan results have finished uploading and processing")
var artifacts []*models.Artifact
var relatedUpload *models.Artifact
var err error
retries := 0
for relatedUpload == nil {
artifacts, err = sys.GetArtifactsOfProjectVersion(projectVersionID)
log.Entry().Debugf("Received %v artifacts for project version ID %v", len(artifacts), projectVersionID)
if err != nil {
return fmt.Errorf("failed to fetch artifacts of project version ID %v", projectVersionID)
}
if len(artifacts) == 0 {
return fmt.Errorf("no uploaded artifacts for assessment detected for project version with ID %v", projectVersionID)
}
latest := artifacts[0]
err = checkArtifactStatus(config, projectVersionID, filterSet, latest, retries, pollingDelay, timeout)
if err != nil {
if err == errProcessing {
retries++
continue
}
return err
}
relatedUpload = findArtifactByBuildLabel(artifacts, buildLabel)
if relatedUpload == nil {
log.Entry().Warn("Unable to identify artifact based on the build label, will consider most recent artifact as related to the scan")
relatedUpload = artifacts[0]
}
}
differenceInSeconds := calculateTimeDifferenceToLastUpload(relatedUpload.UploadDate, projectVersionID)
// Use the absolute value for checking the time difference
if differenceInSeconds > float64(60*config.DeltaMinutes) {
return errors.New("no recent upload detected on Project Version")
}
for _, upload := range artifacts {
if upload.Status == "ERROR_PROCESSING" {
log.Entry().Warn("Previous uploads detected that failed processing, please ensure that your scans are properly configured")
break
}
}
return nil
}
func findArtifactByBuildLabel(artifacts []*models.Artifact, buildLabel string) *models.Artifact {
if len(buildLabel) == 0 {
return nil
}
for _, artifact := range artifacts {
if len(buildLabel) > 0 && artifact.Embed != nil && artifact.Embed.Scans != nil && len(artifact.Embed.Scans) > 0 {
scan := artifact.Embed.Scans[0]
if scan != nil && strings.HasSuffix(scan.BuildLabel, buildLabel) {
return artifact
}
}
}
return nil
}
func calculateTimeDifferenceToLastUpload(uploadDate models.Iso8601MilliDateTime, projectVersionID int64) float64 {
log.Entry().Infof("Last upload on project version %v happened on %v", projectVersionID, uploadDate)
uploadDateAsTime := time.Time(uploadDate)
duration := time.Since(uploadDateAsTime)
log.Entry().Debugf("Difference duration is %v", duration)
absoluteSeconds := math.Abs(duration.Seconds())
log.Entry().Infof("Difference since %v in seconds is %v", uploadDateAsTime, absoluteSeconds)
return absoluteSeconds
}
func executeTemplatedCommand(utils fortifyUtils, cmdTemplate []string, context map[string]string) error {
for index, cmdTemplatePart := range cmdTemplate {
result, err := piperutils.ExecuteTemplate(cmdTemplatePart, context)
if err != nil {
return errors.Wrapf(err, "failed to transform template for command fragment: %v", cmdTemplatePart)
}
cmdTemplate[index] = result
}
err := utils.RunExecutable(cmdTemplate[0], cmdTemplate[1:]...)
if err != nil {
return errors.Wrapf(err, "failed to execute command %v", cmdTemplate)
}
return nil
}
func autoresolvePipClasspath(executable string, parameters []string, file string, utils fortifyUtils) (string, error) {
// redirect stdout and create cp file from command output
outfile, err := os.Create(file)
if err != nil {
return "", errors.Wrapf(err, "failed to create classpath file")
}
defer outfile.Close()
utils.Stdout(outfile)
err = utils.RunExecutable(executable, parameters...)
if err != nil {
return "", errors.Wrapf(err, "failed to run classpath autodetection command %v with parameters %v", executable, parameters)
}
utils.Stdout(log.Entry().Writer())
return readClasspathFile(file), nil
}
func autoresolveMavenClasspath(config fortifyExecuteScanOptions, file string, utils fortifyUtils) (string, error) {
if filepath.IsAbs(file) {
log.Entry().Warnf("Passing an absolute path for -Dmdep.outputFile results in the classpath only for the last module in multi-module maven projects.")
}
defines := generateMavenFortifyDefines(&config, file)
executeOptions := maven.ExecuteOptions{
PomPath: config.BuildDescriptorFile,
ProjectSettingsFile: config.ProjectSettingsFile,
GlobalSettingsFile: config.GlobalSettingsFile,
M2Path: config.M2Path,
Goals: []string{"dependency:build-classpath", "package"},
Defines: defines,
ReturnStdout: false,
}
_, err := maven.Execute(&executeOptions, utils)
if err != nil {
log.Entry().WithError(err).Warnf("failed to determine classpath using Maven: %v", err)
}
return readAllClasspathFiles(file), nil
}
func generateMavenFortifyDefines(config *fortifyExecuteScanOptions, file string) []string {
defines := []string{
fmt.Sprintf("-Dmdep.outputFile=%v", file),
// Parameter to indicate to maven build that the fortify step is the trigger, can be used for optimizations
"-Dfortify",
"-DincludeScope=compile",
"-DskipTests",
"-Dmaven.javadoc.skip=true",
"--fail-at-end"}
if len(config.BuildDescriptorExcludeList) > 0 {
// From the documentation, these are file paths to a module's pom.xml.
// For MTA projects, we support pom.xml files here and skip others.
for _, exclude := range config.BuildDescriptorExcludeList {
if !strings.HasSuffix(exclude, "pom.xml") {
continue
}
exists, _ := piperutils.FileExists(exclude)
if !exists {
continue
}
moduleName := filepath.Dir(exclude)
if moduleName != "" {
defines = append(defines, "-pl", "!"+moduleName)
}
}
}
return defines
}
// readAllClasspathFiles tests whether the passed file is an absolute path. If not, it will glob for
// all files under the current directory with the given file name and concatenate their contents.
// Otherwise it will return the contents pointed to by the absolute path.
func readAllClasspathFiles(file string) string {
var paths []string
if filepath.IsAbs(file) {
paths = []string{file}
} else {
paths, _ = doublestar.Glob(filepath.Join("**", file))
log.Entry().Debugf("Concatenating the class paths from %v", paths)
}
var contents string
const separator = ":"
for _, path := range paths {
contents += separator + readClasspathFile(path)
}
return removeDuplicates(contents, separator)
}
func readClasspathFile(file string) string {
data, err := ioutil.ReadFile(file)
if err != nil {
log.Entry().WithError(err).Warnf("failed to read classpath from file '%v'", file)
}
result := strings.TrimSpace(string(data))
if len(result) == 0 {
log.Entry().Warnf("classpath from file '%v' was empty", file)
}
return result
}
func removeDuplicates(contents, separator string) string {
if separator == "" || contents == "" {
return contents
}
entries := strings.Split(contents, separator)
entrySet := map[string]struct{}{}
contents = ""
for _, entry := range entries {
if entry == "" {
continue
}
_, contained := entrySet[entry]
if !contained {
entrySet[entry] = struct{}{}
contents += entry + separator
}
}
if contents != "" {
// Remove trailing "separator"
contents = contents[:len(contents)-len(separator)]
}
return contents
}
func triggerFortifyScan(config fortifyExecuteScanOptions, utils fortifyUtils, buildID, buildLabel, buildProject string) error {
var err error = nil
// Do special Python related prep
pipVersion := "pip3"
if config.PythonVersion != "python3" {
pipVersion = "pip2"
}
classpath := ""
if config.BuildTool == "maven" {
if config.AutodetectClasspath {
classpath, err = autoresolveMavenClasspath(config, classpathFileName, utils)
if err != nil {
return err
}
}
config.Translate, err = populateMavenTranslate(&config, classpath)
if err != nil {
log.Entry().WithError(err).Warnf("failed to apply src ('%s') or exclude ('%s') parameter", config.Src, config.Exclude)
}
} else if config.BuildTool == "pip" {
if config.AutodetectClasspath {
separator := getSeparator()
script := fmt.Sprintf("import sys;p=sys.path;p.remove('');print('%v'.join(p))", separator)
classpath, err = autoresolvePipClasspath(config.PythonVersion, []string{"-c", script}, classpathFileName, utils)
if err != nil {
return errors.Wrap(err, "failed to autoresolve pip classpath")
}
}
// install the dev dependencies
if len(config.PythonRequirementsFile) > 0 {
context := map[string]string{}
cmdTemplate := []string{pipVersion, "install", "--user", "-r", config.PythonRequirementsFile}
cmdTemplate = append(cmdTemplate, tokenize(config.PythonRequirementsInstallSuffix)...)
executeTemplatedCommand(utils, cmdTemplate, context)
}
executeTemplatedCommand(utils, tokenize(config.PythonInstallCommand), map[string]string{"Pip": pipVersion})
config.Translate, err = populatePipTranslate(&config, classpath)
if err != nil {
log.Entry().WithError(err).Warnf("failed to apply pythonAdditionalPath ('%s') or src ('%s') parameter", config.PythonAdditionalPath, config.Src)
}
} else {
return fmt.Errorf("buildTool '%s' is not supported by this step", config.BuildTool)
}
err = translateProject(&config, utils, buildID, classpath)
if err != nil {
return err
}
return scanProject(&config, utils, buildID, buildLabel, buildProject)
}
func populatePipTranslate(config *fortifyExecuteScanOptions, classpath string) (string, error) {
if len(config.Translate) > 0 {
return config.Translate, nil
}
var translateList []map[string]interface{}
translateList = append(translateList, make(map[string]interface{}))
separator := getSeparator()
translateList[0]["pythonPath"] = classpath + separator +
getSuppliedOrDefaultListAsString(config.PythonAdditionalPath, []string{}, separator)
translateList[0]["src"] = getSuppliedOrDefaultListAsString(
config.Src, []string{"./**/*"}, ":")
translateList[0]["exclude"] = getSuppliedOrDefaultListAsString(
config.Exclude, []string{"./**/tests/**/*", "./**/setup.py"}, separator)
translateJSON, err := json.Marshal(translateList)
return string(translateJSON), err
}
func populateMavenTranslate(config *fortifyExecuteScanOptions, classpath string) (string, error) {
if len(config.Translate) > 0 {
return config.Translate, nil
}
var translateList []map[string]interface{}
translateList = append(translateList, make(map[string]interface{}))
translateList[0]["classpath"] = classpath
setTranslateEntryIfNotEmpty(translateList[0], "src", ":", config.Src,
[]string{"**/*.xml", "**/*.html", "**/*.jsp", "**/*.js", "**/src/main/resources/**/*", "**/src/main/java/**/*", "**/target/main/java/**/*", "**/target/main/resources/**/*", "**/target/generated-sources/**/*"})
setTranslateEntryIfNotEmpty(translateList[0], "exclude", getSeparator(), config.Exclude, []string{"**/src/test/**/*"})
translateJSON, err := json.Marshal(translateList)
return string(translateJSON), err
}
func translateProject(config *fortifyExecuteScanOptions, utils fortifyUtils, buildID, classpath string) error {
var translateList []map[string]string
json.Unmarshal([]byte(config.Translate), &translateList)
log.Entry().Debugf("Translating with options: %v", translateList)
for _, translate := range translateList {
if len(classpath) > 0 {
translate["autoClasspath"] = classpath
}
err := handleSingleTranslate(config, utils, buildID, translate)
if err != nil {
return err
}
}
return nil
}
func handleSingleTranslate(config *fortifyExecuteScanOptions, command fortifyUtils, buildID string, t map[string]string) error {
if t != nil {
log.Entry().Debugf("Handling translate config %v", t)
translateOptions := []string{
"-verbose",
"-64",
"-b",
buildID,
}
translateOptions = append(translateOptions, tokenize(config.Memory)...)
translateOptions = appendToOptions(config, translateOptions, t)
log.Entry().Debugf("Running sourceanalyzer translate command with options %v", translateOptions)
err := command.RunExecutable("sourceanalyzer", translateOptions...)
if err != nil {
return errors.Wrapf(err, "failed to execute sourceanalyzer translate command with options %v", translateOptions)
}
} else {
log.Entry().Debug("Skipping translate with nil value")
}
return nil
}
func scanProject(config *fortifyExecuteScanOptions, command fortifyUtils, buildID, buildLabel, buildProject string) error {
var scanOptions = []string{
"-verbose",
"-64",
"-b",
buildID,
"-scan",
}
scanOptions = append(scanOptions, tokenize(config.Memory)...)
if config.QuickScan {
scanOptions = append(scanOptions, "-quick")
}
if len(config.AdditionalScanParameters) > 0 {
for _, scanParameter := range config.AdditionalScanParameters {
scanOptions = append(scanOptions, scanParameter)
}
}
if len(buildLabel) > 0 {
scanOptions = append(scanOptions, "-build-label", buildLabel)
}
if len(buildProject) > 0 {
scanOptions = append(scanOptions, "-build-project", buildProject)
}
scanOptions = append(scanOptions, "-logfile", "target/fortify-scan.log", "-f", "target/result.fpr")
err := command.RunExecutable("sourceanalyzer", scanOptions...)
if err != nil {
return errors.Wrapf(err, "failed to execute sourceanalyzer scan command with scanOptions %v", scanOptions)
}
return nil
}
func determinePullRequestMerge(config fortifyExecuteScanOptions) (string, string) {
author := ""
//TODO provide parameter for trusted certs
ctx, client, err := piperGithub.NewClient(config.GithubToken, config.GithubAPIURL, "", []string{})
if err == nil && ctx != nil && client != nil {
prID, author, err := determinePullRequestMergeGithub(ctx, config, client.PullRequests)
if err != nil {
log.Entry().WithError(err).Warn("Failed to get PR metadata via GitHub client")
} else {
return prID, author
}
} else {
log.Entry().WithError(err).Warn("Failed to instantiate GitHub client to get PR metadata")
}
log.Entry().Infof("Trying to determine PR ID in commit message: %v", config.CommitMessage)
r, _ := regexp.Compile(config.PullRequestMessageRegex)
matches := r.FindSubmatch([]byte(config.CommitMessage))
if matches != nil && len(matches) > 1 {
return string(matches[config.PullRequestMessageRegexGroup]), author
}
return "0", ""
}
func determinePullRequestMergeGithub(ctx context.Context, config fortifyExecuteScanOptions, pullRequestServiceInstance pullRequestService) (string, string, error) {
number := "0"
author := ""
options := github.PullRequestListOptions{State: "closed", Sort: "updated", Direction: "desc"}
prList, _, err := pullRequestServiceInstance.ListPullRequestsWithCommit(ctx, config.Owner, config.Repository, config.CommitID, &options)
if err == nil && prList != nil && len(prList) > 0 {
number = fmt.Sprintf("%v", prList[0].GetNumber())
if prList[0].GetUser() != nil {
author = prList[0].GetUser().GetLogin()
}
return number, author, nil
} else {
log.Entry().Infof("Unable to resolve PR via commit ID: %v", config.CommitID)
}