internal/control/security_test.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/control/security_test.go

362 lines · 15040 bytes

8 symbols in this file
  1package control
  2
  3import (
  4	"encoding/json"
  5	"os"
  6	"os/exec"
  7	"path/filepath"
  8	"strings"
  9	"testing"
 10	"time"
 11
 12	"gitbay.org/gitbay/internal/ci"
 13	"gitbay.org/gitbay/internal/codescan"
 14	"gitbay.org/gitbay/internal/config"
 15	"gitbay.org/gitbay/internal/protocol"
 16	"gitbay.org/gitbay/internal/store"
 17)
 18
 19const testSARIF = `{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"opengrep"}},"results":[
 20	{"ruleId":"go.lang.security.audit.sqli","level":"error","message":{"text":"SQL built from input"},
 21	 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"store/q.go"},"region":{"startLine":12}}}]}]}]}`
 22
 23// The whole round trip without a runner process: enable, queue, claim,
 24// upload, and the issue that results in.
 25func TestSecurityScanRoundTrip(t *testing.T) {
 26	st, repo, u, root := browseFixture(t)
 27	p := repo.Path()
 28	sec := config.Default().Security
 29	sec.Image = "localhost/gitbay-security:1"
 30
 31	c, out := runnerCtx(st, u.ID, root)
 32	if code := runSecurityEnable(c, []string{p}); code != protocol.ExitFailure || !strings.Contains(out.String(), "no code scanning image") {
 33		t.Fatalf("enable without an image: exit %d %s", code, out)
 34	}
 35	run := func(f func(*Ctx, []string) int, stdin string, args ...string) (int, string) {
 36		t.Helper()
 37		c, out := runnerCtx(st, u.ID, root)
 38		c.Cfg.Security = sec
 39		c.Cfg.Mail.SMTPHost = "localhost:587"
 40		c.Stdin = strings.NewReader(stdin)
 41		c.JSON = true
 42		return f(c, args), out.String()
 43	}
 44	if code, out := run(runSecurityEnable, "", p); code != protocol.ExitOK {
 45		t.Fatalf("enable: %d %s", code, out)
 46	}
 47	if code, out := run(runSecurityRun, "", p); code != protocol.ExitOK {
 48		t.Fatalf("run: %d %s", code, out)
 49	}
 50	if code, out := run(runSecurityRun, "", p); code == protocol.ExitOK || !strings.Contains(out, "already pending") {
 51		t.Fatalf("second run: %d %s", code, out)
 52	}
 53
 54	st.SetBuildSecret(repo.ID, "DEPLOY_TOKEN", "s3cret")
 55	code, claim := run(runRunnerNext, "")
 56	if code != protocol.ExitOK || !strings.Contains(claim, `"job":"`+ci.SecurityJob+`"`) || !strings.Contains(claim, `"results":true`) {
 57		t.Fatalf("claim: %d %s", code, claim)
 58	}
 59	if strings.Contains(claim, "s3cret") {
 60		t.Fatalf("the scan was handed the repository's secrets: %s", claim)
 61	}
 62	var claimed struct {
 63		Data struct {
 64			ID  int64  `json:"id"`
 65			SHA string `json:"sha"`
 66		} `json:"data"`
 67	}
 68	json.Unmarshal([]byte(claim), &claimed)
 69	id := claimed.Data.ID
 70
 71	if code, out := run(runRunnerResults, testSARIF, itoa(id)); code != protocol.ExitOK {
 72		t.Fatalf("results: %d %s", code, out)
 73	}
 74	scan, _ := st.SecurityScanFor(repo.ID)
 75	if scan.IssueNumber == 0 || scan.LastResults == "" {
 76		t.Fatalf("scan = %+v", scan)
 77	}
 78	issue, _ := st.IssueByNumber(repo.ID, scan.IssueNumber)
 79	if issue.Title != codescan.IssueTitle || !strings.Contains(issue.Body, "`store/q.go:12` go.lang.security.audit.sqli (error)") {
 80		t.Errorf("issue %q:\n%s", issue.Title, issue.Body)
 81	}
 82	if code, out := run(runRunnerDone, "", itoa(id), "success"); code != protocol.ExitOK {
 83		t.Fatalf("done: %d %s", code, out)
 84	}
 85	if statuses, _ := st.CommitStatusesFor(repo.ID, []string{claimed.Data.SHA}); len(statuses[claimed.Data.SHA]) != 0 {
 86		t.Errorf("the scan set a commit status: %+v", statuses)
 87	}
 88
 89	var status struct {
 90		Data SecurityOut `json:"data"`
 91	}
 92	json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "security", "status", p, "--json")), &status)
 93	if !status.Data.Enabled || len(status.Data.Findings) != 1 || status.Data.Findings[0].Line != 12 {
 94		t.Errorf("status = %+v", status.Data)
 95	}
 96	screen := atTerminalIn(t, st, u, root, "repo", "security", "status", p)
 97	if !strings.Contains(screen, "Findings (1)") || !strings.Contains(screen, "store/q.go:12") {
 98		t.Errorf("screen:\n%s", screen)
 99	}
