internal/control/security.go

664 lines · 24590 bytes

  1package control
  2
  3import (
  4	"encoding/json"
  5	"errors"
  6	"fmt"
  7	"io"
  8	"path"
  9	"slices"
 10	"sort"
 11	"strconv"
 12	"strings"
 13	"time"
 14
 15	"gitbay.org/gitbay/internal/botissue"
 16	"gitbay.org/gitbay/internal/ci"
 17	"gitbay.org/gitbay/internal/codescan"
 18	"gitbay.org/gitbay/internal/config"
 19	"gitbay.org/gitbay/internal/deps"
 20	"gitbay.org/gitbay/internal/gitutil"
 21	"gitbay.org/gitbay/internal/policy"
 22	"gitbay.org/gitbay/internal/protocol"
 23	"gitbay.org/gitbay/internal/store"
 24)
 25
 26func init() {
 27	// Code scanning: the instance's own job ([security] in the config),
 28	// scheduled per repository that opts in, reporting through an issue.
 29	// Opt-in because the build runs on a runner the repository is attached
 30	// to, which is the owner's arrangement to make.
 31	register(Command{Path: []string{"repo", "security", "enable"},
 32		Summary:  "scan the default branch on the instance's code scanning schedule",
 33		Usage:    "repo security enable <owner/name>",
 34		Examples: []string{"repo security enable krz/gitbay"},
 35		Run:      runSecurityEnable})
 36	register(Command{Path: []string{"repo", "security", "disable"},
 37		Summary:  "stop code scanning",
 38		Usage:    "repo security disable <owner/name>",
 39		Examples: []string{"repo security disable krz/gitbay"},
 40		Run:      runSecurityDisable})
 41	register(Command{Path: []string{"repo", "security", "run"},
 42		Summary:  "queue a code scan of the default branch now",
 43		Usage:    "repo security run <owner/name>",
 44		Examples: []string{"repo security run krz/gitbay"},
 45		Run:      runSecurityRun})
 46	register(Command{Path: []string{"repo", "security", "status"},
 47		Summary:  "show code scanning state and the last scan's findings",
 48		Usage:    "repo security status <owner/name>",
 49		Examples: []string{"repo security status krz/gitbay"},
 50		ReadOnly: true, Run: runSecurityStatus})
 51	register(Command{Path: []string{"repo", "security", "dismiss"},
 52		Summary: "dismiss code scanning findings, which then stay out of the issue",
 53		Usage:   "repo security dismiss <owner/name> <fingerprint>... --reason false-positive|wont-fix|test",
 54		Flags: []Flag{
 55			{"--reason", "false-positive|wont-fix|test", "why: not a problem, accepted, or only in tests", ""},
 56		},
 57		Examples: []string{"repo security dismiss krz/gitbay 3f9a0c1d2e --reason false-positive"},
 58		Run:      runSecurityDismiss})
 59	register(Command{Path: []string{"repo", "security", "reopen"},
 60		Summary:  "take back dismissals of code scanning findings",
 61		Usage:    "repo security reopen <owner/name> <fingerprint>...",
 62		Examples: []string{"repo security reopen krz/gitbay 3f9a0c1d2e"},
 63		Run:      runSecurityReopen})
 64	register(Command{Path: []string{"repo", "settings", "security-ignore"},
 65		Summary:  "paths whose code scanning findings are set aside",
 66		Usage:    "repo settings security-ignore <owner/name> [<glob>...] (none clears the list)",
 67		Examples: []string{"repo settings security-ignore krz/gitbay 'testdata/**' 'web/templates/*.html'"},
 68		Run:      runSecurityIgnore})
 69	register(Command{Path: []string{"repo", "settings", "security-exclude-rule"},
 70		Summary:  "code scanning rules, or families of them, whose findings are set aside",
 71		Usage:    "repo settings security-exclude-rule <owner/name> [<rule>...] (none clears the list)",
 72		Examples: []string{"repo settings security-exclude-rule krz/gitbay swift.lang.crypto.insecure-random"},
 73		Run:      runSecurityExcludeRule})
 74	register(Command{Path: []string{"repo", "settings", "security-frequency"},
 75		Summary:  "how often the code scan runs, within what the instance allows",
 76		Usage:    "repo settings security-frequency <owner/name> daily|weekly|monthly",
 77		Examples: []string{"repo settings security-frequency krz/gitbay weekly"},
 78		Run:      runSecurityFrequency})
 79	register(Command{Path: []string{"runner", "results"},
 80		Summary:    "upload a code scan's SARIF from stdin",
 81		Usage:      "runner results <build-id>",
 82		Examples:   []string{"runner results 431 < results.sarif"},
 83		ReadsStdin: true, Run: runRunnerResults})
 84}
 85
 86// SecurityOut is what `repo security status` emits: the last scan's open
 87// findings, the ones dismissed, and how many it set aside.
 88type SecurityOut struct {
 89	Enabled     bool              `json:"enabled"`
 90	Frequency   string            `json:"frequency,omitempty"`
 91	NextRun     string            `json:"next_run,omitempty"`
 92	LastResults string            `json:"last_results,omitempty"`
 93	IssueNumber int64             `json:"issue_number,omitempty"`
 94	Findings    []SecurityFinding `json:"findings"`
 95	Dismissed   []SecurityFinding `json:"dismissed"`
 96	Aside       codescan.Aside    `json:"aside"`
 97}
 98
 99// SecurityFinding is one result of the last scan.
