detached 388d3be

web_mr_test.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package app
4
5import (
6	"fmt"
7	"html"
8	"net/http"
9	"net/url"
10	"regexp"
11	"strings"
12	"testing"
13
14	"github.com/stretchr/testify/assert"
15	"github.com/stretchr/testify/require"
16
17	"bnema.dev/ermite/internal/domain"
18	"bnema.dev/ermite/internal/ports"
19)
20
21// mrRepo is a public repository "proj" with README.md on main and a branch
22// feat/search that is one commit ahead of it (search.go, three lines).
23type mrRepo struct {
24	*cliHarness
25	wt, url string
26}
27
28func newMRRepo(t *testing.T, vis domain.Visibility) *mrRepo {
29	t.Helper()
30	c := newCLIHarness(t)
31	_, err := c.forge.Repos.Create(c.ctx, domain.Root(), createParams(c.harness, "proj", vis))
32	require.NoError(t, err)
33	r := &mrRepo{cliHarness: c, wt: c.workTree("main", "README.md"), url: c.urlAuth(adminToken, "/proj.git")}
34	c.mustGit(r.wt, "push", "-q", r.url, "main")
35	c.mustGit(r.wt, "checkout", "-q", "-b", "feat/search")
36	c.writeFile(r.wt, "search.go", []byte("package search\n\nfunc Find() {}\n"))
37	c.mustGit(r.wt, "push", "-q", r.url, "feat/search")
38	return r
39}
40
41func (r *mrRepo) headOf(branch string) string { return r.bareGit("proj", "rev-parse", branch) }
42
43// form posts url-encoded values as the signed-in owner, from this site.
44func (b browser) form(path, token string, values url.Values) page {
45	b.h.t.Helper()
46	return b.do("POST", path, post(token), values.Encode())
47}
48
49var reHeadField = regexp.MustCompile(`name="head_id" value="([0-9a-f]{40})"`)
50
51// formHead reads the head the merge form of a page carries.
52func formHead(t *testing.T, body string) string {
53	t.Helper()
54	m := reHeadField.FindStringSubmatch(body)
55	require.Len(t, m, 2, "the page has a merge form")
56	return m[1]
57}
58
59// AC7: the pages as an anonymous visitor sees them on a public repository:
60// read-only, no forms, public cache headers; the same pages signed in carry
61// the forms and the private headers.
62func TestWebMergeRequestPagesRender(t *testing.T) {
63	r := newMRRepo(t, domain.VisibilityPublic)
64	b := browser{r.harness}
65	token := r.signIn(t)
66
67	// The compare page: anonymous reads, the owner gets the form.
68	anon := b.get("/proj/compare/feat/search", nil)
69	require.Equal(t, 200, anon.status, anon.body)
70	assert.Equal(t, "no-cache", anon.hdr.Get("Cache-Control"))
71	assert.Equal(t, []string{"Accept-Encoding"}, anon.hdr.Values("Vary"))
72	assert.Contains(t, anon.body, "feat/search")
73	assert.Contains(t, anon.body, `<span class="kn">package</span> search</td>`, "the diff of the single commit")
74	assert.NotContains(t, anon.body, "<form class=\"cform create\"")
75	assert.NotContains(t, anon.body, `<form class="cform create"`)
76	assertNoInline(t, anon.body)
77	owner := b.get("/proj/compare/feat/search", as(token))
78	require.Equal(t, 200, owner.status)
79	assert.Equal(t, "private, no-store", owner.hdr.Get("Cache-Control"))
80	assert.Contains(t, owner.hdr.Values("Vary"), "Cookie")
81	assert.Contains(t, owner.body, `<form class="cform create" method="post" action="/proj/merge-requests">`)
82	assert.Contains(t, owner.body, `name="source" value="feat/search"`)
83	assert.Contains(t, owner.body, `name="target" value="main"`)
84	assert.Equal(t, 404, b.get("/proj/compare/nope", nil).status)
85	assert.Equal(t, 404, b.get("/proj/compare/main/extra", nil).status)
86	main := b.get("/proj/compare/main", nil)
87	assert.Equal(t, 200, main.status)
88	assert.Contains(t, main.body, "nothing to compare")
89
90	// An empty list, with the way to start one.
91	list := b.get("/proj/merge-requests", nil)
92	require.Equal(t, 200, list.status)
93	assert.Contains(t, list.body, "no open merge requests")
94	assert.Contains(t, list.body, `href="/proj/compare/feat/search"`)
95	assert.Contains(t, list.body, `data-key="m"`, "the section of the nav")
96	assert.NotContains(t, strings.ToLower(list.body), "proposal")
97
98	// Open one from the compare page.
99	res := b.form("/proj/merge-requests", token, url.Values{
100		"source": {"feat/search"}, "target": {"main"}, "title": {"Add <b>search</b>"},
101		"description": {"## Summary\r\n\r\nFinds **things** with `Find()`.\r\n\r\n- See https://example.org/spec) and javascript:alert(1)\r\n- [x](javascript:alert(1)) <script>alert(1)</script>"},
102	})
103	require.Equal(t, http.StatusSeeOther, res.status, res.body)
104	assert.Equal(t, "/proj/merge-requests/1", res.hdr.Get("Location"))
105	assert.Equal(t, "no-store", res.hdr.Get("Cache-Control"))
106	head := r.headOf("feat/search")
107
108	// The same pair twice is refused with a page, and nothing is created.
109	dup := b.form("/proj/merge-requests", token, url.Values{"source": {"feat/search"}, "target": {"main"}, "title": {"dup"}})
110	assert.Equal(t, http.StatusConflict, dup.status)
111	assert.Equal(t, "no-store", dup.hdr.Get("Cache-Control"))
112	assert.Contains(t, dup.body, "already exists")
113	bad := b.form("/proj/merge-requests", token, url.Values{"source": {"feat/search"}, "target": {"main"}, "title": {"bidi\u202etitle"}})
114	assert.Equal(t, http.StatusBadRequest, bad.status)
115	assert.NotContains(t, bad.body, "\u202e")
116
117	// The compare page now points at it.
118	assert.Contains(t, b.get("/proj/compare/feat/search", as(token)).body, `href="/proj/merge-requests/1"`)
119	assert.NotContains(t, b.get("/proj/compare/feat/search", as(token)).body, `<form class="cform create"`)
120
121	// The list.
122	list = b.get("/proj/merge-requests", nil)
123	assert.Contains(t, list.body, `<a href="/proj/merge-requests/1">Add &lt;b&gt;search&lt;/b&gt;</a>`)
124	assert.Contains(t, list.body, "feat/search → main")
125	assert.Equal(t, "no-cache", list.hdr.Get("Cache-Control"))
126	assertNoInline(t, list.body)
127	assert.Equal(t, "private, no-store", b.get("/proj/merge-requests", as(token)).hdr.Get("Cache-Control"))
128
129	// The page, anonymous: read-only.
130	mr := b.get("/proj/merge-requests/1", nil)
131	require.Equal(t, 200, mr.status, mr.body)
132	assert.Equal(t, "no-cache", mr.hdr.Get("Cache-Control"))
133	assert.Equal(t, []string{"Accept-Encoding"}, mr.hdr.Values("Vary"))
134	assert.Contains(t, mr.body, "<h1><span class=\"mute\">#1</span> Add &lt;b&gt;search&lt;/b&gt;</h1>")
135	assert.NotContains(t, mr.body, "<b>search</b>")
136	assert.Contains(t, mr.body, "feat/search")
137	assert.Contains(t, mr.body, `<span class="kn">package</span> search</td>`)
138	assert.Contains(t, mr.body, "no checks")
139	assert.Contains(t, mr.body, "fast-forward, squash")
140	// The description is Markdown, rendered as a README: no raw HTML, no
141	// script URL; its heading ids keep apart from the ids of the page.
142	assert.Contains(t, mr.body, `<article class="mr-desc prose" aria-label="description" hx-ignore>`)
143	assert.Contains(t, mr.body, `<h2 id="mr-desc-summary">Summary</h2>`)
144	assert.Contains(t, mr.body, `<strong>things</strong>`)
145	assert.Contains(t, mr.body, `<code>Find()</code>`)
146	assert.Contains(t, mr.body, `<a href="https://example.org/spec"`, "a bare address is linked")
147	assert.NotContains(t, mr.body, `href="javascript:`)
148	assert.NotContains(t, mr.body, `<script>alert(1)</script>`)
149	assert.NotContains(t, mr.body, "<form", "an anonymous visitor gets no form")
150	assert.NotContains(t, mr.body, "ermite mr merge", "nor the merge line")
151	assert.NotContains(t, mr.body, `id="merge-menu"`)
152	assert.Contains(t, mr.body, `href="/proj/commit/`+head+`"`, "the commits are in the rail")
153	assert.NotContains(t, strings.ToLower(mr.body), "proposal")
154	assertNoInline(t, mr.body)
155	assert.Equal(t, 404, b.get("/proj/merge-requests/1/since", nil).status, "the read position is the owner's")
156	assert.Equal(t, 404, b.get("/proj/merge-requests/9", nil).status)
157	assert.Equal(t, 404, b.get("/proj/merge-requests/01", nil).status)
158	assert.Equal(t, 404, b.get("/proj/merge-requests/x", nil).status)
159
160	// Signed in: forms, the merge box with the head and the CLI lines.
161	own := b.get("/proj/merge-requests/1", as(token))
162	require.Equal(t, 200, own.status)
163	assert.Equal(t, "private, no-store", own.hdr.Get("Cache-Control"))
164	assert.Contains(t, own.hdr.Values("Vary"), "Cookie")
165	assert.Equal(t, head, formHead(t, own.body))
166	assert.Contains(t, own.body, `action="/proj/merge-requests/1/merge"`)
167	assert.Contains(t, own.body, `id="merge-menu"`, "the merge is a menu of the bar above the diff")
168	assert.Contains(t, own.body, `<input type="radio" name="mode" value="fast-forward" checked>`, "the first mode is the default")
169	assert.Contains(t, own.body, `<input type="radio" name="mode" value="squash">`)
170	assert.Contains(t, own.body, "ermite mr merge proj 1 --head "+head)
171	assert.Contains(t, own.body, `name="delete_branch" value="1"> delete feat/search after the merge <kbd aria-hidden="true">D</kbd>`)
172	assert.NotContains(t, own.body, `name="delete_branch" value="1" checked>`, "unchecked by default")
173	assert.Contains(t, own.body, "ermite mr merge proj 1 --head "+head+" --squash")
174	assert.Contains(t, own.body, `action="/proj/merge-requests/1/comments"`)
175	assert.Contains(t, own.body, `action="/proj/merge-requests/1/close"`)
176	assert.Contains(t, own.body, `href="/proj/merge-requests/1?on=new:1:search.go#f`, "line numbers link to their form")
177	assertNoInline(t, own.body)
178
179	// Reading is safe: GET marked nothing as read.
180	assert.NotContains(t, own.body, "since your last read")
181	show := r.cli(t, adminToken, "mr", "show", "proj", "1", "--json").ok(t)
182	assert.Contains(t, show.stdout, `"last_read_id": ""`)
183}
184
185// A private repository is invisible to the anonymous visitor on every merge
186// request page, and the owner sees it.
187func TestWebMergeRequestPrivate(t *testing.T) {
188	r := newMRRepo(t, domain.VisibilityPrivate)
189	b := browser{r.harness}
190	token := r.signIn(t)
191	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "Secret plan").ok(t)
192
193	missing := b.get("/nothere/merge-requests/1", nil)
194	for _, p := range []string{
195		"/proj/merge-requests", "/proj/merge-requests/1", "/proj/merge-requests/1/since", "/proj/compare/feat/search",
196	} {
197		got := b.get(p, nil)
198		assert.Equal(t, 404, got.status, p)
199		assert.NotContains(t, got.body, "Secret plan", p)
200		assert.NotContains(t, got.body, "search.go", p)
201	}
202	assert.Equal(t, missing.body, b.get("/proj/merge-requests/1", nil).body, "same page as a missing repository")
203	assert.Equal(t, 404, b.get("/-/events?topic=repo:proj&view=mrs", nil).status)
204
205	for _, p := range []string{"/proj/merge-requests", "/proj/merge-requests/1", "/proj/merge-requests/1/since", "/proj/compare/feat/search"} {
206		got := b.get(p, as(token))
207		assert.Equal(t, 200, got.status, p)
208		assert.Equal(t, "private, no-store", got.hdr.Get("Cache-Control"), p)
209		assert.Contains(t, got.hdr.Values("Vary"), "Cookie", p)
210	}
211	assert.Contains(t, b.get("/proj/merge-requests", as(token)).body, "Secret plan")
212}
213
214// AC2: every write needs the session and an Origin of this site.
215func TestWebMergeRequestWritesNeedSessionAndOrigin(t *testing.T) {
216	r := newMRRepo(t, domain.VisibilityPublic)
217	b := browser{r.harness}
218	token := r.signIn(t)
219	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "t").ok(t)
220	head := r.headOf("feat/search")
221
222	paths := map[string]string{
223		"/proj/merge-requests":                      "source=feat/search&target=main&title=x",
224		"/proj/merge-requests/1/comments":           "text=hello",
225		"/proj/merge-requests/1/comments/1/resolve": "resolved=true",
226		"/proj/merge-requests/1/merge":              "mode=fast-forward&head_id=" + head,
227		"/proj/merge-requests/1/close":              "",
228		"/proj/merge-requests/1/read":               "head_id=" + head,
229		"/proj/merge-requests/1/ready":              "",
230	}
231	for path, body := range paths {
232		noOrigin := b.do("POST", path, as(token), body)
233		assert.Equal(t, 403, noOrigin.status, path+" without Origin")
234		assert.Equal(t, "no-store", noOrigin.hdr.Get("Cache-Control"))
235		foreign := b.do("POST", path, map[string]string{"Cookie": sessionCookie + "=" + token, "Origin": "https://evil.example"}, body)
236		assert.Equal(t, 403, foreign.status, path+" foreign Origin")
237		anon := b.do("POST", path, map[string]string{"Origin": publicOrigin}, body)
238		assert.Equal(t, 403, anon.status, path+" without a session")
239	}
240	// Nothing happened.
241	out := r.cli(t, "", "mr", "show", "proj", "1", "--json").ok(t).stdout
242	assert.Contains(t, out, `"state": "open"`)
243	assert.NotContains(t, out, "hello")
244	assert.Equal(t, "", strings.TrimSpace(r.bareGit("proj", "rev-list", "main..feat/search", "--not", "feat/search")))
245
246	// A GET on a write route is not a page.
247	assert.Equal(t, 404, b.get("/proj/merge-requests/1/merge", as(token)).status)
248	assert.Equal(t, 404, b.get("/proj/merge-requests/1/close", as(token)).status)
249}
250
251var reNoteID = regexp.MustCompile(`id="c(\d+)"`)
252
253// The review of one request, in the browser's words: a note on a line, a
254// general one, resolve, since the last read after a push, a stale head, the
255// fast-forward merge.
256func TestWebMergeRequestReviewAndFastForward(t *testing.T) {
257	r := newMRRepo(t, domain.VisibilityPublic)
258	b := browser{r.harness}
259	token := r.signIn(t)
260	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "Add search").ok(t)
261	head1 := r.headOf("feat/search")
262	base := "/proj/merge-requests/1"
263
264	// The form of a line, then the note under that line.
265	line := b.get(base+"?on=new:3:search.go", as(token))
266	require.Equal(t, 200, line.status)
267	assert.Contains(t, line.body, `<form class="cform"`)
268	assert.Contains(t, line.body, `name="path" value="search.go"`)
269	assert.Contains(t, line.body, `name="line" value="3"`)
270	assert.Contains(t, line.body, `name="side" value="new"`)
271	assert.Contains(t, line.body, `comment on search.go:3 (new)`, "one line: the title names it")
272	assert.Contains(t, b.get(base+"?on=new:1-3:search.go", as(token)).body, `comment on search.go:1-3 (new)`, "a range: the title names all of it")
273	assert.Equal(t, 0, strings.Count(b.get(base+"?on=new:99:search.go", as(token)).body, `name="line" value="99"`), "a line the diff lacks has no form")
274	assert.Equal(t, 0, strings.Count(b.get(base+"?on=new:3:search.go", nil).body, `<form`), "nor for a visitor")
275
276	res := b.form(base+"/comments", token, url.Values{"text": {"Why <i>empty</i>?\r\nSee https://example.org/a."}, "path": {"search.go"}, "line": {"3"}, "side": {"new"}})
277	require.Equal(t, http.StatusSeeOther, res.status, res.body)
278	assert.Equal(t, base+"#c1", res.hdr.Get("Location"))
279	assert.Equal(t, "no-store", res.hdr.Get("Cache-Control"))
280	res = b.form(base+"/comments", token, url.Values{"text": {"Looks fine overall."}})
281	require.Equal(t, http.StatusSeeOther, res.status, res.body)
282	assert.Equal(t, base+"#c2", res.hdr.Get("Location"))
283
284	anon := b.get(base, nil)
285	i := strings.Index(anon.body, `<tr class="fnote">`)
286	require.GreaterOrEqual(t, i, 0, "a note row under the line")
287	note := anon.body[i:]
288	assert.Less(t, strings.Index(note, "Why &lt;i&gt;empty&lt;/i&gt;?"), strings.Index(note, "</tr>"), "the note sits in the row under its line")
289	assert.Contains(t, anon.body, `<a href="https://example.org/a" rel="nofollow noopener noreferrer">https://example.org/a</a>.`)
290	assert.NotContains(t, anon.body, "<i>empty</i>")
291	assert.Contains(t, anon.body, "Looks fine overall.")
292	assert.Equal(t, 2, len(reNoteID.FindAllString(anon.body, -1)))
293	assert.NotContains(t, anon.body, "[resolve]", "a visitor cannot resolve")
294
295	// A comment that breaks a rule is refused with the rule, nothing is lost.
296	bad := b.form(base+"/comments", token, url.Values{"text": {"ok"}, "path": {"search.go"}, "line": {"99"}, "side": {"new"}})
297	assert.Equal(t, http.StatusBadRequest, bad.status)
298	assert.Equal(t, "no-store", bad.hdr.Get("Cache-Control"))
299	assert.Contains(t, bad.body, "search.go")
300	bad = b.form(base+"/comments", token, url.Values{"text": {"x"}, "path": {"search.go"}, "line": {"zz"}, "side": {"new"}})
301	assert.Equal(t, http.StatusBadRequest, bad.status)
302	bad = b.form(base+"/comments", token, url.Values{"text": {"x"}, "path": {"search.go"}, "line": {"3"}, "side": {"sideways"}})
303	assert.Equal(t, http.StatusBadRequest, bad.status)
304	bad = b.form(base+"/comments", token, url.Values{"text": {"evil\u202etext"}})
305	assert.Equal(t, http.StatusBadRequest, bad.status)
306	assert.NotContains(t, bad.body, "\u202e")
307	assert.Equal(t, 404, b.form("/proj/merge-requests/9/comments", token, url.Values{"text": {"x"}}).status)
308
309	// Resolve and unresolve.
310	own := b.get(base, as(token))
311	assert.Contains(t, own.body, `action="/proj/merge-requests/1/comments/1/resolve"`)
312	res = b.form(base+"/comments/1/resolve", token, url.Values{"resolved": {"true"}})
313	require.Equal(t, http.StatusSeeOther, res.status, res.body)
314	assert.Equal(t, base+"#c1", res.hdr.Get("Location"))
315	own = b.get(base, as(token))
316	assert.Contains(t, own.body, `data-resolved="true"`)
317	assert.Contains(t, own.body, ">Unresolve</button>")
318	assert.Equal(t, http.StatusSeeOther, b.form(base+"/comments/1/resolve", token, url.Values{"resolved": {"false"}}).status)
319	assert.Equal(t, http.StatusBadRequest, b.form(base+"/comments/1/resolve", token, url.Values{"resolved": {"maybe"}}).status)
320	assert.Equal(t, 404, b.form(base+"/comments/42/resolve", token, url.Values{"resolved": {"true"}}).status)
321
322	// Mark read, then push: the since page shows the new change only.
323	assert.Contains(t, own.body, `action="/proj/merge-requests/1/read"`)
324	res = b.form(base+"/read", token, url.Values{"head_id": {head1}})
325	require.Equal(t, http.StatusSeeOther, res.status, res.body)
326	assert.NotContains(t, b.get(base, as(token)).body, "data-read>Mark read", "the head is the one that was read")
327	r.writeFile(r.wt, "extra.txt", []byte("extra\n"))
328	r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
329	head2 := r.headOf("feat/search")
330
331	all := b.get(base, as(token))
332	assert.Contains(t, all.body, `href="/proj/merge-requests/1/since"`)
333	assert.Contains(t, all.body, "since your last read")
334	assert.Contains(t, all.body, "<li data-new>", "the commit pushed since is marked")
335	assert.Contains(t, all.body, "data-read>Mark read")
336	assert.Contains(t, all.body, "outdated", "the notes were written on the earlier head")
337	since := b.get(base+"/since", as(token))
338	require.Equal(t, 200, since.status, since.body)
339	assert.Equal(t, "private, no-store", since.hdr.Get("Cache-Control"))
340	assert.Contains(t, since.body, "changes since "+head1[:7])
341	assert.Contains(t, since.body, "extra</td>")
342	assert.NotContains(t, since.body, `<span class="kn">package</span> search</td>`, "only what changed after the read head")
343	assert.Contains(t, since.body, "empty", "the notes are listed below, their lines are not in this diff")
344	assert.NotContains(t, since.body, "<i>", "raw HTML is dropped")
345	assert.Contains(t, since.body, "search.go:3 (new)")
346	assert.NotContains(t, since.body, `<form class="cform"`, "no comment form on this diff")
347
348	// The merge form of the page the owner read carries that head: the push
349	// that came after is not merged unseen.
350	stale := b.form(base+"/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {head1}})
351	assert.Equal(t, http.StatusConflict, stale.status)
352	assert.Equal(t, "no-store", stale.hdr.Get("Cache-Control"))
353	assert.Contains(t, stale.body, "branch moved")
354	assert.NotEqual(t, head2, r.headOf("main"))
355	assert.Equal(t, http.StatusBadRequest, b.form(base+"/merge", token, url.Values{"mode": {"rebase"}, "head_id": {head2}}).status)
356	assert.Equal(t, http.StatusBadRequest, b.form(base+"/merge", token, url.Values{"mode": {"squash"}, "head_id": {"abc"}}).status)
357
358	// Fast-forward with the head that was read.
359	fresh := b.get(base, as(token))
360	require.Equal(t, head2, formHead(t, fresh.body))
361	res = b.form(base+"/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {formHead(t, fresh.body)}})
362	require.Equal(t, http.StatusSeeOther, res.status, res.body)
363	assert.Equal(t, base, res.hdr.Get("Location"))
364	assert.Equal(t, head2, r.headOf("main"), "the target moved to the head")
365
366	done := b.get(base, nil)
367	assert.Contains(t, done.body, "merged")
368	assert.Contains(t, done.body, "fast-forward")
369	assert.Contains(t, done.body, `href="/proj/commit/`+head2+`"`)
370	assert.NotContains(t, done.body, "<form")
371	assert.NotContains(t, b.get(base, as(token)).body, `id="merge-menu"`, "nothing to merge any more")
372	// Writes on a merged request are refused with a page.
373	late := b.form(base+"/comments", token, url.Values{"text": {"too late"}})
374	assert.Equal(t, http.StatusConflict, late.status)
375	assert.Equal(t, http.StatusConflict, b.form(base+"/close", token, nil).status)
376	list := b.get("/proj/merge-requests", nil)
377	assert.Contains(t, list.body, "Merged and closed")
378	assert.Regexp(t, `(?s)Merged and closed.*Add search`, list.body)
379}
380
381// Squash and close, and the order of the list: open first, then the decided.
382func TestWebMergeRequestSquashCloseAndList(t *testing.T) {
383	r := newMRRepo(t, domain.VisibilityPublic)
384	b := browser{r.harness}
385	token := r.signIn(t)
386	head := r.headOf("feat/search")
387	main0 := r.headOf("main")
388
389	// Open from compare with a description; the merge form squashes.
390	res := b.form("/proj/merge-requests", token, url.Values{
391		"source": {"feat/search"}, "target": {"main"}, "title": {"Squash me"}, "description": {""},
392	})
393	require.Equal(t, http.StatusSeeOther, res.status, res.body)
394	assert.Contains(t, b.get("/proj/merge-requests/1", as(token)).body, `name="delete_branch" value="1"`, "the box offers to delete the branch")
395	res = b.form("/proj/merge-requests/1/merge", token, url.Values{"mode": {"squash"}, "head_id": {head}, "delete_branch": {"1"}})
396	require.Equal(t, http.StatusSeeOther, res.status, res.body)
397	assert.Empty(t, r.bareGit("proj", "for-each-ref", "refs/heads/feat/search"), "the source branch is deleted")
398	merged := r.headOf("main")
399	assert.NotEqual(t, head, merged, "squash makes a new commit")
400	assert.Equal(t, main0, r.bareGit("proj", "rev-parse", "main^"), "on top of the old target")
401	assert.Contains(t, r.bareGit("proj", "cat-file", "-p", "main"), "gpgsig", "signed by the instance key")
402	page := b.get("/proj/merge-requests/1", nil)
403	assert.Contains(t, page.body, "squash")
404	assert.Contains(t, page.body, `href="/proj/commit/`+merged+`"`)
405
406	// A second request: closed.
407	r.mustGit(r.wt, "checkout", "-q", "-b", "feat/other", "main")
408	r.mustGit(r.wt, "pull", "-q", r.url, "main")
409	r.writeFile(r.wt, "other.go", []byte("package other\n"))
410	r.mustGit(r.wt, "push", "-q", r.url, "feat/other")
411	r.mustGit(r.wt, "checkout", "-q", "-b", "feat/third", "feat/other")
412	r.writeFile(r.wt, "third.go", []byte("package third\n"))
413	r.mustGit(r.wt, "push", "-q", r.url, "feat/third")
414	for _, title := range []struct{ src, title string }{{"feat/other", "Other change"}, {"feat/third", "Third change"}} {
415		res = b.form("/proj/merge-requests", token, url.Values{"source": {title.src}, "target": {"main"}, "title": {title.title}})
416		require.Equal(t, http.StatusSeeOther, res.status, res.body)
417	}
418	res = b.form("/proj/merge-requests/2/close", token, nil)
419	require.Equal(t, http.StatusSeeOther, res.status, res.body)
420	assert.Equal(t, "/proj/merge-requests/2", res.hdr.Get("Location"))
421	assert.Equal(t, "no-store", res.hdr.Get("Cache-Control"))
422	closed := b.get("/proj/merge-requests/2", nil)
423	assert.Contains(t, closed.body, `data-state="closed"`)
424	assert.NotContains(t, closed.body, "<form")
425	assert.Equal(t, http.StatusConflict, b.form("/proj/merge-requests/2/close", token, nil).status, "closing twice says so")
426
427	// Open one first, then merged and closed ones, newest first within each.
428	list := b.get("/proj/merge-requests", nil).body
429	third, squash, other := strings.Index(list, "Third change"), strings.Index(list, "Squash me"), strings.Index(list, "Other change")
430	require.True(t, third >= 0 && squash >= 0 && other >= 0, list)
431	assert.Less(t, third, squash, "the open request comes first")
432	assert.Less(t, third, other)
433	assert.Less(t, strings.Index(list, ">Open<"), strings.Index(list, "Merged and closed"))
434	assert.Less(t, other, squash, "newest first among the decided")
435
436	// A compare page of a branch that is behind says so.
437	r.mustGit(r.wt, "checkout", "-q", "-b", "feat/stale", main0)
438	r.writeFile(r.wt, "stale.go", []byte("package stale\n"))
439	r.mustGit(r.wt, "push", "-q", r.url, "feat/stale")
440	stale := b.get("/proj/compare/feat/stale", nil)
441	assert.Equal(t, 200, stale.status)
442	assert.Contains(t, stale.body, "has moved on")
443}
444
445// A "WIP:" request is a draft: the list and the page say so, the box offers
446// "Ready for review" instead of the merge form and the terminal lines, the
447// merge is refused; ready drops the prefix and the merge form comes back. The
448// tab counts the open requests.
449func TestWebMergeRequestDraft(t *testing.T) {
450	r := newMRRepo(t, domain.VisibilityPublic)
451	b := browser{r.harness}
452	token := r.signIn(t)
453	head := r.headOf("feat/search")
454	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "WIP: search").ok(t)
455
456	page := b.get("/proj/merge-requests/1", as(token)).body
457	assert.Contains(t, page, `data-state="draft"`)
458	assert.Contains(t, page, `action="/proj/merge-requests/1/ready"`)
459	assert.NotContains(t, page, `action="/proj/merge-requests/1/merge"`)
460	assert.NotContains(t, page, "ermite mr merge", "no terminal line for a draft")
461	assert.Contains(t, page, `<span class="count">1<span class="sr"> open</span></span>`, "the tab counts the open requests")
462	assert.Contains(t, b.get("/proj/merge-requests", nil).body, `data-state="draft"`)
463
464	res := b.form("/proj/merge-requests/1/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {head}})
465	assert.Equal(t, http.StatusConflict, res.status, "a draft is not merged")
466
467	res = b.form("/proj/merge-requests/1/ready", token, nil)
468	require.Equal(t, http.StatusSeeOther, res.status, res.body)
469	page = b.get("/proj/merge-requests/1", as(token)).body
470	assert.Contains(t, page, "> search</h1>", "the prefix is gone")
471	assert.Contains(t, page, `data-state="open"`)
472	assert.Contains(t, page, `action="/proj/merge-requests/1/merge"`)
473	assert.Contains(t, page, `<details class="d-or">`, "the terminal lines fold away")
474	assert.Equal(t, http.StatusConflict, b.form("/proj/merge-requests/1/ready", token, nil).status, "not a draft any more")
475}
476
477// A request opened with a token shows the owner's name, not the label of the
478// token, which names a device.
479func TestWebMergeRequestAuthorIsTheOwner(t *testing.T) {
480	r := newMRRepo(t, domain.VisibilityPublic)
481	out, errOut, code := r.bin(t, adminToken, "token", "create", "laptop", "--preset", "cli")
482	require.Equal(t, 0, code, errOut)
483	r.cli(t, strings.TrimSpace(out), "mr", "create", "proj", "--source", "feat/search", "--title", "search").ok(t)
484
485	b := browser{r.harness}
486	for _, path := range []string{"/proj/merge-requests/1", "/proj/merge-requests"} {
487		body := b.get(path, nil).body
488		assert.NotContains(t, body, "laptop", path)
489	}
490	assert.Contains(t, b.get("/proj/merge-requests", nil).body, `<td class="c-who dim">owner</td>`)
491}
492
493// The box offers no deletion for the default branch; a fast-forward with the
494// box checked deletes the source.
495func TestWebMergeDeleteBranchBox(t *testing.T) {
496	r := newMRRepo(t, domain.VisibilityPublic)
497	b := browser{r.harness}
498	token := r.signIn(t)
499	// old is an orphan branch: main can be proposed to it, and main stays an
500	// ancestor of feat/search so that it fast-forwards.
501	r.mustGit(r.wt, "checkout", "-q", "--orphan", "old")
502	r.writeFile(r.wt, "old.txt", []byte("old\n")) // commits
503	r.mustGit(r.wt, "push", "-q", r.url, "old")
504
505	for _, mr := range []url.Values{
506		{"source": {"feat/search"}, "target": {"main"}, "title": {"Search"}},
507		{"source": {"main"}, "target": {"old"}, "title": {"Back"}},
508	} {
509		require.Equal(t, http.StatusSeeOther, b.form("/proj/merge-requests", token, mr).status)
510	}
511	assert.NotContains(t, b.get("/proj/merge-requests/2", as(token)).body, `name="delete_branch"`, "never for the default branch")
512
513	one := b.get("/proj/merge-requests/1", as(token))
514	res := b.form("/proj/merge-requests/1/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {formHead(t, one.body)}, "delete_branch": {"1"}})
515	require.Equal(t, http.StatusSeeOther, res.status, res.body)
516	assert.Empty(t, r.bareGit("proj", "for-each-ref", "refs/heads/feat/search"))
517	done := b.get("/proj/merge-requests/1", nil)
518	assert.Equal(t, 200, done.status, "the merged page reads without its branch")
519	assert.NotContains(t, done.body, `href="/proj/tree/feat/search"`, "no link to a gone branch")
520}
521
522// The comment limit of the API is a message, not a crash.
523func TestWebMergeRequestLimitIsFriendly(t *testing.T) {
524	r := newMRRepo(t, domain.VisibilityPublic)
525	b := browser{r.harness}
526	token := r.signIn(t)
527	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "t").ok(t)
528	for i := 0; i < 1000; i++ {
529		_, err := r.forge.MergeRequests.AddComment(r.ctx, domain.Root(), r.name("proj"), 1, ports.AddCommentParams{Text: "n"})
530		require.NoError(t, err)
531	}
532	full := b.form("/proj/merge-requests/1/comments", token, url.Values{"text": {"one more"}})
533	assert.Equal(t, http.StatusConflict, full.status)
534	assert.Contains(t, full.body, "limit reached")
535	assert.Contains(t, full.body, "1000 comments")
536	assert.Equal(t, "no-store", full.hdr.Get("Cache-Control"))
537}
538
539// Text is escaped everywhere and invisible characters are shown as markers.
540func TestWebMergeRequestEscapesText(t *testing.T) {
541	r := newMRRepo(t, domain.VisibilityPublic)
542	b := browser{r.harness}
543	token := r.signIn(t)
544	res := b.form("/proj/merge-requests", token, url.Values{
545		"source": {"feat/search"}, "target": {"main"}, "title": {`"><script>alert(1)</script>`},
546		"description": {"<img src=x onerror=alert(1)>\nhttp://x.test/\"onmouseover=\"alert(1)"},
547	})
548	require.Equal(t, http.StatusSeeOther, res.status, res.body)
549	r.cli(t, adminToken, "mr", "comment", "proj", "1", "-m", "<script>x</script> & more").ok(t)
550	for _, tok := range []string{"", token} {
551		var h map[string]string
552		if tok != "" {
553			h = as(tok)
554		}
555		body := b.get("/proj/merge-requests/1", h).body
556		assert.NotContains(t, body, "<script>alert")
557		assert.NotContains(t, body, "<img src=x")
558		assert.NotContains(t, body, "<script>x</script>")
559		assert.Contains(t, html.UnescapeString(body), `"><script>alert(1)</script>`)
560		// A note is safe Markdown: a line that opens with an HTML tag is an HTML
561		// block, dropped whole.
562		assert.Contains(t, body, `class="c-body prose"><!-- raw HTML omitted -->`)
563		assertNoInline(t, body)
564		assert.NotContains(t, body, `onmouseover="alert`, "an address stops at a quote")
565	}
566}
567
568// The merge request pages learn of changes over the event stream: a fixed
569// sentence and a link, never the text of a comment or a title.
570func TestWebMergeRequestEvents(t *testing.T) {
571	r := newMRRepo(t, domain.VisibilityPublic)
572	list := r.sse("topic=repo:proj&view=mrs", "")
573	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "Secret <title>").ok(t)
574	ev := list.next(t, watchWait)
575	assert.Equal(t, "mr-notice", ev.name)
576	assert.Contains(t, ev.data, `<div id="mr-notice" class="live-slot" role="status" data-slot>`)
577	assert.Contains(t, ev.data, `href="/proj/merge-requests"`)
578	assert.NotContains(t, ev.data, "Secret")
579
580	one := r.sse("topic=repo:proj&view=mr&n=1&ref=feat/search", "")
581	other := r.sse("topic=repo:proj&view=mr&n=2&ref=feat/other", "")
582	r.cli(t, adminToken, "mr", "comment", "proj", "1", "-m", "private words").ok(t)
583	ev = one.next(t, watchWait)
584	assert.Equal(t, "mr-notice", ev.name)
585	assert.Contains(t, ev.data, "a comment was added")
586	assert.Contains(t, ev.data, `href="/proj/merge-requests/1"`)
587	assert.NotContains(t, ev.data, "private words")
588
589	r.writeFile(r.wt, "more.txt", []byte("more\n"))
590	r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
591	ev = one.next(t, watchWait)
592	assert.Contains(t, ev.data, "the branch changed")
593
594	r.cli(t, adminToken, "mr", "close", "proj", "1").ok(t)
595	assert.Contains(t, one.next(t, watchWait).data, "was closed")
596
597	// A page of another request hears nothing of this one.
598	for drained := false; !drained; {
599		select {
600		case ev := <-other.events:
601			if !ev.comment && ev.name != "" {
602				t.Fatalf("unexpected event %+v", ev)
603			}
604		default:
605			drained = true
606		}
607	}
608	assert.Contains(t, r.get1("/proj/merge-requests/1"), `hx-sse:connect="/-/events?topic=repo%3Aproj&amp;view=mr&amp;n=1&amp;ref=feat%2Fsearch&amp;head=`+r.headOf("feat/search")+`"`)
609}
610
611func (r *mrRepo) get1(path string) string {
612	r.t.Helper()
613	_, _, body := r.get(path)
614	return body
615}
616
617// A rewritten branch that dropped the commit the owner read says so, and shows
618// the whole change.
619func TestWebMergeRequestSinceAfterForcePush(t *testing.T) {
620	r := newMRRepo(t, domain.VisibilityPublic)
621	b := browser{r.harness}
622	token := r.signIn(t)
623	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "t").ok(t)
624	base := "/proj/merge-requests/1"
625
626	nothing := b.get(base+"/since", as(token))
627	assert.Equal(t, 200, nothing.status)
628	assert.Contains(t, nothing.body, "nothing was marked read yet")
629
630	head1 := r.headOf("feat/search")
631	require.Equal(t, http.StatusSeeOther, b.form(base+"/read", token, url.Values{"head_id": {head1}}).status)
632	assert.Equal(t, http.StatusBadRequest, b.form(base+"/read", token, url.Values{"head_id": {strings.Repeat("0", 40)}}).status, "not a commit of the repository")
633	r.mustGit(r.wt, "reset", "-q", "--hard", "main")
634	r.writeFile(r.wt, "other.txt", []byte("o\n"))
635	r.mustGit(r.wt, "push", "-q", "--force", r.url, "feat/search")
636	r.bareGit("proj", "reflog", "expire", "--expire=now", "--all")
637	r.bareGit("proj", "gc", "-q", "--prune=now")
638
639	lost := b.get(base+"/since", as(token))
640	require.Equal(t, 200, lost.status)
641	assert.Contains(t, lost.body, "is gone, the branch was rewritten")
642	assert.Contains(t, lost.body, "other.txt", "the whole change is shown")
643}
644
645// A request of many files: the page lists every file and holds the hunks of
646// the first window only; the other files are placeholders that load their
647// window from /files, which carries the base and the head of the diff. A
648// comment on a far file comes with its window; a moved head answers 409; the
649// page of a window (?from=, the links of a page without scripts) shows its
650// hunks and its line forms.
651func TestWebMergeRequestFileWindows(t *testing.T) {
652	r := newMRRepo(t, domain.VisibilityPublic)
653	b := browser{r.harness}
654	token := r.signIn(t)
655	const n = 60
656	for i := range n {
657		r.writeFile(r.wt, fmt.Sprintf("many/f%02d.txt", i), []byte(fmt.Sprintf("line %d\n", i)))
658	}
659	r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
660	head := r.headOf("feat/search")
661	r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "Many").ok(t)
662	r.cli(t, adminToken, "mr", "comment", "proj", "1", "--path", "many/f55.txt", "--line", "1", "-m", "far note").ok(t)
663
664	page := b.get("/proj/merge-requests/1", nil)
665	require.Equal(t, 200, page.status)
666	assert.Equal(t, n+1, strings.Count(page.body, `<li><a href="#f`), "every file is listed")
667	assert.Equal(t, n+1-25, strings.Count(page.body, `class="dlazy`), "the files past the first window are placeholders")
668	assert.NotContains(t, page.body, "far note", "the comment of a far file comes with its window")
669	assert.Contains(t, page.body, `data-notes="c1"`, "its placeholder knows it")
670	assert.Contains(t, page.body, `<span class="cn" title="1 open comment">1</span>`, "the list counts it")
671	m := reWindowSrc.FindStringSubmatch(page.body)
672	require.Len(t, m, 2, "a placeholder holds the address of its window")
673	src := html.UnescapeString(m[1])
674	assert.Contains(t, src, "head="+head)
675
676	win := b.get(strings.Replace(src, "from=25", "from=50", 1), nil)
677	require.Equal(t, 200, win.status, win.body)
678	assert.Contains(t, win.body, "far note")
679	assert.Contains(t, win.body, `line 55</td>`)
680	assert.NotContains(t, win.body, "<html", "a window is a fragment")
681	assert.NotContains(t, win.body, `class="dlazy`)
682	// The window renders the layouts of the page: both when it switches them,
683	// the one it shows otherwise.
684	both := b.get(src+"&view=split&layouts=both", nil)
685	assert.Contains(t, both.body, `class="dt uni"`)
686	assert.Contains(t, both.body, `class="dt spl"`)
687	one := b.get(src+"&view=split&layouts=one", nil)
688	assert.NotContains(t, one.body, `class="dt uni"`)
689	assert.Contains(t, one.body, `class="dt spl"`)
690	assert.Equal(t, 404, b.get(strings.Replace(src, "from=25", "from=7", 1), nil).status, "not a window start")
691	assert.Equal(t, 404, b.get(strings.Replace(src, "from=25", "from=100", 1), nil).status, "past the files")
692
693	// The page of a window, without scripts: its hunks, the line forms of the
694	// owner point back to it.
695	own := b.get("/proj/merge-requests/1?from=50", as(token))
696	require.Equal(t, 200, own.status)
697	assert.Contains(t, own.body, "line 55</td>")
698	assert.Contains(t, own.body, `href="/proj/merge-requests/1?from=50&amp;on=new:1:many%2Ff55.txt#f`)
699	assert.NotContains(t, own.body, "line 0</td>", "the first window is a placeholder there")
700	assert.Contains(t, own.body, `href="/proj/merge-requests/1?view=split&amp;from=50"`, "the layout links keep the window")
701	assert.Equal(t, 404, b.get("/proj/merge-requests/1?from=3", nil).status)
702
703	// A comment on a line of a far window: its form, its cancel link and the
704	// answer return to that window.
705	form := b.get("/proj/merge-requests/1?from=50&on=new:1:many%2Ff55.txt", as(token))
706	require.Equal(t, 200, form.status)
707	assert.Contains(t, form.body, `name="from" value="50"`)
708	assert.Contains(t, form.body, `class="btn" href="/proj/merge-requests/1?from=50#f`)
709	res := b.form("/proj/merge-requests/1/comments", token, url.Values{"text": {"near it"}, "path": {"many/f55.txt"}, "line": {"1"}, "side": {"new"}, "from": {"50"}})
710	require.Equal(t, http.StatusSeeOther, res.status, res.body)
711	assert.Equal(t, "/proj/merge-requests/1?from=50#c2", res.hdr.Get("Location"))
712	assert.Contains(t, b.get("/proj/merge-requests/1?from=50", as(token)).body, `<input type="hidden" name="from" value="50">`, "its resolve form too")
713	res = b.form("/proj/merge-requests/1/comments/2/resolve", token, url.Values{"resolved": {"true"}, "from": {"50"}})
714	assert.Equal(t, "/proj/merge-requests/1?from=50#c2", res.hdr.Get("Location"))
715	res = b.form("/proj/merge-requests/1/comments/2/resolve", token, url.Values{"resolved": {"false"}, "from": {"7"}})
716	assert.Equal(t, "/proj/merge-requests/1#c2", res.hdr.Get("Location"), "a window that is none is dropped")
717
718	// The head moved: the window says to reload, never a file of another diff.
719	r.writeFile(r.wt, "later.txt", []byte("later\n"))
720	r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
721	stale := b.get(src, nil)
722	assert.Equal(t, http.StatusConflict, stale.status)
723	assert.Contains(t, stale.body, "data-moved")
724}
725
726var reWindowSrc = regexp.MustCompile(`data-src="([^"]*from=25[^"]*)"`)

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 4

Tags 45

↑↓ moveenter openesc close