e2e/secretscan_test.go
68 lines · 2667 bytes
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}