internal/control/secretscan.go
159 lines · 5607 bytes
8 symbols in this file
1package control
2
3import (
4 "context"
5 "fmt"
6 "io"
7 "slices"
8 "strconv"
9 "strings"
10 "time"
11
12 "gitbay.org/gitbay/internal/leaks"
13 "gitbay.org/gitbay/internal/policy"
14 "gitbay.org/gitbay/internal/protocol"
15 "gitbay.org/gitbay/internal/store"
16)
17
18func init() {
19 // The push-time scan runs in pre-receive (internal/hookd); these set
20 // what it does and scan what is already in the history.
21 register(Command{Path: []string{"repo", "settings", "secret-scan"},
22 Summary: "scan pushes for credentials: off, warn the pusher, or block the push",
23 Usage: "repo settings secret-scan <owner/name> off|warn|block",
24 Examples: []string{"repo settings secret-scan krz/gitbay block"},
25 Run: runSecretScanMode})
26 register(Command{Path: []string{"repo", "settings", "secret-scan-allow"},
27 Summary: "paths whose secret scan findings are ignored",
28 Usage: "repo settings secret-scan-allow <owner/name> [<glob>...] (none clears the list)",
29 Examples: []string{"repo settings secret-scan-allow krz/gitbay 'testdata/**' internal/mailin/dkim_test.go"},
30 Run: runSecretScanAllow})
31 register(Command{Path: []string{"repo", "secret-scan"},
32 Summary: "scan the whole history for credentials",
33 Usage: "repo secret-scan <owner/name>",
34 Examples: []string{"repo secret-scan krz/gitbay"},
35 ReadOnly: true, Run: runSecretScanHistory})
36}
37
38// maxSecretScanAllow bounds the allowlist, as maxRequiredContexts bounds
39// the contexts.
40const maxSecretScanAllow = 50
41
42func runSecretScanMode(c *Ctx, args []string) int {
43 if len(args) != 2 || !slices.Contains([]string{leaks.ModeOff, leaks.ModeWarn, leaks.ModeBlock}, args[1]) {
44 return c.usage()
45 }
46 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
47 if code >= 0 {
48 return code
49 }
50 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.SecretScan = args[1] })
51 if err != nil {
52 return c.fail(protocol.ExitFailure, "%v", err)
53 }
54 return c.emit(s, func(w io.Writer) {
55 fmt.Fprintf(w, "secret_scan %s on %s\n", args[1], repo.Path())
56 })
57}
58
59func runSecretScanAllow(c *Ctx, args []string) int {
60 if len(args) < 1 {
61 return c.usage()
62 }
63 var globs []string
64 for _, g := range args[1:] {
65 if g == "" || len(g) > 200 || strings.ContainsAny(g, "\t\r\n") {
66 return c.fail(protocol.ExitUsage, "a glob is 1 to 200 characters on one line: %q", g)
67 }
68 if !slices.Contains(globs, g) {
69 globs = append(globs, g)
70 }
71 }
72 if len(globs) > maxSecretScanAllow {
73 return c.fail(protocol.ExitUsage, "at most %d allowed paths", maxSecretScanAllow)
74 }
75 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
76 if code >= 0 {
77 return code
78 }
79 s, err := c.Store.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.SecretScanAllow = globs })
80 if err != nil {
81 return c.fail(protocol.ExitFailure, "%v", err)
82 }
83 return c.emit(s, func(w io.Writer) {
84 if len(globs) == 0 {
85 fmt.Fprintf(w, "secret scan allowlist cleared on %s\n", repo.Path())
86 return
87 }
88 fmt.Fprintf(w, "secret scan allows on %s: %s\n", repo.Path(), strings.Join(globs, ", "))
89 })
90}
91
92// historyScanDeadline bounds a history scan, which runs while the caller
93// waits on the session.
94const historyScanDeadline = 2 * time.Minute
95
96// SecretScanOut is what `repo secret-scan` emits.
97type SecretScanOut struct {
98 Findings []leaks.Finding `json:"findings"`
99 Blobs int `json:"blobs"`
100 Truncated bool `json:"truncated"`
101}
102
103// runSecretScanHistory scans every blob reachable from any ref, for what
104// arrived before the push-time scan or never passed through it: imports,
105// pull mirrors, and server-side writes. Admin only, since a scan reads up
106// to leaks.MaxScanBytes and a reader could otherwise ask for one on every
107// call. The allowlist applies, as it does at push time.
108func runSecretScanHistory(c *Ctx, args []string) int {
109 if len(args) != 1 {
110 return c.usage()
111 }
112 repo, code := resolveRepo(c, args[0], policy.CanAdmin)
113 if code >= 0 {
114 return code
115 }
116 ctx, cancel := context.WithTimeout(context.Background(), historyScanDeadline)
117 defer cancel()
118 rep := leaks.Scan(ctx, RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name), "--all")
119 if rep.Error != "" {
120 return c.fail(protocol.ExitFailure, "secret scan: %s", rep.Error)
121 }
122 out := SecretScanOut{Findings: leaks.Allowed(rep.Findings, repo.Settings.SecretScanAllow),
123 Blobs: rep.Blobs, Truncated: rep.Truncated}
124 if out.Findings == nil {
125 out.Findings = []leaks.Finding{}
126 }
127 return c.emitView(out, func(w io.Writer) {
128 v := c.view(w)
129 v.fields(
130 "blobs", strconv.Itoa(out.Blobs),
131 "findings", strconv.Itoa(len(out.Findings)),
132 "truncated", strconv.FormatBool(out.Truncated),
133 )
134 if len(out.Findings) > 0 {
135 tb := c.table(w, "COMMIT", "PATH", "LINE", "RULE")
136 for _, f := range out.Findings {
137 tb.row(cText(shortCommit(f.Commit)), cRef(f.Path), cNum(int64(f.Line)), cText(f.Rule))
138 }
139 tb.flush()
140 }
141 }, func() screen {
142 s := screen{fields: []field{
143 {"Repo", []cell{cLink(repo.Path(), c.siteURL(repo.Path()))}},
144 {"Blobs", []cell{cText(strconv.Itoa(out.Blobs))}},
145 }}
146 if out.Truncated {
147 s.fields = append(s.fields, field{"Truncated", []cell{cMark("stopped at the size limit", sgrRed)}})
148 }
149 found := section{title: "Findings", n: len(out.Findings)}
150 for _, f := range out.Findings {
151 found.rows = append(found.rows, rowOf(cRef(f.Path+":"+strconv.Itoa(f.Line)), cText(f.Rule), cMeta(shortCommit(f.Commit))))
152 }
153 s.sections = []section{found}
154 s.actions = []action{{"Settings", []string{"repo", "settings", "secret-scan-allow", repo.Path(), "<glob>"}}}
155 return s
156 })
157}
158
159func shortCommit(sha string) string { return sha[:min(len(sha), 10)] }