internal/codescan/scope.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/codescan/scope.go

223 lines · 6918 bytes

11 symbols in this file
  1package codescan
  2
  3import (
  4	"bufio"
  5	"bytes"
  6	"path"
  7	"slices"
  8	"strings"
  9
 10	"gitbay.org/gitbay/internal/ci"
 11	"gitbay.org/gitbay/internal/store"
 12)
 13
 14// Scope is what a repository sets aside from what its scan reports.
 15type Scope struct {
 16	// Ignore are path globs, as CI paths take them (security-ignore).
 17	Ignore []string
 18	// Vendored are the .gitattributes patterns Vendored returns.
 19	Vendored []string
 20	// ExcludeRules are rule ids or families (security-exclude-rule).
 21	ExcludeRules []string
 22	// Uses reports whether the scanned commit depends on any of packages,
 23	// written as library lists them. Nil uses everything.
 24	Uses func(packages []string) bool
 25	// Read returns a file at the scanned commit, for rules whose hits are
 26	// checked against the source. Nil checks nothing.
 27	Read func(path string) ([]byte, error)
 28	// Paths are the files at the scanned commit, for rules whose hits are
 29	// checked against the rest of the repository. Nil checks nothing.
 30	Paths []string
 31}
 32
 33// maxPythonFiles bounds how many Python files a scope reads for the names
 34// they define.
 35const maxPythonFiles = 2000
 36
 37// Aside counts the findings a scope set aside: Ignored by path or rule,
 38// Unused by the library a rule is about, Quoted by reading the template an
 39// unquoted-attribute hit is in, Unsplit by reading the script an
 40// unquoted-expansion hit is in, Joined by reading the Python file a
 41// string-concat-in-list hit is in, NoReturn by reading the line a return
 42// hit is on, Attributes by reading what the repository defines an
 43// is_ name as, InTests by the path of an insecure-random hit.
 44type Aside struct {
 45	Ignored    int            `json:"ignored,omitempty"`
 46	Unused     map[string]int `json:"unused,omitempty"`
 47	Quoted     int            `json:"quoted,omitempty"`
 48	Unsplit    int            `json:"unsplit,omitempty"`
 49	Joined     int            `json:"joined,omitempty"`
 50	NoReturn   int            `json:"no_return,omitempty"`
 51	Attributes int            `json:"attributes,omitempty"`
 52	InTests    int            `json:"in_tests,omitempty"`
 53}
 54
 55// Any reports whether anything was set aside.
 56func (a Aside) Any() bool {
 57	return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 || a.Unsplit > 0 || a.Joined > 0 ||
 58		a.NoReturn > 0 || a.Attributes > 0 || a.InTests > 0
 59}
 60
 61// Apply splits findings into those reported, at most MaxFindings of them,
 62// and counts of those set aside. It reports whether reported ones were
 63// dropped for the cap.
 64func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding, Aside, bool) {
 65	var kept []store.SecurityFinding
 66	var aside Aside
 67	truncated := false
 68	unquoted, unsplit, joined := map[string]map[int]bool{}, map[string]map[int]bool{}, map[string]map[int]bool{}
 69	returns := map[string]map[int]bool{}
 70	var names *pyNames
 71	for _, f := range findings {
 72		if s.ignored(f) {
 73			aside.Ignored++
 74			continue
 75		}
 76		if l, ok := libraryFor(f.Rule); ok && s.Uses != nil && !s.Uses(l.packages) {
 77			if aside.Unused == nil {
 78				aside.Unused = map[string]int{}
 79			}
 80			aside.Unused[l.name()]++
 81			continue
 82		}
 83		if ruleIn(f.Rule, unquotedAttrRule) && !s.onLine(f, unquoted, unquotedLines) {
 84			aside.Quoted++
 85			continue
 86		}
 87		if ruleIn(f.Rule, unquotedExpansionRule) && !s.onLine(f, unsplit, splitLines) {
 88			aside.Unsplit++
 89			continue
 90		}
 91		if ruleIn(f.Rule, joinedStringRule) && !s.onLine(f, joined, keepJoined) {
 92			aside.Joined++
 93			continue
 94		}
 95		if slices.ContainsFunc(returnRules, func(r string) bool { return ruleIn(f.Rule, r) }) && !s.onLine(f, returns, returnLines) {
 96			aside.NoReturn++
 97			continue
 98		}
 99		if ruleIn(f.Rule, attrCallRule) && s.attribute(f, &names) {
100			aside.Attributes++
101			continue
102		}
103		if ruleIn(f.Rule, insecureRandomRule) && testPath(f.Path) {
104			aside.InTests++
105			continue
106		}
107		if len(kept) == MaxFindings {
108			truncated = true
109			continue
110		}
111		kept = append(kept, f)
112	}
113	return kept, aside, truncated
114}
115
116// onLine reports whether a hit is on a line that lines, reading the file,
117// marks, or the file cannot be read to say. Files are read once, into seen.
118func (s Scope) onLine(f store.SecurityFinding, seen map[string]map[int]bool, lines func([]byte) (map[int]bool, bool)) bool {
119	if s.Read == nil || f.Path == "" || f.Line == 0 {
120		return true
121	}
122	marked, read := seen[f.Path]
123	if !read {
124		if src, err := s.Read(f.Path); err == nil {
125			if l, ok := lines(src); ok {
126				marked = l
127			}
128		}
129		seen[f.Path] = marked
130	}
131	return marked == nil || marked[f.Line]
132}
133
134// attribute reports whether an is-function-without-parentheses hit names
135// something the repository's Python files define as an attribute and never
136// as a method. The files are read on the first such hit, into names.
137func (s Scope) attribute(f store.SecurityFinding, names **pyNames) bool {
138	m := attrCallName.FindStringSubmatch(f.Message)
139	if m == nil || s.Read == nil || s.Paths == nil {
140		return false
141	}
142	if *names == nil {
143		n := pyNames{methods: map[string]bool{}, attrs: map[string]bool{}}
144		read := 0
145		for _, p := range s.Paths {
146			if !strings.HasSuffix(p, ".py") || otherProject(p) {
147				continue
148			}
149			if read == maxPythonFiles {
150				break
151			}
152			read++
153			if src, err := s.Read(p); err == nil {
154				n.add(src)
155			}
156		}
157		*names = &n
158	}
159	return (*names).attribute(m[1])
160}
161
162// otherProject reports whether a path is inside a directory of other
163// projects' code or an environment.
164func otherProject(p string) bool {
165	for _, part := range strings.Split(path.Dir(p), "/") {
166		switch part {
167		case "node_modules", "vendor", "third_party", "site-packages", ".venv", "venv":
168			return true
169		}
170	}
171	return false
172}
173
174func (s Scope) ignored(f store.SecurityFinding) bool {
175	for _, g := range s.Ignore {
176		if ci.Match(g, f.Path) {
177			return true
178		}
179	}
180	for _, p := range s.Vendored {
181		if attrMatch(p, f.Path) {
182			return true
183		}
184	}
185	for _, r := range s.ExcludeRules {
186		if ruleIn(f.Rule, r) {
187			return true
188		}
189	}
190	return false
191}
192
193// Vendored returns the patterns a .gitattributes file marks
194// linguist-vendored or linguist-generated. Unset and false values are left
195// out.
196func Vendored(gitattributes []byte) []string {
197	var out []string
198	sc := bufio.NewScanner(bytes.NewReader(gitattributes))
199	for sc.Scan() {
200		fields := strings.Fields(sc.Text())
201		if len(fields) < 2 || strings.HasPrefix(fields[0], "#") {
202			continue
203		}
204		for _, a := range fields[1:] {
205			if a == "linguist-vendored" || a == "linguist-generated" || a == "linguist-vendored=true" || a == "linguist-generated=true" {
206				out = append(out, fields[0])
207				break
208			}
209		}
210	}
211	return out
212}
213
214// attrMatch matches a path the way git matches a .gitattributes pattern: one
215// without a slash names files by base name at any depth, one with a slash is
216// relative to the top.
217func attrMatch(pattern, file string) bool {
218	if !strings.Contains(pattern, "/") {
219		ok, err := path.Match(pattern, path.Base(file))
220		return err == nil && ok
221	}
222	return ci.Match(strings.TrimPrefix(pattern, "/"), file)
223}