From 6c57ae1628c42ebf2de515fd3f079477e0dc4f21 Mon Sep 17 00:00:00 2001 From: Dmitry Salakhov Date: Fri, 5 Feb 2021 09:06:04 +0000 Subject: [PATCH] Fix sarif formatting issues (#565) * include tool version * change declared safix shema version * dedup rules, fix result locations * refactor rules collection creation --- output/formatter.go | 29 +++++++++++++++++++++-------- output/sarif_format.go | 6 ++++-- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/output/formatter.go b/output/formatter.go index 850de9a..8aa55e8 100644 --- a/output/formatter.go +++ b/output/formatter.go @@ -180,27 +180,39 @@ func convertToSonarIssues(rootPaths []string, data *reportInfo) (*sonarIssues, e func convertToSarifReport(rootPaths []string, data *reportInfo) (*sarifReport, error) { sr := buildSarifReport() - var rules []*sarifRule - var locations []*sarifLocation + type rule struct { + index int + rule *sarifRule + } + + rules := make([]*sarifRule, 0) + rulesIndices := make(map[string]rule) + lastRuleIndex := -1 + results := []*sarifResult{} - for index, issue := range data.Issues { - rules = append(rules, buildSarifRule(issue)) + for _, issue := range data.Issues { + r, ok := rulesIndices[issue.RuleID] + if !ok { + lastRuleIndex++ + r = rule{index: lastRuleIndex, rule: buildSarifRule(issue)} + rulesIndices[issue.RuleID] = r + rules = append(rules, r.rule) + } location, err := buildSarifLocation(issue, rootPaths) if err != nil { return nil, err } - locations = append(locations, location) result := &sarifResult{ - RuleID: fmt.Sprintf("%s (CWE-%s)", issue.RuleID, issue.Cwe.ID), - RuleIndex: index, + RuleID: r.rule.ID, + RuleIndex: r.index, Level: getSarifLevel(issue.Severity.String()), Message: &sarifMessage{ Text: issue.What, }, - Locations: locations, + Locations: []*sarifLocation{location}, } results = append(results, result) @@ -209,6 +221,7 @@ func convertToSarifReport(rootPaths []string, data *reportInfo) (*sarifReport, e tool := &sarifTool{ Driver: &sarifDriver{ Name: "gosec", + Version: "2.1.0", InformationURI: "https://github.com/securego/gosec/", Rules: rules, }, diff --git a/output/sarif_format.go b/output/sarif_format.go index 393a27e..16624be 100644 --- a/output/sarif_format.go +++ b/output/sarif_format.go @@ -2,9 +2,10 @@ package output import ( "fmt" - "github.com/securego/gosec/v2" "strconv" "strings" + + "github.com/securego/gosec/v2" ) type sarifLevel string @@ -68,6 +69,7 @@ type sarifResult struct { type sarifDriver struct { Name string `json:"name"` + Version string `json:"version"` InformationURI string `json:"informationUri"` Rules []*sarifRule `json:"rules,omitempty"` } @@ -91,7 +93,7 @@ type sarifReport struct { func buildSarifReport() *sarifReport { return &sarifReport{ Version: "2.1.0", - Schema: "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.4.json", + Schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json", Runs: []*sarifRun{}, } }