internal/control/stage3repo_test.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/control/stage3repo_test.go

407 lines · 16563 bytes

17 symbols in this file
  1package control
  2
  3import (
  4	"bytes"
  5	"crypto/ed25519"
  6	"encoding/json"
  7	"os"
  8	"os/exec"
  9	"path/filepath"
 10	"strings"
 11	"testing"
 12
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15	"golang.org/x/crypto/ssh"
 16)
 17
 18// dispatchAs runs argv as u with stdin, piped, and returns stdout; a
 19// non-zero exit fails t.
 20func dispatchAs(t *testing.T, st *store.Store, u store.User, stdin string, argv ...string) string {
 21	t.Helper()
 22	return dispatchIn(t, st, u, "", stdin, argv...)
 23}
 24
 25// dispatchIn is dispatchAs with repositories under root.
 26func dispatchIn(t *testing.T, st *store.Store, u store.User, root, stdin string, argv ...string) string {
 27	t.Helper()
 28	out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
 29	c := &Ctx{User: u, Scope: "full", Store: st, Stdout: out, Stderr: errOut, Stdin: strings.NewReader(stdin)}
 30	c.Cfg.Server.Root = root
 31	// Fixtures write a lot as user 1; the write limiter is global to
 32	// the package, so leave its budget to the tests that exercise it.
 33	c.Cfg.Limits.WriteRate = -1
 34	c.Cfg.Limits.MaxSnippetBytes = 1 << 20
 35	c.Cfg.Limits.MaxBlobBytes = 1 << 20
 36	if code := Dispatch(c, argv); code != protocol.ExitOK {
 37		t.Fatalf("%v: exit %d: %s", argv, code, errOut)
 38	}
 39	return out.String()
 40}
 41
 42// atTerminal runs argv as u at a 100-column terminal without colour
 43// and returns stdout; a non-zero exit fails t.
 44func atTerminal(t *testing.T, st *store.Store, u store.User, argv ...string) string {
 45	t.Helper()
 46	return atTerminalIn(t, st, u, "", argv...)
 47}
 48
 49// atTerminalIn is atTerminal with repositories under root.
 50func atTerminalIn(t *testing.T, st *store.Store, u store.User, root string, argv ...string) string {
 51	t.Helper()
 52	out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
 53	c := &Ctx{User: u, Scope: "full", Store: st, Stdout: out, Stderr: errOut, Stdin: strings.NewReader(""), Term: Term{Cols: 100}}
 54	c.Cfg.Server.Root = root
 55	// Fixtures write a lot as user 1; the write limiter is global to
 56	// the package, so leave its budget to the tests that exercise it.
 57	c.Cfg.Limits.WriteRate = -1
 58	c.Cfg.Limits.MaxSnippetBytes = 1 << 20
 59	c.Cfg.Limits.MaxBlobBytes = 1 << 20
 60	if code := Dispatch(c, argv); code != protocol.ExitOK {
 61		t.Fatalf("%v: exit %d: %s", argv, code, errOut)
 62	}
 63	return out.String()
 64}
 65
 66// checkLegend fails t for any suggested command in a rendered screen
 67// (a line starting "gitbay ", or after "+n more  ") that the registry
 68// would not dispatch with the flags it names.
 69func checkLegend(t *testing.T, out string) {
 70	t.Helper()
 71	var s screen
 72	for _, line := range strings.Split(out, "\n") {
 73		if i := strings.Index(line, "more  gitbay "); i >= 0 {
 74			line = line[i+len("more  "):]
 75		}
 76		for _, cmd := range strings.Split(line, "  ") {
 77			cmd = strings.TrimSpace(cmd)
 78			if !strings.HasPrefix(cmd, "gitbay ") {
 79				continue
 80			}
 81			argv, err := protocol.Tokenize(strings.TrimPrefix(cmd, "gitbay "))
 82			if err != nil {
 83				t.Errorf("%q: %v", cmd, err)
 84				continue
 85			}
 86			s.actions = append(s.actions, action{"", argv})
 87		}
 88	}
 89	if len(s.actions) == 0 {
 90		t.Errorf("no suggested commands in:\n%s", out)
 91	}
 92	checkActions(t, s)
 93}
 94
 95// newPubKey is an ed25519 public key in authorized_keys form, the same
 96// on every run so its fingerprint can be pinned.
 97func newPubKey(t *testing.T) string {
 98	t.Helper()
 99	pub := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize)).Public().(ed25519.PublicKey)
