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