internal/codescan/codescan.go

366 lines · 10722 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	"strconv"
 16	"strings"
 17
 18	"gitbay.org/gitbay/internal/store"
 19)
 20
 21// IssueTitle is fixed so the issue is recognizable across scans.
 22const IssueTitle = "Code scanning findings"
 23
 24// MaxUpload bounds one upload, maxResults what is read from it, and
 25// MaxFindings what is reported of that once a Scope has set some aside.
 26const (
 27	MaxUpload   = 8 << 20
 28	maxResults  = 10 * MaxFindings
 29	MaxFindings = 500
 30)
 31
 32type sarif struct {
 33	Runs []struct {
 34		Tool struct {
 35			Driver struct {
 36				Name string `json:"name"`
 37			} `json:"driver"`
 38		} `json:"tool"`
 39		Results []struct {
 40			RuleID  string `json:"ruleId"`
 41			Level   string `json:"level"`
 42			Message struct {
 43				Text string `json:"text"`
 44			} `json:"message"`
 45			Locations []struct {
 46				PhysicalLocation struct {
 47					ArtifactLocation struct {
 48						URI string `json:"uri"`
 49					} `json:"artifactLocation"`
 50					Region struct {
 51						StartLine int `json:"startLine"`
 52						Snippet   struct {
 53							Text string `json:"text"`
 54						} `json:"snippet"`
 55					} `json:"region"`
 56				} `json:"physicalLocation"`
 57			} `json:"locations"`
 58			Fingerprints        map[string]string `json:"fingerprints"`
 59			PartialFingerprints map[string]string `json:"partialFingerprints"`
 60		} `json:"results"`
 61	} `json:"runs"`
 62}
 63
 64// Parse returns the findings in a SARIF document, deduplicated by
 65// fingerprint and sorted by path and line. It reports whether results past
 66// maxResults were dropped.
 67func Parse(raw []byte) ([]store.SecurityFinding, bool, error) {
 68	var doc sarif
 69	if err := json.Unmarshal(raw, &doc); err != nil {
 70		return nil, false, fmt.Errorf("not SARIF: %w", err)
 71	}
 72	if doc.Runs == nil {
 73		return nil, false, errors.New("not SARIF: no runs")
 74	}
 75	var hits []hit
 76	for _, run := range doc.Runs {
 77		tool := clean(run.Tool.Driver.Name, 40)
 78		var found []hit
 79		for _, r := range run.Results {
 80			h := hit{f: store.SecurityFinding{Tool: tool, Rule: clean(r.RuleID, 200),
 81				Level: level(r.Level), Message: clean(r.Message.Text, 200)}}
 82			if len(r.Locations) > 0 {
 83				loc := r.Locations[0].PhysicalLocation
 84				h.f.Path = relPath(loc.ArtifactLocation.URI)
 85				h.f.Line = max(loc.Region.StartLine, 0)
 86				h.snippet = strings.Join(strings.Fields(loc.Region.Snippet.Text), " ")
 87			}
 88			h.own = ownFingerprint(r.Fingerprints, r.PartialFingerprints)
 89			found = append(found, h)
 90		}
 91		if !distinct(found) {
 92			for i := range found {
 93				found[i].own = ""
 94			}
 95		}
 96		hits = append(hits, found...)
 97	}
 98	// File order, so hits that look alike are numbered the same way on
 99	// every scan.
100	sort.SliceStable(hits, func(i, j int) bool {
101		if hits[i].f.Path != hits[j].f.Path {
102			return hits[i].f.Path < hits[j].f.Path
103		}
104		return hits[i].f.Line < hits[j].f.Line
105	})
106	seen := map[string]bool{}
107	alike := map[string]int{}
108	var out []store.SecurityFinding
109	truncated := false
110	for _, h := range hits {
111		if seen[h.place()] {
112			continue
113		}
114		seen[h.place()] = true
115		if len(out) >= maxResults {
116			truncated = true
117			break
118		}
119		h.f.Fingerprint = fingerprint(h, alike)
120		out = append(out, h.f)
121	}
122	sort.Slice(out, func(i, j int) bool {
123		if out[i].Path != out[j].Path {
124			return out[i].Path < out[j].Path
125		}
126		if out[i].Line != out[j].Line {
127			return out[i].Line < out[j].Line
128		}
129		return out[i].Fingerprint < out[j].Fingerprint
130	})
131	return out, truncated, nil
132}
133
134// hit is one result before its fingerprint is settled: own is the tool's
135// fingerprint for it, snippet the code it matched, either possibly empty.
136type hit struct {
137	f            store.SecurityFinding
138	own, snippet string
139}
140
141// place is where a result was reported. One reported twice at the same
142// place is one finding.
143func (h hit) place() string {
144	return h.f.Tool + "\x00" + h.f.Rule + "\x00" + h.f.Path + "\x00" + strconv.Itoa(h.f.Line) + "\x00" + h.f.Message
145}
146
147// ownFingerprint picks the tool's fingerprint for a result, preferring the
148// full ones over partial, and the first by name for a stable choice.
149func ownFingerprint(sets ...map[string]string) string {
150	for _, set := range sets {
151		names := make([]string, 0, len(set))
152		for name := range set {
153			names = append(names, name)
154		}
155		sort.Strings(names)
156		for _, name := range names {
157			if v := set[name]; v != "" && !strings.ContainsAny(v, " \t\r\n") && len(v) <= 200 {
158				return name + "=" + v
159			}
160		}
161	}
162	return ""
163}
164
165// distinct reports whether a run's own fingerprints can be trusted: every
166// result has one, and no two places share one. A tool that writes a
167// placeholder or a per-rule constant there falls back to ours.
168func distinct(found []hit) bool {
169	at := map[string]string{}
170	for _, h := range found {
171		if h.own == "" {
172			return false
173		}
174		if p, ok := at[h.own]; ok && p != h.place() {
175			return false
176		}
177		at[h.own] = h.place()
178	}
179	return true
180}
181
182// fingerprint identifies a finding across scans. The line is left out so
183// an edit above it does not make it a new finding. The tool's own
184// fingerprint is used when it gives one. Otherwise the matched code tells
185// apart hits of one rule in one file, and hits that still look alike are
186// numbered in file order, the first keeping the plain form; alike counts
187// them across calls.
188func fingerprint(h hit, alike map[string]int) string {
189	key := h.f.Tool + "\x00" + h.f.Rule + "\x00" + h.f.Path + "\x00"
190	if h.own != "" {
191		key += "own\x00" + h.own
192	} else {
193		key += h.f.Message
194		if h.snippet != "" {
195			key += "\x00" + h.snippet
196		}
197	}
198	n := alike[key]
199	alike[key]++
200	if n > 0 {
201		key += "\x00" + strconv.Itoa(n)
202	}
203	sum := sha256.Sum256([]byte(key))
204	return hex.EncodeToString(sum[:12])
205}
206
207// level is SARIF's result level, which defaults to warning.
208func level(l string) string {
209	switch l {
210	case "error", "warning", "note", "none":
211		return l
212	}
213	return "warning"
214}
215
216// relPath turns an artifact URI into a repository path: tools write
217// `file:///workspace/x.go`, `./x.go` or `x.go` for the same file.
218func relPath(uri string) string {
219	p := uri
220	if u, err := url.Parse(uri); err == nil && u.Scheme == "file" {
221		p = u.Path
222	}
223	p = strings.TrimPrefix(p, "/workspace/")
224	p = strings.TrimPrefix(p, "./")
225	return clean(p, 300)
226}
227
228// clean is one line of at most n bytes of valid UTF-8, since every field
229// lands in an issue body and a mail.
230func clean(s string, n int) string {
231	s = strings.ToValidUTF8(strings.Join(strings.Fields(s), " "), "")
232	if len(s) > n {
233		s = strings.ToValidUTF8(s[:n], "") + "…"
234	}
235	return s
236}
237
238// Same reports whether two sets name the same findings, which decides
239// between leaving the issue alone and rewriting it. Both arrive sorted by
240// fingerprint. A line moving is not a change.
241func Same(a, b []store.SecurityFinding) bool {
242	if len(a) != len(b) {
243		return false
244	}
245	for i := range a {
246		if a[i].Fingerprint != b[i].Fingerprint {
247			return false
248		}
249	}
250	return true
251}
252
253// ByPlace sorts a set by path and line, the way a scan lists it.
254func ByPlace(fs []store.SecurityFinding) []store.SecurityFinding {
255	out := append([]store.SecurityFinding(nil), fs...)
256	sort.SliceStable(out, func(i, j int) bool {
257		if out[i].Path != out[j].Path {
258			return out[i].Path < out[j].Path
259		}
260		return out[i].Line < out[j].Line
261	})
262	return out
263}
264
265// ByFingerprint sorts a set the way the store returns it, for Same.
266func ByFingerprint(fs []store.SecurityFinding) []store.SecurityFinding {
267	out := append([]store.SecurityFinding(nil), fs...)
268	sort.Slice(out, func(i, j int) bool { return out[i].Fingerprint < out[j].Fingerprint })
269	return out
270}
271
272// Report is what the issue says: the findings still open, and how many
273// others were dismissed or set aside.
274type Report struct {
275	Repo, Branch string
276	Open         []store.SecurityFinding
277	Dismissed    int
278	Aside        Aside
279	Truncated    bool
280}
281
282// Body renders the issue: one list per tool, a line per finding with its
283// fingerprint, then what is not listed.
284func Body(r Report) string {
285	var b strings.Builder
286	fmt.Fprintf(&b, "The scheduled code scan of `%s` reported these findings. "+
287		"This issue is kept up to date as that changes, and closed once none are open.\n", r.Branch)
288	byTool := map[string][]store.SecurityFinding{}
289	var tools []string
290	for _, f := range r.Open {
291		if _, ok := byTool[f.Tool]; !ok {
292			tools = append(tools, f.Tool)
293		}
294		byTool[f.Tool] = append(byTool[f.Tool], f)
295	}
296	sort.Strings(tools)
297	for _, tool := range tools {
298		name := tool
299		if name == "" {
300			name = "Unnamed tool"
301		}
302		fmt.Fprintf(&b, "\n### %s\n\n", name)
303		for _, f := range byTool[tool] {
304			fmt.Fprintf(&b, "- `%s:%d` %s (%s): %s `%s`\n", f.Path, f.Line, f.Rule, f.Level, f.Message, Short(f.Fingerprint))
305		}
306	}
307	if r.Truncated {
308		fmt.Fprintf(&b, "\nOnly the first %d findings are listed.\n", MaxFindings)
309	}
310	var notListed []string
311	if r.Dismissed > 0 {
312		notListed = append(notListed, fmt.Sprintf("%d dismissed", r.Dismissed))
313	}
314	if r.Aside.Ignored > 0 {
315		notListed = append(notListed, fmt.Sprintf("%d under paths or rules the repository ignores", r.Aside.Ignored))
316	}
317	if len(r.Aside.Unused) > 0 {
318		notListed = append(notListed, fmt.Sprintf("%d from rules for libraries it does not use (%s)", total(r.Aside.Unused), counts(r.Aside.Unused)))
319	}
320	if r.Aside.Quoted > 0 {
321		notListed = append(notListed, fmt.Sprintf("%d unquoted-attribute hits on attributes the template quotes", r.Aside.Quoted))
322	}
323	if len(notListed) > 0 {
324		fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo)
325	}
326	if len(r.Open) > 0 {
327		fmt.Fprintf(&b, "\nTo dismiss one: `repo security dismiss %s <fingerprint> --reason false-positive|wont-fix|test`.\n", r.Repo)
328	}
329	return b.String()
330}
331
332// Short is the fingerprint as the issue prints it; Dismiss takes it back.
333func Short(fingerprint string) string {
334	return fingerprint[:min(len(fingerprint), ShortLen)]
335}
336
337// ShortLen is how much of a fingerprint is printed and the least that
338// names one.
339const ShortLen = 10
340
341func total(m map[string]int) int {
342	n := 0
343	for _, v := range m {
344		n += v
345	}
346	return n
347}
348
349// counts lists a map's keys with their counts, most first.
350func counts(m map[string]int) string {
351	keys := make([]string, 0, len(m))
352	for k := range m {
353		keys = append(keys, k)
354	}
355	sort.Slice(keys, func(i, j int) bool {
356		if m[keys[i]] != m[keys[j]] {
357			return m[keys[i]] > m[keys[j]]
358		}
359		return keys[i] < keys[j]
360	})
361	parts := make([]string, len(keys))
362	for i, k := range keys {
363		parts[i] = fmt.Sprintf("%s %d", k, m[k])
364	}
365	return strings.Join(parts, ", ")
366}