internal/control/security.go
681 lines · 25160 bytes
24 symbols in this file
initSecurityOutSecurityFindingdismissReasonsrunSecurityEnablerunSecurityDisablerunSecurityRunrunSecurityStatusrunRunnerResultsmaintainFindingsmanifestLimitmaxManifestDirsscanScopedependencyDirasideTextrunSecurityDismissrunSecurityReopenchangeDismissalsresolveFingerprintrunSecurityFrequencymaxSecurityListrunSecurityIgnorerunSecurityExcludeRulesetSecurityList
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 sc.Paths = make([]string, 0, len(entries))
421 for _, e := range entries {
422 sc.Paths = append(sc.Paths, e.Name)
423 d := path.Dir(e.Name)
424 if seen[d] || len(dirs) == maxManifestDirs || !slices.Contains(deps.ManifestFiles, path.Base(e.Name)) || dependencyDir(d) {
425 continue
426 }
427 seen[d] = true
428 dirs = append(dirs, d)
429 }
430 }
431 uses := map[string]bool{}
432 for _, d := range dirs {
433 read := func(p string) ([]byte, error) {
434 if d != "" {
435 p = d + "/" + p
436 }
437 return gitutil.ReadBlob(dir, sha, p, manifestLimit)
438 }
439 for _, dep := range deps.Names(read) {
440 uses[dep.Ecosystem+":"+dep.Name] = true
441 }
442 }
443 sc.Uses = func(packages []string) bool {
444 for _, p := range packages {
445 if name, ok := strings.CutPrefix(p, "root:"); ok {
446 if root[name] {
447 return true
448 }
449 continue
450 }
451 if strings.HasPrefix(p, "go:") && strings.HasSuffix(p, "/") {
452 for u := range uses {
453 if strings.HasPrefix(u, p) {
454 return true
455 }
456 }
457 continue
458 }
459 if uses[p] {
460 return true
461 }
462 }
463 return false
464 }
465 return sc
466}
467
468// dependencyDir reports whether a directory holds other projects' code
469// rather than the repository's own.
470func dependencyDir(d string) bool {
471 for _, part := range strings.Split(d, "/") {
472 if part == "node_modules" || part == "vendor" || part == "third_party" {
473 return true
474 }
475 }
476 return false
477}
478
479// asideText is what the last scan set aside, in a line.
480func asideText(a codescan.Aside) string {
481 var parts []string
482 if a.Ignored > 0 {
483 parts = append(parts, fmt.Sprintf("%d ignored", a.Ignored))
484 }
485 libs := make([]string, 0, len(a.Unused))
486 for l := range a.Unused {
487 libs = append(libs, l)
488 }
489 sort.Strings(libs)
490 for _, l := range libs {
491 parts = append(parts, fmt.Sprintf("%d %s (not used)", a.Unused[l], l))
492 }
493 if a.Quoted > 0 {
494 parts = append(parts, fmt.Sprintf("%d quoted attributes", a.Quoted))
495 }
496 if a.Unsplit > 0 {
497 parts = append(parts, fmt.Sprintf("%d unsplit expansions", a.Unsplit))
498 }
499 if a.Joined > 0 {
500 parts = append(parts, fmt.Sprintf("%d strings joined in calls", a.Joined))
501 }
502 if a.NoReturn > 0 {
503 parts = append(parts, fmt.Sprintf("%d lines with no return", a.NoReturn))
504 }
505 if a.Attributes > 0 {
506 parts = append(parts, fmt.Sprintf("%d is_ attributes", a.Attributes))
507 }
508 if a.InTests > 0 {
509 parts = append(parts, fmt.Sprintf("%d random in tests", a.InTests))
510 }
511 return strings.Join(parts, ", ")
512}
513
514func runSecurityDismiss(c *Ctx, args []string) int {
515 f, err := c.parseArgs(args, flagSpec{Values: []string{"--reason"}, MaxPos: -1, Usage: c.Cmd.Usage})
516 if err != nil {
517 return c.fail(protocol.ExitUsage, "%v", err)
518 }
519 if len(f.Pos) < 2 {
520 return c.usage()
521 }
522 reason := f.Value("--reason")
523 if !slices.Contains(dismissReasons, reason) {
524 return c.fail(protocol.ExitUsage, "--reason is one of %s", strings.Join(dismissReasons, ", "))
525 }
526 return changeDismissals(c, f.Pos[0], f.Pos[1:], func(repoID int64, fps []string) error {
527 return c.Store.DismissFindings(repoID, c.User.ID, fps, reason)
528 }, "dismissed")
529}
530
531func runSecurityReopen(c *Ctx, args []string) int {
532 if len(args) < 2 {
533 return c.usage()
534 }
535 return changeDismissals(c, args[0], args[1:], c.Store.ReopenFindings, "reopened")
536}
537
538// changeDismissals resolves fingerprints, given in full or as the issue
539// prints them, against the last scan's findings, applies change, and
540// rewrites the issue to match. Writers may do it: it decides what the
541// issue lists, as editing the issue would.
542func changeDismissals(c *Ctx, name string, given []string, change func(int64, []string) error, verb string) int {
543 repo, code := resolveRepo(c, name, policy.CanWrite)
544 if code >= 0 {
545 return code
546 }
547 scan, err := c.Store.SecurityScanFor(repo.ID)
548 if errors.Is(err, store.ErrNotFound) {
549 return c.fail(protocol.ExitFailure, "code scanning is off on %s (repo security enable %s)", repo.Path(), repo.Path())
550 } else if err != nil {
551 return c.fail(protocol.ExitFailure, "%v", err)
552 }
553 findings, err := c.Store.ReportedFindings(repo.ID)
554 if err != nil {
555 return c.fail(protocol.ExitFailure, "%v", err)
556 }
557 var fps []string
558 for _, g := range given {
559 fp, msg := resolveFingerprint(findings, g)
560 if msg != "" {
561 return c.fail(protocol.ExitNotFound, "%s", msg)
562 }
563 if !slices.Contains(fps, fp) {
564 fps = append(fps, fp)
565 }
566 }
567 if err := change(repo.ID, fps); err != nil {
568 return c.fail(protocol.ExitFailure, "%v", err)
569 }
570 var aside codescan.Aside
571 json.Unmarshal([]byte(scan.Aside), &aside)
572 err = maintainFindings(c, repo, scan, findings, aside, len(findings) >= codescan.MaxFindings, true,
573 func() error { return nil })
574 if err != nil {
575 return c.fail(protocol.ExitFailure, "%v", err)
576 }
577 return c.emit(map[string]any{verb: fps}, func(w io.Writer) {
578 fmt.Fprintf(w, "%s %d on %s\n", verb, len(fps), repo.Path())
579 })
580}
581
582// resolveFingerprint finds the one finding a fingerprint or a prefix of at
583// least codescan.ShortLen names, or says why not.
584func resolveFingerprint(findings []store.SecurityFinding, given string) (string, string) {
585 if len(given) < codescan.ShortLen {
586 return "", fmt.Sprintf("fingerprint %q is too short; give at least %d characters", given, codescan.ShortLen)
587 }
588 match := ""
589 for _, f := range findings {
590 if strings.HasPrefix(f.Fingerprint, given) {
591 if match != "" {
592 return "", fmt.Sprintf("fingerprint %q names more than one finding", given)
593 }
594 match = f.Fingerprint
595 }
596 }
597 if match == "" {
598 return "", fmt.Sprintf("no finding %q in the last scan", given)
599 }
600 return match, ""
601}
602
603// runSecurityFrequency sets how often the repository is scanned and, when
604// scanning is on, moves the next scan to match.
605func runSecurityFrequency(c *Ctx, args []string) int {
606 if len(args) != 2 || !slices.Contains(config.ScanFrequencies, args[1]) {
607 return c.usage()
608 }
609 freq := args[1]
610 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
611 if code >= 0 {
612 return code
613 }
614 if allowed := c.Cfg.Security.Frequencies(); !slices.Contains(allowed, freq) {
615 return c.fail(protocol.ExitFailure, "this instance scans %s", strings.Join(allowed, ", "))
616 }
617 if _, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.SecurityFrequency = freq }); err != nil {
618 return c.fail(protocol.ExitFailure, "%v", err)
619 }
620 next := ""
621 if _, err := c.Store.SecurityScanFor(repo.ID); err == nil {
622 next = ci.SecurityNextRun(c.Cfg.Security, freq, time.Now())
623 if err := c.Store.SetSecurityNext(repo.ID, next); err != nil {
624 return c.fail(protocol.ExitFailure, "%v", err)
625 }
626 }
627 return c.emit(map[string]any{"frequency": freq, "next_run": next}, func(w io.Writer) {
628 if next == "" {
629 fmt.Fprintf(w, "%s scans %s once scanning is on\n", repo.Path(), freq)
630 return
631 }
632 fmt.Fprintf(w, "%s scans %s; next scan %s\n", repo.Path(), freq, next)
633 })
634}
635
636// maxSecurityList bounds the ignore and exclude-rule settings.
637const maxSecurityList = 50
638
639func runSecurityIgnore(c *Ctx, args []string) int {
640 return setSecurityList(c, args, "a glob", func(s *store.RepoSettings, xs []string) { s.SecurityIgnore = xs }, "ignores")
641}
642
643func runSecurityExcludeRule(c *Ctx, args []string) int {
644 return setSecurityList(c, args, "a rule", func(s *store.RepoSettings, xs []string) { s.SecurityExcludeRules = xs }, "excludes")
645}
646
647// setSecurityList replaces one of the code scanning lists, which apply from
648// the next scan.
649func setSecurityList(c *Ctx, args []string, what string, set func(*store.RepoSettings, []string), verb string) int {
650 if len(args) < 1 {
651 return c.usage()
652 }
653 var xs []string
654 for _, x := range args[1:] {
655 if x == "" || len(x) > 200 || strings.ContainsAny(x, " \t\r\n") {
656 return c.fail(protocol.ExitUsage, "%s is 1 to 200 characters with no spaces: %q", what, x)
657 }
658 if !slices.Contains(xs, x) {
659 xs = append(xs, x)
660 }
661 }
662 if len(xs) > maxSecurityList {
663 return c.fail(protocol.ExitUsage, "at most %d entries", maxSecurityList)
664 }
665 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
666 if code >= 0 {
667 return code
668 }
669 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { set(s, xs) })
670 if err != nil {
671 return c.fail(protocol.ExitFailure, "%v", err)
672 }
673 return c.emit(s, func(w io.Writer) {
674 if len(xs) == 0 {
675 fmt.Fprintf(w, "code scanning %s cleared on %s\n", verb, repo.Path())
676 return
677 }
678 fmt.Fprintf(w, "code scanning %s on %s: %s; from the next scan (repo security run %s)\n",
679 verb, repo.Path(), strings.Join(xs, ", "), repo.Path())
680 })
681}