Commit 4158ea427f

4158ea427f526c90111f5cb0745c17976c6b7843

parent: a30ca59fb3

Verified · cmc ci/build: success ci/quality: success ci/test: success

cmc <hello@cleberg.net> · 2026-10-31 06:37 UTC

Scan pushes for credentials

pre-receive gains a phase after signature checks: the daemon asks, the
hook scans the blobs the push adds or changes (still in quarantine) and
answers with commit, path, line and rule for each match, never the
value. internal/leaks holds the rules (self-identifying token formats
and private key blocks) and the bounded git log --raw / cat-file scan.

repo settings secret-scan <repo> off|warn|block, default warn: warn
accepts and prints the findings for the pusher and audits push.secrets;
block refuses, including a scan that failed. repo settings
secret-scan-allow takes CI path globs whose findings are ignored.
repo secret-scan scans every ref for content that never passed through
a push. Settings page and repo settings show carry both settings.

No new module dependencies: the rules are in-tree rather than the
gitleaks library, which brings about 65 modules including a WebAssembly
regex engine into the hook process.

Closes #339

Layout: unified · split

.gitbay/wiki/Architecture/02-Components.org +2 −1
@@ -36,7 +36,8 @@ the hidden =hook= used by git (=cmd/gitbayd/main.go=,
3636| =internal/notify=, =internal/mail= | Mail queue drain and SMTP. |
3737| =internal/push= | APNs queue drain and provider-token signing. |
3838| =internal/mailin=, =internal/imapc=, =internal/mailreply= | Reply by mail: the IMAP client, the reply token, and the processor that posts a reply through =issue comment= / =mr comment=. |
39| =internal/deps= | Dependency manifest parsing and registry checks (opt-in per repository). |
39| =internal/deps= | Dependency manifest and lockfile parsing; registry and OSV checks (opt-in per repository). |
40| =internal/leaks= | Credential rules and the blob scan pre-receive and =repo secret-scan= run. |
4041| =internal/config= | Configuration load and validation. |
4142| =internal/web= | Embedded templates, stylesheet and fonts. |
4243| =internal/protocol= | Exit codes, JSON envelope, argv tokenizer. |
.gitbay/wiki/Parity.org +2
@@ -243,6 +243,8 @@ there shows the app's rendering rather than the one the web page shows.
243243| build trigger | yes | yes | yes |
244244| build cancel | yes | yes | yes |
245245| job image (ci.yml) | yes | n/a | n/a |
246| secret scan mode, allowlist | yes | yes | yes |
247| secret scan of the history | yes | no | yes |
246248| dependency checks on/off | yes | yes | yes |
247249| dependency status | yes | yes | yes |
248250| delete, transfer | yes | yes | yes |
.gitbay/wiki/Users.org +18
@@ -238,6 +238,9 @@ gitbay repo settings require-mr you/project on # protected branches: merge
238238gitbay repo settings protect-tag you/project 'v*' # matching tags: created once, never moved or deleted
239239gitbay repo settings default-branch you/project trunk # HEAD, and what the web shows
240240gitbay repo settings require-signed you/project on # every commit must verify
241gitbay repo settings secret-scan you/project block # off | warn (default) | block
242gitbay repo settings secret-scan-allow you/project 'testdata/**' # paths whose findings are ignored
243gitbay repo secret-scan you/project # scan the whole history
241244gitbay repo settings git-daemon you/project on # expose over git://
242245gitbay repo topics add you/project cli forge # free-form tags, shown on the web
243246gitbay repo search forge # find repos by name/description/topic
@@ -249,6 +252,21 @@ gitbay repo archive you/project # read-only: pushes and issu
249252gitbay repo unarchive you/project # writes refused, browsing intact
250253#+end_src
251254
255Every push is scanned for credentials in formats that identify
256themselves: private key blocks, cloud and forge tokens with a vendor
257prefix (AWS, GitHub, GitLab, gitbay, Slack, Stripe, Google, npm, PyPI,
258OpenAI, Anthropic, SendGrid, DigitalOcean, Shopify), and age secret
259keys. The pre-receive hook reads the files the push adds or changes
260and reports the commit, path, line and kind of each match, never the
261value. Under =warn=, the default, the push is accepted and the pusher
262sees where; the finding is recorded in the audit log. Under =block= the
263push is refused, and so is a push the scan could not complete. A scan
264reads at most 64 MiB, skips files over 1 MiB and binary files, and
265stops after 90 seconds; a scan cut short says so. Merge commits are not
266diffed. Content that does not pass through a push — =repo import=, pull
267mirrors, the web editor, applied suggestions — is covered only by
268=repo secret-scan=, which an admin runs over every ref.
269
252270A push to the default branch queues a symbol index of its tree, built in
253271the background after the push completes; a tree that is already indexed
254272is not indexed again. =repo symbols <owner/name> [--kind k] <query>=
cmd/gitbay/main.go +4 −1
@@ -596,7 +596,8 @@ func repoCmd() *cobra.Command {
596596 pass("remove", passOpts{server: []string{"repo", "mirror", "remove"}, needsRepo: true}),
597597 pass("sync", passOpts{server: []string{"repo", "mirror", "sync"}, needsRepo: true}),
598598 ),
599 group("deps", "check dependencies against upstream registries",
599 pass("secret-scan", passOpts{server: []string{"repo", "secret-scan"}, needsRepo: true}),
600 group("deps", "check dependencies against upstream registries and OSV",
600601 pass("enable", passOpts{server: []string{"repo", "deps", "enable"}, needsRepo: true}),
601602 pass("disable", passOpts{server: []string{"repo", "deps", "disable"}, needsRepo: true}),
602603 pass("status", passOpts{server: []string{"repo", "deps", "status"}, needsRepo: true}),
@@ -636,6 +637,8 @@ func repoCmd() *cobra.Command {
636637 pass("require-contexts", passOpts{server: []string{"repo", "settings", "require-contexts"}, needsRepo: true}),
637638 pass("visibility", passOpts{server: []string{"repo", "settings", "visibility"}, needsRepo: true}),
638639 pass("require-signed", passOpts{server: []string{"repo", "settings", "require-signed"}, needsRepo: true}),
640 pass("secret-scan", passOpts{server: []string{"repo", "settings", "secret-scan"}, needsRepo: true}),
641 pass("secret-scan-allow", passOpts{server: []string{"repo", "settings", "secret-scan-allow"}, needsRepo: true}),
639642 pass("require-mr", passOpts{server: []string{"repo", "settings", "require-mr"}, needsRepo: true}),
640643 pass("description", passOpts{server: []string{"repo", "settings", "description"}, needsRepo: true}),
641644 pass("website", passOpts{server: []string{"repo", "settings", "website"}, needsRepo: true}),
cmd/gitbay/summaries_gen.go +3
@@ -196,6 +196,7 @@ var summaries = map[string]string{
196196 "repo secret list": "list build secret names",
197197 "repo secret remove": "remove a build secret",
198198 "repo secret set": "set a build secret",
199 "repo secret-scan": "scan the whole history for credentials",
199200 "repo settings default-branch": "set the default branch",
200201 "repo settings description": "set the repository description",
201202 "repo settings git-daemon": "expose over git://",
@@ -208,6 +209,8 @@ var summaries = map[string]string{
208209 "repo settings require-mr": "protected branches take changes through merge requests only",
209210 "repo settings require-resolved": "require all review threads resolved to merge",
210211 "repo settings require-signed": "require verified commit signatures",
212 "repo settings secret-scan": "scan pushes for credentials: off, warn the pusher, or block the push",
213 "repo settings secret-scan-allow": "paths whose secret scan findings are ignored",
211214 "repo settings show": "show settings",
212215 "repo settings unprotect": "unprotect a branch",
213216 "repo settings unprotect-tag": "drop a protected-tag glob",
cmd/gitbayd/hook.go +28
@@ -9,11 +9,13 @@ import (
99 "os/exec"
1010 "strconv"
1111 "strings"
12 "time"
1213
1314 "github.com/spf13/cobra"
1415
1516 "gitbay.org/gitbay/internal/gitutil"
1617 "gitbay.org/gitbay/internal/hookd"
18 "gitbay.org/gitbay/internal/leaks"
1719 "gitbay.org/gitbay/internal/policy"
1820 "gitbay.org/gitbay/internal/toolpath"
1921)
@@ -129,6 +131,27 @@ func streamIncomingCommits(updates []policy.RefUpdate, emit func(hookd.RawCommit
129131 return nil
130132}
131133
134// scanDeadline bounds the secret scan of one push. Past it the scan is
135// reported as truncated: the pusher is waiting.
136const scanDeadline = 90 * time.Second
137
138// scanIncoming scans the blobs this push introduces. Like incomingSHAs it
139// runs in the hook process, the only one that can read the quarantine.
140func scanIncoming(updates []policy.RefUpdate) leaks.Report {
141 var revs []string
142 for _, u := range updates {
143 if !u.IsDelete {
144 revs = append(revs, u.New)
145 }
146 }
147 if len(revs) == 0 {
148 return leaks.Report{}
149 }
150 ctx, cancel := context.WithTimeout(context.Background(), scanDeadline)
151 defer cancel()
152 return leaks.Scan(ctx, ".", append(revs, "--not", "--all")...)
153}
154
132155// hookCmd runs inside a git hook. It computes git facts here — the hook
133156// process inherits git's quarantine environment, so incoming objects are
134157// visible — and asks the daemon for a policy decision over the unix socket.
@@ -176,6 +199,8 @@ func hookCmd() *cobra.Command {
176199 Updates: updates,
177200 }, func(emit func(hookd.RawCommit) error) error {
178201 return streamIncomingCommits(updates, emit)
202 }, func() leaks.Report {
203 return scanIncoming(updates)
179204 })
180205 if err != nil {
181206 return fmt.Errorf("gitbay daemon unreachable: %w", err)
@@ -184,6 +209,9 @@ func hookCmd() *cobra.Command {
184209 fmt.Fprintln(os.Stderr, resp.Message)
185210 os.Exit(1)
186211 }
212 if resp.Message != "" {
213 fmt.Fprintln(os.Stderr, resp.Message)
214 }
187215 return nil
188216 },
189217 }
e2e/readonly_test.go +1
@@ -142,6 +142,7 @@ func TestReadOnlyCommandsWriteNothing(t *testing.T) {
142142 "repo mirror list": {"alice/app"},
143143 "repo domain list": {"alice/app"},
144144 "repo deps status": {"alice/app"},
145 "repo secret-scan": {"alice/app"},
145146 "status list": {"alice/app", sha},
146147 "issue list": {"alice/app"},
147148 "issue show": {"alice/app", "1"},
e2e/secretscan_test.go added +68
@@ -0,0 +1,68 @@
1package e2e
2
3import (
4 "os"
5 "path/filepath"
6 "strings"
7 "testing"
8)
9
10// The push-time secret scan runs in the real pre-receive hook, against
11// objects still in quarantine: warn accepts and tells the pusher where,
12// block refuses, and an allowed path is let through (#339).
13func TestSecretScanOnPush(t *testing.T) {
14 t.Parallel()
15 inst := startInstance(t)
16 aliceKey := inst.newKey(t, "alice")
17 inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub")
18 if _, errOut, code := inst.ssh(t, aliceKey, "", "repo", "create", "alice/app"); code != 0 {
19 t.Fatalf("repo create: %s", errOut)
20 }
21 work := t.TempDir()
22 env := inst.gitEnv(aliceKey)
23 mustGit(t, work, env, "clone", "-q", inst.sshURL("alice/app"), "w")
24 dir := filepath.Join(work, "w")
25 mustGit(t, dir, env, "checkout", "-q", "-b", "main")
26 write := func(name, body string) {
27 t.Helper()
28 p := filepath.Join(dir, name)
29 os.MkdirAll(filepath.Dir(p), 0o755)
30 if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
31 t.Fatal(err)
32 }
33 mustGit(t, dir, env, "add", ".")
34 mustGit(t, dir, env, "commit", "-q", "-m", name)
35 }
36 // Assembled, so this file is not itself a finding.
37 token := "gh" + "p_" + strings.Repeat("aB3dE5", 6)
38
39 write("README.md", "# app\n")
40 write("deploy.env", "x=1\nGITHUB_TOKEN="+token+"\n")
41 out, code := gitRun(t, dir, env, "push", "origin", "main")
42 if code != 0 || !strings.Contains(out, "deploy.env:2 github-token") || !strings.Contains(out, "the push was accepted") {
43 t.Fatalf("warn: %d\n%s", code, out)
44 }
45 if strings.Contains(out, token) {
46 t.Fatalf("push output carries the token:\n%s", out)
47 }
48
49 if _, errOut, code := inst.ssh(t, aliceKey, "", "repo", "settings", "secret-scan", "alice/app", "block"); code != 0 {
50 t.Fatalf("secret-scan block: %s", errOut)
51 }
52 write("testdata/fixture.env", token+"\n")
53 if out, code := gitRun(t, dir, env, "push", "origin", "main"); code == 0 || !strings.Contains(out, "refused, 1 possible secret") {
54 t.Fatalf("block: %d\n%s", code, out)
55 }
56 if _, errOut, code := inst.ssh(t, aliceKey, "", "repo", "settings", "secret-scan-allow", "alice/app", "'testdata/**'"); code != 0 {
57 t.Fatalf("secret-scan-allow: %s", errOut)
58 }
59 if out, code := gitRun(t, dir, env, "push", "origin", "main"); code != 0 || strings.Contains(out, "secret scan") {
60 t.Fatalf("allowed path: %d\n%s", code, out)
61 }
62
63 // Everything already pushed is in the history scan, allowlist applied.
64 out, errOut, code := inst.ssh(t, aliceKey, "", "repo", "secret-scan", "alice/app", "--json")
65 if code != 0 || !strings.Contains(out, `"path":"deploy.env"`) || strings.Contains(out, "testdata/") {
66 t.Fatalf("history: %d %s\n%s", code, errOut, out)
67 }
68}
internal/control/repo.go +5
@@ -13,6 +13,7 @@ import (
1313
1414 "gitbay.org/gitbay/internal/backuplock"
1515 "gitbay.org/gitbay/internal/gitutil"
16 "gitbay.org/gitbay/internal/leaks"
1617 "gitbay.org/gitbay/internal/policy"
1718 "gitbay.org/gitbay/internal/protocol"
1819 "gitbay.org/gitbay/internal/store"
@@ -841,6 +842,8 @@ func runSettingsShow(c *Ctx, args []string) int {
841842 "require checks", strconv.FormatBool(repo.Settings.RequireChecks),
842843 "required contexts", strings.Join(repo.Settings.RequiredContexts, ", "),
843844 "require signed commits", strconv.FormatBool(repo.Settings.RequireSignedCommits),
845 "secret scan", leaks.Mode(repo.Settings.SecretScan),
846 "secret scan allow", strings.Join(repo.Settings.SecretScanAllow, ", "),
844847 "git daemon", strconv.FormatBool(repo.Settings.GitDaemon),
845848 "archived", strconv.FormatBool(repo.Settings.Archived),
846849 )
@@ -877,6 +880,8 @@ func runSettingsShow(c *Ctx, args []string) int {
877880 {"Resolved threads", []cell{onOff(set.RequireResolved)}},
878881 {"Code owners", []cell{onOff(set.RequireCodeowners)}},
879882 {"Signed commits", []cell{onOff(set.RequireSignedCommits)}},
883 {"Secret scan", []cell{cText(leaks.Mode(set.SecretScan))}},
884 {"Scan allows", []cell{list(set.SecretScanAllow)}},
880885 {"Git daemon", []cell{onOff(set.GitDaemon)}},
881886 {"Archived", []cell{onOff(set.Archived)}},
882887 }, actions: []action{
internal/control/secretscan.go added +159
@@ -0,0 +1,159 @@
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)] }
internal/control/secretscan_test.go added +82
@@ -0,0 +1,82 @@
1package control
2
3import (
4 "encoding/json"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10
11 "gitbay.org/gitbay/internal/store"
12)
13
14func TestSecretScanSettings(t *testing.T) {
15 st, repo, u, root := browseFixture(t)
16 p := repo.Path()
17 dispatchIn(t, st, u, root, "", "repo", "settings", "secret-scan", p, "block")
18 dispatchIn(t, st, u, root, "", "repo", "settings", "secret-scan-allow", p, "testdata/**", "*.pem", "*.pem")
19 got, err := st.RepoByID(repo.ID)
20 if err != nil {
21 t.Fatal(err)
22 }
23 if got.Settings.SecretScan != "block" || strings.Join(got.Settings.SecretScanAllow, " ") != "testdata/** *.pem" {
24 t.Fatalf("settings = %+v", got.Settings)
25 }
26 show := dispatchIn(t, st, u, root, "", "repo", "settings", "show", p)
27 if !strings.Contains(show, "secret scan block") || !strings.Contains(show, "testdata/**, *.pem") {
28 t.Errorf("show:\n%s", show)
29 }
30 dispatchIn(t, st, u, root, "", "repo", "settings", "secret-scan-allow", p)
31 if got, _ := st.RepoByID(repo.ID); len(got.Settings.SecretScanAllow) != 0 {
32 t.Errorf("allowlist not cleared: %v", got.Settings.SecretScanAllow)
33 }
34}
35
36func TestSecretScanHistory(t *testing.T) {
37 st, repo, u, root := browseFixture(t)
38 p := repo.Path()
39 src, dir := filepath.Join(root, "src"), RepoDir(root, repo.OwnerName, repo.Name)
40 git := func(dir string, args ...string) {
41 t.Helper()
42 cmd := exec.Command("git", args...)
43 cmd.Dir, cmd.Env = dir, gitTestEnv()
44 if out, err := cmd.CombinedOutput(); err != nil {
45 t.Fatalf("git %v: %v\n%s", args, err, out)
46 }
47 }
48 // Assembled, so this file is not itself a finding.
49 token := "gh" + "p_" + strings.Repeat("aB3dE5", 6)
50 os.MkdirAll(filepath.Join(src, "testdata"), 0o755)
51 os.WriteFile(filepath.Join(src, "deploy.env"), []byte("# deploy\nGITHUB_TOKEN="+token+"\n"), 0o644)
52 os.WriteFile(filepath.Join(src, "testdata", "fixture.env"), []byte(token+"\n"), 0o644)
53 git(src, "add", ".")
54 git(src, "commit", "-q", "-m", "config")
55 git(dir, "fetch", "-q", src, "main:main")
56
57 var got struct {
58 Data SecretScanOut `json:"data"`
59 }
60 if err := json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "secret-scan", p, "--json")), &got); err != nil {
61 t.Fatal(err)
62 }
63 if len(got.Data.Findings) != 2 || got.Data.Findings[0].Path != "deploy.env" || got.Data.Findings[0].Line != 2 {
64 t.Fatalf("findings = %+v", got.Data.Findings)
65 }
66 if out := dispatchIn(t, st, u, root, "", "repo", "secret-scan", p, "--json"); strings.Contains(out, token) {
67 t.Error("output carries the matched value")
68 }
69
70 if _, err := st.UpdateRepoSettings(repo.ID, func(s *store.RepoSettings) { s.SecretScanAllow = []string{"testdata/**"} }); err != nil {
71 t.Fatal(err)
72 }
73 plain := dispatchIn(t, st, u, root, "", "repo", "secret-scan", p)
74 if !strings.Contains(plain, "findings 1") || strings.Contains(plain, "testdata/") {
75 t.Errorf("allowlisted plain:\n%s", plain)
76 }
77 out := atTerminalIn(t, st, u, root, "repo", "secret-scan", p)
78 if !strings.Contains(out, "Findings (1)") || !strings.Contains(out, "deploy.env:2") {
79 t.Errorf("screen:\n%s", out)
80 }
81 checkLegend(t, out)
82}
internal/control/testdata/plain/repo-settings-show.txt +1
@@ -3,5 +3,6 @@ alice/app settings
33 require mr false
44 require checks false
55 require signed commits false
6 secret scan warn
67 git daemon false
78 archived false
internal/hookd/hookd.go +103 −26
@@ -6,6 +6,10 @@
66// pre-receive is two-phase when the repo requires signed commits: the first
77// response sets NeedCommits, and the hook answers with the raw commit
88// objects (only the hook can read them out of quarantine) for verification.
9// A further phase follows when the repo's secret scan is on: the response
10// sets ScanSecrets, the hook scans the incoming blobs and answers with a
11// leaks.Report — where each match is, never what it matched — and the
12// daemon decides what the findings mean for the push.
913package hookd
1014
1115import (
@@ -16,12 +20,14 @@ import (
1620 "net"
1721 "os"
1822 "path/filepath"
23 "slices"
1924 "strings"
2025 "sync"
2126
2227 "gitbay.org/gitbay/internal/config"
2328 "gitbay.org/gitbay/internal/control"
2429 "gitbay.org/gitbay/internal/gitutil"
30 "gitbay.org/gitbay/internal/leaks"
2531 "gitbay.org/gitbay/internal/policy"
2632 "gitbay.org/gitbay/internal/sig"
2733 "gitbay.org/gitbay/internal/store"
@@ -64,10 +70,13 @@ type RawCommit struct {
6470// Done marks the end of the commit stream.
6571func (c RawCommit) Done() bool { return c.SHA == "" }
6672
73// Response is the daemon's answer. A Message on an allowed push is a
74// warning the hook prints for the pusher.
6775type Response struct {
6876 Allow bool `json:"allow"`
6977 Message string `json:"message,omitempty"`
7078 NeedCommits bool `json:"need_commits,omitempty"`
79 ScanSecrets bool `json:"scan_secrets,omitempty"`
7180}
7281
7382// SocketPath returns the hook socket location. It prefers the server root,
@@ -204,14 +213,41 @@ func (s *Server) preReceive(req Request, dec *json.Decoder, enc *json.Encoder) {
204213 s.refusePush(enc, req, repo, msg)
205214 return
206215 }
207 if !repo.Settings.RequireSignedCommits {
208 enc.Encode(Response{Allow: true})
209 return
216 if repo.Settings.RequireSignedCommits {
217 if msg, ok := s.verifyIncoming(dec, enc); !ok {
218 return
219 } else if msg != "" {
220 s.refusePush(enc, req, repo, msg)
221 return
222 }
223 }
224 warning := ""
225 if leaks.Mode(repo.Settings.SecretScan) != leaks.ModeOff {
226 if err := enc.Encode(Response{Allow: true, ScanSecrets: true}); err != nil {
227 return
228 }
229 var rep leaks.Report
230 if err := dec.Decode(&rep); err != nil {
231 enc.Encode(Response{Allow: false, Message: "bad secret scan payload"})
232 return
233 }
234 msg, refuse := s.judgeSecrets(req, repo, rep)
235 if refuse {
236 s.refusePush(enc, req, repo, msg)
237 return
238 }
239 warning = msg
210240 }
241 enc.Encode(Response{Allow: true, Message: warning})
242}
211243
212 // Phase two: ask the hook for the incoming commit objects.
244// verifyIncoming is the signed-commits phase: it asks the hook for the
245// incoming commit objects and verifies each. ok is false when the exchange
246// itself failed and has been answered; otherwise msg is the refusal, or ""
247// when every commit verified.
248func (s *Server) verifyIncoming(dec *json.Decoder, enc *json.Encoder) (msg string, ok bool) {
213249 if err := enc.Encode(Response{Allow: true, NeedCommits: true}); err != nil {
214 return
250 return "", false
215251 }
216252 // Each commit is verified as it arrives, so nothing holds the push in
217253 // memory. The first refusal decides the answer, but the stream is
@@ -224,7 +260,7 @@ func (s *Server) preReceive(req Request, dec *json.Decoder, enc *json.Encoder) {
224260 var rc RawCommit
225261 if err := dec.Decode(&rc); err != nil {
226262 enc.Encode(Response{Allow: false, Message: "bad commits payload"})
227 return
263 return "", false
228264 }
229265 if rc.Done() {
230266 break
@@ -246,11 +282,45 @@ func (s *Server) preReceive(req Request, dec *json.Decoder, enc *json.Encoder) {
246282 refusal = fmt.Sprintf("this repository requires signed commits: %.10s is %s", rc.SHA, state)
247283 }
248284 }
249 if refusal != "" {
250 s.refusePush(enc, req, repo, refusal)
251 return
285 return refusal, true
286}
287
288// judgeSecrets applies the repository's mode and allowlist to the hook's
289// scan. It returns the message for the pusher, and whether the push is
290// refused. A scan that failed refuses under block, since block promises
291// nothing unscanned lands, and warns under warn. Accepted findings are
292// audited, so they are on record after the warning scrolls away.
293func (s *Server) judgeSecrets(req Request, repo store.Repo, rep leaks.Report) (string, bool) {
294 block := leaks.Mode(repo.Settings.SecretScan) == leaks.ModeBlock
295 if rep.Error != "" {
296 msg := "secret scan failed: " + rep.Error
297 if block {
298 return msg + "\nthis repository blocks pushes it cannot scan", true
299 }
300 return msg, false
301 }
302 found := leaks.Allowed(rep.Findings, repo.Settings.SecretScanAllow)
303 if len(found) == 0 {
304 return "", false
305 }
306 if block {
307 return leaks.Describe("secret scan: refused, "+leaks.Plural(len(found))+" in this push:", found, rep.Truncated) +
308 "\nremove them from the commits and push again; an admin can allow a path with" +
309 "\n repo settings secret-scan-allow " + repo.Path() + " <glob>...", true
310 }
311 rules := map[string]bool{}
312 for _, f := range found {
313 rules[f.Rule] = true
314 }
315 ruleList := make([]string, 0, len(rules))
316 for r := range rules {
317 ruleList = append(ruleList, r)
252318 }
253 enc.Encode(Response{Allow: true})
319 slices.Sort(ruleList)
320 s.st.Audit(req.UserID, "push.secrets", map[string]any{
321 "repo": repo.Path(), "findings": len(found), "rules": ruleList, "truncated": rep.Truncated})
322 return leaks.Describe("secret scan: "+leaks.Plural(len(found))+" in this push:", found, rep.Truncated) +
323 "\nthe push was accepted. A real credential is now in this repository's history: revoke it.", false
254324}
255325
256326// releaseAnchors refuses deleting or moving a tag that a release is
@@ -282,8 +352,9 @@ func (s *Server) postReceive(req Request) {
282352
283353// Ask sends one request from the hook process to the daemon. stream is
284354// called if the daemon asks for the incoming commit objects; it hands each
285// commit to the callback, which writes it on the wire.
286func Ask(socketPath string, req Request, stream func(emit func(RawCommit) error) error) (Response, error) {
355// commit to the callback, which writes it on the wire. scan is called if
356// the daemon asks for a secret scan of the incoming blobs.
357func Ask(socketPath string, req Request, stream func(emit func(RawCommit) error) error, scan func() leaks.Report) (Response, error) {
287358 conn, err := net.Dial("unix", socketPath)
288359 if err != nil {
289360 return Response{}, err
@@ -294,21 +365,27 @@ func Ask(socketPath string, req Request, stream func(emit func(RawCommit) error)
294365 if err := enc.Encode(req); err != nil {
295366 return Response{}, err
296367 }
297 var resp Response
298 if err := dec.Decode(&resp); err != nil {
299 return Response{}, err
300 }
301 if !resp.NeedCommits {
302 return resp, nil
303 }
304 if err := stream(func(rc RawCommit) error { return enc.Encode(rc) }); err != nil {
305 return Response{}, err
306 }
307 if err := enc.Encode(RawCommit{}); err != nil { // end of stream
308 return Response{}, err
368 for {
369 var resp Response
370 if err := dec.Decode(&resp); err != nil {
371 return Response{}, err
372 }
373 switch {
374 case resp.NeedCommits:
375 if err := stream(func(rc RawCommit) error { return enc.Encode(rc) }); err != nil {
376 return Response{}, err
377 }
378 if err := enc.Encode(RawCommit{}); err != nil { // end of stream
379 return Response{}, err
380 }
381 case resp.ScanSecrets:
382 if err := enc.Encode(scan()); err != nil {
383 return Response{}, err
384 }
385 default:
386 return resp, nil
387 }
309388 }
310 err = dec.Decode(&resp)
311 return resp, err
312389}
313390
314391// WriteHookScripts (re)generates the shared hooks directory. Called at
internal/hookd/secrets_test.go added +86
@@ -0,0 +1,86 @@
1package hookd
2
3import (
4 "strings"
5 "testing"
6
7 "gitbay.org/gitbay/internal/leaks"
8 "gitbay.org/gitbay/internal/policy"
9 "gitbay.org/gitbay/internal/store"
10)
11
12func noScan() leaks.Report { return leaks.Report{} }
13
14// The hook scans; the daemon decides. Each mode is the same scan answered
15// three ways, and the allowlist and a failed scan change the answer.
16func TestPreReceiveSecretScan(t *testing.T) {
17 sock, st, repoID, uid := serveSocket(t)
18 token, err := st.CreatePushToken(repoID, uid, "full")
19 if err != nil {
20 t.Fatal(err)
21 }
22 req := Request{Hook: "pre-receive", RepoID: repoID, UserID: uid, Scope: "full", Token: token,
23 Updates: []policy.RefUpdate{{Old: strings.Repeat("0", 40), New: strings.Repeat("a", 40), Ref: "refs/heads/main"}}}
24 finding := leaks.Report{Blobs: 3, Findings: []leaks.Finding{
25 {Commit: strings.Repeat("b", 40), Path: "config/prod.env", Line: 4, Rule: "aws-access-key-id"}}}
26 set := func(mode string, allow ...string) {
27 t.Helper()
28 if _, err := st.UpdateRepoSettings(repoID, func(s *store.RepoSettings) {
29 s.SecretScan, s.SecretScanAllow = mode, allow
30 }); err != nil {
31 t.Fatal(err)
32 }
33 }
34 ask := func(rep leaks.Report) (Response, bool) {
35 t.Helper()
36 scanned := false
37 resp, err := Ask(sock, req, nil, func() leaks.Report { scanned = true; return rep })
38 if err != nil {
39 t.Fatal(err)
40 }
41 return resp, scanned
42 }
43
44 // The default is warn: accepted, with the finding for the pusher.
45 resp, scanned := ask(finding)
46 if !scanned || !resp.Allow || !strings.Contains(resp.Message, "bbbbbbbbbb config/prod.env:4 aws-access-key-id") {
47 t.Fatalf("warn: scanned=%v %+v", scanned, resp)
48 }
49 if strings.Contains(resp.Message, "AKIA") {
50 t.Error("message carries a matched value")
51 }
52
53 set(leaks.ModeBlock)
54 if resp, _ := ask(finding); resp.Allow || !strings.Contains(resp.Message, "refused, 1 possible secret") {
55 t.Fatalf("block: %+v", resp)
56 }
57 if resp, _ := ask(leaks.Report{Error: "git log: exit 128"}); resp.Allow {
58 t.Fatalf("block on a failed scan: %+v", resp)
59 }
60 if resp, _ := ask(noScan()); !resp.Allow || resp.Message != "" {
61 t.Fatalf("block, clean: %+v", resp)
62 }
63
64 set(leaks.ModeBlock, "config/**")
65 if resp, _ := ask(finding); !resp.Allow || resp.Message != "" {
66 t.Fatalf("allowlisted: %+v", resp)
67 }
68
69 set(leaks.ModeWarn)
70 if resp, _ := ask(leaks.Report{Error: "git log: exit 128"}); !resp.Allow || !strings.Contains(resp.Message, "secret scan failed") {
71 t.Fatalf("warn on a failed scan: %+v", resp)
72 }
73
74 set(leaks.ModeOff)
75 if resp, scanned := ask(finding); scanned || !resp.Allow {
76 t.Fatalf("off: scanned=%v %+v", scanned, resp)
77 }
78
79 rows, err := st.AuditEntries(store.AuditFilter{ActionPrefix: "push.secrets", Limit: 10})
80 if err != nil {
81 t.Fatal(err)
82 }
83 if len(rows) != 1 {
84 t.Errorf("warned pushes audited %d times, want 1", len(rows))
85 }
86}
internal/hookd/socket_test.go +12 −12
@@ -59,7 +59,7 @@ func TestHookRequestNeedsItsPushToken(t *testing.T) {
5959 sock, st, repoID, uid := serveSocket(t)
6060 req := Request{Hook: "pre-receive", RepoID: repoID, UserID: uid, Scope: "full"}
6161
62 resp, err := Ask(sock, req, nil)
62 resp, err := Ask(sock, req, nil, noScan)
6363 if err != nil {
6464 t.Fatal(err)
6565 }
@@ -72,7 +72,7 @@ func TestHookRequestNeedsItsPushToken(t *testing.T) {
7272 t.Fatal(err)
7373 }
7474 req.Token = token
75 if resp, err = Ask(sock, req, nil); err != nil || !resp.Allow {
75 if resp, err = Ask(sock, req, nil, noScan); err != nil || !resp.Allow {
7676 t.Fatalf("with token: %+v, %v", resp, err)
7777 }
7878
@@ -82,7 +82,7 @@ func TestHookRequestNeedsItsPushToken(t *testing.T) {
8282 }
8383 forged := req
8484 forged.UserID = other
85 if resp, err = Ask(sock, forged, nil); err != nil || resp.Allow {
85 if resp, err = Ask(sock, forged, nil, noScan); err != nil || resp.Allow {
8686 t.Fatalf("token for another account: %+v, %v", resp, err)
8787 }
8888
@@ -92,20 +92,20 @@ func TestHookRequestNeedsItsPushToken(t *testing.T) {
9292 }
9393 forged = req
9494 forged.RepoID = otherRepo
95 if resp, err = Ask(sock, forged, nil); err != nil || resp.Allow {
95 if resp, err = Ask(sock, forged, nil, noScan); err != nil || resp.Allow {
9696 t.Fatalf("token for another repository: %+v, %v", resp, err)
9797 }
9898
9999 forged = req
100100 forged.Scope = "read"
101 if resp, err = Ask(sock, forged, nil); err != nil || resp.Allow {
101 if resp, err = Ask(sock, forged, nil, noScan); err != nil || resp.Allow {
102102 t.Fatalf("token for another scope: %+v, %v", resp, err)
103103 }
104104
105105 if err := st.DeletePushToken(token); err != nil {
106106 t.Fatal(err)
107107 }
108 if resp, err = Ask(sock, req, nil); err != nil || resp.Allow {
108 if resp, err = Ask(sock, req, nil, noScan); err != nil || resp.Allow {
109109 t.Fatalf("finished push: %+v, %v", resp, err)
110110 }
111111}
@@ -125,7 +125,7 @@ func TestHookRefusalsAreAudited(t *testing.T) {
125125 sock, st, repoID, uid := serveSocket(t)
126126
127127 forged := Request{Hook: "pre-receive", RepoID: repoID, UserID: uid, Scope: "full", Token: "not-a-live-token"}
128 if resp, err := Ask(sock, forged, nil); err != nil || resp.Allow {
128 if resp, err := Ask(sock, forged, nil, noScan); err != nil || resp.Allow {
129129 t.Fatalf("forged: %+v, %v", resp, err)
130130 }
131131 rows := refusedRows(t, st, "refused hook")
@@ -140,7 +140,7 @@ func TestHookRefusalsAreAudited(t *testing.T) {
140140 }
141141 req := Request{Hook: "pre-receive", RepoID: repoID, UserID: uid, Scope: "full", Token: token,
142142 Updates: []policy.RefUpdate{{Ref: "refs/merge-requests/1/head", Old: zeroSHA40, New: strings.Repeat("a", 40)}}}
143 if resp, err := Ask(sock, req, nil); err != nil || resp.Allow {
143 if resp, err := Ask(sock, req, nil, noScan); err != nil || resp.Allow {
144144 t.Fatalf("push to a server-owned ref: %+v, %v", resp, err)
145145 }
146146 rows = refusedRows(t, st, "refused push")
@@ -159,7 +159,7 @@ func TestPeerRefusalIsAudited(t *testing.T) {
159159 // The server answers and closes without reading the request, so the
160160 // client may see the refusal or a broken pipe; either way it is not
161161 // allowed, and the row is written before the connection closes.
162 if resp, err := Ask(sock, Request{Hook: "pre-receive", RepoID: repoID, UserID: uid}, nil); err == nil && resp.Allow {
162 if resp, err := Ask(sock, Request{Hook: "pre-receive", RepoID: repoID, UserID: uid}, nil, noScan); err == nil && resp.Allow {
163163 t.Fatalf("refused peer was allowed: %+v", resp)
164164 }
165165 rows := refusedRows(t, st, "refused hook")
@@ -181,7 +181,7 @@ func TestRefusedPushCapsRefs(t *testing.T) {
181181 req.Updates = append(req.Updates, policy.RefUpdate{Ref: fmt.Sprintf("refs/merge-requests/%d/head", i),
182182 Old: zeroSHA40, New: strings.Repeat("a", 40)})
183183 }
184 if resp, err := Ask(sock, req, nil); err != nil || resp.Allow {
184 if resp, err := Ask(sock, req, nil, noScan); err != nil || resp.Allow {
185185 t.Fatalf("push: %+v, %v", resp, err)
186186 }
187187 rows := refusedRows(t, st, "refused push")
@@ -211,7 +211,7 @@ func TestPreReceiveSignalsItsPush(t *testing.T) {
211211 started, forget := AwaitPreReceive(token)
212212 defer forget()
213213 forged := Request{Hook: "pre-receive", RepoID: repoID, UserID: uid, Scope: "read", Token: token}
214 if resp, err := Ask(sock, forged, nil); err != nil || resp.Allow {
214 if resp, err := Ask(sock, forged, nil, noScan); err != nil || resp.Allow {
215215 t.Fatalf("forged: %+v, %v", resp, err)
216216 }
217217 select {
@@ -220,7 +220,7 @@ func TestPreReceiveSignalsItsPush(t *testing.T) {
220220 default:
221221 }
222222 req := Request{Hook: "pre-receive", RepoID: repoID, UserID: uid, Scope: "full", Token: token}
223 if resp, err := Ask(sock, req, nil); err != nil || !resp.Allow {
223 if resp, err := Ask(sock, req, nil, noScan); err != nil || !resp.Allow {
224224 t.Fatalf("pre-receive: %+v, %v", resp, err)
225225 }
226226 select {
internal/httpd/settings.go +4
@@ -155,6 +155,10 @@ func (s *Server) settingsSubmit(w http.ResponseWriter, r *http.Request, u store.
155155 argv = []string{"repo", "settings", "require-mr", repo, onOff(v("require-mr"))}
156156 case "require-signed":
157157 argv = []string{"repo", "settings", "require-signed", repo, onOff(v("require-signed"))}
158 case "secret-scan":
159 argv = []string{"repo", "settings", "secret-scan", repo, v("secret-scan")}
160 case "secret-scan-allow":
161 argv = append([]string{"repo", "settings", "secret-scan-allow", repo}, strings.Fields(v("secret-scan-allow"))...)
158162 case "require-approvals":
159163 argv = []string{"repo", "settings", "require-approvals", repo, v("approvals")}
160164 case "protect":
internal/leaks/leaks_test.go added +141
@@ -0,0 +1,141 @@
1package leaks
2
3import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10)
11
12// Token-shaped strings are assembled here rather than written out, so this
13// file is not itself a finding for this scanner or any other.
14func fake(prefix string, n int, alphabet string) string {
15 var b strings.Builder
16 b.WriteString(prefix)
17 for i := 0; i < n; i++ {
18 b.WriteByte(alphabet[i%len(alphabet)])
19 }
20 return b.String()
21}
22
23const (
24 alnum = "aB3dE5fG7hJ9kL2mN4pQ6rS8tU"
25 hex = "0123456789abcdef"
26 upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
27)
28
29func TestFindRules(t *testing.T) {
30 keyBody := strings.Repeat("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQ", 2)
31 for _, tc := range []struct {
32 rule, text string
33 }{
34 {"private-key", "-----BEGIN " + "OPENSSH PRIVATE KEY-----\n" + keyBody + "\n-----END OPENSSH PRIVATE KEY-----\n"},
35 {"private-key", "-----BEGIN " + "PGP PRIVATE KEY BLOCK-----\nVersion: x\n\n" + keyBody + "\n"},
36 {"aws-access-key-id", "key = " + fake("AK"+"IA", 16, upper)},
37 {"github-token", fake("gh"+"p_", 36, alnum)},
38 {"github-fine-grained-token", fake("github"+"_pat_", 82, alnum)},
39 {"gitlab-token", fake("gl"+"pat-", 20, alnum)},
40 {"gitbay-token", "Authorization: Bearer " + fake("g"+"b_", 64, hex)},
41 {"slack-token", "xox" + "b-123456789012-" + fake("", 24, alnum)},
42 {"stripe-live-key", fake("sk"+"_live_", 24, alnum)},
43 {"google-api-key", fake("AI"+"za", 35, alnum)},
44 {"npm-token", fake("np"+"m_", 36, alnum)},
45 {"age-secret-key", fake("AGE-SECRET"+"-KEY-1", 58, "QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L")},
46 {"digitalocean-token", fake("do"+"p_v1_", 64, hex)},
47 } {
48 hits := Find([]byte("line one\n" + tc.text + "\n"))
49 if len(hits) != 1 || hits[0].Rule != tc.rule || hits[0].Line != 2 {
50 t.Errorf("%s: hits = %+v", tc.rule, hits)
51 }
52 }
53}
54
55// Text that mentions a format without carrying a credential is not a
56// finding: a stopping rule has to be right when it fires.
57func TestFindIgnoresMentions(t *testing.T) {
58 for _, text := range []string{
59 "pem.Encode(f, &pem.Block{Type: \"PRIVATE KEY\", Bytes: der})",
60 "-----BEGIN " + "PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",
61 "AK" + "IAEXAMPLE",
62 "tokens start with gh" + "p_ followed by 36 characters",
63 "sk_test_" + strings.Repeat("a", 30),
64 "gb_ prefix makes leaked tokens findable",
65 } {
66 if hits := Find([]byte(text)); len(hits) != 0 {
67 t.Errorf("%q: hits = %+v", text, hits)
68 }
69 }
70}
71
72func git(t *testing.T, dir string, args ...string) string {
73 t.Helper()
74 cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
75 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.test",
76 "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.test", "GIT_CONFIG_NOSYSTEM=1", "HOME="+t.TempDir())
77 out, err := cmd.CombinedOutput()
78 if err != nil {
79 t.Fatalf("git %v: %v\n%s", args, err, out)
80 }
81 return strings.TrimSpace(string(out))
82}
83
84func commit(t *testing.T, dir string, files map[string]string, msg string) string {
85 t.Helper()
86 for name, body := range files {
87 p := filepath.Join(dir, name)
88 os.MkdirAll(filepath.Dir(p), 0o755)
89 if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
90 t.Fatal(err)
91 }
92 git(t, dir, "add", name)
93 }
94 git(t, dir, "commit", "-q", "-m", msg)
95 return git(t, dir, "rev-parse", "HEAD")
96}
97
98func TestScanRange(t *testing.T) {
99 dir := t.TempDir()
100 git(t, dir, "init", "-q", "-b", "main")
101 token := fake("gh"+"p_", 36, alnum)
102 first := commit(t, dir, map[string]string{"old.env": "TOKEN=" + token + "\n"}, "old")
103 second := commit(t, dir, map[string]string{
104 "a b/new.env": "x\nTOKEN=" + token + "\n",
105 "binary.dat": "\x00" + token,
106 "clean.txt": "nothing here\n",
107 "old.env": "TOKEN=" + token + "\n", // unchanged blob: already seen
108 }, "new")
109
110 // A push: only what the existing refs do not have.
111 rep := Scan(context.Background(), dir, second, "--not", first)
112 if rep.Error != "" || rep.Truncated {
113 t.Fatalf("report = %+v", rep)
114 }
115 if len(rep.Findings) != 1 {
116 t.Fatalf("findings = %+v", rep.Findings)
117 }
118 f := rep.Findings[0]
119 if f.Commit != second || f.Path != "a b/new.env" || f.Line != 2 || f.Rule != "github-token" {
120 t.Errorf("finding = %+v", f)
121 }
122
123 // The history: both files.
124 rep = Scan(context.Background(), dir, "--all")
125 if len(rep.Findings) != 2 || rep.Findings[1].Path != "old.env" || rep.Findings[1].Commit != first {
126 t.Errorf("history findings = %+v", rep.Findings)
127 }
128
129 // Nothing selected is an empty report, not an error.
130 if rep := Scan(context.Background(), dir, second, "--not", "--all"); rep.Error != "" || len(rep.Findings) != 0 {
131 t.Errorf("empty range = %+v", rep)
132 }
133}
134
135func TestAllowed(t *testing.T) {
136 in := []Finding{{Path: "internal/mailin/dkim_test.go"}, {Path: "testdata/k.pem"}, {Path: "config/prod.env"}}
137 got := Allowed(in, []string{"testdata/**", "*_test.go", "internal/*/*_test.go"})
138 if len(got) != 1 || got[0].Path != "config/prod.env" {
139 t.Errorf("allowed = %+v", got)
140 }
141}
internal/leaks/report.go added +76
@@ -0,0 +1,76 @@
1package leaks
2
3import (
4 "fmt"
5 "strings"
6
7 "gitbay.org/gitbay/internal/ci"
8)
9
10// Modes a repository's secret scan runs in. The empty setting is
11// ModeWarn: scanning sends nothing anywhere and warning blocks nothing, so
12// it is on unless an admin turns it off.
13const (
14 ModeOff = "off"
15 ModeWarn = "warn"
16 ModeBlock = "block"
17)
18
19// Mode resolves a repository's setting.
20func Mode(setting string) string {
21 if setting == "" {
22 return ModeWarn
23 }
24 return setting
25}
26
27// Allowed drops findings under a path the repository allows, given as CI
28// path globs (`testdata/**`, `*.pem`).
29func Allowed(findings []Finding, allow []string) []Finding {
30 if len(allow) == 0 {
31 return findings
32 }
33 var out []Finding
34 for _, f := range findings {
35 skip := false
36 for _, g := range allow {
37 if ci.Match(g, f.Path) {
38 skip = true
39 break
40 }
41 }
42 if !skip {
43 out = append(out, f)
44 }
45 }
46 return out
47}
48
49// listed is how many findings a message names; the count covers the rest.
50const listed = 20
51
52// Describe lists findings for a person: one line each, commit, path, line
53// and rule. heading leads it.
54func Describe(heading string, findings []Finding, truncated bool) string {
55 var b strings.Builder
56 b.WriteString(heading)
57 for i, f := range findings {
58 if i == listed {
59 fmt.Fprintf(&b, "\n and %d more", len(findings)-listed)
60 break
61 }
62 fmt.Fprintf(&b, "\n %.10s %s:%d %s", f.Commit, f.Path, f.Line, f.Rule)
63 }
64 if truncated {
65 b.WriteString("\n (scan stopped at its size limit; not every file was read)")
66 }
67 return b.String()
68}
69
70// Plural is "1 possible secret" or "n possible secrets".
71func Plural(n int) string {
72 if n == 1 {
73 return "1 possible secret"
74 }
75 return fmt.Sprintf("%d possible secrets", n)
76}
internal/leaks/rules.go added +80
@@ -0,0 +1,80 @@
1// Package leaks finds credentials in git content. The rules are token
2// formats that identify themselves — a vendor prefix, a fixed length, a
3// key block with a body — rather than entropy guesses, so a finding is
4// worth stopping a push for. Only where a match is (path, line, rule) ever
5// leaves this package; the matched text does not.
6package leaks
7
8import (
9 "bytes"
10 "regexp"
11)
12
13// Rule is one credential format. keyword is a literal every match
14// contains, checked before the expression so most content costs a substring
15// search and nothing else.
16type Rule struct {
17 ID string
18 keyword string
19 re *regexp.Regexp
20}
21
22var rules = []Rule{
23 {"private-key", "PRIVATE KEY", regexp.MustCompile(`-----BEGIN[ A-Z0-9]*PRIVATE KEY(?: BLOCK)?-----[ \t]*\r?\n(?:[A-Za-z0-9-]+: [^\n]*\r?\n)*\s*[A-Za-z0-9+/=]{40,}`)},
24 {"age-secret-key", "AGE-SECRET-KEY-1", regexp.MustCompile(`AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}`)},
25 {"aws-access-key-id", "A", regexp.MustCompile(`\b(?:AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16}\b`)},
26 {"github-token", "gh", regexp.MustCompile(`\bgh[pousr]_[A-Za-z0-9]{36}\b`)},
27 {"github-fine-grained-token", "github_pat_", regexp.MustCompile(`\bgithub_pat_[A-Za-z0-9_]{82}\b`)},
28 {"gitlab-token", "glpat-", regexp.MustCompile(`\bglpat-[A-Za-z0-9_\-]{20,}\b`)},
29 {"gitbay-token", "gb_", regexp.MustCompile(`\bgb_[0-9a-f]{64}\b`)},
30 {"slack-token", "xox", regexp.MustCompile(`\bxox[baprs]-[0-9]{6,}-[A-Za-z0-9-]{10,}\b`)},
31 {"slack-webhook", "hooks.slack.com", regexp.MustCompile(`https://hooks\.slack\.com/services/T[A-Z0-9]{6,}/B[A-Z0-9]{6,}/[A-Za-z0-9]{20,}`)},
32 {"stripe-live-key", "_live_", regexp.MustCompile(`\b[rs]k_live_[A-Za-z0-9]{24,}\b`)},
33 {"google-api-key", "AIza", regexp.MustCompile(`\bAIza[0-9A-Za-z_\-]{35}\b`)},
34 {"npm-token", "npm_", regexp.MustCompile(`\bnpm_[A-Za-z0-9]{36}\b`)},
35 {"pypi-token", "pypi-AgEIcHlwaS5vcmc", regexp.MustCompile(`\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_\-]{50,}`)},
36 {"openai-key", "sk-", regexp.MustCompile(`\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_\-]{40,}`)},
37 {"anthropic-key", "sk-ant-", regexp.MustCompile(`\bsk-ant-(?:api|admin)[0-9]{2}-[A-Za-z0-9_\-]{80,}`)},
38 {"sendgrid-key", "SG.", regexp.MustCompile(`\bSG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43}\b`)},
39 {"digitalocean-token", "_v1_", regexp.MustCompile(`\bdo[opr]_v1_[a-f0-9]{64}\b`)},
40 {"shopify-token", "shp", regexp.MustCompile(`\bshp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}\b`)},
41}
42
43// Hit is one match inside a blob.
44type Hit struct {
45 Line int `json:"line"`
46 Rule string `json:"rule"`
47}
48
49// maxHitsPerBlob bounds what one file reports; a file with more is not
50// made more urgent by listing them all.
51const maxHitsPerBlob = 10
52
53// Find returns where data matches a rule, one hit per rule and line.
54func Find(data []byte) []Hit {
55 var out []Hit
56 for _, r := range rules {
57 if !bytes.Contains(data, []byte(r.keyword)) {
58 continue
59 }
60 last := 0
61 for _, loc := range r.re.FindAllIndex(data, maxHitsPerBlob) {
62 line := 1 + bytes.Count(data[:loc[0]], []byte("\n"))
63 if line == last {
64 continue
65 }
66 last = line
67 out = append(out, Hit{Line: line, Rule: r.ID})
68 if len(out) >= maxHitsPerBlob {
69 return out
70 }
71 }
72 }
73 return out
74}
75
76// binary reports whether data looks like something other than text: a NUL
77// in the first 8000 bytes, git's own test.
78func binary(data []byte) bool {
79 return bytes.IndexByte(data[:min(len(data), 8000)], 0) >= 0
80}
internal/leaks/scan.go added +243
@@ -0,0 +1,243 @@
1package leaks
2
3import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "os/exec"
10 "sort"
11 "strconv"
12 "strings"
13
14 "gitbay.org/gitbay/internal/toolpath"
15)
16
17// Bounds on one scan. A push or a history bigger than these is scanned in
18// part and reported as truncated rather than holding the push open: the
19// hook runs while the pusher waits.
20const (
21 MaxBlobBytes = 1 << 20 // a larger file is skipped: generated, vendored, or data
22 MaxScanBytes = 64 << 20 // total content read
23 MaxBlobs = 20000
24 MaxFindings = 100
25)
26
27// Finding is one match: which commit added the content, where, and which
28// rule matched. Never the matched text.
29type Finding struct {
30 Commit string `json:"commit"`
31 Path string `json:"path"`
32 Line int `json:"line"`
33 Rule string `json:"rule"`
34}
35
36// Report is the outcome of one scan. Truncated means a bound or the
37// deadline stopped it before every blob was read; Error that git failed.
38type Report struct {
39 Findings []Finding `json:"findings"`
40 Blobs int `json:"blobs"`
41 Truncated bool `json:"truncated,omitempty"`
42 Error string `json:"error,omitempty"`
43}
44
45type origin struct{ commit, path string }
46
47// Scan reads the blobs the commits selected by revs add or change, as
48// `git log` arguments (`<tip> --not --all` for a push, `--all` for a
49// history), and reports where they match a rule. Merge commits are not
50// diffed, so a secret introduced only in a conflict resolution is missed.
51// The deadline on ctx ends the scan early as a truncation, not an error.
52func Scan(ctx context.Context, dir string, revs ...string) Report {
53 oids, origins, truncated, err := changedBlobs(ctx, dir, revs)
54 rep := Report{Truncated: truncated}
55 if err != nil {
56 rep.Error = err.Error()
57 return rep
58 }
59 if len(oids) == 0 {
60 return rep
61 }
62 more, err := readBlobs(ctx, dir, oids, func(oid string, data []byte) bool {
63 rep.Blobs++
64 if binary(data) {
65 return true
66 }
67 o := origins[oid]
68 for _, h := range Find(data) {
69 if len(rep.Findings) >= MaxFindings {
70 rep.Truncated = true
71 return false
72 }
73 rep.Findings = append(rep.Findings, Finding{Commit: o.commit, Path: o.path, Line: h.Line, Rule: h.Rule})
74 }
75 return true
76 })
77 rep.Truncated = rep.Truncated || more
78 if err != nil {
79 rep.Error = err.Error()
80 }
81 sort.Slice(rep.Findings, func(i, j int) bool {
82 a, b := rep.Findings[i], rep.Findings[j]
83 if a.Path != b.Path {
84 return a.Path < b.Path
85 }
86 return a.Line < b.Line
87 })
88 return rep
89}
90
91// changedBlobs lists the distinct blobs the selected commits add or
92// modify, with the commit and path each was first seen under. Symlinks and
93// submodules carry no content worth reading.
94func changedBlobs(ctx context.Context, dir string, revs []string) ([]string, map[string]origin, bool, error) {
95 args := append([]string{"-C", dir, "-c", "core.quotePath=false", "log", "--raw", "--no-abbrev",
96 "--no-renames", "--format=commit %H"}, revs...)
97 cmd := exec.CommandContext(ctx, toolpath.Look("git"), args...)
98 stdout, err := cmd.StdoutPipe()
99 if err != nil {
100 return nil, nil, false, err
101 }
102 if err := cmd.Start(); err != nil {
103 return nil, nil, false, fmt.Errorf("git log: %w", err)
104 }
105 var (
106 oids []string
107 origins = map[string]origin{}
108 commit string
109 truncated bool
110 )
111 sc := bufio.NewScanner(stdout)
112 sc.Buffer(make([]byte, 64<<10), 1<<20)
113 for sc.Scan() {
114 line := sc.Text()
115 if sha, ok := strings.CutPrefix(line, "commit "); ok {
116 commit = sha
117 continue
118 }
119 meta, path, ok := strings.Cut(line, "\t")
120 if !ok || !strings.HasPrefix(meta, ":") {
121 continue
122 }
123 f := strings.Fields(meta)
124 if len(f) != 5 || f[4] == "D" || (f[1] != "100644" && f[1] != "100755") {
125 continue
126 }
127 if strings.HasPrefix(path, `"`) {
128 if p, err := strconv.Unquote(path); err == nil {
129 path = p
130 }
131 }
132 oid := f[3]
133 if _, seen := origins[oid]; seen {
134 continue
135 }
136 if len(oids) >= MaxBlobs {
137 truncated = true
138 break
139 }
140 origins[oid] = origin{commit, path}
141 oids = append(oids, oid)
142 }
143 // Stopping early leaves git writing into a pipe nobody reads; killing it
144 // is how the early stop ends it, so that exit is not an error.
145 if truncated {
146 cmd.Process.Kill()
147 }
148 waitErr := cmd.Wait()
149 switch {
150 case ctx.Err() != nil:
151 return oids, origins, true, nil
152 case truncated:
153 return oids, origins, true, nil
154 case sc.Err() != nil:
155 return nil, nil, false, sc.Err()
156 case waitErr != nil:
157 return nil, nil, false, fmt.Errorf("git log: %w", waitErr)
158 }
159 return oids, origins, false, nil
160}
161
162// readBlobs streams oids through one `cat-file --batch`, handing each blob
163// within MaxBlobBytes to fn until fn returns false. It reports whether it
164// stopped before the end, on a bound or the deadline.
165func readBlobs(ctx context.Context, dir string, oids []string, fn func(oid string, data []byte) bool) (bool, error) {
166 ctx, cancel := context.WithCancel(ctx)
167 defer cancel()
168 cmd := exec.CommandContext(ctx, toolpath.Look("git"), "-C", dir, "cat-file", "--batch")
169 stdin, err := cmd.StdinPipe()
170 if err != nil {
171 return false, err
172 }
173 stdout, err := cmd.StdoutPipe()
174 if err != nil {
175 return false, err
176 }
177 if err := cmd.Start(); err != nil {
178 return false, fmt.Errorf("cat-file --batch: %w", err)
179 }
180 defer cmd.Wait() // after cancel, which ends git on an early return
181 // Fed from another goroutine: the pipe holds fewer names than a large
182 // push has, and git blocks writing output nobody is reading yet.
183 go func() {
184 defer stdin.Close()
185 w := bufio.NewWriter(stdin)
186 for _, oid := range oids {
187 if _, err := fmt.Fprintln(w, oid); err != nil {
188 return
189 }
190 }
191 w.Flush()
192 }()
193 r := bufio.NewReader(stdout)
194 var total int64
195 for range oids {
196 header, err := r.ReadString('\n')
197 if err != nil {
198 if ctx.Err() != nil {
199 return true, nil
200 }
201 return true, fmt.Errorf("cat-file --batch: %w", err)
202 }
203 f := strings.Fields(header)
204 if len(f) == 2 && f[1] == "missing" {
205 continue
206 }
207 if len(f) != 3 {
208 return true, fmt.Errorf("cat-file --batch: unexpected %q", strings.TrimSpace(header))
209 }
210 size, err := strconv.ParseInt(f[2], 10, 64)
211 if err != nil {
212 return true, fmt.Errorf("cat-file --batch: bad size in %q", strings.TrimSpace(header))
213 }
214 if size > MaxBlobBytes {
215 if _, err := r.Discard(int(size) + 1); err != nil {
216 return true, readErr(ctx, err)
217 }
218 continue
219 }
220 if total += size; total > MaxScanBytes {
221 return true, nil
222 }
223 data := make([]byte, size)
224 if _, err := io.ReadFull(r, data); err != nil {
225 return true, readErr(ctx, err)
226 }
227 if _, err := r.Discard(1); err != nil {
228 return true, readErr(ctx, err)
229 }
230 if !fn(f[0], data) {
231 return true, nil
232 }
233 }
234 return false, nil
235}
236
237// readErr is nil when the deadline caused the failed read: a truncation.
238func readErr(ctx context.Context, err error) error {
239 if ctx.Err() != nil || errors.Is(err, context.Canceled) {
240 return nil
241 }
242 return fmt.Errorf("cat-file --batch: %w", err)
243}
internal/store/repos.go +4
@@ -38,6 +38,10 @@ type RepoSettings struct {
3838 GitDaemon bool `json:"git_daemon,omitempty"`
3939 Archived bool `json:"archived,omitempty"`
4040 Website string `json:"website,omitempty"`
41 // SecretScan is off, warn or block; empty is warn (leaks.Mode).
42 SecretScan string `json:"secret_scan,omitempty"`
43 // SecretScanAllow are CI path globs whose findings are ignored.
44 SecretScanAllow []string `json:"secret_scan_allow,omitempty"`
4145}
4246
4347// Path returns the canonical owner/name form.
internal/web/templates/settings.html +15
@@ -171,6 +171,21 @@
171171</form>
172172</section>
173173
174<section id="secret-scan"><h2>Secret scan</h2>
175<form method="post" action="{{$base}}" class="setform">
176 <input type="hidden" name="field" value="secret-scan">
177 <div><label for="secret-scan">Pushes</label><p class="hint">Each push's new files are checked for credentials in known formats. Warn accepts the push and tells the pusher where; block refuses it. Only the path, line and kind of credential are reported, never the value.</p></div>
178 <div><select id="secret-scan" name="secret-scan">{{$mode := or .Repo.Settings.SecretScan "warn"}}<option value="off"{{if eq $mode "off"}} selected{{end}}>off</option><option value="warn"{{if eq $mode "warn"}} selected{{end}}>warn</option><option value="block"{{if eq $mode "block"}} selected{{end}}>block</option></select></div>
179 <div><button type="submit" class="btn">Save</button></div>
180</form>
181<form method="post" action="{{$base}}" class="setform">
182 <input type="hidden" name="field" value="secret-scan-allow">
183 <div><label for="secret-scan-allow">Allowed paths</label><p class="hint">Findings under these paths are ignored, for test fixtures. Path globs separated by spaces: <code>testdata/**</code>, <code>*_test.go</code>.</p></div>
184 <div><input type="text" id="secret-scan-allow" name="secret-scan-allow" value="{{join .Repo.Settings.SecretScanAllow " "}}"></div>
185 <div><button type="submit" class="btn">Save</button></div>
186</form>
187</section>
188
174189<section id="branches"><h2>Protected branches</h2>
175190{{if .Repo.Settings.ProtectedBranches}}
176191<ul class="protlist">