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 <b>search</b></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 <b>search</b></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.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")
272 assert.Equal(t, 0, strings.Count(b.get(base+"?on=new:3:search.go", nil).body, `<form`), "nor for a visitor")
273
274 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"}})
275 require.Equal(t, http.StatusSeeOther, res.status, res.body)
276 assert.Equal(t, base+"#c1", res.hdr.Get("Location"))
277 assert.Equal(t, "no-store", res.hdr.Get("Cache-Control"))
278 res = b.form(base+"/comments", token, url.Values{"text": {"Looks fine overall."}})
279 require.Equal(t, http.StatusSeeOther, res.status, res.body)
280 assert.Equal(t, base+"#c2", res.hdr.Get("Location"))
281
282 anon := b.get(base, nil)
283 i := strings.Index(anon.body, `<tr class="fnote">`)
284 require.GreaterOrEqual(t, i, 0, "a note row under the line")
285 note := anon.body[i:]
286 assert.Less(t, strings.Index(note, "Why <i>empty</i>?"), strings.Index(note, "</tr>"), "the note sits in the row under its line")
287 assert.Contains(t, anon.body, `<a href="https://example.org/a" rel="nofollow noopener noreferrer">https://example.org/a</a>.`)
288 assert.NotContains(t, anon.body, "<i>empty</i>")
289 assert.Contains(t, anon.body, "Looks fine overall.")
290 assert.Equal(t, 2, len(reNoteID.FindAllString(anon.body, -1)))
291 assert.NotContains(t, anon.body, "[resolve]", "a visitor cannot resolve")
292
293 // A comment that breaks a rule is refused with the rule, nothing is lost.
294 bad := b.form(base+"/comments", token, url.Values{"text": {"ok"}, "path": {"search.go"}, "line": {"99"}, "side": {"new"}})
295 assert.Equal(t, http.StatusBadRequest, bad.status)
296 assert.Equal(t, "no-store", bad.hdr.Get("Cache-Control"))
297 assert.Contains(t, bad.body, "search.go")
298 bad = b.form(base+"/comments", token, url.Values{"text": {"x"}, "path": {"search.go"}, "line": {"zz"}, "side": {"new"}})
299 assert.Equal(t, http.StatusBadRequest, bad.status)
300 bad = b.form(base+"/comments", token, url.Values{"text": {"x"}, "path": {"search.go"}, "line": {"3"}, "side": {"sideways"}})
301 assert.Equal(t, http.StatusBadRequest, bad.status)
302 bad = b.form(base+"/comments", token, url.Values{"text": {"evil\u202etext"}})
303 assert.Equal(t, http.StatusBadRequest, bad.status)
304 assert.NotContains(t, bad.body, "\u202e")
305 assert.Equal(t, 404, b.form("/proj/merge-requests/9/comments", token, url.Values{"text": {"x"}}).status)
306
307 // Resolve and unresolve.
308 own := b.get(base, as(token))
309 assert.Contains(t, own.body, `action="/proj/merge-requests/1/comments/1/resolve"`)
310 res = b.form(base+"/comments/1/resolve", token, url.Values{"resolved": {"true"}})
311 require.Equal(t, http.StatusSeeOther, res.status, res.body)
312 assert.Equal(t, base+"#c1", res.hdr.Get("Location"))
313 own = b.get(base, as(token))
314 assert.Contains(t, own.body, `data-resolved="true"`)
315 assert.Contains(t, own.body, ">Unresolve</button>")
316 assert.Equal(t, http.StatusSeeOther, b.form(base+"/comments/1/resolve", token, url.Values{"resolved": {"false"}}).status)
317 assert.Equal(t, http.StatusBadRequest, b.form(base+"/comments/1/resolve", token, url.Values{"resolved": {"maybe"}}).status)
318 assert.Equal(t, 404, b.form(base+"/comments/42/resolve", token, url.Values{"resolved": {"true"}}).status)
319
320 // Mark read, then push: the since page shows the new change only.
321 assert.Contains(t, own.body, `action="/proj/merge-requests/1/read"`)
322 res = b.form(base+"/read", token, url.Values{"head_id": {head1}})
323 require.Equal(t, http.StatusSeeOther, res.status, res.body)
324 assert.NotContains(t, b.get(base, as(token)).body, "data-read>Mark read", "the head is the one that was read")
325 r.writeFile(r.wt, "extra.txt", []byte("extra\n"))
326 r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
327 head2 := r.headOf("feat/search")
328
329 all := b.get(base, as(token))
330 assert.Contains(t, all.body, `href="/proj/merge-requests/1/since"`)
331 assert.Contains(t, all.body, "since your last read")
332 assert.Contains(t, all.body, "<li data-new>", "the commit pushed since is marked")
333 assert.Contains(t, all.body, "data-read>Mark read")
334 assert.Contains(t, all.body, "outdated", "the notes were written on the earlier head")
335 since := b.get(base+"/since", as(token))
336 require.Equal(t, 200, since.status, since.body)
337 assert.Equal(t, "private, no-store", since.hdr.Get("Cache-Control"))
338 assert.Contains(t, since.body, "changes since "+head1[:7])
339 assert.Contains(t, since.body, "extra</td>")
340 assert.NotContains(t, since.body, `<span class="kn">package</span> search</td>`, "only what changed after the read head")
341 assert.Contains(t, since.body, "empty", "the notes are listed below, their lines are not in this diff")
342 assert.NotContains(t, since.body, "<i>", "raw HTML is dropped")
343 assert.Contains(t, since.body, "search.go:3 (new)")
344 assert.NotContains(t, since.body, `<form class="cform"`, "no comment form on this diff")
345
346 // The merge form of the page the owner read carries that head: the push
347 // that came after is not merged unseen.
348 stale := b.form(base+"/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {head1}})
349 assert.Equal(t, http.StatusConflict, stale.status)
350 assert.Equal(t, "no-store", stale.hdr.Get("Cache-Control"))
351 assert.Contains(t, stale.body, "branch moved")
352 assert.NotEqual(t, head2, r.headOf("main"))
353 assert.Equal(t, http.StatusBadRequest, b.form(base+"/merge", token, url.Values{"mode": {"rebase"}, "head_id": {head2}}).status)
354 assert.Equal(t, http.StatusBadRequest, b.form(base+"/merge", token, url.Values{"mode": {"squash"}, "head_id": {"abc"}}).status)
355
356 // Fast-forward with the head that was read.
357 fresh := b.get(base, as(token))
358 require.Equal(t, head2, formHead(t, fresh.body))
359 res = b.form(base+"/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {formHead(t, fresh.body)}})
360 require.Equal(t, http.StatusSeeOther, res.status, res.body)
361 assert.Equal(t, base, res.hdr.Get("Location"))
362 assert.Equal(t, head2, r.headOf("main"), "the target moved to the head")
363
364 done := b.get(base, nil)
365 assert.Contains(t, done.body, "merged")
366 assert.Contains(t, done.body, "fast-forward")
367 assert.Contains(t, done.body, `href="/proj/commit/`+head2+`"`)
368 assert.NotContains(t, done.body, "<form")
369 assert.NotContains(t, b.get(base, as(token)).body, `id="merge-menu"`, "nothing to merge any more")
370 // Writes on a merged request are refused with a page.
371 late := b.form(base+"/comments", token, url.Values{"text": {"too late"}})
372 assert.Equal(t, http.StatusConflict, late.status)
373 assert.Equal(t, http.StatusConflict, b.form(base+"/close", token, nil).status)
374 list := b.get("/proj/merge-requests", nil)
375 assert.Contains(t, list.body, "Merged and closed")
376 assert.Regexp(t, `(?s)Merged and closed.*Add search`, list.body)
377}
378
379// Squash and close, and the order of the list: open first, then the decided.
380func TestWebMergeRequestSquashCloseAndList(t *testing.T) {
381 r := newMRRepo(t, domain.VisibilityPublic)
382 b := browser{r.harness}
383 token := r.signIn(t)
384 head := r.headOf("feat/search")
385 main0 := r.headOf("main")
386
387 // Open from compare with a description; the merge form squashes.
388 res := b.form("/proj/merge-requests", token, url.Values{
389 "source": {"feat/search"}, "target": {"main"}, "title": {"Squash me"}, "description": {""},
390 })
391 require.Equal(t, http.StatusSeeOther, res.status, res.body)
392 assert.Contains(t, b.get("/proj/merge-requests/1", as(token)).body, `name="delete_branch" value="1"`, "the box offers to delete the branch")
393 res = b.form("/proj/merge-requests/1/merge", token, url.Values{"mode": {"squash"}, "head_id": {head}, "delete_branch": {"1"}})
394 require.Equal(t, http.StatusSeeOther, res.status, res.body)
395 assert.Empty(t, r.bareGit("proj", "for-each-ref", "refs/heads/feat/search"), "the source branch is deleted")
396 merged := r.headOf("main")
397 assert.NotEqual(t, head, merged, "squash makes a new commit")
398 assert.Equal(t, main0, r.bareGit("proj", "rev-parse", "main^"), "on top of the old target")
399 assert.Contains(t, r.bareGit("proj", "cat-file", "-p", "main"), "gpgsig", "signed by the instance key")
400 page := b.get("/proj/merge-requests/1", nil)
401 assert.Contains(t, page.body, "squash")
402 assert.Contains(t, page.body, `href="/proj/commit/`+merged+`"`)
403
404 // A second request: closed.
405 r.mustGit(r.wt, "checkout", "-q", "-b", "feat/other", "main")
406 r.mustGit(r.wt, "pull", "-q", r.url, "main")
407 r.writeFile(r.wt, "other.go", []byte("package other\n"))
408 r.mustGit(r.wt, "push", "-q", r.url, "feat/other")
409 r.mustGit(r.wt, "checkout", "-q", "-b", "feat/third", "feat/other")
410 r.writeFile(r.wt, "third.go", []byte("package third\n"))
411 r.mustGit(r.wt, "push", "-q", r.url, "feat/third")
412 for _, title := range []struct{ src, title string }{{"feat/other", "Other change"}, {"feat/third", "Third change"}} {
413 res = b.form("/proj/merge-requests", token, url.Values{"source": {title.src}, "target": {"main"}, "title": {title.title}})
414 require.Equal(t, http.StatusSeeOther, res.status, res.body)
415 }
416 res = b.form("/proj/merge-requests/2/close", token, nil)
417 require.Equal(t, http.StatusSeeOther, res.status, res.body)
418 assert.Equal(t, "/proj/merge-requests/2", res.hdr.Get("Location"))
419 assert.Equal(t, "no-store", res.hdr.Get("Cache-Control"))
420 closed := b.get("/proj/merge-requests/2", nil)
421 assert.Contains(t, closed.body, `data-state="closed"`)
422 assert.NotContains(t, closed.body, "<form")
423 assert.Equal(t, http.StatusConflict, b.form("/proj/merge-requests/2/close", token, nil).status, "closing twice says so")
424
425 // Open one first, then merged and closed ones, newest first within each.
426 list := b.get("/proj/merge-requests", nil).body
427 third, squash, other := strings.Index(list, "Third change"), strings.Index(list, "Squash me"), strings.Index(list, "Other change")
428 require.True(t, third >= 0 && squash >= 0 && other >= 0, list)
429 assert.Less(t, third, squash, "the open request comes first")
430 assert.Less(t, third, other)
431 assert.Less(t, strings.Index(list, ">Open<"), strings.Index(list, "Merged and closed"))
432 assert.Less(t, other, squash, "newest first among the decided")
433
434 // A compare page of a branch that is behind says so.
435 r.mustGit(r.wt, "checkout", "-q", "-b", "feat/stale", main0)
436 r.writeFile(r.wt, "stale.go", []byte("package stale\n"))
437 r.mustGit(r.wt, "push", "-q", r.url, "feat/stale")
438 stale := b.get("/proj/compare/feat/stale", nil)
439 assert.Equal(t, 200, stale.status)
440 assert.Contains(t, stale.body, "has moved on")
441}
442
443// A "WIP:" request is a draft: the list and the page say so, the box offers
444// "Ready for review" instead of the merge form and the terminal lines, the
445// merge is refused; ready drops the prefix and the merge form comes back. The
446// tab counts the open requests.
447func TestWebMergeRequestDraft(t *testing.T) {
448 r := newMRRepo(t, domain.VisibilityPublic)
449 b := browser{r.harness}
450 token := r.signIn(t)
451 head := r.headOf("feat/search")
452 r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "WIP: search").ok(t)
453
454 page := b.get("/proj/merge-requests/1", as(token)).body
455 assert.Contains(t, page, `data-state="draft"`)
456 assert.Contains(t, page, `action="/proj/merge-requests/1/ready"`)
457 assert.NotContains(t, page, `action="/proj/merge-requests/1/merge"`)
458 assert.NotContains(t, page, "ermite mr merge", "no terminal line for a draft")
459 assert.Contains(t, page, `<span class="count">1<span class="sr"> open</span></span>`, "the tab counts the open requests")
460 assert.Contains(t, b.get("/proj/merge-requests", nil).body, `data-state="draft"`)
461
462 res := b.form("/proj/merge-requests/1/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {head}})
463 assert.Equal(t, http.StatusConflict, res.status, "a draft is not merged")
464
465 res = b.form("/proj/merge-requests/1/ready", token, nil)
466 require.Equal(t, http.StatusSeeOther, res.status, res.body)
467 page = b.get("/proj/merge-requests/1", as(token)).body
468 assert.Contains(t, page, "> search</h1>", "the prefix is gone")
469 assert.Contains(t, page, `data-state="open"`)
470 assert.Contains(t, page, `action="/proj/merge-requests/1/merge"`)
471 assert.Contains(t, page, `<details class="d-or">`, "the terminal lines fold away")
472 assert.Equal(t, http.StatusConflict, b.form("/proj/merge-requests/1/ready", token, nil).status, "not a draft any more")
473}
474
475// A request opened with a token shows the owner's name, not the label of the
476// token, which names a device.
477func TestWebMergeRequestAuthorIsTheOwner(t *testing.T) {
478 r := newMRRepo(t, domain.VisibilityPublic)
479 out, errOut, code := r.bin(t, adminToken, "token", "create", "laptop", "--preset", "cli")
480 require.Equal(t, 0, code, errOut)
481 r.cli(t, strings.TrimSpace(out), "mr", "create", "proj", "--source", "feat/search", "--title", "search").ok(t)
482
483 b := browser{r.harness}
484 for _, path := range []string{"/proj/merge-requests/1", "/proj/merge-requests"} {
485 body := b.get(path, nil).body
486 assert.NotContains(t, body, "laptop", path)
487 }
488 assert.Contains(t, b.get("/proj/merge-requests", nil).body, `<td class="c-who dim">owner</td>`)
489}
490
491// The box offers no deletion for the default branch; a fast-forward with the
492// box checked deletes the source.
493func TestWebMergeDeleteBranchBox(t *testing.T) {
494 r := newMRRepo(t, domain.VisibilityPublic)
495 b := browser{r.harness}
496 token := r.signIn(t)
497 // old is an orphan branch: main can be proposed to it, and main stays an
498 // ancestor of feat/search so that it fast-forwards.
499 r.mustGit(r.wt, "checkout", "-q", "--orphan", "old")
500 r.writeFile(r.wt, "old.txt", []byte("old\n")) // commits
501 r.mustGit(r.wt, "push", "-q", r.url, "old")
502
503 for _, mr := range []url.Values{
504 {"source": {"feat/search"}, "target": {"main"}, "title": {"Search"}},
505 {"source": {"main"}, "target": {"old"}, "title": {"Back"}},
506 } {
507 require.Equal(t, http.StatusSeeOther, b.form("/proj/merge-requests", token, mr).status)
508 }
509 assert.NotContains(t, b.get("/proj/merge-requests/2", as(token)).body, `name="delete_branch"`, "never for the default branch")
510
511 one := b.get("/proj/merge-requests/1", as(token))
512 res := b.form("/proj/merge-requests/1/merge", token, url.Values{"mode": {"fast-forward"}, "head_id": {formHead(t, one.body)}, "delete_branch": {"1"}})
513 require.Equal(t, http.StatusSeeOther, res.status, res.body)
514 assert.Empty(t, r.bareGit("proj", "for-each-ref", "refs/heads/feat/search"))
515 done := b.get("/proj/merge-requests/1", nil)
516 assert.Equal(t, 200, done.status, "the merged page reads without its branch")
517 assert.NotContains(t, done.body, `href="/proj/tree/feat/search"`, "no link to a gone branch")
518}
519
520// The comment limit of the API is a message, not a crash.
521func TestWebMergeRequestLimitIsFriendly(t *testing.T) {
522 r := newMRRepo(t, domain.VisibilityPublic)
523 b := browser{r.harness}
524 token := r.signIn(t)
525 r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "t").ok(t)
526 for i := 0; i < 1000; i++ {
527 _, err := r.forge.MergeRequests.AddComment(r.ctx, domain.Root(), r.name("proj"), 1, ports.AddCommentParams{Text: "n"})
528 require.NoError(t, err)
529 }
530 full := b.form("/proj/merge-requests/1/comments", token, url.Values{"text": {"one more"}})
531 assert.Equal(t, http.StatusConflict, full.status)
532 assert.Contains(t, full.body, "limit reached")
533 assert.Contains(t, full.body, "1000 comments")
534 assert.Equal(t, "no-store", full.hdr.Get("Cache-Control"))
535}
536
537// Text is escaped everywhere and invisible characters are shown as markers.
538func TestWebMergeRequestEscapesText(t *testing.T) {
539 r := newMRRepo(t, domain.VisibilityPublic)
540 b := browser{r.harness}
541 token := r.signIn(t)
542 res := b.form("/proj/merge-requests", token, url.Values{
543 "source": {"feat/search"}, "target": {"main"}, "title": {`"><script>alert(1)</script>`},
544 "description": {"<img src=x onerror=alert(1)>\nhttp://x.test/\"onmouseover=\"alert(1)"},
545 })
546 require.Equal(t, http.StatusSeeOther, res.status, res.body)
547 r.cli(t, adminToken, "mr", "comment", "proj", "1", "-m", "<script>x</script> & more").ok(t)
548 for _, tok := range []string{"", token} {
549 var h map[string]string
550 if tok != "" {
551 h = as(tok)
552 }
553 body := b.get("/proj/merge-requests/1", h).body
554 assert.NotContains(t, body, "<script>alert")
555 assert.NotContains(t, body, "<img src=x")
556 assert.NotContains(t, body, "<script>x</script>")
557 assert.Contains(t, html.UnescapeString(body), `"><script>alert(1)</script>`)
558 // A note is safe Markdown: a line that opens with an HTML tag is an HTML
559 // block, dropped whole.
560 assert.Contains(t, body, `class="c-body prose"><!-- raw HTML omitted -->`)
561 assertNoInline(t, body)
562 assert.NotContains(t, body, `onmouseover="alert`, "an address stops at a quote")
563 }
564}
565
566// The merge request pages learn of changes over the event stream: a fixed
567// sentence and a link, never the text of a comment or a title.
568func TestWebMergeRequestEvents(t *testing.T) {
569 r := newMRRepo(t, domain.VisibilityPublic)
570 list := r.sse("topic=repo:proj&view=mrs", "")
571 r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "Secret <title>").ok(t)
572 ev := list.next(t, watchWait)
573 assert.Equal(t, "mr-notice", ev.name)
574 assert.Contains(t, ev.data, `<div id="mr-notice" class="live-slot" role="status" data-slot>`)
575 assert.Contains(t, ev.data, `href="/proj/merge-requests"`)
576 assert.NotContains(t, ev.data, "Secret")
577
578 one := r.sse("topic=repo:proj&view=mr&n=1&ref=feat/search", "")
579 other := r.sse("topic=repo:proj&view=mr&n=2&ref=feat/other", "")
580 r.cli(t, adminToken, "mr", "comment", "proj", "1", "-m", "private words").ok(t)
581 ev = one.next(t, watchWait)
582 assert.Equal(t, "mr-notice", ev.name)
583 assert.Contains(t, ev.data, "a comment was added")
584 assert.Contains(t, ev.data, `href="/proj/merge-requests/1"`)
585 assert.NotContains(t, ev.data, "private words")
586
587 r.writeFile(r.wt, "more.txt", []byte("more\n"))
588 r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
589 ev = one.next(t, watchWait)
590 assert.Contains(t, ev.data, "the branch changed")
591
592 r.cli(t, adminToken, "mr", "close", "proj", "1").ok(t)
593 assert.Contains(t, one.next(t, watchWait).data, "was closed")
594
595 // A page of another request hears nothing of this one.
596 for drained := false; !drained; {
597 select {
598 case ev := <-other.events:
599 if !ev.comment && ev.name != "" {
600 t.Fatalf("unexpected event %+v", ev)
601 }
602 default:
603 drained = true
604 }
605 }
606 assert.Contains(t, r.get1("/proj/merge-requests/1"), `hx-sse:connect="/-/events?topic=repo%3Aproj&view=mr&n=1&ref=feat%2Fsearch&head=`+r.headOf("feat/search")+`"`)
607}
608
609func (r *mrRepo) get1(path string) string {
610 r.t.Helper()
611 _, _, body := r.get(path)
612 return body
613}
614
615// A rewritten branch that dropped the commit the owner read says so, and shows
616// the whole change.
617func TestWebMergeRequestSinceAfterForcePush(t *testing.T) {
618 r := newMRRepo(t, domain.VisibilityPublic)
619 b := browser{r.harness}
620 token := r.signIn(t)
621 r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "t").ok(t)
622 base := "/proj/merge-requests/1"
623
624 nothing := b.get(base+"/since", as(token))
625 assert.Equal(t, 200, nothing.status)
626 assert.Contains(t, nothing.body, "nothing was marked read yet")
627
628 head1 := r.headOf("feat/search")
629 require.Equal(t, http.StatusSeeOther, b.form(base+"/read", token, url.Values{"head_id": {head1}}).status)
630 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")
631 r.mustGit(r.wt, "reset", "-q", "--hard", "main")
632 r.writeFile(r.wt, "other.txt", []byte("o\n"))
633 r.mustGit(r.wt, "push", "-q", "--force", r.url, "feat/search")
634 r.bareGit("proj", "reflog", "expire", "--expire=now", "--all")
635 r.bareGit("proj", "gc", "-q", "--prune=now")
636
637 lost := b.get(base+"/since", as(token))
638 require.Equal(t, 200, lost.status)
639 assert.Contains(t, lost.body, "is gone, the branch was rewritten")
640 assert.Contains(t, lost.body, "other.txt", "the whole change is shown")
641}
642
643// A request of many files: the page lists every file and holds the hunks of
644// the first window only; the other files are placeholders that load their
645// window from /files, which carries the base and the head of the diff. A
646// comment on a far file comes with its window; a moved head answers 409; the
647// page of a window (?from=, the links of a page without scripts) shows its
648// hunks and its line forms.
649func TestWebMergeRequestFileWindows(t *testing.T) {
650 r := newMRRepo(t, domain.VisibilityPublic)
651 b := browser{r.harness}
652 token := r.signIn(t)
653 const n = 60
654 for i := range n {
655 r.writeFile(r.wt, fmt.Sprintf("many/f%02d.txt", i), []byte(fmt.Sprintf("line %d\n", i)))
656 }
657 r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
658 head := r.headOf("feat/search")
659 r.cli(t, adminToken, "mr", "create", "proj", "--source", "feat/search", "--title", "Many").ok(t)
660 r.cli(t, adminToken, "mr", "comment", "proj", "1", "--path", "many/f55.txt", "--line", "1", "-m", "far note").ok(t)
661
662 page := b.get("/proj/merge-requests/1", nil)
663 require.Equal(t, 200, page.status)
664 assert.Equal(t, n+1, strings.Count(page.body, `<li><a href="#f`), "every file is listed")
665 assert.Equal(t, n+1-25, strings.Count(page.body, `class="dlazy`), "the files past the first window are placeholders")
666 assert.NotContains(t, page.body, "far note", "the comment of a far file comes with its window")
667 assert.Contains(t, page.body, `data-notes="c1"`, "its placeholder knows it")
668 assert.Contains(t, page.body, `<span class="cn" title="1 open comment">1</span>`, "the list counts it")
669 m := reWindowSrc.FindStringSubmatch(page.body)
670 require.Len(t, m, 2, "a placeholder holds the address of its window")
671 src := html.UnescapeString(m[1])
672 assert.Contains(t, src, "head="+head)
673
674 win := b.get(strings.Replace(src, "from=25", "from=50", 1), nil)
675 require.Equal(t, 200, win.status, win.body)
676 assert.Contains(t, win.body, "far note")
677 assert.Contains(t, win.body, `line 55</td>`)
678 assert.NotContains(t, win.body, "<html", "a window is a fragment")
679 assert.NotContains(t, win.body, `class="dlazy`)
680 // The window renders the layouts of the page: both when it switches them,
681 // the one it shows otherwise.
682 both := b.get(src+"&view=split&layouts=both", nil)
683 assert.Contains(t, both.body, `class="dt uni"`)
684 assert.Contains(t, both.body, `class="dt spl"`)
685 one := b.get(src+"&view=split&layouts=one", nil)
686 assert.NotContains(t, one.body, `class="dt uni"`)
687 assert.Contains(t, one.body, `class="dt spl"`)
688 assert.Equal(t, 404, b.get(strings.Replace(src, "from=25", "from=7", 1), nil).status, "not a window start")
689 assert.Equal(t, 404, b.get(strings.Replace(src, "from=25", "from=100", 1), nil).status, "past the files")
690
691 // The page of a window, without scripts: its hunks, the line forms of the
692 // owner point back to it.
693 own := b.get("/proj/merge-requests/1?from=50", as(token))
694 require.Equal(t, 200, own.status)
695 assert.Contains(t, own.body, "line 55</td>")
696 assert.Contains(t, own.body, `href="/proj/merge-requests/1?from=50&on=new:1:many%2Ff55.txt#f`)
697 assert.NotContains(t, own.body, "line 0</td>", "the first window is a placeholder there")
698 assert.Contains(t, own.body, `href="/proj/merge-requests/1?view=split&from=50"`, "the layout links keep the window")
699 assert.Equal(t, 404, b.get("/proj/merge-requests/1?from=3", nil).status)
700
701 // A comment on a line of a far window: its form, its cancel link and the
702 // answer return to that window.
703 form := b.get("/proj/merge-requests/1?from=50&on=new:1:many%2Ff55.txt", as(token))
704 require.Equal(t, 200, form.status)
705 assert.Contains(t, form.body, `name="from" value="50"`)
706 assert.Contains(t, form.body, `class="btn" href="/proj/merge-requests/1?from=50#f`)
707 res := b.form("/proj/merge-requests/1/comments", token, url.Values{"text": {"near it"}, "path": {"many/f55.txt"}, "line": {"1"}, "side": {"new"}, "from": {"50"}})
708 require.Equal(t, http.StatusSeeOther, res.status, res.body)
709 assert.Equal(t, "/proj/merge-requests/1?from=50#c2", res.hdr.Get("Location"))
710 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")
711 res = b.form("/proj/merge-requests/1/comments/2/resolve", token, url.Values{"resolved": {"true"}, "from": {"50"}})
712 assert.Equal(t, "/proj/merge-requests/1?from=50#c2", res.hdr.Get("Location"))
713 res = b.form("/proj/merge-requests/1/comments/2/resolve", token, url.Values{"resolved": {"false"}, "from": {"7"}})
714 assert.Equal(t, "/proj/merge-requests/1#c2", res.hdr.Get("Location"), "a window that is none is dropped")
715
716 // The head moved: the window says to reload, never a file of another diff.
717 r.writeFile(r.wt, "later.txt", []byte("later\n"))
718 r.mustGit(r.wt, "push", "-q", r.url, "feat/search")
719 stale := b.get(src, nil)
720 assert.Equal(t, http.StatusConflict, stale.status)
721 assert.Contains(t, stale.body, "data-moved")
722}
723
724var reWindowSrc = regexp.MustCompile(`data-src="([^"]*from=25[^"]*)"`)