e2e/readonly_test.go

v1.46.1
gitbay/e2e/readonly_test.go

333 lines · 12795 bytes

  1package e2e
  2
  3import (
  4	"crypto/sha256"
  5	"database/sql"
  6	"encoding/hex"
  7	"fmt"
  8	"os"
  9	"path/filepath"
 10	"regexp"
 11	"strings"
 12	"testing"
 13	"unicode"
 14
 15	"golang.org/x/text/width"
 16	_ "modernc.org/sqlite"
 17
 18	"gitbay.org/gitbay/internal/control"
 19)
 20
 21// ReadOnly is one flag with four consequences: a read-scoped token may run
 22// the command, GET /api/v1/read reaches it, it draws on the read rate
 23// budget, and it is not audited. A mutating command mis-flagged ReadOnly
 24// becomes GET-able and unaudited in one line. This test runs every
 25// ReadOnly command against a populated instance and fails on any command
 26// that changes a row (#97).
 27//
 28// Every ReadOnly command needs an entry in readArgs; a new one without
 29// arguments here fails the test rather than going untested.
 30func TestReadOnlyCommandsWriteNothing(t *testing.T) {
 31	t.Parallel()
 32	inst := startInstanceWith(t, "[web]\nmode = \"accounts\"\n[webhooks]\nallow_local = true\n")
 33	aliceKey := inst.newKey(t, "alice")
 34	inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub",
 35		"--email", "alice@example.test", "--verified", "--admin")
 36	deployKey := inst.newKey(t, "deploy")
 37	must := func(stdin string, args ...string) string {
 38		t.Helper()
 39		out, errOut, code := inst.ssh(t, aliceKey, stdin, args...)
 40		if code != 0 {
 41			t.Fatalf("fixture %v: exit %d\n%s%s", args, code, out, errOut)
 42		}
 43		return out
 44	}
 45
 46	// A repository with history, a tag, a branch, a build, and everything
 47	// the read commands can look at.
 48	must("", "repo", "create", "alice/app")
 49	work := t.TempDir()
 50	env := inst.gitEnv(aliceKey)
 51	mustGit(t, work, env, "clone", inst.sshURL("alice/app"), "w")
 52	dir := filepath.Join(work, "w")
 53	os.MkdirAll(filepath.Join(dir, ".gitbay"), 0o755)
 54	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte("jobs:\n  ok:\n    steps:\n      - echo hi\n"), 0o644)
 55	os.WriteFile(filepath.Join(dir, "README.md"), []byte("# app\n\nhello\n"), 0o644)
 56	os.WriteFile(filepath.Join(dir, "f.go"), []byte("package app\n"), 0o644)
 57	mustGit(t, dir, env, "checkout", "-q", "-b", "main")
 58	mustGit(t, dir, env, "add", ".")
 59	mustGit(t, dir, env, "commit", "-q", "-m", "base")
 60	mustGit(t, dir, env, "tag", "v1")
 61	mustGit(t, dir, env, "push", "-q", "origin", "main", "v1")
 62	sha := strings.TrimSpace(mustGit(t, dir, env, "rev-parse", "HEAD"))
 63	mustGit(t, dir, env, "checkout", "-q", "-b", "feat")
 64	os.WriteFile(filepath.Join(dir, "f.go"), []byte("package app\n\nvar V = 1\n"), 0o644)
 65	mustGit(t, dir, env, "add", ".")
 66	mustGit(t, dir, env, "commit", "-q", "-m", "change")
 67	mustGit(t, dir, env, "push", "-q", "origin", "feat")
 68
 69	must("", "issue", "create", "alice/app", "--title", "one", "--body", "body")
 70	must("", "issue", "label", "alice/app", "1", "--add", "bug")
 71	must("", "label", "set", "alice/app", "bug", "--color", "ff0000")
 72	must("", "milestone", "create", "alice/app", "m1")
 73	must("", "mr", "create", "alice/app", "--source", "feat", "--target", "main", "--title", "change")
 74	must("", "mr", "diff-comment", "alice/app", "1", "--path", "f.go", "--line", "3", "--message", "why")
 75	must("", "status", "set", "alice/app", sha, "--context", "ext/x", "--state", "success")
 76	must("", "release", "create", "alice/app", "v1", "--title", "first")
 77	must("data\n", "release", "asset", "add", "alice/app", "v1", "a.txt")
 78	snippetOut := must("hello\n", "snippet", "create", "a.txt", "--json")
 79	snippetID := regexp.MustCompile(`"id":"([0-9a-f]{12})"`).FindStringSubmatch(snippetOut)[1]
 80	must("", "org", "create", "theorg")
 81	must("", "org", "team", "create", "theorg", "core")
 82	must("", "token", "create", "--name", "t")
 83	must("", "query", "save", "q", "is:open")
 84	must("", "web", "login")
 85	pub, _ := os.ReadFile(deployKey + ".pub")
 86	must(string(pub), "repo", "deploy-key", "add", "alice/app")
 87	must("secret\n", "repo", "secret", "set", "alice/app", "S")
 88	// Added last, for an event that already happened: no delivery is
 89	// pending to be retried while the reads run.
 90	must("", "webhook", "add", "alice/app", "http://127.0.0.1:1/hook", "--events", "release.created")
 91
 92	readArgs := map[string][]string{
 93		"help":                        {},
 94		"whoami":                      {},
 95		"dashboard":                   {},
 96		"feed":                        {},
 97		"explore":                     {},
 98		"audit":                       {},
 99		"keys list":                   {},
100		"email list":                  {},
101		"pgp list":                    {},
102		"token list":                  {},
103		"web sessions list":           {},
104		"web theme show":              {},
105		"web diff show":               {},
106		"account export":              {},
107		"org list":                    {},
108		"repo list":                   {},
109		"admin user list":             {},
110		"admin runners":               {},
111		"admin repo list":             {},
112		"admin stats":                 {},
113		"admin mail inbound check":    {},
114		"admin user show":             {"alice"},
115		"profile show":                {"alice"},
116		"org show":                    {"theorg"},
117		"org members list":            {"theorg"},
118		"org team list":               {"theorg"},
119		"org team show":               {"theorg", "core"},
120		"org label list":              {"theorg"},
121		"org milestone list":          {"theorg"},
122		"repo search":                 {"app"},
123		"repo show":                   {"alice/app"},
124		"repo access list":            {"alice/app"},
125		"repo settings show":          {"alice/app"},
126		"repo topics":                 {"alice/app"},
127		"repo refs":                   {"alice/app"},
128		"repo readme":                 {"alice/app"},
129		"repo log":                    {"alice/app"},
130		"repo tree":                   {"alice/app"},
131		"repo cat":                    {"alice/app", "f.go"},
132		"repo blame":                  {"alice/app", "f.go"},
133		"repo grep":                   {"alice/app", "hello"},
134		"repo symbols":                {"alice/app", "app"},
135		"repo definitions":            {"alice/app", "f.go"},
136		"repo diff":                   {"alice/app", "main", "feat"},
137		"repo commit":                 {"alice/app", sha},
138		"repo download":               {"alice/app"},
139		"repo deploy-key list":        {"alice/app"},
140		"repo runner list":            {"alice/app"},
141		"repo secret list":            {"alice/app"},
142		"repo mirror list":            {"alice/app"},
143		"repo domain list":            {"alice/app"},
144		"repo deps status":            {"alice/app"},
145		"repo secret-scan":            {"alice/app"},
146		"repo security status":        {"alice/app"},
147		"status list":                 {"alice/app", sha},
148		"issue list":                  {"alice/app"},
149		"issue show":                  {"alice/app", "1"},
150		"issue templates":             {"alice/app"},
151		"label list":                  {"alice/app"},
152		"milestone list":              {"alice/app"},
153		"mr list":                     {"alice/app"},
154		"mr show":                     {"alice/app", "1"},
155		"mr diff":                     {"alice/app", "1"},
156		"mr threads":                  {"alice/app", "1"},
157		"build list":                  {"alice/app"},
158		"build jobs":                  {"alice/app"},
159		"build show":                  {"alice/app", "1"},
160		"build log":                   {"alice/app", "1"},
161		"release list":                {"alice/app"},
162		"release show":                {"alice/app", "v1"},
163		"release notes":               {"alice/app", "main"},
164		"release asset get":           {"alice/app", "v1", "a.txt"},
165		"snippet show":                {snippetID},
166		"snippet list":                {},
167		"snippet file get":            {snippetID, "a.txt"},
168		"notifications list":          nil,
169		"notifications settings show": nil,
170		"notifications device list":   nil,
171		"repo bookmarks":              nil,
172		"search":                      {"app"},
173		"query list":                  {},
174		"query show":                  {"q"},
175		"query run":                   {"q"},
176		"mr revisions":                {"alice/app", "1"},
177		"mr range-diff":               {"alice/app", "1"},
178		"webhook list":                {"alice/app"},
179		"webhook deliveries":          {"alice/app"},
180		"wiki list":                   {"alice/app"},
181		"wiki show":                   {"alice/app"},
182	}
183	// Reads whose subject legitimately does not exist in this fixture.
184	notFoundOK := map[string]bool{"wiki show": true, "repo deps status": true}
185	// rawOutput prints content verbatim (a file, a log, a diff) and is
186	// not fitted to the terminal.
187	rawOutput := map[string]bool{
188		"repo download":  true,
189		"account export": true,
190	}
191	// binaryOutput's bytes are not text: a stray 0x1b is coincidence, not
192	// an SGR sequence escaping into plain output.
193	binaryOutput := map[string]bool{"repo download": true}
194
195	// The push to main asked for a symbol index; the worker writing it
196	// mid-loop would be blamed on whichever read ran then.
197	waitFor(t, "symbol index", func() bool {
198		_, _, code := inst.ssh(t, aliceKey, "", "repo", "symbols", "alice/app", "app")
199		return code == 0
200	})
201
202	dbPath := filepath.Join(inst.root, "gitbay.db")
203	before := dbFingerprint(t, dbPath)
204	for _, cmd := range control.Commands() {
205		if !cmd.ReadOnly {
206			continue
207		}
208		path := strings.Join(cmd.Path, " ")
209		args, ok := readArgs[path]
210		if !ok {
211			t.Errorf("%s is ReadOnly and has no arguments in this test; add an entry", path)
212			continue
213		}
214		_, errOut, code := inst.ssh(t, aliceKey, "", append(append([]string{}, cmd.Path...), args...)...)
215		if code != 0 && !(code == 3 && notFoundOK[path]) {
216			t.Errorf("%s: exit %d: %s", path, code, strings.TrimSpace(errOut))
217		}
218		after := dbFingerprint(t, dbPath)
219		for table, h := range after {
220			// The signature cache is filled by whichever read first shows
221			// a commit; a memo of a pure function is not state.
222			if table == "commit_signatures" {
223				continue
224			}
225			if before[table] != h {
226				t.Errorf("%s is ReadOnly but changed table %s", path, table)
227			}
228		}
229		before = after
230
231		argv := append(append([]string{}, cmd.Path...), args...)
232		plainOut, plainErrOut, plainCode := inst.sshTerm(t, aliceKey, "", argv...)
233		if plainCode != 0 && !(plainCode == 3 && notFoundOK[path]) {
234			t.Errorf("%s: --term= plain exit %d: %s", path, plainCode, strings.TrimSpace(plainErrOut))
235		}
236		if !binaryOutput[path] && strings.Contains(plainOut, "\x1b") {
237			t.Errorf("%s: SGR bytes in plain output", path)
238		}
239		termOut, termErrOut, termCode := inst.sshTerm(t, aliceKey, "60,color", argv...)
240		if termCode != 0 && !(termCode == 3 && notFoundOK[path]) {
241			t.Errorf("%s: --term=60,color exit %d: %s", path, termCode, strings.TrimSpace(termErrOut))
242		}
243		if !rawOutput[path] {
244			for _, line := range strings.Split(termOut, "\n") {
245				if w := displayCells(stripSGRe2e(line)); w > 60 {
246					t.Errorf("%s: line of %d cells at 60 columns: %q", path, w, line)
247					break
248				}
249			}
250		}
251	}
252}
253
254var sgrRe = regexp.MustCompile("\x1b\\[[0-9;]*m")
255
256func stripSGRe2e(s string) string {
257	return sgrRe.ReplaceAllString(s, "")
258}
259
260func displayCells(s string) int {
261	n := 0
262	for _, r := range s {
263		switch {
264		case unicode.In(r, unicode.Mn, unicode.Me):
265		case width.LookupRune(r).Kind() == width.EastAsianWide || width.LookupRune(r).Kind() == width.EastAsianFullwidth:
266			n += 2
267		default:
268			n++
269		}
270	}
271	return n
272}
273
274// dbFingerprint hashes every row of every table, per table. Columns that
275// record a read happening (a key's last use, an account's last sight) are
276// left out: an ssh session touches them by design.
277func dbFingerprint(t *testing.T, path string) map[string]string {
278	t.Helper()
279	db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
280	if err != nil {
281		t.Fatal(err)
282	}
283	defer db.Close()
284	rows, err := db.Query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
285	if err != nil {
286		t.Fatal(err)
287	}
288	var tables []string
289	for rows.Next() {
290		var n string
291		rows.Scan(&n)
292		tables = append(tables, n)
293	}
294	rows.Close()
295	out := map[string]string{}
296	for _, table := range tables {
297		cols, err := db.Query(fmt.Sprintf("PRAGMA table_info(%q)", table))
298		if err != nil {
299			t.Fatal(err)
300		}
301		var names []string
302		for cols.Next() {
303			var cid int
304			var name, typ string
305			var notnull, pk int
306			var dflt any
307			cols.Scan(&cid, &name, &typ, &notnull, &dflt, &pk)
308			switch name {
309			case "last_used_at", "last_seen", "last_seen_at":
310				continue
311			}
312			names = append(names, fmt.Sprintf("%q", name))
313		}
314		cols.Close()
315		h := sha256.New()
316		data, err := db.Query(fmt.Sprintf("SELECT %s FROM %q ORDER BY %s", strings.Join(names, ","), table, strings.Join(names, ",")))
317		if err != nil {
318			t.Fatal(err)
319		}
320		vals := make([]any, len(names))
321		ptrs := make([]any, len(names))
322		for i := range vals {
323			ptrs[i] = &vals[i]
324		}
325		for data.Next() {
326			data.Scan(ptrs...)
327			fmt.Fprintf(h, "%v\n", vals)
328		}
329		data.Close()
330		out[table] = hex.EncodeToString(h.Sum(nil))
331	}
332	return out
333}