e2e/readonly_test.go

7a667c7b40578f9e76675c36ac11f236a882d711
gitbay/e2e/readonly_test.go history · blame · raw

251 lines · 9782 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 runner list":            {"alice/app"},
126		"repo secret list":            {"alice/app"},
127		"repo mirror list":            {"alice/app"},
128		"repo domain list":            {"alice/app"},
129		"repo deps status":            {"alice/app"},
130		"status list":                 {"alice/app", sha},
131		"issue list":                  {"alice/app"},
132		"issue show":                  {"alice/app", "1"},
133		"issue templates":             {"alice/app"},
134		"label list":                  {"alice/app"},
135		"milestone list":              {"alice/app"},
136		"mr list":                     {"alice/app"},
137		"mr show":                     {"alice/app", "1"},
138		"mr diff":                     {"alice/app", "1"},
139		"mr threads":                  {"alice/app", "1"},
140		"build list":                  {"alice/app"},
141		"build jobs":                  {"alice/app"},
142		"build show":                  {"alice/app", "1"},
143		"build log":                   {"alice/app", "1"},
144		"release list":                {"alice/app"},
145		"release show":                {"alice/app", "v1"},
146		"release asset get":           {"alice/app", "v1", "a.txt"},
147		"notifications list":          nil,
148		"notifications settings show": nil,
149		"repo bookmarks":              nil,
150		"search":                      {"app"},
151		"mr revisions":                {"alice/app", "1"},
152		"mr range-diff":               {"alice/app", "1"},
153		"webhook list":                {"alice/app"},
154		"webhook deliveries":          {"alice/app"},
155		"wiki list":                   {"alice/app"},
156		"wiki show":                   {"alice/app"},
157	}
158	// Reads whose subject legitimately does not exist in this fixture.
159	notFoundOK := map[string]bool{"wiki show": true, "repo deps status": true}
160
161	dbPath := filepath.Join(inst.root, "gitbay.db")
162	before := dbFingerprint(t, dbPath)
163	for _, cmd := range control.Commands() {
164		if !cmd.ReadOnly {
165			continue
166		}
167		path := strings.Join(cmd.Path, " ")
168		args, ok := readArgs[path]
169		if !ok {
170			t.Errorf("%s is ReadOnly and has no arguments in this test; add an entry", path)
171			continue
172		}
173		_, errOut, code := inst.ssh(t, aliceKey, "", append(append([]string{}, cmd.Path...), args...)...)
174		if code != 0 && !(code == 3 && notFoundOK[path]) {
175			t.Errorf("%s: exit %d: %s", path, code, strings.TrimSpace(errOut))
176		}
177		after := dbFingerprint(t, dbPath)
178		for table, h := range after {
179			// The signature cache is filled by whichever read first shows
180			// a commit; a memo of a pure function is not state.
181			if table == "commit_signatures" {
182				continue
183			}
184			if before[table] != h {
185				t.Errorf("%s is ReadOnly but changed table %s", path, table)
186			}
187		}
188		before = after
189	}
190}
191
192// dbFingerprint hashes every row of every table, per table. Columns that
193// record a read happening (a key's last use, an account's last sight) are
194// left out: an ssh session touches them by design.
195func dbFingerprint(t *testing.T, path string) map[string]string {
196	t.Helper()
197	db, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
198	if err != nil {
199		t.Fatal(err)
200	}
201	defer db.Close()
202	rows, err := db.Query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
203	if err != nil {
204		t.Fatal(err)
205	}
206	var tables []string
207	for rows.Next() {
208		var n string
209		rows.Scan(&n)
210		tables = append(tables, n)
211	}
212	rows.Close()
213	out := map[string]string{}
214	for _, table := range tables {
215		cols, err := db.Query(fmt.Sprintf("PRAGMA table_info(%q)", table))
216		if err != nil {
217			t.Fatal(err)
218		}
219		var names []string
220		for cols.Next() {
221			var cid int
222			var name, typ string
223			var notnull, pk int
224			var dflt any
225			cols.Scan(&cid, &name, &typ, &notnull, &dflt, &pk)
226			switch name {
227			case "last_used_at", "last_seen", "last_seen_at":
228				continue
229			}
230			names = append(names, fmt.Sprintf("%q", name))
231		}
232		cols.Close()
233		h := sha256.New()
234		data, err := db.Query(fmt.Sprintf("SELECT %s FROM %q ORDER BY %s", strings.Join(names, ","), table, strings.Join(names, ",")))
235		if err != nil {
236			t.Fatal(err)
237		}
238		vals := make([]any, len(names))
239		ptrs := make([]any, len(names))
240		for i := range vals {
241			ptrs[i] = &vals[i]
242		}
243		for data.Next() {
244			data.Scan(ptrs...)
245			fmt.Fprintf(h, "%v\n", vals)
246		}
247		data.Close()
248		out[table] = hex.EncodeToString(h.Sum(nil))
249	}
250	return out
251}