internal/codescan/codescan_test.go
145 lines · 5767 bytes
1package codescan
2
3import (
4 "gitbay.org/gitbay/internal/store"
5 "strconv"
6 "strings"
7 "testing"
8)
9
10func TestParse(t *testing.T) {
11 raw := []byte(`{"version":"2.1.0","runs":[
12 {"tool":{"driver":{"name":"opengrep"}},"results":[
13 {"ruleId":"r1","message":{"text":"first\nline"},
14 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"file:///workspace/a/b.go"},"region":{"startLine":3}}}]},
15 {"ruleId":"r1","message":{"text":"first\nline"},
16 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"./a/b.go"},"region":{"startLine":3}}}]},
17 {"ruleId":"r2","level":"note","message":{"text":"second"},
18 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"a/a.go"},"region":{"startLine":9}}}]}
19 ]},
20 {"tool":{"driver":{"name":"other"}},"results":[{"ruleId":"x","level":"bogus","message":{"text":"no location"}}]}
21 ]}`)
22 got, truncated, err := Parse(raw)
23 if err != nil || truncated {
24 t.Fatalf("Parse: %v %v", err, truncated)
25 }
26 if len(got) != 3 {
27 t.Fatalf("findings = %+v", got)
28 }
29 // Sorted by path; the duplicate under two URI spellings folded; the
30 // default level applied; whitespace collapsed.
31 if got[0].Path != "" || got[0].Level != "warning" || got[0].Tool != "other" {
32 t.Errorf("got[0] = %+v", got[0])
33 }
34 if got[1].Path != "a/a.go" || got[1].Level != "note" {
35 t.Errorf("got[1] = %+v", got[1])
36 }
37 if got[2].Path != "a/b.go" || got[2].Line != 3 || got[2].Message != "first line" || got[2].Level != "warning" {
38 t.Errorf("got[2] = %+v", got[2])
39 }
40 if _, _, err := Parse([]byte(`{"nope":1}`)); err == nil {
41 t.Error("a document without runs parsed")
42 }
43}
44
45func TestParseTruncates(t *testing.T) {
46 var b strings.Builder
47 b.WriteString(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[`)
48 for i := 0; i < maxResults+5; i++ {
49 if i > 0 {
50 b.WriteString(",")
51 }
52 b.WriteString(`{"ruleId":"r","message":{"text":"m` + strings.Repeat("x", i%7) + itoa(i) + `"}}`)
53 }
54 b.WriteString(`]}]}`)
55 got, truncated, err := Parse([]byte(b.String()))
56 if err != nil || !truncated || len(got) != maxResults {
57 t.Fatalf("len %d truncated %v err %v", len(got), truncated, err)
58 }
59}
60
61func itoa(i int) string { return strconv.Itoa(i) }
62
63// A finding that moves is the same finding.
64func TestSameIgnoresLines(t *testing.T) {
65 a, _, _ := Parse([]byte(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[{"ruleId":"r","message":{"text":"m"},
66 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"x.go"},"region":{"startLine":1}}}]}]}]}`))
67 b, _, _ := Parse([]byte(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[{"ruleId":"r","message":{"text":"m"},
68 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"x.go"},"region":{"startLine":40}}}]}]}]}`))
69 if !Same(ByFingerprint(a), ByFingerprint(b)) {
70 t.Error("a moved finding counted as a change")
71 }
72}
73
74// sarifOf builds a one-run document from results given as JSON objects.
75func sarifOf(results ...string) []byte {
76 return []byte(`{"runs":[{"tool":{"driver":{"name":"t"}},"results":[` + strings.Join(results, ",") + `]}]}`)
77}
78
79func result(line int, snippet, extra string) string {
80 region := `"startLine":` + itoa(line)
81 if snippet != "" {
82 region += `,"snippet":{"text":` + strconv.Quote(snippet) + `}`
83 }
84 if extra != "" {
85 extra = "," + extra
86 }
87 return `{"ruleId":"r","message":{"text":"m"},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"x.go"},"region":{` +
88 region + `}}}]` + extra + `}`
89}
90
91func fingerprints(t *testing.T, raw []byte) []string {
92 t.Helper()
93 got, _, err := Parse(raw)
94 if err != nil {
95 t.Fatal(err)
96 }
97 var out []string
98 for _, f := range got {
99 out = append(out, f.Fingerprint)
100 }
101 return out
102}
103
104// Hits of one rule in one file are separate findings, and the first keeps
105// the fingerprint a scan without snippets always gave it.
106func TestParseKeepsAlikeHits(t *testing.T) {
107 fps := fingerprints(t, sarifOf(result(3, "", ""), result(9, "", "")))
108 if len(fps) != 2 || fps[0] == fps[1] {
109 t.Fatalf("fingerprints = %v", fps)
110 }
111 if want := fingerprint(hit{f: store.SecurityFinding{Tool: "t", Rule: "r", Path: "x.go", Message: "m"}}, map[string]int{}); fps[0] != want {
112 t.Errorf("first hit = %s, want %s", fps[0], want)
113 }
114 // Moved, they are still the same two.
115 if moved := fingerprints(t, sarifOf(result(13, "", ""), result(19, "", ""))); strings.Join(moved, " ") != strings.Join(fps, " ") {
116 t.Errorf("moved = %v, was %v", moved, fps)
117 }
118}
119
120// With the matched code, a new hit above others leaves theirs alone, and
121// reindenting the code changes nothing.
122func TestParseSnippetsSurviveInsertion(t *testing.T) {
123 before := fingerprints(t, sarifOf(result(3, "a()", ""), result(9, "b(x, y)", "")))
124 after := fingerprints(t, sarifOf(result(1, "c()", ""), result(4, "a()", ""), result(10, "\t b(x,\n y)", "")))
125 if len(after) != 3 || after[1] != before[0] || after[2] != before[1] {
126 t.Errorf("before %v after %v", before, after)
127 }
128}
129
130// The tool's own fingerprints are used when every result has a distinct
131// one, and ignored when they are placeholders or shared.
132func TestParseOwnFingerprints(t *testing.T) {
133 own := func(v string) string { return `"fingerprints":{"matchBasedId/v1":"` + v + `"}` }
134 a := fingerprints(t, sarifOf(result(3, "", own("aaa")), result(9, "", own("bbb"))))
135 b := fingerprints(t, sarifOf(result(30, "", own("aaa")), result(1, "", own("bbb"))))
136 if len(a) != 2 || a[0] != b[1] || a[1] != b[0] {
137 t.Errorf("own fingerprints not followed: %v %v", a, b)
138 }
139 plain := fingerprints(t, sarifOf(result(3, "", ""), result(9, "", "")))
140 for _, v := range []string{"requires login", "same"} {
141 if got := fingerprints(t, sarifOf(result(3, "", own(v)), result(9, "", own(v)))); strings.Join(got, " ") != strings.Join(plain, " ") {
142 t.Errorf("%q: got %v, want the fallback %v", v, got, plain)
143 }
144 }
145}