e2e/readonly_test.go

0caaaedf8fa3d930b6b4fb83e249b1e0e3265c0a
gitbay/e2e/readonly_test.go history · blame · raw

249 lines · 9213 bytes

  1package e2e
  2
  3import (
  4	"crypto/sha256"
  5	"database/sql"
  6	"encoding/hex"
  7	"fmt"
  8	"os"
  9	"path/filepath"
 10	"strings"
 11	"testing"
 12
 13	_ "modernc.org/sqlite"
 14
 15	"gitbay.org/gitbay/internal/control"
 16)
 17
 18// ReadOnly is one flag with four consequences: a read-scoped token may run
 19// the command, GET /api/v1/read reaches it, it draws on the read rate
 20// budget, and it is not audited. A mutating command mis-flagged ReadOnly
 21// becomes GET-able and unaudited in one line. This test runs every
 22// ReadOnly command against a populated instance and fails on any command
 23// that changes a row (#97).
 24//
 25// Every ReadOnly command needs an entry in readArgs; a new one without
 26// arguments here fails the test rather than going untested.
 27func TestReadOnlyCommandsWriteNothing(t *testing.T) {
 28	inst := startInstanceWith(t, "[web]\nmode = \"accounts\"\n[webhooks]\nallow_local = true\n")
 29	aliceKey := inst.newKey(t, "alice")
 30	inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub",
 31		"--email", "alice@example.test", "--verified", "--admin")
 32	deployKey := inst.newKey(t, "deploy")
 33	must := func(stdin string, args ...string) string {
 34		t.Helper()
 35		out, errOut, code := inst.ssh(t, aliceKey, stdin, args...)
 36		if code != 0 {
 37			t.Fatalf("fixture %v: exit %d\n%s%s", args, code, out, errOut)
 38		}
 39		return out
 40	}
 41
 42	// A repository with history, a tag, a branch, a build, and everything
 43	// the read commands can look at.
 44	must("", "repo", "create", "alice/app")
 45	work := t.TempDir()
 46	env := inst.gitEnv(aliceKey)
 47	mustGit(t, work, env, "clone", inst.sshURL("alice/app"), "w")
 48	dir := filepath.Join(work, "w")
 49	os.MkdirAll(filepath.Join(dir, ".gitbay"), 0o755)
 50	os.WriteFile(filepath.Join(dir, ".gitbay", "ci.yml"), []byte("jobs:\n  ok:\n    steps:\n      - echo hi\n"), 0o644)
 51	os.WriteFile(filepath.Join(dir, "README.md"), []byte("# app\n\nhello\n"), 0o644)
 52	os.WriteFile(filepath.Join(dir, "f.go"), []byte("package app\n"), 0o644)
 53	mustGit(t, dir, env, "checkout", "-q", "-b", "main")
 54	mustGit(t, dir, env, "add", ".")
 55	mustGit(t, dir, env, "commit", "-q", "-m", "base")
 56	mustGit(t, dir, env, "tag", "v1")
 57	mustGit(t, dir, env, "push", "-q", "origin", "main", "v1")
 58	sha := strings.TrimSpace(mustGit(t, dir, env, "rev-parse", "HEAD"))
 59	mustGit(t, dir, env, "checkout", "-q", "-b", "feat")
 60	os.WriteFile(filepath.Join(dir, "f.go"), []byte("package app\n\nvar V = 1\n"), 0o644)
 61	mustGit(t, dir, env, "add", ".")
 62	mustGit(t, dir, env, "commit", "-q", "-m", "change")
 63	mustGit(t, dir, env, "push", "-q", "origin", "feat")
 64
 65	must("", "issue", "create", "alice/app", "--title", "one", "--body", "body")
 66	must("", "issue", "label", "alice/app", "1", "--add", "bug")
 67	must("", "label", "set", "alice/app", "bug", "--color", "ff0000")
 68	must("", "milestone", "create", "alice/app", "m1")
 69	must("", "mr", "create", "alice/app", "--source", "feat", "--target", "main", "--title", "change")
 70	must("", "mr", "diff-comment", "alice/app", "1", "--path", "f.go", "--line", "3", "--message", "why")
 71	must("", "status", "set", "alice/app", sha, "--context", "ci/x", "--state", "success")
 72	must("", "release", "create", "alice/app", "v1", "--title", "first")
 73	must("data\n", "release", "asset", "add", "alice/app", "v1", "a.txt")
 74	must("", "org", "create", "theorg")
 75	must("", "org", "team", "create", "theorg", "core")
 76	must("", "token", "create", "--name", "t")
 77	must("", "web", "login")
 78	pub, _ := os.ReadFile(deployKey + ".pub")
 79	must(string(pub), "repo", "deploy-key", "add", "alice/app")
 80	must("secret\n", "repo", "secret", "set", "alice/app", "S")
 81	// Added last, for an event that already happened: no delivery is
 82	// pending to be retried while the reads run.
 83	must("", "webhook", "add", "alice/app", "http://127.0.0.1:1/hook", "--events", "release.created")
 84
 85	readArgs := map[string][]string{
 86		"help":                 {},
 87		"whoami":               {},
 88		"dashboard":            {},
 89		"feed":                 {},
 90		"explore":              {},
 91		"audit":                {},
 92		"keys list":            {},
 93		"email list":           {},
 94		"pgp list":             {},
 95		"token list":           {},
 96		"web sessions list":    {},
 97		"account export":       {},
 98		"org list":             {},
 99		"repo list":            {},
100		"admin user list":      {},
101		"admin runners":        {},
102		"admin repo list":      {},
103		"admin stats":          {},
104		"admin user show":      {"alice"},
105		"profile show":         {"alice"},
106		"org show":             {"theorg"},
107		"org members list":     {"theorg"},
108		"org team list":        {"theorg"},
109		"org team show":        {"theorg", "core"},
110		"repo search":          {"app"},
111		"repo show":            {"alice/app"},
112		"repo access list":     {"alice/app"},
113		"repo settings show":   {"alice/app"},
114		"repo topics":          {"alice/app"},
115		"repo refs":            {"alice/app"},
116		"repo log":             {"alice/app"},
117		"repo tree":            {"alice/app"},
118		"repo cat":             {"alice/app", "f.go"},
119		"repo blame":           {"alice/app", "f.go"},
120		"repo grep":            {"alice/app", "hello"},
121		"repo diff":            {"alice/app", "main", "feat"},
122		"repo commit":          {"alice/app", sha},
123		"repo download":        {"alice/app"},
124		"repo deploy-key list": {"alice/app"},
125		"repo secret list":     {"alice/app"},
126		"repo mirror list":     {"alice/app"},
127		"repo domain list":     {"alice/app"},
128		"repo deps status":     {"alice/app"},
129		"status list":          {"alice/app", sha},
130		"issue list":           {"alice/app"},
131		"issue show":           {"alice/app", "1"},
132		"issue templates":      {"alice/app"},
133		"label list":           {"alice/app"},
134		"milestone list":       {"alice/app"},
135		"mr list":              {"alice/app"},
136		"mr show":              {"alice/app", "1"},
137		"mr diff":              {"alice/app", "1"},
138		"mr threads":           {"alice/app", "1"},
139		"build list":           {"alice/app"},
140		"build jobs":           {"alice/app"},
141		"build show":           {"alice/app", "1"},
142		"build log":            {"alice/app", "1"},
143		"release list":         {"alice/app"},
144		"release show":         {"alice/app", "v1"},
145		"release asset get":    {"alice/app", "v1", "a.txt"},
146		"notifications list":   nil,
147		"repo bookmarks":       nil,
148		"search":               {"app"},
149		"mr revisions":         {"alice/app", "1"},
150		"mr range-diff":        {"alice/app", "1"},
151		"webhook list":         {"alice/app"},
152		"webhook deliveries":   {"alice/app"},
153		"wiki list":            {"alice/app"},
154		"wiki show":            {"alice/app"},
155	}
156	// Reads whose subject legitimately does not exist in this fixture.
157	notFoundOK := map[string]bool{"wiki show": true, "repo deps status": true}
158
159	dbPath := filepath.Join(inst.root, "gitbay.db")
160	before := dbFingerprint(t, dbPath)
161	for _, cmd := range control.Commands() {
162		if !cmd.ReadOnly {
163			continue
164		}
165		path := strings.Join(cmd.Path, " ")
166		args, ok := readArgs[path]
167		if !ok {
168			t.Errorf("%s is ReadOnly and has no arguments in this test; add an entry", path)
169			continue
170		}
171		_, errOut, code := inst.ssh(t, aliceKey, "", append(append([]string{}, cmd.Path...), args...)...)
172		if code != 0 && !(code == 3 && notFoundOK[path]) {
173			t.Errorf("%s: exit %d: %s", path, code, strings.TrimSpace(errOut))
174		}
175		after := dbFingerprint(t, dbPath)
176		for table, h := range after {
177			// The signature cache is filled by whichever read first shows
178			// a commit; a memo of a pure function is not state.
179			if table == "commit_signatures" {
180				continue
181			}
182			if before[table] != h {
183				t.Errorf("%s is ReadOnly but changed table %s", path, table)
184			}
185		}
186		before = after
187	}
188}
189
190// dbFingerprint hashes every row of every table, per table. Columns that
191// record a read happening (a key's last use, an account's last sight) are
192// left out: an ssh session touches them by design.
193func dbFingerprint(t *testing.T, path string) map[string]string {
194	t.Helper()
195	db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
196	if err != nil {
197		t.Fatal(err)
198	}
199	defer db.Close()
200	rows, err := db.Query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
201	if err != nil {
202		t.Fatal(err)
203	}
204	var tables []string
205	for rows.Next() {
206		var n string
207		rows.Scan(&n)
208		tables = append(tables, n)
209	}
210	rows.Close()
211	out := map[string]string{}
212	for _, table := range tables {
213		cols, err := db.Query(fmt.Sprintf("PRAGMA table_info(%q)", table))
214		if err != nil {
215			t.Fatal(err)
216		}
217		var names []string
218		for cols.Next() {
219			var cid int
220			var name, typ string
221			var notnull, pk int
222			var dflt any
223			cols.Scan(&cid, &name, &typ, &notnull, &dflt, &pk)
224			switch name {
225			case "last_used_at", "last_seen", "last_seen_at":
226				continue
227			}
228			names = append(names, fmt.Sprintf("%q", name))
229		}
230		cols.Close()
231		h := sha256.New()
232		data, err := db.Query(fmt.Sprintf("SELECT %s FROM %q ORDER BY %s", strings.Join(names, ","), table, strings.Join(names, ",")))
233		if err != nil {
234			t.Fatal(err)
235		}
236		vals := make([]any, len(names))
237		ptrs := make([]any, len(names))
238		for i := range vals {
239			ptrs[i] = &vals[i]
240		}
241		for data.Next() {
242			data.Scan(ptrs...)
243			fmt.Fprintf(h, "%v\n", vals)
244		}
245		data.Close()
246		out[table] = hex.EncodeToString(h.Sum(nil))
247	}
248	return out
249}