internal/leaks/leaks_test.go
141 lines · 4926 bytes
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}