internal/control/security.go

279 lines · 10093 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"strconv"
  8	"time"
  9
 10	"gitbay.org/gitbay/internal/botissue"
 11	"gitbay.org/gitbay/internal/ci"
 12	"gitbay.org/gitbay/internal/codescan"
 13	"gitbay.org/gitbay/internal/policy"
 14	"gitbay.org/gitbay/internal/protocol"
 15	"gitbay.org/gitbay/internal/store"
 16)
 17
 18func init() {
 19	// Code scanning: the instance's own job ([security] in the config),
 20	// scheduled per repository that opts in, reporting through an issue.
 21	// Opt-in because the build runs on a runner the repository is attached
 22	// to, which is the owner's arrangement to make.
 23	register(Command{Path: []string{"repo", "security", "enable"},
 24		Summary:  "scan the default branch on the instance's code scanning schedule",
 25		Usage:    "repo security enable <owner/name>",
 26		Examples: []string{"repo security enable krz/gitbay"},
 27		Run:      runSecurityEnable})
 28	register(Command{Path: []string{"repo", "security", "disable"},
 29		Summary:  "stop code scanning",
 30		Usage:    "repo security disable <owner/name>",
 31		Examples: []string{"repo security disable krz/gitbay"},
 32		Run:      runSecurityDisable})
 33	register(Command{Path: []string{"repo", "security", "run"},
 34		Summary:  "queue a code scan of the default branch now",
 35		Usage:    "repo security run <owner/name>",
 36		Examples: []string{"repo security run krz/gitbay"},
 37		Run:      runSecurityRun})
 38	register(Command{Path: []string{"repo", "security", "status"},
 39		Summary:  "show code scanning state and the last scan's findings",
 40		Usage:    "repo security status <owner/name>",
 41		Examples: []string{"repo security status krz/gitbay"},
 42		ReadOnly: true, Run: runSecurityStatus})
 43	register(Command{Path: []string{"runner", "results"},
 44		Summary:    "upload a code scan's SARIF from stdin",
 45		Usage:      "runner results <build-id>",
 46		Examples:   []string{"runner results 431 < results.sarif"},
 47		ReadsStdin: true, Run: runRunnerResults})
 48}
 49
 50// SecurityOut is what `repo security status` emits.
 51type SecurityOut struct {
 52	Enabled     bool              `json:"enabled"`
 53	NextRun     string            `json:"next_run,omitempty"`
 54	LastResults string            `json:"last_results,omitempty"`
 55	IssueNumber int64             `json:"issue_number,omitempty"`
 56	Findings    []SecurityFinding `json:"findings"`
 57}
 58
 59// SecurityFinding is one result of the last scan.
 60type SecurityFinding struct {
 61	Tool    string `json:"tool"`
 62	Rule    string `json:"rule"`
 63	Level   string `json:"level"`
 64	Path    string `json:"path"`
 65	Line    int    `json:"line"`
 66	Message string `json:"message"`
 67}
 68
 69func runSecurityEnable(c *Ctx, args []string) int {
 70	if len(args) != 1 {
 71		return c.usage()
 72	}
 73	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 74	if code >= 0 {
 75		return code
 76	}
 77	if c.Cfg.Security.Image == "" {
 78		return c.fail(protocol.ExitFailure, "this instance has no code scanning image; an operator sets [security] image")
 79	}
 80	next := ci.NextRun(c.Cfg.Security.Schedule, time.Now())
 81	if err := c.Store.EnableSecurityScan(repo.ID, next); err != nil {
 82		return c.fail(protocol.ExitFailure, "%v", err)
 83	}
 84	return c.emit(map[string]any{"enabled": true, "next_run": next}, func(w io.Writer) {
 85		fmt.Fprintf(w, "code scanning enabled on %s; first scan %s\n", repo.Path(), next)
 86	})
 87}
 88
 89func runSecurityDisable(c *Ctx, args []string) int {
 90	if len(args) != 1 {
 91		return c.usage()
 92	}
 93	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
 94	if code >= 0 {
 95		return code
 96	}
 97	if err := c.Store.DisableSecurityScan(repo.ID); err != nil {
 98		return c.fail(protocol.ExitFailure, "%v", err)
 99	}
100	return c.emit(map[string]any{"enabled": false}, func(w io.Writer) {
101		fmt.Fprintf(w, "code scanning disabled on %s\n", repo.Path())
102	})
103}
104
105func runSecurityRun(c *Ctx, args []string) int {
106	if len(args) != 1 {
107		return c.usage()
108	}
109	repo, code := resolveRepo(c, args[0], policy.CanAdmin)
110	if code >= 0 {
111		return code
112	}
113	if _, err := c.Store.SecurityScanFor(repo.ID); errors.Is(err, store.ErrNotFound) {
114		return c.fail(protocol.ExitFailure, "code scanning is off on %s (repo security enable %s)", repo.Path(), repo.Path())
115	} else if err != nil {
116		return c.fail(protocol.ExitFailure, "%v", err)
117	}
118	if c.Cfg.Security.Image == "" {
119		return c.fail(protocol.ExitFailure, "this instance has no code scanning image; an operator sets [security] image")
120	}
121	n, err := ci.QueueSecurityScan(c.Store, c.Cfg.Security, RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), repo)
122	if err != nil {
123		return c.fail(protocol.ExitFailure, "%v", err)
124	}
125	return c.emit(map[string]any{"build": n}, func(w io.Writer) {
126		fmt.Fprintf(w, "queued build %d: %s on %s\n", n, ci.SecurityJob, repo.Path())
127	})
128}
129
130func runSecurityStatus(c *Ctx, args []string) int {
131	if len(args) != 1 {
132		return c.usage()
133	}
134	repo, code := resolveRepo(c, args[0], policy.CanRead)
135	if code >= 0 {
136		return code
137	}
138	scan, err := c.Store.SecurityScanFor(repo.ID)
139	if errors.Is(err, store.ErrNotFound) {
140		return c.emitView(map[string]any{"enabled": false}, func(w io.Writer) {
141			c.view(w).fields("scanning", fmt.Sprintf("off (repo security enable %s)", repo.Path()))
142		}, func() screen {
143			return screen{
144				fields:  []field{{"Scanning", []cell{cText("off")}}},
145				actions: []action{{"Security", []string{"repo", "security", "enable", repo.Path()}}},
146			}
147		})
148	}
149	if err != nil {
150		return c.fail(protocol.ExitFailure, "%v", err)
151	}
152	reported, err := c.Store.ReportedFindings(repo.ID)
153	if err != nil {
154		return c.fail(protocol.ExitFailure, "%v", err)
155	}
156	out := SecurityOut{Enabled: true, NextRun: scan.NextRun, LastResults: scan.LastResults,
157		IssueNumber: scan.IssueNumber, Findings: []SecurityFinding{}}
158	for _, f := range reported {
159		out.Findings = append(out.Findings, SecurityFinding{f.Tool, f.Rule, f.Level, f.Path, f.Line, f.Message})
160	}
161	return c.emitView(out, func(w io.Writer) {
162		tracked := ""
163		if scan.IssueNumber != 0 {
164			tracked = fmt.Sprintf("#%d", scan.IssueNumber)
165		}
166		v := c.view(w)
167		v.fields(
168			"scanning", "on",
169			"next scan", scan.NextRun,
170			"last results", c.when(scan.LastResults),
171			"tracked in", tracked,
172		)
173		if len(out.Findings) > 0 {
174			v.section("findings")
175			tb := c.table(w, "TOOL", "RULE", "LEVEL", "PATH", "LINE")
176			for _, f := range out.Findings {
177				tb.row(cText(f.Tool), cText(f.Rule), cText(f.Level), cRef(f.Path), cNum(int64(f.Line)))
178			}
179			tb.flush()
180		}
181	}, func() screen {
182		s := screen{fields: []field{
183			{"Scanning", []cell{cGlyph("ok"), cText("on")}},
184			{"Next scan", []cell{cText(scan.NextRun)}},
185			{"Last results", []cell{cAge(scan.LastResults)}},
186		}}
187		if scan.IssueNumber != 0 {
188			n := strconv.FormatInt(scan.IssueNumber, 10)
189			s.fields = append(s.fields, field{"Tracked in", []cell{cLink("#"+n, c.siteURL(repo.Path(), "issues", n))}})
190		}
191		found := section{title: "Findings", n: len(out.Findings)}
192		for _, f := range out.Findings {
193			found.rows = append(found.rows, rowOf(cRef(f.Path+":"+strconv.Itoa(f.Line)), cText(f.Rule), cMeta(f.Level)))
194		}
195		s.sections = []section{found}
196		s.actions = []action{{"Security", []string{"repo", "security", "run", repo.Path()}}}
197		return s
198	})
199}
200
201// runRunnerResults takes a security build's SARIF from the runner that
202// claimed it, replaces the repository's findings with it, and brings the
203// findings issue in line. Only the instance's own job may upload: its
204// steps are the operator's, where any other job's are the repository's.
205func runRunnerResults(c *Ctx, args []string) int {
206	key, code := runnerSession(c)
207	if code >= 0 {
208		return code
209	}
210	if len(args) != 1 {
211		return c.usage()
212	}
213	id, err := strconv.ParseInt(args[0], 10, 64)
214	if err != nil {
215		return c.fail(protocol.ExitUsage, "bad build id %q", args[0])
216	}
217	b, err := c.Store.BuildByID(id)
218	if err != nil {
219		return c.fail(protocol.ExitNotFound, "no build %d", id)
220	}
221	if ok, err := runnerMayBuild(c, key, b.RepoID); err != nil {
222		return c.fail(protocol.ExitFailure, "%v", err)
223	} else if !ok {
224		return c.fail(protocol.ExitDenied, "this key is not attached to the build's repository; a repository admin attaches it with repo runner add")
225	}
226	if b.Job != ci.SecurityJob {
227		return c.fail(protocol.ExitDenied, "results are accepted from the %s job only", ci.SecurityJob)
228	}
229	if b.Status != "running" {
230		return c.fail(protocol.ExitFailure, "build %d is %s", id, b.Status)
231	}
232	scan, err := c.Store.SecurityScanFor(b.RepoID)
233	if errors.Is(err, store.ErrNotFound) {
234		// Disabled while the build ran: nothing to report into.
235		return c.emit(map[string]any{"findings": 0}, func(w io.Writer) {})
236	}
237	if err != nil {
238		return c.fail(protocol.ExitFailure, "%v", err)
239	}
240	raw, err := io.ReadAll(io.LimitReader(c.Stdin, codescan.MaxUpload+1))
241	if err != nil {
242		return c.fail(protocol.ExitFailure, "reading results: %v", err)
243	}
244	if len(raw) > codescan.MaxUpload {
245		return c.fail(protocol.ExitFailure, "results are over %d bytes", codescan.MaxUpload)
246	}
247	findings, truncated, err := codescan.Parse(raw)
248	if err != nil {
249		return c.fail(protocol.ExitFailure, "%v", err)
250	}
251	repo, err := c.Store.RepoByID(b.RepoID)
252	if err != nil {
253		return c.fail(protocol.ExitFailure, "%v", err)
254	}
255	previous, err := c.Store.ReportedFindings(repo.ID)
256	if err != nil {
257		return c.fail(protocol.ExitFailure, "%v", err)
258	}
259	err = botissue.Maintain(c.Store, c.Cfg, repo, botissue.Tracked{
260		Title:   codescan.IssueTitle,
261		Number:  scan.IssueNumber,
262		Record:  func(n int64) error { return c.Store.SetSecurityIssue(repo.ID, n) },
263		Empty:   len(findings) == 0,
264		Changed: !codescan.Same(previous, codescan.ByFingerprint(findings)),
265		Save:    func() error { return c.Store.ReplaceFindings(repo.ID, findings) },
266		Body:    func() string { return codescan.Body(repo.DefaultBranch, findings, truncated) },
267	})
268	if err != nil {
269		return c.fail(protocol.ExitFailure, "%v", err)
270	}
271	// Stamped whether or not the set changed: the status says when results
272	// last arrived.
273	if err := c.Store.StampSecurityResults(repo.ID); err != nil {
274		return c.fail(protocol.ExitFailure, "%v", err)
275	}
276	return c.emit(map[string]any{"findings": len(findings), "truncated": truncated}, func(w io.Writer) {
277		fmt.Fprintf(w, "%d findings recorded for build %d\n", len(findings), b.Number)
278	})
279}