100	sp, err := ssh.NewPublicKey(pub)
101	if err != nil {
102		t.Fatal(err)
103	}
104	return string(ssh.MarshalAuthorizedKey(sp))
105}
106
107// repoListsFixture is a repository with something in every list task 1
108// migrates.
109func repoListsFixture(t *testing.T) (*store.Store, store.Repo, store.User) {
110	t.Helper()
111	st, repo, uid := newQueueTestRepo(t)
112	owner := store.User{ID: uid, Username: "alice", IsAdmin: true}
113	p := repo.Path()
114	dispatchAs(t, st, owner, "", "repo", "topics", "add", p, "cli", "forge")
115	dispatchAs(t, st, owner, "s3cret\n", "repo", "secret", "set", p, "DEPLOY_TOKEN")
116	dispatchAs(t, st, owner, testRunnerPub, "repo", "deploy-key", "add", p)
117	dispatchAs(t, st, owner, "", "repo", "domain", "add", p, "docs.example.test")
118	dispatchAs(t, st, owner, "", "repo", "bookmark", p)
119	// mirror add resolves the host, so the fixture goes to the store.
120	if _, err := st.AddMirror(repo.ID, "push", "https://mirror.example.test/app.git", "", "tok"); err != nil {
121		t.Fatal(err)
122	}
123	dispatchAs(t, st, owner, newPubKey(t), "repo", "runner", "add", p)
124	return st, repo, owner
125}
126
127func TestRepoListsPlainPinned(t *testing.T) {
128	st, repo, owner := repoListsFixture(t)
129	p := repo.Path()
130	for name, argv := range map[string][]string{
131		"repo-topics":          {"repo", "topics", p},
132		"repo-secret-list":     {"repo", "secret", "list", p},
133		"repo-deploy-key-list": {"repo", "deploy-key", "list", p},
134		"repo-domain-list":     {"repo", "domain", "list", p},
135		"repo-access-list":     {"repo", "access", "list", p},
136		"repo-bookmarks":       {"repo", "bookmarks"},
137		"repo-search":          {"repo", "search", "app"},
138		"repo-list":            {"repo", "list"},
139		"repo-mirror-list":     {"repo", "mirror", "list", p},
140		"repo-runner-list":     {"repo", "runner", "list", p},
141	} {
142		pinPlain(t, name, dispatchAs(t, st, owner, "", argv...))
143	}
144	pinPlain(t, "repo-topics-add", dispatchAs(t, st, owner, "", "repo", "topics", "add", p, "git"))
145}
146
147func TestRepoListScreens(t *testing.T) {
148	st, repo, owner := repoListsFixture(t)
149	p := repo.Path()
150	for _, tc := range []struct {
151		argv []string
152		want []string
153	}{
154		{[]string{"repo", "topics", p}, []string{"Topics (2)\ncli\nforge\n"}},
155		{[]string{"repo", "topics", "add", p, "git"}, []string{"Topics (3)\n"}},
156		{[]string{"repo", "secret", "list", p}, []string{"Build secrets (1)\nDEPLOY_TOKEN\n"}},
157		{[]string{"repo", "deploy-key", "list", p}, []string{"Deploy keys (1)\n", "  ro  runner@test  ssh-ed25519 · used never"}},
158		{[]string{"repo", "domain", "list", p}, []string{"Pages domains (1)\n", "◐  docs.example.test  pending"}},
159		{[]string{"repo", "access", "list", p}, []string{"Access (1)\nalice  admin  via owner\n"}},
160		{[]string{"repo", "mirror", "list", p}, []string{"Mirrors (1)\n1  ◐  https://mirror.example.test/app.git  push · never synced"}},
161		{[]string{"repo", "runner", "list", p}, []string{"Runners (1)\n", "  alice  ssh-ed25519 · never seen"}},
162		{[]string{"repo", "bookmarks"}, []string{"Bookmarks (1)\nalice/app  public  1 bookmark\n"}},
163		{[]string{"repo", "search", "app"}, []string{"Repositories matching \"app\" (1)\nalice/app  public  cli, forge"}},
164		{[]string{"repo", "list"}, []string{"Repositories (1)\nalice/app  public\n"}},
165	} {
166		out := atTerminal(t, st, owner, tc.argv...)
167		for _, w := range tc.want {
168			if !strings.Contains(out, w) {
169				t.Errorf("%v: missing %q in:\n%s", tc.argv, w, out)
170			}
171		}
172		if strings.Contains(out, "s3cret") || strings.Contains(out, "tok\n") {
173			t.Errorf("%v: secret on screen:\n%s", tc.argv, out)
174		}
175		checkLegend(t, out)
176	}
177}
178
179// browseFixture is a repository on disk under root: two commits on main
180// (the second touching docs/), a branch, and a tag, with fixed dates so
181// the shas are the same on every run.
182func browseFixture(t *testing.T) (*store.Store, store.Repo, store.User, string) {
183	t.Helper()
184	st, repo, uid := newQueueTestRepo(t)
185	root := t.TempDir()
186	env := append(gitTestEnv(), "GIT_AUTHOR_DATE=2026-09-01T10:00:00Z", "GIT_COMMITTER_DATE=2026-09-01T10:00:00Z")
187	git := func(dir string, args ...string) {
188		t.Helper()
189		cmd := exec.Command("git", args...)
190		cmd.Dir, cmd.Env = dir, env
191		if out, err := cmd.CombinedOutput(); err != nil {
192			t.Fatalf("git %v: %v\n%s", args, err, out)
193		}
194	}
195	src := filepath.Join(root, "src")
196	if err := os.MkdirAll(filepath.Join(src, "docs"), 0o755); err != nil {
197		t.Fatal(err)
198	}
199	os.WriteFile(filepath.Join(src, "README.md"), []byte("# app\n"), 0o644)
200	git(root, "init", "-q", "-b", "main", "src")
201	git(src, "add", ".")
202	git(src, "commit", "-q", "-m", "first")
203	os.WriteFile(filepath.Join(src, "docs", "guide.md"), []byte("# guide\n"), 0o644)
204	git(src, "add", ".")
205	git(src, "commit", "-q", "-m", "docs: guide")
206	git(src, "tag", "v1.0.0")
207	git(src, "branch", "feature")
208	dir := RepoDir(root, repo.OwnerName, repo.Name)
209	os.MkdirAll(filepath.Dir(dir), 0o755)
210	git(root, "clone", "-q", "--bare", src, dir)
211	return st, repo, store.User{ID: uid, Username: "alice"}, root
212}
213
214func TestRepoBrowsePlainPinned(t *testing.T) {
215	st, repo, u, root := browseFixture(t)
216	p := repo.Path()
217	for name, argv := range map[string][]string{
218		"repo-log":       {"repo", "log", p},
219		"repo-log-path":  {"repo", "log", p, "--path", "docs/guide.md"},
220		"repo-tree":      {"repo", "tree", p},
221		"repo-tree-docs": {"repo", "tree", p, "docs"},
222		"repo-refs":      {"repo", "refs", p},
223	} {
224		pinPlain(t, name, dispatchIn(t, st, u, root, "", argv...))
225	}
226	sst, srepo, alice, _ := symbolsFixture(t)
227	pinPlain(t, "repo-symbols", dispatchAs(t, sst, alice, "", "repo", "symbols", srepo.Path(), "Pars"))
228}
229
230func TestRepoBrowseScreens(t *testing.T) {
231	st, repo, u, root := browseFixture(t)
232	p := repo.Path()
233	for _, tc := range []struct {
234		argv []string
235		want []string
236	}{
237		{[]string{"repo", "log", p}, []string{"Commits on main (2)\n", "  docs: guide  t · "}},
238		{[]string{"repo", "log", p, "--path", "docs/guide.md"}, []string{"Commits on main touching docs/guide.md (1)\n"}},
239		{[]string{"repo", "tree", p}, []string{"alice/app at main (2)\n", "docs/", "README.md"}},
240		{[]string{"repo", "tree", p, "docs"}, []string{"alice/app/docs at main (1)\n", "guide.md"}},
241		{[]string{"repo", "refs", p}, []string{"Branches (2)\nmain", "default", "Tags (1)\nv1.0.0"}},
242	} {
243		out := atTerminalIn(t, st, u, root, tc.argv...)
244		for _, w := range tc.want {
245			if !strings.Contains(out, w) {
246				t.Errorf("%v: missing %q in:\n%s", tc.argv, w, out)
247			}
248		}
249		checkLegend(t, out)
250	}
251	sst, srepo, alice, _ := symbolsFixture(t)
252	out := atTerminal(t, sst, alice, "repo", "symbols", srepo.Path(), "Pars")
253	if !strings.Contains(out, "Symbols matching \"Pars\" (") || !strings.Contains(out, "Parse       function  p.go:1") {
254		t.Errorf("symbols:\n%s", out)
255	}
256	checkLegend(t, out)
257}
258
259func TestRepoShowsPlainPinned(t *testing.T) {
260	st, repo, u, root := browseFixture(t)
261	p := repo.Path()
262	pinPlain(t, "repo-settings-show", dispatchIn(t, st, u, root, "", "repo", "settings", "show", p))
263	pinPlain(t, "repo-deps-status-off", dispatchIn(t, st, u, root, "", "repo", "deps", "status", p))
264	pinPlain(t, "repo-commit", dispatchIn(t, st, u, root, "", "repo", "commit", p, "aee4475ad9"))
265	dispatchIn(t, st, u, root, "", "repo", "deps", "enable", p)
266	pinPlain(t, "repo-deps-status", dispatchIn(t, st, u, root, "", "repo", "deps", "status", p))
267}
268
269func TestRepoShowScreens(t *testing.T) {
270	st, repo, u, root := browseFixture(t)
271	p := repo.Path()
272	for _, tc := range []struct {
273		argv []string
274		want []string
275	}{
276		{[]string{"repo", "settings", "show", p}, []string{"Repo:", "alice/app", "Require MR:", "off", "Approvals:"}},
277		{[]string{"repo", "deps", "status", p}, []string{"Checks:  off\n", "gitbay repo deps enable alice/app"}},
278		{[]string{"repo", "commit", p, "aee4475ad9"}, []string{"Commit:", "aee4475ad9  docs: guide", "Author:", "t <t@example.test>", "gitbay repo log alice/app --ref aee4475ad9", "+# guide"}},
279	} {
280		out := atTerminalIn(t, st, u, root, tc.argv...)
281		for _, w := range tc.want {
282			if !strings.Contains(out, w) {
283				t.Errorf("%v: missing %q in:\n%s", tc.argv, w, out)
284			}
285		}
286		checkLegend(t, out)
287	}
288	dispatchIn(t, st, u, root, "", "repo", "deps", "enable", p)
289	out := atTerminalIn(t, st, u, root, "repo", "deps", "status", p)
290	if !strings.Contains(out, "Checks:") || !strings.Contains(out, "gitbay repo deps disable alice/app") {
291		t.Errorf("deps on:\n%s", out)
292	}
293	checkLegend(t, out)
294	if i, j := strings.Index(out, "gitbay repo deps"), strings.Index(out, "Checks:"); i < j {
295		t.Errorf("legend before the header:\n%s", out)
296	}
297}
298
299// At 60 columns no screen line is wider than the terminal, apart from a
300// suggested command: e2e's readonly test holds every read command to it.
301func TestRepoScreensFitSixtyColumns(t *testing.T) {
302	st, repo, owner := repoListsFixture(t)
303	p := repo.Path()
304	for _, argv := range [][]string{
305		{"repo", "deploy-key", "list", p},
306		{"repo", "runner", "list", p},
307		{"repo", "mirror", "list", p},
308	} {
309		out, errOut := &bytes.Buffer{}, &bytes.Buffer{}
310		c := &Ctx{User: owner, Scope: "full", Store: st, Stdout: out, Stderr: errOut, Term: Term{Cols: 60}}
311		c.Cfg.Limits.WriteRate = -1
312		if code := Dispatch(c, argv); code != protocol.ExitOK {
313			t.Fatalf("%v: exit %d: %s", argv, code, errOut)
314		}
315		for _, line := range strings.Split(out.String(), "\n") {
316			if cells(line) > 60 && !strings.HasPrefix(line, "gitbay ") {
317				t.Errorf("%v: %d cells: %q", argv, cells(line), line)
318			}
319		}
320	}
321}
322
323func TestRepoDepsStatusAdvisories(t *testing.T) {
324	st, repo, u, root := browseFixture(t)
325	p := repo.Path()
326	dispatchIn(t, st, u, root, "", "repo", "deps", "enable", p)
327	if err := st.ReplaceDepAdvisories(repo.ID, []store.DepAdvisory{{Ecosystem: "go", Name: "golang.org/x/net",
328		Version: "v0.1.0", ID: "GO-2026-1", Summary: "reset flood", Severity: "high", Fixed: "0.7.0"}}); err != nil {
329		t.Fatal(err)
330	}
331	if err := st.SetDepAdvisoryIssue(repo.ID, 7); err != nil {
332		t.Fatal(err)
333	}
334	var got struct {
335		Data DepsOut `json:"data"`
336	}
337	if err := json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "deps", "status", p, "--json")), &got); err != nil {
338		t.Fatal(err)
339	}
340	if got.Data.AdvisoryIssueNumber != 7 || len(got.Data.Advisories) != 1 || got.Data.Advisories[0].ID != "GO-2026-1" {
341		t.Errorf("status = %+v", got.Data)
342	}
343	plain := dispatchIn(t, st, u, root, "", "repo", "deps", "status", p)
344	if !strings.Contains(plain, "advisories in  #7") || !strings.Contains(plain, "GO-2026-1") {
345		t.Errorf("plain:\n%s", plain)
346	}
347	out := atTerminalIn(t, st, u, root, "repo", "deps", "status", p)
348	if !strings.Contains(out, "Advisories (1)") || !strings.Contains(out, "v0.1.0 → 0.7.0") {
349		t.Errorf("screen:\n%s", out)
350	}
351	checkLegend(t, out)
352}
353
354// Dismissing an advisory takes it out of the issue and closes the issue
355// once none are open; one nothing imports is listed apart; reopening brings
356// a dismissed one back.
357func TestRepoDepsDismiss(t *testing.T) {
358	st, repo, u, root := browseFixture(t)
359	p := repo.Path()
360	dispatchIn(t, st, u, root, "", "repo", "deps", "enable", p)
361	matched := []store.DepAdvisory{
362		{Ecosystem: "go", Name: "golang.org/x/net", Version: "v0.1.0", ID: "GO-2026-1", Summary: "reset flood"},
363		{Ecosystem: "go", Name: "golang.org/x/crypto", Version: "v0.58.0", ID: "GO-2026-5932", Summary: "openpgp", NotImported: true},
364	}
365	if err := st.ReplaceDepAdvisories(repo.ID, matched); err != nil {
366		t.Fatal(err)
367	}
368	c, out := runnerCtx(st, u.ID, root)
369	if code := runDepsDismiss(c, []string{p, "GO-2026-1", "--reason", "nope"}); code != protocol.ExitUsage {
370		t.Errorf("bad reason: %d %s", code, out)
371	}
372	c, out = runnerCtx(st, u.ID, root)
373	if code := runDepsDismiss(c, []string{p, "GO-9", "--reason", "not-affected"}); code != protocol.ExitNotFound {
374		t.Errorf("unknown advisory: %d %s", code, out)
375	}
376	// Reopen first so there is an issue to watch: a reopen of nothing
377	// dismissed still rewrites it.
378	c, out = runnerCtx(st, u.ID, root)
379	if code := runDepsReopen(c, []string{p, "GO-2026-1"}); code != protocol.ExitOK {
380		t.Fatalf("reopen: %d %s", code, out)
381	}
382	check, _ := st.DepCheckFor(repo.ID)
383	issue, _ := st.IssueByNumber(repo.ID, check.AdvisoryIssueNumber)
384	if issue.State != "open" || !strings.Contains(issue.Body, "GO-2026-1:") || !strings.Contains(issue.Body, "imports: GO-2026-5932") {
385		t.Fatalf("issue (%s):\n%s", issue.State, issue.Body)
386	}
387	c, out = runnerCtx(st, u.ID, root)
388	if code := runDepsDismiss(c, []string{p, "GO-2026-1", "--reason", "not-affected"}); code != protocol.ExitOK {
389		t.Fatalf("dismiss: %d %s", code, out)
390	}
391	if closed, _ := st.IssueByNumber(repo.ID, check.AdvisoryIssueNumber); closed.State != "closed" {
392		t.Errorf("issue with nothing open is %s", closed.State)
393	}
394	var got struct {
395		Data DepsOut `json:"data"`
396	}
397	json.Unmarshal([]byte(dispatchIn(t, st, u, root, "", "repo", "deps", "status", p, "--json")), &got)
398	if len(got.Data.Advisories) != 0 || len(got.Data.Dismissed) != 1 || got.Data.Dismissed[0].Reason != "not-affected" ||
399		len(got.Data.NotImported) != 1 || got.Data.NotImported[0].ID != "GO-2026-5932" {
400		t.Errorf("status = %+v", got.Data)
401	}
402	screen := atTerminalIn(t, st, u, root, "repo", "deps", "status", p)
403	if !strings.Contains(screen, "Dismissed (1)") || !strings.Contains(screen, "Not imported (1)") {
404		t.Errorf("screen:\n%s", screen)
405	}
406	checkLegend(t, screen)
407}