100type SecurityFinding struct {
101	Fingerprint string `json:"fingerprint"`
102	Tool        string `json:"tool"`
103	Rule        string `json:"rule"`
104	Level       string `json:"level"`
105	Path        string `json:"path"`
106	Line        int    `json:"line"`
107	Message     string `json:"message"`
108	Reason      string `json:"reason,omitempty"`
109	DismissedBy string `json:"dismissed_by,omitempty"`
110}
111
112// Reasons a finding is dismissed for.
113var dismissReasons = []string{"false-positive", "wont-fix", "test"}
114
115func runSecurityEnable(c *Ctx, args []string) int {
116	if len(args) != 1 {
117		return c.usage()
118	}
119	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
120	if code >= 0 {
121		return code
122	}
123	if c.Cfg.Security.Image == "" {
124		return c.fail(protocol.ExitFailure, "this instance has no code scanning image; an operator sets [security] image")
125	}
126	next := ci.SecurityNextRun(c.Cfg.Security, repo.Settings.SecurityFrequency, time.Now())
127	if err := c.Store.EnableSecurityScan(repo.ID, next); err != nil {
128		return c.fail(protocol.ExitFailure, "%v", err)
129	}
130	return c.emit(map[string]any{"enabled": true, "next_run": next}, func(w io.Writer) {
131		fmt.Fprintf(w, "code scanning enabled on %s; first scan %s\n", repo.Path(), next)
132	})
133}
134
135func runSecurityDisable(c *Ctx, args []string) int {
136	if len(args) != 1 {
137		return c.usage()
138	}
139	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
140	if code >= 0 {
141		return code
142	}
143	if err := c.Store.DisableSecurityScan(repo.ID); err != nil {
144		return c.fail(protocol.ExitFailure, "%v", err)
145	}
146	return c.emit(map[string]any{"enabled": false}, func(w io.Writer) {
147		fmt.Fprintf(w, "code scanning disabled on %s\n", repo.Path())
148	})
149}
150
151func runSecurityRun(c *Ctx, args []string) int {
152	if len(args) != 1 {
153		return c.usage()
154	}
155	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
156	if code >= 0 {
157		return code
158	}
159	if _, err := c.Store.SecurityScanFor(repo.ID); errors.Is(err, store.ErrNotFound) {
160		return c.fail(protocol.ExitFailure, "code scanning is off on %s (repo security enable %s)", repo.Path(), repo.Path())
161	} else if err != nil {
162		return c.fail(protocol.ExitFailure, "%v", err)
163	}
164	if c.Cfg.Security.Image == "" {
165		return c.fail(protocol.ExitFailure, "this instance has no code scanning image; an operator sets [security] image")
166	}
167	n, err := ci.QueueSecurityScan(c.Store, c.Cfg.Security, RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), repo)
168	if err != nil {
169		return c.fail(protocol.ExitFailure, "%v", err)
170	}
171	return c.emit(map[string]any{"build": n}, func(w io.Writer) {
172		fmt.Fprintf(w, "queued build %d: %s on %s\n", n, ci.SecurityJob, repo.Path())
173	})
174}
175
176func runSecurityStatus(c *Ctx, args []string) int {
177	if len(args) != 1 {
178		return c.usage()
179	}
180	repo, code := resolveRepo(c, args[0], policy.CanRead)
181	if code >= 0 {
182		return code
183	}
184	scan, err := c.Store.SecurityScanFor(repo.ID)
185	if errors.Is(err, store.ErrNotFound) {
186		return c.emitView(map[string]any{"enabled": false}, func(w io.Writer) {
187			c.view(w).fields("scanning", fmt.Sprintf("off (repo security enable %s)", repo.Path()))
188		}, func() screen {
189			return screen{
190				fields:  []field{{"Scanning", []cell{cText("off")}}},
191				actions: []action{{"Security", []string{"repo", "security", "enable", repo.Path()}}},
192			}
193		})
194	}
195	if err != nil {
196		return c.fail(protocol.ExitFailure, "%v", err)
197	}
198	reported, err := c.Store.ReportedFindings(repo.ID)
199	if err != nil {
200		return c.fail(protocol.ExitFailure, "%v", err)
201	}
202	dismissed, err := c.Store.SecurityDismissals(repo.ID)
203	if err != nil {
204		return c.fail(protocol.ExitFailure, "%v", err)
205	}
206	freq := c.Cfg.Security.Frequency(repo.Settings.SecurityFrequency)
207	out := SecurityOut{Enabled: true, Frequency: freq, NextRun: scan.NextRun, LastResults: scan.LastResults,
208		IssueNumber: scan.IssueNumber, Findings: []SecurityFinding{}, Dismissed: []SecurityFinding{}}
209	json.Unmarshal([]byte(scan.Aside), &out.Aside)
210	for _, f := range codescan.ByPlace(reported) {
211		o := SecurityFinding{Fingerprint: f.Fingerprint, Tool: f.Tool, Rule: f.Rule, Level: f.Level,
212			Path: f.Path, Line: f.Line, Message: f.Message}
213		if d, ok := dismissed[f.Fingerprint]; ok {
214			o.Reason, o.DismissedBy = d.Reason, d.By
215			out.Dismissed = append(out.Dismissed, o)
216			continue
217		}
218		out.Findings = append(out.Findings, o)
219	}
220	return c.emitView(out, func(w io.Writer) {
221		tracked := ""
222		if scan.IssueNumber != 0 {
223			tracked = fmt.Sprintf("#%d", scan.IssueNumber)
224		}
225		v := c.view(w)
226		v.fields(
227			"scanning", "on",
228			"frequency", freq,
229			"next scan", scan.NextRun,
230			"last results", c.when(scan.LastResults),
231			"tracked in", tracked,
232			"set aside", asideText(out.Aside),
233		)
234		if len(out.Findings) > 0 {
235			v.section("findings")
236			tb := c.table(w, "FINGERPRINT", "TOOL", "RULE", "LEVEL", "PATH", "LINE")
237			for _, f := range out.Findings {
238				tb.row(cRef(codescan.Short(f.Fingerprint)), cText(f.Tool), cText(f.Rule), cText(f.Level), cRef(f.Path), cNum(int64(f.Line)))
239			}
240			tb.flush()
241		}
242		if len(out.Dismissed) > 0 {
243			v.section("dismissed")
244			tb := c.table(w, "FINGERPRINT", "REASON", "BY", "RULE", "PATH", "LINE")
245			for _, f := range out.Dismissed {
246				tb.row(cRef(codescan.Short(f.Fingerprint)), cText(f.Reason), cText(f.DismissedBy), cText(f.Rule), cRef(f.Path), cNum(int64(f.Line)))
247			}
248			tb.flush()
249		}
250	}, func() screen {
251		s := screen{fields: []field{
252			{"Scanning", []cell{cGlyph("ok"), cText("on")}},
253			{"Frequency", []cell{cText(freq)}},
254			{"Next scan", []cell{cText(scan.NextRun)}},
255			{"Last results", []cell{cAge(scan.LastResults)}},
256		}}
257		if scan.IssueNumber != 0 {
258			n := strconv.FormatInt(scan.IssueNumber, 10)
259			s.fields = append(s.fields, field{"Tracked in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}})
260		}
261		if a := asideText(out.Aside); a != "" {
262			s.fields = append(s.fields, field{"Set aside", []cell{cMeta(a)}})
263		}
264		found := section{title: "Findings", n: len(out.Findings)}
265		for _, f := range out.Findings {
266			found.rows = append(found.rows, rowOf(cRef(f.Path+":"+strconv.Itoa(f.Line)), cText(f.Rule), cFlexRef(codescan.Short(f.Fingerprint))))
267		}
268		s.sections = []section{found}
269		if len(out.Dismissed) > 0 {
270			gone := section{title: "Dismissed", n: len(out.Dismissed)}
271			for _, f := range out.Dismissed {
272				gone.rows = append(gone.rows, rowOf(cRef(f.Path+":"+strconv.Itoa(f.Line)), cState(f.Reason), cFlexRef(codescan.Short(f.Fingerprint))))
273			}
274			s.sections = append(s.sections, gone)
275		}
276		s.actions = []action{{"Security", []string{"repo", "security", "run", repo.Path()}}}
277		if len(out.Findings) > 0 {
278			s.actions = append(s.actions, action{"Security", []string{"repo", "security", "dismiss", repo.Path(), "<fp>", "--reason", "<why>"}})
279		}
280		return s
281	})
282}
283
284// runRunnerResults takes a security build's SARIF from the runner that
285// claimed it, replaces the repository's findings with it, and brings the
286// findings issue in line. Only the instance's own job may upload: its
287// steps are the operator's, where any other job's are the repository's.
288func runRunnerResults(c *Ctx, args []string) int {
289	key, code := runnerSession(c)
290	if code >= 0 {
291		return code
292	}
293	if len(args) != 1 {
294		return c.usage()
295	}
296	id, err := strconv.ParseInt(args[0], 10, 64)
297	if err != nil {
298		return c.fail(protocol.ExitUsage, "bad build id %q", args[0])
299	}
300	b, err := c.Store.BuildByID(id)
301	if err != nil {
302		return c.fail(protocol.ExitNotFound, "no build %d", id)
303	}
304	if ok, err := runnerMayBuild(c, key, b.RepoID); err != nil {
305		return c.fail(protocol.ExitFailure, "%v", err)
306	} else if !ok {
307		return c.fail(protocol.ExitDenied, "this key is not attached to the build's repository; a repository admin attaches it with repo runner add")
308	}
309	if b.Job != ci.SecurityJob {
310		return c.fail(protocol.ExitDenied, "results are accepted from the %s job only", ci.SecurityJob)
311	}
312	if b.Status != "running" {
313		return c.fail(protocol.ExitFailure, "build %d is %s", id, b.Status)
314	}
315	scan, err := c.Store.SecurityScanFor(b.RepoID)
316	if errors.Is(err, store.ErrNotFound) {
317		// Disabled while the build ran: nothing to report into.
318		return c.emit(map[string]any{"findings": 0}, func(w io.Writer) {})
319	}
320	if err != nil {
321		return c.fail(protocol.ExitFailure, "%v", err)
322	}
323	raw, err := io.ReadAll(io.LimitReader(c.Stdin, codescan.MaxUpload+1))
324	if err != nil {
325		return c.fail(protocol.ExitFailure, "reading results: %v", err)
326	}
327	if len(raw) > codescan.MaxUpload {
328		return c.fail(protocol.ExitFailure, "results are over %d bytes", codescan.MaxUpload)
329	}
330	all, overflow, err := codescan.Parse(raw)
331	if err != nil {
332		return c.fail(protocol.ExitFailure, "%v", err)
333	}
334	repo, err := c.Store.RepoByID(b.RepoID)
335	if err != nil {
336		return c.fail(protocol.ExitFailure, "%v", err)
337	}
338	findings, aside, truncated := scanScope(RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), repo, b.SHA).Apply(all)
339	previous, err := c.Store.ReportedFindings(repo.ID)
340	if err != nil {
341		return c.fail(protocol.ExitFailure, "%v", err)
342	}
343	asideJSON := ""
344	if aside.Any() {
345		j, _ := json.Marshal(aside)
346		asideJSON = string(j)
347	}
348	changed := !codescan.Same(previous, codescan.ByFingerprint(findings)) || asideJSON != scan.Aside
349	err = maintainFindings(c, repo, scan, findings, aside, truncated || overflow, changed,
350		func() error { return c.Store.ReplaceFindings(repo.ID, findings, asideJSON) })
351	if err != nil {
352		return c.fail(protocol.ExitFailure, "%v", err)
353	}
354	// Stamped whether or not the set changed: the status says when results
355	// last arrived.
356	if err := c.Store.StampSecurityResults(repo.ID); err != nil {
357		return c.fail(protocol.ExitFailure, "%v", err)
358	}
359	return c.emit(map[string]any{"findings": len(findings), "truncated": truncated}, func(w io.Writer) {
360		fmt.Fprintf(w, "%d findings recorded for build %d\n", len(findings), b.Number)
361	})
362}
363
364// maintainFindings brings the findings issue in line with a set of
365// findings: the open ones listed, the dismissed and set-aside ones
366// counted, closed when none are open.
367func maintainFindings(c *Ctx, repo store.Repo, scan store.SecurityScan, findings []store.SecurityFinding,
368	aside codescan.Aside, truncated, changed bool, save func() error) error {
369	dismissed, err := c.Store.SecurityDismissals(repo.ID)
370	if err != nil {
371		return err
372	}
373	var open []store.SecurityFinding
374	for _, f := range findings {
375		if _, ok := dismissed[f.Fingerprint]; !ok {
376			open = append(open, f)
377		}
378	}
379	return botissue.Maintain(c.Store, c.Cfg, repo, botissue.Tracked{
380		Title:   codescan.IssueTitle,
381		Number:  scan.IssueNumber,
382		Record:  func(n int64) error { return c.Store.SetSecurityIssue(repo.ID, n) },
383		Empty:   len(open) == 0,
384		Changed: changed,
385		Save:    save,
386		Body: func() string {
387			return codescan.Body(codescan.Report{Repo: repo.Path(), Branch: repo.DefaultBranch, Open: codescan.ByPlace(open),
388				Dismissed: len(findings) - len(open), Aside: aside, Truncated: truncated})
389		},
390	})
391}
392
393// manifestLimit bounds a manifest or .gitattributes read for a scan's scope.
394const manifestLimit = 1 << 20
395
396// maxManifestDirs bounds how many directories' manifests a scope reads.
397const maxManifestDirs = 50
398
399// scanScope is what a repository sets aside from a scan of commit sha: its
400// settings, what .gitattributes marks vendored or generated, and findings
401// from rules about libraries no manifest at that commit names. Manifests are
402// read in every directory that has one, outside dependency directories, so
403// a monorepo's web/package.json counts. Files at sha are read for rules
404// whose hits are checked against the source.
405func scanScope(dir string, repo store.Repo, sha string) codescan.Scope {
406	sc := codescan.Scope{Ignore: repo.Settings.SecurityIgnore, ExcludeRules: repo.Settings.SecurityExcludeRules}
407	if raw, err := gitutil.ReadBlob(dir, sha, ".gitattributes", manifestLimit); err == nil {
408		sc.Vendored = codescan.Vendored(raw)
409	}
410	sc.Read = func(p string) ([]byte, error) { return gitutil.ReadBlob(dir, sha, p, manifestLimit) }
411	root := map[string]bool{}
412	if entries, err := gitutil.ListTree(dir, sha, ""); err == nil {
413		for _, e := range entries {
414			root[e.Name] = true
415		}
416	}
417	dirs := []string{""}
418	if entries, err := gitutil.ListTreeRecursive(dir, sha, ""); err == nil {
419		seen := map[string]bool{"": true}
420		for _, e := range entries {
421			d := path.Dir(e.Name)
422			if seen[d] || len(dirs) == maxManifestDirs || !slices.Contains(deps.ManifestFiles, path.Base(e.Name)) || dependencyDir(d) {
423				continue
424			}
425			seen[d] = true
426			dirs = append(dirs, d)
427		}
428	}
429	uses := map[string]bool{}
430	for _, d := range dirs {
431		read := func(p string) ([]byte, error) {
432			if d != "" {
433				p = d + "/" + p
434			}
435			return gitutil.ReadBlob(dir, sha, p, manifestLimit)
436		}
437		for _, dep := range deps.Names(read) {
438			uses[dep.Ecosystem+":"+dep.Name] = true
439		}
440	}
441	sc.Uses = func(packages []string) bool {
442		for _, p := range packages {
443			if name, ok := strings.CutPrefix(p, "root:"); ok {
444				if root[name] {
445					return true
446				}
447				continue
448			}
449			if strings.HasPrefix(p, "go:") && strings.HasSuffix(p, "/") {
450				for u := range uses {
451					if strings.HasPrefix(u, p) {
452						return true
453					}
454				}
455				continue
456			}
457			if uses[p] {
458				return true
459			}
460		}
461		return false
462	}
463	return sc
464}
465
466// dependencyDir reports whether a directory holds other projects' code
467// rather than the repository's own.
468func dependencyDir(d string) bool {
469	for _, part := range strings.Split(d, "/") {
470		if part == "node_modules" || part == "vendor" || part == "third_party" {
471			return true
472		}
473	}
474	return false
475}
476
477// asideText is what the last scan set aside, in a line.
478func asideText(a codescan.Aside) string {
479	var parts []string
480	if a.Ignored > 0 {
481		parts = append(parts, fmt.Sprintf("%d ignored", a.Ignored))
482	}
483	libs := make([]string, 0, len(a.Unused))
484	for l := range a.Unused {
485		libs = append(libs, l)
486	}
487	sort.Strings(libs)
488	for _, l := range libs {
489		parts = append(parts, fmt.Sprintf("%d %s (not used)", a.Unused[l], l))
490	}
491	if a.Quoted > 0 {
492		parts = append(parts, fmt.Sprintf("%d quoted attributes", a.Quoted))
493	}
494	return strings.Join(parts, ", ")
495}
496
497func runSecurityDismiss(c *Ctx, args []string) int {
498	f, err := c.parseArgs(args, flagSpec{Values: []string{"--reason"}, MaxPos: -1, Usage: c.Cmd.Usage})
499	if err != nil {
500		return c.fail(protocol.ExitUsage, "%v", err)
501	}
502	if len(f.Pos) < 2 {
503		return c.usage()
504	}
505	reason := f.Value("--reason")
506	if !slices.Contains(dismissReasons, reason) {
507		return c.fail(protocol.ExitUsage, "--reason is one of %s", strings.Join(dismissReasons, ", "))
508	}
509	return changeDismissals(c, f.Pos[0], f.Pos[1:], func(repoID int64, fps []string) error {
510		return c.Store.DismissFindings(repoID, c.User.ID, fps, reason)
511	}, "dismissed")
512}
513
514func runSecurityReopen(c *Ctx, args []string) int {
515	if len(args) < 2 {
516		return c.usage()
517	}
518	return changeDismissals(c, args[0], args[1:], c.Store.ReopenFindings, "reopened")
519}
520
521// changeDismissals resolves fingerprints, given in full or as the issue
522// prints them, against the last scan's findings, applies change, and
523// rewrites the issue to match. Writers may do it: it decides what the
524// issue lists, as editing the issue would.
525func changeDismissals(c *Ctx, name string, given []string, change func(int64, []string) error, verb string) int {
526	repo, code := resolveRepo(c, name, policy.CanWrite)
527	if code >= 0 {
528		return code
529	}
530	scan, err := c.Store.SecurityScanFor(repo.ID)
531	if errors.Is(err, store.ErrNotFound) {
532		return c.fail(protocol.ExitFailure, "code scanning is off on %s (repo security enable %s)", repo.Path(), repo.Path())
533	} else if err != nil {
534		return c.fail(protocol.ExitFailure, "%v", err)
535	}
536	findings, err := c.Store.ReportedFindings(repo.ID)
537	if err != nil {
538		return c.fail(protocol.ExitFailure, "%v", err)
539	}
540	var fps []string
541	for _, g := range given {
542		fp, msg := resolveFingerprint(findings, g)
543		if msg != "" {
544			return c.fail(protocol.ExitNotFound, "%s", msg)
545		}
546		if !slices.Contains(fps, fp) {
547			fps = append(fps, fp)
548		}
549	}
550	if err := change(repo.ID, fps); err != nil {
551		return c.fail(protocol.ExitFailure, "%v", err)
552	}
553	var aside codescan.Aside
554	json.Unmarshal([]byte(scan.Aside), &aside)
555	err = maintainFindings(c, repo, scan, findings, aside, len(findings) >= codescan.MaxFindings, true,
556		func() error { return nil })
557	if err != nil {
558		return c.fail(protocol.ExitFailure, "%v", err)
559	}
560	return c.emit(map[string]any{verb: fps}, func(w io.Writer) {
561		fmt.Fprintf(w, "%s %d on %s\n", verb, len(fps), repo.Path())
562	})
563}
564
565// resolveFingerprint finds the one finding a fingerprint or a prefix of at
566// least codescan.ShortLen names, or says why not.
567func resolveFingerprint(findings []store.SecurityFinding, given string) (string, string) {
568	if len(given) < codescan.ShortLen {
569		return "", fmt.Sprintf("fingerprint %q is too short; give at least %d characters", given, codescan.ShortLen)
570	}
571	match := ""
572	for _, f := range findings {
573		if strings.HasPrefix(f.Fingerprint, given) {
574			if match != "" {
575				return "", fmt.Sprintf("fingerprint %q names more than one finding", given)
576			}
577			match = f.Fingerprint
578		}
579	}
580	if match == "" {
581		return "", fmt.Sprintf("no finding %q in the last scan", given)
582	}
583	return match, ""
584}
585
586// runSecurityFrequency sets how often the repository is scanned and, when
587// scanning is on, moves the next scan to match.
588func runSecurityFrequency(c *Ctx, args []string) int {
589	if len(args) != 2 || !slices.Contains(config.ScanFrequencies, args[1]) {
590		return c.usage()
591	}
592	freq := args[1]
593	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
594	if code >= 0 {
595		return code
596	}
597	if allowed := c.Cfg.Security.Frequencies(); !slices.Contains(allowed, freq) {
598		return c.fail(protocol.ExitFailure, "this instance scans %s", strings.Join(allowed, ", "))
599	}
600	if _, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.SecurityFrequency = freq }); err != nil {
601		return c.fail(protocol.ExitFailure, "%v", err)
602	}
603	next := ""
604	if _, err := c.Store.SecurityScanFor(repo.ID); err == nil {
605		next = ci.SecurityNextRun(c.Cfg.Security, freq, time.Now())
606		if err := c.Store.SetSecurityNext(repo.ID, next); err != nil {
607			return c.fail(protocol.ExitFailure, "%v", err)
608		}
609	}
610	return c.emit(map[string]any{"frequency": freq, "next_run": next}, func(w io.Writer) {
611		if next == "" {
612			fmt.Fprintf(w, "%s scans %s once scanning is on\n", repo.Path(), freq)
613			return
614		}
615		fmt.Fprintf(w, "%s scans %s; next scan %s\n", repo.Path(), freq, next)
616	})
617}
618
619// maxSecurityList bounds the ignore and exclude-rule settings.
620const maxSecurityList = 50
621
622func runSecurityIgnore(c *Ctx, args []string) int {
623	return setSecurityList(c, args, "a glob", func(s *store.RepoSettings, xs []string) { s.SecurityIgnore = xs }, "ignores")
624}
625
626func runSecurityExcludeRule(c *Ctx, args []string) int {
627	return setSecurityList(c, args, "a rule", func(s *store.RepoSettings, xs []string) { s.SecurityExcludeRules = xs }, "excludes")
628}
629
630// setSecurityList replaces one of the code scanning lists, which apply from
631// the next scan.
632func setSecurityList(c *Ctx, args []string, what string, set func(*store.RepoSettings, []string), verb string) int {
633	if len(args) < 1 {
634		return c.usage()
635	}
636	var xs []string
637	for _, x := range args[1:] {
638		if x == "" || len(x) > 200 || strings.ContainsAny(x, " \t\r\n") {
639			return c.fail(protocol.ExitUsage, "%s is 1 to 200 characters with no spaces: %q", what, x)
640		}
641		if !slices.Contains(xs, x) {
642			xs = append(xs, x)
643		}
644	}
645	if len(xs) > maxSecurityList {
646		return c.fail(protocol.ExitUsage, "at most %d entries", maxSecurityList)
647	}
648	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
649	if code >= 0 {
650		return code
651	}
652	s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { set(s, xs) })
653	if err != nil {
654		return c.fail(protocol.ExitFailure, "%v", err)
655	}
656	return c.emit(s, func(w io.Writer) {
657		if len(xs) == 0 {
658			fmt.Fprintf(w, "code scanning %s cleared on %s\n", verb, repo.Path())
659			return
660		}
661		fmt.Fprintf(w, "code scanning %s on %s: %s; from the next scan (repo security run %s)\n",
662			verb, repo.Path(), strings.Join(xs, ", "), repo.Path())
663	})
664}