internal/leaks/leaks_test.go

171 lines · 5892 bytes

  1package leaks
  2
  3import (
  4	"context"
  5	"os"
  6	"os/exec"
  7	"path/filepath"
  8	"strings"
  9	"testing"
 10	"time"
 11)
 12
 13// Token-shaped strings are assembled here rather than written out, so this
 14// file is not itself a finding for this scanner or any other.
 15func fake(prefix string, n int, alphabet string) string {
 16	var b strings.Builder
 17	b.WriteString(prefix)
 18	for i := 0; i < n; i++ {
 19		b.WriteByte(alphabet[i%len(alphabet)])
 20	}
 21	return b.String()
 22}
 23
 24const (
 25	alnum = "aB3dE5fG7hJ9kL2mN4pQ6rS8tU"
 26	hex   = "0123456789abcdef"
 27	upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
 28)
 29
 30func TestFindRules(t *testing.T) {
 31	keyBody := strings.Repeat("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQ", 2)
 32	for _, tc := range []struct {
 33		rule, text string
 34	}{
 35		{"private-key", "-----BEGIN " + "OPENSSH PRIVATE KEY-----\n" + keyBody + "\n-----END OPENSSH PRIVATE KEY-----\n"},
 36		{"private-key", "-----BEGIN " + "PGP PRIVATE KEY BLOCK-----\nVersion: x\n\n" + keyBody + "\n"},
 37		{"aws-access-key-id", "key = " + fake("AK"+"IA", 16, upper)},
 38		{"github-token", fake("gh"+"p_", 36, alnum)},
 39		{"github-fine-grained-token", fake("github"+"_pat_", 82, alnum)},
 40		{"gitlab-token", fake("gl"+"pat-", 20, alnum)},
 41		{"gitbay-token", "Authorization: Bearer " + fake("g"+"b_", 64, hex)},
 42		{"slack-token", "xox" + "b-123456789012-" + fake("", 24, alnum)},
 43		{"stripe-live-key", fake("sk"+"_live_", 24, alnum)},
 44		{"google-api-key", fake("AI"+"za", 35, alnum)},
 45		{"npm-token", fake("np"+"m_", 36, alnum)},
 46		{"age-secret-key", fake("AGE-SECRET"+"-KEY-1", 58, "QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L")},
 47		{"digitalocean-token", fake("do"+"p_v1_", 64, hex)},
 48	} {
 49		hits := Find([]byte("line one\n" + tc.text + "\n"))
 50		if len(hits) != 1 || hits[0].Rule != tc.rule || hits[0].Line != 2 {
 51			t.Errorf("%s: hits = %+v", tc.rule, hits)
 52		}
 53	}
 54}
 55
 56// Text that mentions a format without carrying a credential is not a
 57// finding: a stopping rule has to be right when it fires.
 58func TestFindIgnoresMentions(t *testing.T) {
 59	for _, text := range []string{
 60		"pem.Encode(f, &pem.Block{Type: \"PRIVATE KEY\", Bytes: der})",
 61		"-----BEGIN " + "PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----",
 62		"AK" + "IAEXAMPLE",
 63		"tokens start with gh" + "p_ followed by 36 characters",
 64		"sk_test_" + strings.Repeat("a", 30),
 65		"gb_ prefix makes leaked tokens findable",
 66	} {
 67		if hits := Find([]byte(text)); len(hits) != 0 {
 68			t.Errorf("%q: hits = %+v", text, hits)
 69		}
 70	}
 71}
 72
 73func git(t *testing.T, dir string, args ...string) string {
 74	t.Helper()
 75	cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
 76	cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.test",
 77		"GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.test", "GIT_CONFIG_NOSYSTEM=1", "HOME="+t.TempDir())
 78	out, err := cmd.CombinedOutput()
 79	if err != nil {
 80		t.Fatalf("git %v: %v\n%s", args, err, out)
 81	}
 82	return strings.TrimSpace(string(out))
 83}
 84
 85func commit(t *testing.T, dir string, files map[string]string, msg string) string {
 86	t.Helper()
 87	for name, body := range files {
 88		p := filepath.Join(dir, name)
 89		os.MkdirAll(filepath.Dir(p), 0o755)
 90		if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
 91			t.Fatal(err)
 92		}
 93		git(t, dir, "add", name)
 94	}
 95	git(t, dir, "commit", "-q", "-m", msg)
 96	return git(t, dir, "rev-parse", "HEAD")
 97}
 98
 99func TestScanRange(t *testing.T) {
100	dir := t.TempDir()
101	git(t, dir, "init", "-q", "-b", "main")
102	token := fake("gh"+"p_", 36, alnum)
103	first := commit(t, dir, map[string]string{"old.env": "TOKEN=" + token + "\n"}, "old")
104	second := commit(t, dir, map[string]string{
105		"a b/new.env": "x\nTOKEN=" + token + "\n",
106		"binary.dat":  "\x00" + token,
107		"clean.txt":   "nothing here\n",
108		"old.env":     "TOKEN=" + token + "\n", // unchanged blob: already seen
109	}, "new")
110
111	// A push: only what the existing refs do not have.
112	rep := Scan(context.Background(), dir, second, "--not", first)
113	if rep.Error != "" || rep.Truncated {
114		t.Fatalf("report = %+v", rep)
115	}
116	if len(rep.Findings) != 1 {
117		t.Fatalf("findings = %+v", rep.Findings)
118	}
119	f := rep.Findings[0]
120	if f.Commit != second || f.Path != "a b/new.env" || f.Line != 2 || f.Rule != "github-token" {
121		t.Errorf("finding = %+v", f)
122	}
123
124	// The history: both files.
125	rep = Scan(context.Background(), dir, "--all")
126	if len(rep.Findings) != 2 || rep.Findings[1].Path != "old.env" || rep.Findings[1].Commit != first {
127		t.Errorf("history findings = %+v", rep.Findings)
128	}
129
130	// Nothing selected is an empty report, not an error.
131	if rep := Scan(context.Background(), dir, second, "--not", "--all"); rep.Error != "" || len(rep.Findings) != 0 {
132		t.Errorf("empty range = %+v", rep)
133	}
134}
135
136func TestAllowed(t *testing.T) {
137	in := []Finding{{Path: "internal/mailin/dkim_test.go"}, {Path: "testdata/k.pem"}, {Path: "config/prod.env"}}
138	got := Allowed(in, []string{"testdata/**", "*_test.go", "internal/*/*_test.go"})
139	if len(got) != 1 || got[0].Path != "config/prod.env" {
140		t.Errorf("allowed = %+v", got)
141	}
142}
143
144// Stopping part-way returns at once. git is left with more output than a
145// pipe holds, and Wait before cancel used to block until the deadline.
146func TestReadBlobsStopsPromptly(t *testing.T) {
147	dir := t.TempDir()
148	git(t, dir, "init", "-q", "-b", "main")
149	files := map[string]string{}
150	for i := 0; i < 20; i++ {
151		files[fake("f", 4, alnum)+string(rune('a'+i))] = strings.Repeat(string(rune('a'+i)), 200<<10)
152	}
153	commit(t, dir, files, "big")
154	oids, _, _, err := changedBlobs(context.Background(), dir, []string{"--all"})
155	if err != nil || len(oids) != 20 {
156		t.Fatalf("oids %d: %v", len(oids), err)
157	}
158	done := make(chan bool, 1)
159	go func() {
160		more, _ := readBlobs(context.Background(), dir, oids, func(string, []byte) bool { return false })
161		done <- more
162	}()
163	select {
164	case more := <-done:
165		if !more {
166			t.Error("an early stop was not reported")
167		}
168	case <-time.After(10 * time.Second):
169		t.Fatal("readBlobs did not return after fn stopped it")
170	}
171}