100	checkLegend(t, screen)
101
102	// A clean scan closes the issue.
103	run(runSecurityRun, "", p)
104	_, claim = run(runRunnerNext, "")
105	json.Unmarshal([]byte(claim), &claimed)
106	if code, out := run(runRunnerResults, `{"version":"2.1.0","runs":[]}`, itoa(claimed.Data.ID)); code != protocol.ExitOK {
107		t.Fatalf("clean results: %d %s", code, out)
108	}
109	if closed, _ := st.IssueByNumber(repo.ID, scan.IssueNumber); closed.State != "closed" {
110		t.Errorf("issue state after a clean scan = %q", closed.State)
111	}
112
113	// A job of the repository's own may not upload.
114	other, err := st.CreateBuild(repo.ID, "unit", claimed.Data.SHA, "main", "[]", "", "", true)
115	if err != nil {
116		t.Fatal(err)
117	}
118	if code, out := run(runRunnerResults, testSARIF, itoa(other)); code != protocol.ExitDenied {
119		t.Errorf("results from another job: %d %s", code, out)
120	}
121}
122
123// scopeRepo commits files to a bare repository and returns its directory
124// and the commit.
125func scopeRepo(t *testing.T, files map[string]string) (string, string) {
126	t.Helper()
127	root := t.TempDir()
128	src, dir := filepath.Join(root, "src"), filepath.Join(root, "bare.git")
129	git := func(cwd string, args ...string) string {
130		t.Helper()
131		cmd := exec.Command("git", args...)
132		cmd.Dir, cmd.Env = cwd, gitTestEnv()
133		out, err := cmd.CombinedOutput()
134		if err != nil {
135			t.Fatalf("git %v: %v\n%s", args, err, out)
136		}
137		return strings.TrimSpace(string(out))
138	}
139	for name, body := range files {
140		os.MkdirAll(filepath.Join(src, filepath.Dir(name)), 0o755)
141		os.WriteFile(filepath.Join(src, name), []byte(body), 0o644)
142	}
143	git(root, "init", "-q", "-b", "main", "src")
144	git(src, "add", ".")
145	git(src, "commit", "-q", "-m", "first")
146	git(root, "clone", "-q", "--bare", src, dir)
147	return dir, git(dir, "rev-parse", "HEAD")
148}
149
150func TestScanScope(t *testing.T) {
151	dir, sha := scopeRepo(t, map[string]string{
152		"requirements.txt":            "flask>=3\n",
153		"web/package.json":            `{"dependencies":{"react":"^19"}}`,
154		"node_modules/x/package.json": `{"dependencies":{"jquery":"3"}}`,
155		".gitattributes":              "Sources/Vendored/** linguist-vendored\n*.min.js linguist-generated\ndocs/** -linguist-vendored\n",
156		"app.py":                      "",
157	})
158	repo := store.Repo{Settings: store.RepoSettings{SecurityIgnore: []string{"testdata/**"},
159		SecurityExcludeRules: []string{"swift.lang.crypto.insecure-random"}}}
160	f := func(rule, path string) store.SecurityFinding {
161		return store.SecurityFinding{Rule: "opt.opengrep-rules." + rule, Path: path}
162	}
163	in := []store.SecurityFinding{
164		f("python.flask.security.xss.x", "app.py"),                         // flask is used
165		f("python.django.security.django-no-csrf-token", "t.html"),         // django is not
166		f("javascript.jquery.security.audit.prohibit-jquery-html", "a.ts"), // only node_modules has it
167		f("typescript.react.security.audit.x", "web/a.tsx"),                // web/package.json
168		f("typescript.react.portability.i18next.jsx-not-internationalized", "web/a.tsx"),
169		f("yaml.semgrep.missing-language-field", "rules.yaml"),
170		f("python.lang.security.audit.x", "testdata/a.py"),
171		f("swift.lang.crypto.insecure-random", "A.swift"),
172		f("c.lang.security.insecure-use-memset", "Sources/Vendored/a.c"),
173		f("javascript.browser.security.insecure-innerhtml", "lib/x.min.js"),
174		f("javascript.browser.security.insecure-innerhtml", "docs/x.js"),
175	}
176	kept, aside, truncated := scanScope(dir, repo, sha).Apply(in)
177	var got []string
178	for _, k := range kept {
179		got = append(got, k.Path)
180	}
181	if strings.Join(got, " ") != "app.py web/a.tsx docs/x.js" || truncated {
182		t.Errorf("kept %v truncated %v", got, truncated)
183	}
184	if aside.Ignored != 4 || aside.Unused["django"] != 1 || aside.Unused["jquery"] != 1 ||
185		aside.Unused["i18next"] != 1 || aside.Unused["semgrep"] != 1 || len(aside.Unused) != 4 {
186		t.Errorf("aside = %+v", aside)
187	}
188
189	// A repository that authors rules keeps the rule lints.
190	dir, sha = scopeRepo(t, map[string]string{".semgrep/rules.yaml": "rules: []\n"})
191	if kept, _, _ := scanScope(dir, store.Repo{}, sha).Apply(in[5:6]); len(kept) != 1 {
192		t.Errorf("rule lints set aside in a repository with .semgrep")
193	}
194}
195
196const twoFindings = `{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"opengrep"}},"results":[
197	{"ruleId":"go.lang.security.audit.sqli","message":{"text":"SQL built from input"},
198	 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"store/q.go"},"region":{"startLine":12}}}]},
199	{"ruleId":"go.lang.security.audit.sqli","message":{"text":"SQL built from input"},
200	 "locations":[{"physicalLocation":{"artifactLocation":{"uri":"store/q.go"},"region":{"startLine":40}}}]}]}]}`
201
202// Dismissing takes a finding out of the issue and closes it once none are
203// open; reopening brings it back.
204func TestSecurityDismiss(t *testing.T) {
205	st, repo, u, root := browseFixture(t)
206	p := repo.Path()
207	sec := config.Default().Security
208	sec.Image = "localhost/gitbay-security:1"
209	run := func(f func(*Ctx, []string) int, stdin string, args ...string) (int, string) {
210		t.Helper()
211		c, out := runnerCtx(st, u.ID, root)
212		c.Cfg.Security = sec
213		c.Stdin = strings.NewReader(stdin)
214		c.JSON = true
215		return f(c, args), out.String()
216	}
217	run(runSecurityEnable, "", p)
218	run(runSecurityRun, "", p)
219	_, claim := run(runRunnerNext, "")
220	var claimed struct {
221		Data struct {
222			ID int64 `json:"id"`
223		} `json:"data"`
224	}
225	json.Unmarshal([]byte(claim), &claimed)
226	if code, out := run(runRunnerResults, twoFindings, itoa(claimed.Data.ID)); code != protocol.ExitOK {
227		t.Fatalf("results: %d %s", code, out)
228	}
229	scan, _ := st.SecurityScanFor(repo.ID)
230	findings, _ := st.ReportedFindings(repo.ID)
231	if len(findings) != 2 {
232		t.Fatalf("two hits of one rule in one file stored as %d", len(findings))
233	}
234	issue, _ := st.IssueByNumber(repo.ID, scan.IssueNumber)
235	first, second := codescan.ByPlace(findings)[0].Fingerprint, codescan.ByPlace(findings)[1].Fingerprint
236	if !strings.Contains(issue.Body, codescan.Short(first)) || !strings.Contains(issue.Body, "repo security dismiss "+p) {
237		t.Fatalf("issue:\n%s", issue.Body)
238	}
239
240	dismiss := func(args ...string) (int, string) {
241		t.Helper()
242		var out strings.Builder
243		c, buf := runnerCtx(st, u.ID, root)
244		code := runSecurityDismiss(c, args)
245		out.WriteString(buf.String())
246		return code, out.String()
247	}
248	if code, out := dismiss(p, codescan.Short(first), "--reason", "nope"); code != protocol.ExitUsage {
249		t.Errorf("bad reason: %d %s", code, out)
250	}
251	if code, out := dismiss(p, first[:4], "--reason", "test"); code != protocol.ExitNotFound || !strings.Contains(out, "too short") {
252		t.Errorf("short prefix: %d %s", code, out)
253	}
254	if code, out := dismiss(p, codescan.Short(first), "--reason", "false-positive"); code != protocol.ExitOK {
255		t.Fatalf("dismiss: %d %s", code, out)
256	}
257	issue, _ = st.IssueByNumber(repo.ID, scan.IssueNumber)
258	if strings.Contains(issue.Body, codescan.Short(first)) || !strings.Contains(issue.Body, codescan.Short(second)) ||
259		!strings.Contains(issue.Body, "1 dismissed") || issue.State != "open" {
260		t.Errorf("after one dismissal (%s):\n%s", issue.State, issue.Body)
261	}
262
263	var status struct {
264		Data SecurityOut `json:"data"`
265	}
266	json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "security", "status", p, "--json")), &status)
267	if len(status.Data.Findings) != 1 || len(status.Data.Dismissed) != 1 ||
268		status.Data.Dismissed[0].Reason != "false-positive" || status.Data.Dismissed[0].DismissedBy != u.Username {
269		t.Errorf("status = %+v", status.Data)
270	}
271	screen := atTerminalIn(t, st, u, root, "repo", "security", "status", p)
272	if !strings.Contains(screen, "Dismissed (1)") {
273		t.Errorf("screen:\n%s", screen)
274	}
275	checkLegend(t, screen)
276
277	// The same set from the next scan leaves the issue alone.
278	run(runSecurityRun, "", p)
279	_, claim = run(runRunnerNext, "")
280	json.Unmarshal([]byte(claim), &claimed)
281	run(runRunnerResults, twoFindings, itoa(claimed.Data.ID))
282	if again, _ := st.IssueByNumber(repo.ID, scan.IssueNumber); again.Body != issue.Body || again.State != "open" {
283		t.Errorf("an unchanged scan rewrote the issue:\n%s", again.Body)
284	}
285
286	if code, out := dismiss(p, second, "--reason", "wont-fix"); code != protocol.ExitOK {
287		t.Fatalf("dismiss second: %d %s", code, out)
288	}
289	if closed, _ := st.IssueByNumber(repo.ID, scan.IssueNumber); closed.State != "closed" {
290		t.Errorf("issue with nothing open is %s", closed.State)
291	}
292	c, out := runnerCtx(st, u.ID, root)
293	if code := runSecurityReopen(c, []string{p, codescan.Short(second)}); code != protocol.ExitOK {
294		t.Fatalf("reopen: %d %s", code, out)
295	}
296	reopened, _ := st.SecurityScanFor(repo.ID)
297	if reopened.IssueNumber == scan.IssueNumber || reopened.IssueNumber == 0 {
298		t.Errorf("reopening a finding should open a fresh issue, got #%d", reopened.IssueNumber)
299	}
300}
301
302// A default branch is passed to git by name, so one shaped like an option
303// is refused before it is looked up.
304func TestDefaultBranchRefusesOptionShape(t *testing.T) {
305	st, repo, u, root := browseFixture(t)
306	c, out := runnerCtx(st, u.ID, root)
307	if code := runSetDefaultBranch(c, []string{repo.Path(), "--output=/tmp/x"}); code != protocol.ExitUsage ||
308		!strings.Contains(out.String(), "may not start with '-'") {
309		t.Errorf("exit %d: %s", code, out)
310	}
311	c, out = runnerCtx(st, u.ID, root)
312	if code := runSetDefaultBranch(c, []string{repo.Path(), "feature"}); code != protocol.ExitOK {
313		t.Errorf("a normal branch: exit %d: %s", code, out)
314	}
315}
316
317func TestSecurityFrequency(t *testing.T) {
318	st, repo, u, root := browseFixture(t)
319	p := repo.Path()
320	sec := config.Default().Security
321	sec.Image = "localhost/gitbay-security:1"
322	run := func(f func(*Ctx, []string) int, args ...string) (int, string) {
323		t.Helper()
324		c, out := runnerCtx(st, u.ID, root)
325		c.Cfg.Security = sec
326		c.JSON = true
327		return f(c, args), out.String()
328	}
329	// Before scanning is on the choice is kept and nothing is scheduled.
330	if code, out := run(runSecurityFrequency, p, "monthly"); code != protocol.ExitOK || !strings.Contains(out, `"next_run":""`) {
331		t.Fatalf("monthly while off: %d %s", code, out)
332	}
333	run(runSecurityEnable, p)
334	if sc, _ := st.SecurityScanFor(repo.ID); !strings.Contains(sc.NextRun, "-01T04:00:00Z") {
335		t.Fatalf("enable ignored the monthly choice: %q", sc.NextRun)
336	}
337	code, out := run(runSecurityFrequency, p, "weekly")
338	if code != protocol.ExitOK {
339		t.Fatalf("weekly: %d %s", code, out)
340	}
341	sc, _ := st.SecurityScanFor(repo.ID)
342	next, err := time.Parse("2006-01-02T15:04:05Z", sc.NextRun)
343	if err != nil || next.Weekday() != time.Sunday || next.Hour() != 4 || !strings.Contains(out, sc.NextRun) {
344		t.Fatalf("next run %q (%v), out %s", sc.NextRun, err, out)
345	}
346	if _, out := run(runSecurityStatus, p); !strings.Contains(out, `"frequency":"weekly"`) {
347		t.Fatalf("status: %s", out)
348	}
349	if code, _ := run(runSecurityFrequency, p, "hourly"); code != protocol.ExitUsage {
350		t.Fatalf("hourly: exit %d", code)
351	}
352	// Narrowed: daily is refused, and the stored monthly scans weekly.
353	sec.LeastOften, sec.Default, sec.MostOften = "weekly", "weekly", "weekly"
354	if code, out := run(runSecurityFrequency, p, "daily"); code != protocol.ExitFailure || !strings.Contains(out, "scans weekly") {
355		t.Fatalf("daily outside the range: %d %s", code, out)
356	}
357	sec.MostOften, sec.LeastOften = "daily", "daily"
358	sec.Default = "daily"
359	if _, out := run(runSecurityStatus, p); !strings.Contains(out, `"frequency":"daily"`) {
360		t.Fatalf("weekly outside the range: %s", out)
361	}
362}