internal/codescan/codescan.go

192 lines · 5476 bytes

  1// Package codescan reads the SARIF a security build uploads and renders
  2// the issue that reports it. Only the parts of SARIF 2.1.0 a finding needs
  3// are read: the tool's name, and each result's rule, level, message and
  4// first location.
  5package codescan
  6
  7import (
  8	"crypto/sha256"
  9	"encoding/hex"
 10	"encoding/json"
 11	"errors"
 12	"fmt"
 13	"net/url"
 14	"sort"
 15	"strings"
 16
 17	"gitbay.org/gitbay/internal/store"
 18)
 19
 20// IssueTitle is fixed so the issue is recognizable across scans.
 21const IssueTitle = "Code scanning findings"
 22
 23// MaxUpload bounds one upload. MaxFindings bounds what is kept from it.
 24const (
 25	MaxUpload   = 8 << 20
 26	MaxFindings = 500
 27)
 28
 29type sarif struct {
 30	Runs []struct {
 31		Tool struct {
 32			Driver struct {
 33				Name string `json:"name"`
 34			} `json:"driver"`
 35		} `json:"tool"`
 36		Results []struct {
 37			RuleID  string `json:"ruleId"`
 38			Level   string `json:"level"`
 39			Message struct {
 40				Text string `json:"text"`
 41			} `json:"message"`
 42			Locations []struct {
 43				PhysicalLocation struct {
 44					ArtifactLocation struct {
 45						URI string `json:"uri"`
 46					} `json:"artifactLocation"`
 47					Region struct {
 48						StartLine int `json:"startLine"`
 49					} `json:"region"`
 50				} `json:"physicalLocation"`
 51			} `json:"locations"`
 52		} `json:"results"`
 53	} `json:"runs"`
 54}
 55
 56// Parse returns the findings in a SARIF document, deduplicated by
 57// fingerprint and sorted by path and line. It reports whether results past
 58// MaxFindings were dropped.
 59func Parse(raw []byte) ([]store.SecurityFinding, bool, error) {
 60	var doc sarif
 61	if err := json.Unmarshal(raw, &doc); err != nil {
 62		return nil, false, fmt.Errorf("not SARIF: %w", err)
 63	}
 64	if doc.Runs == nil {
 65		return nil, false, errors.New("not SARIF: no runs")
 66	}
 67	seen := map[string]bool{}
 68	var out []store.SecurityFinding
 69	truncated := false
 70	for _, run := range doc.Runs {
 71		tool := clean(run.Tool.Driver.Name, 40)
 72		for _, r := range run.Results {
 73			if len(out) >= MaxFindings {
 74				truncated = true
 75				break
 76			}
 77			f := store.SecurityFinding{Tool: tool, Rule: clean(r.RuleID, 200),
 78				Level: level(r.Level), Message: clean(r.Message.Text, 200)}
 79			if len(r.Locations) > 0 {
 80				loc := r.Locations[0].PhysicalLocation
 81				f.Path = relPath(loc.ArtifactLocation.URI)
 82				f.Line = max(loc.Region.StartLine, 0)
 83			}
 84			f.Fingerprint = fingerprint(f)
 85			if seen[f.Fingerprint] {
 86				continue
 87			}
 88			seen[f.Fingerprint] = true
 89			out = append(out, f)
 90		}
 91	}
 92	sort.Slice(out, func(i, j int) bool {
 93		if out[i].Path != out[j].Path {
 94			return out[i].Path < out[j].Path
 95		}
 96		if out[i].Line != out[j].Line {
 97			return out[i].Line < out[j].Line
 98		}
 99		return out[i].Fingerprint < out[j].Fingerprint
100	})
101	return out, truncated, nil
102}
103
104// fingerprint identifies a finding across scans. The line is left out so
105// an edit above it does not make it a new finding.
106func fingerprint(f store.SecurityFinding) string {
107	sum := sha256.Sum256([]byte(f.Tool + "\x00" + f.Rule + "\x00" + f.Path + "\x00" + f.Message))
108	return hex.EncodeToString(sum[:12])
109}
110
111// level is SARIF's result level, which defaults to warning.
112func level(l string) string {
113	switch l {
114	case "error", "warning", "note", "none":
115		return l
116	}
117	return "warning"
118}
119
120// relPath turns an artifact URI into a repository path: tools write
121// `file:///workspace/x.go`, `./x.go` or `x.go` for the same file.
122func relPath(uri string) string {
123	p := uri
124	if u, err := url.Parse(uri); err == nil && u.Scheme == "file" {
125		p = u.Path
126	}
127	p = strings.TrimPrefix(p, "/workspace/")
128	p = strings.TrimPrefix(p, "./")
129	return clean(p, 300)
130}
131
132// clean is one line of at most n bytes of valid UTF-8, since every field
133// lands in an issue body and a mail.
134func clean(s string, n int) string {
135	s = strings.ToValidUTF8(strings.Join(strings.Fields(s), " "), "")
136	if len(s) > n {
137		s = strings.ToValidUTF8(s[:n], "") + "…"
138	}
139	return s
140}
141
142// Same reports whether two sets name the same findings, which decides
143// between leaving the issue alone and rewriting it. Both arrive sorted by
144// fingerprint. A line moving is not a change.
145func Same(a, b []store.SecurityFinding) bool {
146	if len(a) != len(b) {
147		return false
148	}
149	for i := range a {
150		if a[i].Fingerprint != b[i].Fingerprint {
151			return false
152		}
153	}
154	return true
155}
156
157// ByFingerprint sorts a set the way the store returns it, for Same.
158func ByFingerprint(fs []store.SecurityFinding) []store.SecurityFinding {
159	out := append([]store.SecurityFinding(nil), fs...)
160	sort.Slice(out, func(i, j int) bool { return out[i].Fingerprint < out[j].Fingerprint })
161	return out
162}
163
164// Body renders the issue: one list per tool, a line per finding.
165func Body(branch string, findings []store.SecurityFinding, truncated bool) string {
166	var b strings.Builder
167	fmt.Fprintf(&b, "The scheduled code scan of `%s` reported these findings. "+
168		"This issue is kept up to date as that changes, and closed once a scan reports none.\n", branch)
169	byTool := map[string][]store.SecurityFinding{}
170	var tools []string
171	for _, f := range findings {
172		if _, ok := byTool[f.Tool]; !ok {
173			tools = append(tools, f.Tool)
174		}
175		byTool[f.Tool] = append(byTool[f.Tool], f)
176	}
177	sort.Strings(tools)
178	for _, tool := range tools {
179		name := tool
180		if name == "" {
181			name = "Unnamed tool"
182		}
183		fmt.Fprintf(&b, "\n### %s\n\n", name)
184		for _, f := range byTool[tool] {
185			fmt.Fprintf(&b, "- `%s:%d` %s (%s): %s\n", f.Path, f.Line, f.Rule, f.Level, f.Message)
186		}
187	}
188	if truncated {
189		fmt.Fprintf(&b, "\nOnly the first %d results are listed.\n", MaxFindings)
190	}
191	return b.String()
192}