gunk-dev/the-valley

server_test.go

source199a804cf927main's published tip history
139.8 KiB
1package server
2
3import (
4 "archive/tar"
5 "bufio"
6 "bytes"
7 "compress/gzip"
8 "context"
9 "crypto/sha256"
10 "encoding/base64"
11 "errors"
12 "fmt"
13 "io"
14 "net"
15 "net/http"
16 "net/http/httptest"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "regexp"
21 "runtime"
22 "slices"
23 "strconv"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "syscall"
28 "testing"
29 "time"
30
31 "the-valley/knot"
32 "the-valley/web/export"
33 "the-valley/web/export/exporttest"
34)
35
36// harness is a server over a real store that the fixture's export was
37// uploaded to, with a clock the test sets.
38type harness struct {
39 t *testing.T
40 f *exporttest.Fixture
41 store *export.Store
42 srv *Server
43 now time.Time
44}
45
46// newHarness serves the fixture's export, two minutes after it was
47// collected.
48func newHarness(t *testing.T) *harness {
49 t.Helper()
50 f := exporttest.New(t)
51 store, err := export.OpenStore(exporttest.StorePath(t), func(err error) { t.Errorf("the store reported: %v", err) })
52 if err != nil {
53 t.Fatal(err)
54 }
55 f.Upload(t, store)
56 h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)}
57 h.srv = New(Config{Store: store, Now: func() time.Time { return h.now },
58 Log: func(err error) { t.Errorf("the server logged: %v", err) }})
59 return h
60}
61
62func (h *harness) do(method, target string) *httptest.ResponseRecorder {
63 h.t.Helper()
64 w := httptest.NewRecorder()
65 h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil))
66 return w
67}
68
69func (h *harness) get(target string) *httptest.ResponseRecorder {
70 h.t.Helper()
71 return h.do("GET", target)
72}
73
74// page is the body of a GET that must answer 200.
75func (h *harness) page(target string) string {
76 h.t.Helper()
77 w := h.get(target)
78 if w.Code != http.StatusOK {
79 h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body)
80 }
81 return w.Body.String()
82}
83
84// tip is the fixture's published source tip of app.
85func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip }
86
87// publish activates a new generation, signed at: the fixture's export
88// changed by change, with the bundles given, by project, in place of the
89// fixture's.
90func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation {
91 t := h.t
92 t.Helper()
93 e, err := export.Decode(h.f.ExportJSON)
94 if err != nil {
95 t.Fatal(err)
96 }
97 change(e)
98 h.authorizeAll(e)
99 data, err := e.Encode()
100 if err != nil {
101 t.Fatal(err)
102 }
103 paths := map[string]string{}
104 for _, p := range e.Projects {
105 if paths[p.Name] = bundles[p.Name]; paths[p.Name] == "" {
106 paths[p.Name] = h.f.Bundles[p.Name]
107 }
108 }
109 bodies := map[string]export.Body{}
110 for name, path := range paths {
111 if bodies[name], err = export.FileBody(name, path); err != nil {
112 t.Fatal(err)
113 }
114 }
115 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies)
116 if err != nil {
117 t.Fatal(err)
118 }
119 hw, err := h.store.HighWater()
120 if err != nil {
121 t.Fatal(err)
122 }
123 a := h.f.Admission()
124 a.Now, a.HighWater = at.Add(time.Second), hw
125 if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil {
126 t.Fatal(err)
127 }
128 st, err := h.store.Stage(context.Background(), m)
129 if err != nil {
130 t.Fatal(err)
131 }
132 inv, err := h.store.Inventory(st)
133 if err != nil {
134 t.Fatal(err)
135 }
136 for _, need := range inv.Needs {
137 body := data
138 if need.Name != export.ExportFile {
139 if body, err = os.ReadFile(paths[need.Name]); err != nil {
140 t.Fatal(err)
141 }
142 }
143 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body))
144 if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil {
145 t.Fatal(err)
146 }
147 }
148 g, err := h.store.Activate(context.Background(), st)
149 if err != nil {
150 t.Fatal(err)
151 }
152 return g
153}
154
155// authorizeAll stores an authorization that lets anyone read every
156// project of e, unless the stored one does already.
157func (h *harness) authorizeAll(e *export.Export) {
158 h.t.Helper()
159 a, _, err := h.store.Authorization()
160 if err != nil {
161 h.t.Fatal(err)
162 }
163 all := true
164 for _, p := range e.Projects {
165 all = all && a.Allows(export.Anyone, p.Name, p.Identity)
166 }
167 if all {
168 return
169 }
170 next := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination,
171 Sequence: a.Sequence + 1, Checked: a.Checked}
172 for _, p := range e.Projects {
173 next.Projects = append(next.Projects, export.AuthorizedProject{Name: p.Name, Identity: p.Identity, Readers: []string{export.Anyone}})
174 }
175 h.authorize(next)
176}
177
178// authorize stores the authorization a, as the receiver does.
179func (h *harness) authorize(a *export.Authorization) {
180 h.t.Helper()
181 if err := h.store.Authorize(context.Background(), a, exporttest.SignAuthorization(h.t, a)); err != nil {
182 h.t.Fatal(err)
183 }
184}
185
186// active is the generation the store serves.
187func (h *harness) active() export.Generation {
188 h.t.Helper()
189 g, release, err := h.store.Open()
190 if err != nil {
191 h.t.Fatal(err)
192 }
193 release()
194 return g
195}
196
197// git runs git on the repository at repo, with no configuration of the
198// caller's and a fixed identity for the commits it writes.
199func git(t *testing.T, repo string, stdin []byte, args ...string) string {
200 t.Helper()
201 cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...)
202 for _, kv := range os.Environ() {
203 if !strings.HasPrefix(kv, "GIT_") {
204 cmd.Env = append(cmd.Env, kv)
205 }
206 }
207 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
208 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000",
209 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000")
210 if stdin != nil {
211 cmd.Stdin = bytes.NewReader(stdin)
212 }
213 var out, stderr bytes.Buffer
214 cmd.Stdout, cmd.Stderr = &out, &stderr
215 if err := exporttest.Run(t, cmd, 2*time.Minute); err != nil {
216 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
217 }
218 return strings.TrimSpace(out.String())
219}
220
221// section is the part of a page from one marker up to the next.
222func section(t *testing.T, page, from, to string) string {
223 t.Helper()
224 i := strings.Index(page, from)
225 j := strings.Index(page[max(i, 0):], to)
226 if i < 0 || j < 0 {
227 t.Fatalf("the page has no section from %q to %q", from, to)
228 }
229 return page[i : i+j]
230}
231
232// The plan page keeps the template's reading order, says what free to
233// start means, shows the ready changes as one card in no order, and
234// shows how old the export is.
235func TestPlanPage(t *testing.T) {
236 h := newHarness(t)
237 page := h.page("/-/knots")
238
239 at := -1
240 for _, heading := range []string{">Waiting on you<", ">In flight<", ">Paths<", ">Milestones<"} {
241 i := strings.Index(page, heading)
242 if i <= at {
243 t.Fatalf("%s is not where the reading order puts it", heading)
244 }
245 at = i
246 }
247 for _, want := range []string{
248 "free to start: an open, unclaimed, unblocked outcome or bug",
249 "Nothing here waits on you.",
250 "Ready changes — order not assessed",
251 `<span class="handle">kmno</span>`, "plan: list the milestones", "app v2", "approved · integrator: stale",
252 "Collected 2026-10-25 12:00 UTC. Policy last checked 2026-10-25 12:00 UTC, 2 minutes ago",
253 "claimed by agent 2 hours ago",
254 "in progress, unclaimed",
255 "Readers browse the app&#39;s plan", "1 of 5 done",
256 "Unfiled", "Render Markdown in a later slice",
257 `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`,
258 } {
259 if !strings.Contains(page, want) {
260 t.Errorf("the plan page does not show %q", want)
261 }
262 }
263 if strings.Count(page, "Ready changes") != 1 {
264 t.Error("the ready changes are not one card")
265 }
266
267 // The bug nobody claims and nothing blocks is free to start.
268 if !strings.Contains(page, `<i class="k ready" role="img" aria-label="free to start" title="free to start"></i><span class="body"><a class="id" href="/tools/app/knots/bd-a000004">`) {
269 t.Error("bd-a000004 is not shown as free to start")
270 }
271
272 // The milestone's path puts oc-a000003 after the knot it waits on.
273 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
274 second := strings.Index(paths, `<span class="stage-num">2</span>`)
275 if second < 0 || strings.Index(paths, "oc-a000002") > second || strings.Index(paths, "oc-a000003") < second {
276 t.Errorf("the path does not order oc-a000003 after oc-a000002:\n%s", paths)
277 }
278
279 // Nothing of the hidden project is linked or named, and nothing is
280 // fetched from another origin.
281 for _, want := range []string{"lands in an unpublished project", "lands in a knot in an unpublished project"} {
282 if !strings.Contains(page, want) {
283 t.Errorf("the plan page does not show %q", want)
284 }
285 }
286 for _, unwanted := range append([]string{"/tools/site/knots/", "/tools/site/source/", "/site/knots/", "/site/source/", "http://", "https://", `class="chip stale"`}, unpublishedText...) {
287 if strings.Contains(page, unwanted) {
288 t.Errorf("the plan page holds %q", unwanted)
289 }
290 }
291
292 h.now = exporttest.Collected.Add(6 * time.Minute)
293 page = h.page("/-/knots")
294 if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC. Policy last checked 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) {
295 t.Error("a policy check six minutes old is not marked stale")
296 }
297}
298
299// A blocked knot's chip names the published knots it waits on, and says
300// once that it also waits on unpublished work, naming nothing of it:
301// oc-a000003 waits on oc-a000002 and on a knot of the hidden site, which
302// the export leaves out of waiting_on and marks with waiting_on_hidden.
303// A knot waiting on unpublished work alone says only that. An export
304// without the field, as v1 exports before it, is read, and its chip
305// names what waiting_on holds.
306func TestWaitsOnChip(t *testing.T) {
307 h := newHarness(t)
308 chip := func(text string) string { return `<span class="chip blocked">waits on ` + text + `</span>` }
309 cases := []struct {
310 name string
311 change func(*export.Knot)
312 want string
313 }{
314 {"a published and an unpublished blocker", func(*export.Knot) {}, "oc-a000002, a knot in an unpublished project"},
315 {"two published blockers and an unpublished one", func(k *export.Knot) { k.WaitingOn = append(k.WaitingOn, "oc-a000006") },
316 "oc-a000002, oc-a000006, a knot in an unpublished project"},
317 {"an unpublished blocker alone", func(k *export.Knot) { k.WaitingOn = []string{} }, "a knot in an unpublished project"},
318 {"an export without waiting_on_hidden", func(k *export.Knot) { k.WaitingOnHidden = false }, "oc-a000002"},
319 }
320 for i, c := range cases {
321 t.Run(c.name, func(t *testing.T) {
322 h.publish(exporttest.SignedAt.Add(time.Duration(i+1)*time.Minute), nil, func(e *export.Export) {
323 for j := range e.Projects[0].Knots {
324 if k := &e.Projects[0].Knots[j]; k.ID == "oc-a000003" {
325 if !k.WaitingOnHidden {
326 t.Fatal("the fixture's oc-a000003 does not carry waiting_on_hidden")
327 }
328 c.change(k)
329 }
330 }
331 })
332 page := h.page("/-/knots")
333 if !strings.Contains(page, chip(c.want)) {
334 t.Errorf("the plan page does not show %q:\n%s", chip(c.want), section(t, page, `id="ms-h"`, "</body>"))
335 }
336 if n := strings.Count(page, `<span class="chip blocked">`); n != 1 {
337 t.Errorf("the plan page shows %d blocked chips", n)
338 }
339 for _, unwanted := range unpublishedText {
340 if strings.Contains(page, unwanted) {
341 t.Errorf("the plan page holds %q", unwanted)
342 }
343 }
344 })
345 }
346}
347
348// unpublishedText is what of the hidden project site the fixture's
349// references hold: its name and its knots' IDs. No page shows any of it.
350var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"}
351
352// A knot's page shows its body and comments, and marks the edited
353// comment. A reference into a hidden project is shown as unpublished,
354// with nothing of its text, and a missing knot of a public project is
355// named as missing.
356func TestKnotPage(t *testing.T) {
357 h := newHarness(t)
358 page := h.page("/tools/app/knots/oc-a000002")
359 for _, want := range []string{
360 "Each milestone is listed with its progress.",
361 "Start with the milestones that have open children.",
362 "Claimed; the change is ready for approval.",
363 `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`,
364 `<a href="/tools/app/knots/oc-a000001">Readers browse the app&#39;s plan</a>`,
365 } {
366 if !strings.Contains(page, want) {
367 t.Errorf("the knot's page does not show %q", want)
368 }
369 }
370 if n := strings.Count(page, ">edited<"); n != 1 {
371 t.Errorf("%d comments are marked edited; one was edited", n)
372 }
373
374 page = h.page("/tools/app/knots/oc-a000003")
375 if !strings.Contains(page, `<a href="/tools/app/knots/oc-a000002">The plan page lists milestones</a>`) {
376 t.Error("the local blocker is not linked")
377 }
378 for _, want := range []string{
379 `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`,
380 "<dt>Lands in</dt><dd>an unpublished project</dd>",
381 } {
382 if !strings.Contains(page, want) {
383 t.Errorf("the knot's page does not show %q", want)
384 }
385 }
386 page += h.page("/tools/app/knots/bd-a000004")
387 if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") {
388 t.Error("a target in the hidden project is not shown as unpublished")
389 }
390 for _, unwanted := range append([]string{"/tools/site/knots/", "/tools/site/source/", "/site/knots/", "/site/source/"}, unpublishedText...) {
391 if strings.Contains(page, unwanted) {
392 t.Errorf("the knot's page shows %q", unwanted)
393 }
394 }
395 if w := h.get("/tools/app/knots/oc-fffffff"); w.Code != http.StatusNotFound {
396 t.Errorf("a missing knot answered %d", w.Code)
397 }
398
399 // A knot of a public project the graph does not hold, and a local
400 // knot that is not there, are named as missing. A change of the
401 // hidden project is not named.
402 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
403 for i := range e.Projects[0].Knots {
404 if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" {
405 k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee")
406 k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling})
407 k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm")
408 }
409 }
410 })
411 page = h.page("/tools/app/knots/oc-a000003")
412 for _, want := range []string{
413 `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`,
414 `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`,
415 `<li class="mono">a change in an unpublished project</li>`,
416 `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`,
417 } {
418 if !strings.Contains(page, want) {
419 t.Errorf("the knot's page does not show %q", want)
420 }
421 }
422 for _, unwanted := range unpublishedText {
423 if strings.Contains(page, unwanted) {
424 t.Errorf("the knot's page shows %q", unwanted)
425 }
426 }
427}
428
429// A project the export does not hold as public answers every route
430// exactly as a project that does not exist, even when its repository is
431// in the generation's directory: under its group's name, under a group
432// that does not exist, and under the short alias and the former name the
433// instance gives it, which the export does not carry. Through the group's
434// alias, both answer with the same redirect.
435func TestHiddenProjectAnswersLikeMissing(t *testing.T) {
436 h := newHarness(t)
437 g := h.active()
438 if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil {
439 t.Fatal(err)
440 }
441 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
442 notFound := h.get("/tools/app/knots/oc-fffffff")
443 for _, route := range []string{
444 "",
445 "/",
446 "/knots/oc-b000001",
447 "/source",
448 "/source/",
449 "/source/tree/" + siteTip + "/",
450 "/source/blob/" + siteTip + "/README.md",
451 "/source/log/" + siteTip,
452 "/source/archive/" + siteTip + ".tar.gz",
453 "/source/archive/main.tar.gz",
454 "/source/tree/" + siteTip + "/no/such/path/",
455 "/source/anything",
456 } {
457 for _, pair := range [][2]string{
458 {"/tools/site" + route, "/tools/nosuch" + route},
459 {"/core/site" + route, "/nosuch/site" + route},
460 {"/site" + route, "/nosuch" + route},
461 {"/tools/old-site" + route, "/tools/nosuch" + route},
462 } {
463 hidden, missing := h.get(pair[0]), h.get(pair[1])
464 if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound {
465 t.Errorf("%s answered %d hidden, and %s %d missing", pair[0], hidden.Code, pair[1], missing.Code)
466 }
467 if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) {
468 t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", pair[0], hidden.Header(), missing.Header())
469 }
470 if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) {
471 t.Errorf("%s answered with another page hidden than missing", pair[0])
472 }
473 }
474 for _, name := range []string{"site", "old-site"} {
475 hidden, missing := h.get("/t/"+name+route), h.get("/t/nosuch"+route)
476 if hidden.Code != http.StatusPermanentRedirect || hidden.Header().Get("Location") != "/tools/"+name+route ||
477 missing.Code != http.StatusPermanentRedirect || missing.Header().Get("Location") != "/tools/nosuch"+route ||
478 !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) {
479 t.Errorf("/t/%s%s answered %d to %q, and /t/nosuch%s %d to %q", name, route, hidden.Code, hidden.Header().Get("Location"),
480 route, missing.Code, missing.Header().Get("Location"))
481 }
482 }
483 }
484}
485
486// A group's or a project's name may be any word the server's routes use:
487// source, knots, or web-export, the receiver's first segment. A project
488// so named, in a group so named, is served on every route, and
489// /<group>/<project>/ redirects to its tree. The server's own paths, under
490// /-/, are never a group's, and a project's path without its group is no
491// route.
492func TestProjectNamesBesideTheServersPaths(t *testing.T) {
493 for _, name := range []string{"source", "knots", "web-export"} {
494 t.Run(name, func(t *testing.T) {
495 h := newHarness(t)
496 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{name: h.f.Bundles["app"]},
497 func(e *export.Export) {
498 e.Groups[0].Name = name
499 e.Projects[0].Name, e.Projects[0].WebName = name, name
500 })
501 tip := h.tip()
502 base := "/" + name + "/" + name
503 tree := base + "/source/tree/" + tip + "/"
504 if plan := h.page("/-/knots"); !strings.Contains(plan, `href="`+base+`/knots/oc-a000002"`) {
505 t.Errorf("the plan page does not link %s's knots", name)
506 }
507 for _, target := range []string{
508 base + "/knots/oc-a000002",
509 tree,
510 base + "/source/blob/" + tip + "/docs/guide.md",
511 base + "/source/log/" + tip,
512 } {
513 h.page(target)
514 }
515 for _, target := range []string{base + "/", base, base + "/source/"} {
516 if w := h.get(target); w.Code != http.StatusFound || w.Header().Get("Location") != tree {
517 t.Errorf("GET %s answered %d to %q, not a redirect to %s", target, w.Code, w.Header().Get("Location"), tree)
518 }
519 }
520 for _, target := range []string{
521 "/-", "/-/", "/-/" + name + "/", "/-/knots/oc-a000002", "/-/source/tree/" + tip + "/",
522 "/-/" + name + "/" + name + "/source/tree/" + tip + "/", "/-" + base + "/",
523 "/" + name + "/source/tree/" + tip + "/", "/" + name + "/knots/oc-a000002",
524 "/" + name, "/" + name + "/", "/tools/app/", "/core/" + name + "/", "/site/", "/site",
525 } {
526 if w := h.get(target); w.Code != http.StatusNotFound {
527 t.Errorf("GET %s answered %d, not 404", target, w.Code)
528 }
529 }
530 })
531 }
532}
533
534// / lands on source: it redirects to the tree, at its published tip, of
535// the first project the reader may see, in the export's order, and to the
536// knots page when the reader may see none. The knots page is /-/knots,
537// the one page under /-/, and its title, its heading and its link in the
538// navigation say knots, as the knot page's trail and the error page's
539// link do. HEAD answers each as GET does.
540func TestLandingAndTheKnotsPage(t *testing.T) {
541 h := newHarness(t)
542 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"site": h.f.Bundles["app"]}, func(e *export.Export) {
543 site := e.Projects[0]
544 site.Name, site.Group, site.WebName, site.FormerNames, site.Aliases = "site", "web", "site", nil, nil
545 e.Projects = append(e.Projects, site)
546 e.Groups = append(e.Groups, export.Group{ID: "web", Name: "docs"})
547 })
548 tip := h.tip()
549 lands := func(want string) {
550 t.Helper()
551 for _, method := range []string{"GET", "HEAD"} {
552 if w := h.do(method, "/"); w.Code != http.StatusFound || w.Header().Get("Location") != want {
553 t.Errorf("%s / answered %d to %q, not a redirect to %s", method, w.Code, w.Header().Get("Location"), want)
554 }
555 }
556 }
557 lands("/tools/app/source/tree/" + tip + "/")
558
559 w := h.get("/-/knots")
560 page := w.Body.String()
561 for _, want := range []string{
562 "<title>knots</title>", "<h1>knots</h1>",
563 `<nav class="site" aria-label="Pages"><a href="/-/knots">knots</a><a href="/tools/app/source/tree/` + tip + `/">app source</a><a href="/docs/site/source/tree/` + tip + `/">site source</a>`,
564 } {
565 if w.Code != http.StatusOK || !strings.Contains(page, want) {
566 t.Errorf("/-/knots answered %d without %q", w.Code, want)
567 }
568 }
569 if head := h.do("HEAD", "/-/knots"); head.Code != http.StatusOK || fmt.Sprint(head.Header()) != fmt.Sprint(w.Header()) {
570 t.Errorf("HEAD /-/knots answered %d with the headers\n%v\nnot\n%v", head.Code, head.Header(), w.Header())
571 }
572 if page := h.page("/tools/app/knots/oc-a000002"); !strings.Contains(page, `<nav class="trail" aria-label="Where this knot sits"><a href="/-/knots">knots</a>`) {
573 t.Error("the knot page's trail does not start at the knots page")
574 }
575 if page := h.page("/tools/app/source/tree/" + tip + "/"); !strings.Contains(page, `<span class="eyebrow">source</span>`) {
576 t.Error("the source page's eyebrow does not read source")
577 }
578 if !bytes.Contains(busyPage, []byte(`<p><a href="/-/knots">knots</a></p>`)) {
579 t.Error("the error page does not link the knots page")
580 }
581 for _, target := range []string{"/-", "/-/", "/-/knots/", "/-/knots/oc-a000002", "/-/Knots", "/-/plan", "/-/knots/x"} {
582 for _, method := range []string{"GET", "HEAD"} {
583 if w := h.do(method, target); w.Code != http.StatusNotFound {
584 t.Errorf("%s %s answered %d, not 404", method, target, w.Code)
585 }
586 }
587 }
588
589 a, _, err := h.store.Authorization()
590 if err != nil {
591 t.Fatal(err)
592 }
593 only := exporttest.Authorization(a.Sequence + 1)
594 only.Projects = []export.AuthorizedProject{{Name: "site", Identity: exporttest.Identities["app"], Readers: []string{export.Anyone}}}
595 h.authorize(only)
596 lands("/docs/site/source/tree/" + tip + "/")
597
598 h.authorize(exporttest.Authorization(a.Sequence + 2))
599 lands("/-/knots")
600 empty := h.page("/-/knots")
601 if !strings.Contains(empty, "<h1>knots</h1>") || strings.Contains(empty, " source</a>") || strings.Contains(empty, "/tools/app") {
602 t.Errorf("with no project to see, the knots page is not its empty state:\n%s", empty)
603 }
604}
605
606// An alias answers with a permanent redirect to the same path under what
607// it stands for: a group's alias to the group's name, a project's former
608// name to its web name in its group, and a project's short alias to
609// /<group>/<project>. The rest of the path and the query are kept as they
610// were sent, escapes, dot segments and a bare "?" too, and the redirect
611// leads to the page. A group's identifier, a name in another case, and a
612// group with no project named answer 404.
613func TestAliasesRedirectPermanently(t *testing.T) {
614 h := newHarness(t)
615 tip := h.tip()
616 for from, to := range map[string]string{
617 "/t": "/tools",
618 "/t/": "/tools/",
619 "/t/app/knots/oc-a000002": "/tools/app/knots/oc-a000002",
620 "/t/old-app/knots/oc-a000002": "/tools/old-app/knots/oc-a000002",
621 "/tools/old-app": "/tools/app",
622 "/tools/old-app/": "/tools/app/",
623 "/tools/old-app/knots/oc-a000002": "/tools/app/knots/oc-a000002",
624 "/tools/old-app/source/log/" + tip: "/tools/app/source/log/" + tip,
625 "/app": "/tools/app",
626 "/app/": "/tools/app/",
627 "/app/knots/oc-a000002": "/tools/app/knots/oc-a000002",
628 "/app/source/log/" + tip + "?from=" + tip: "/tools/app/source/log/" + tip + "?from=" + tip,
629 "/app/source/log/" + tip + "?": "/tools/app/source/log/" + tip + "?",
630 "/tools/old-app/knots/oc-a000002?": "/tools/app/knots/oc-a000002?",
631 "/app/source/blob/" + tip + "/docs%2Fguide.md": "/tools/app/source/blob/" + tip + "/docs%2Fguide.md",
632 "/app/source/blob/" + tip + "/docs/../README.md": "/tools/app/source/blob/" + tip + "/docs/../README.md",
633 "/t/app/source/tree/" + tip + "/docs/": "/tools/app/source/tree/" + tip + "/docs/",
634 "/app//knots": "/tools/app//knots",
635 } {
636 for _, method := range []string{"GET", "HEAD"} {
637 w := h.do(method, from)
638 if w.Code != http.StatusPermanentRedirect || w.Header().Get("Location") != to {
639 t.Errorf("%s %s answered %d to %q, not a permanent redirect to %s", method, from, w.Code, w.Header().Get("Location"), to)
640 }
641 }
642 }
643 for _, target := range []string{"/tools/app/knots/oc-a000002", "/tools/app/source/tree/" + tip + "/docs/"} {
644 h.page(target)
645 }
646 if w := h.get("/app/"); w.Code == http.StatusPermanentRedirect {
647 if next := h.get(w.Header().Get("Location")); next.Code != http.StatusFound ||
648 next.Header().Get("Location") != "/tools/app/source/tree/"+tip+"/" {
649 t.Errorf("/app/ leads to %d %q, not to app's tree", next.Code, next.Header().Get("Location"))
650 }
651 }
652 for _, target := range []string{"/tools", "/tools/", "/core/app/", "/Tools/app/", "/T/app/", "/App/", "/tools/App/",
653 "/tools/Old-app/", "/old-app/", "/core/old-app/"} {
654 if w := h.get(target); w.Code != http.StatusNotFound {
655 t.Errorf("GET %s answered %d, not 404", target, w.Code)
656 }
657 }
658}
659
660// A project's web name is its own within its group, and need not be its
661// identifier. Two projects that are each app on the web, in two groups,
662// are served apart, each under its group's name, while the plan page
663// links each. A project's identifier is no web name of its own.
664func TestTwoGroupsEachHoldAnApp(t *testing.T) {
665 h := newHarness(t)
666 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"site": h.f.Bundles["app"]}, func(e *export.Export) {
667 site := e.Projects[0]
668 site.Name, site.Group, site.WebName, site.FormerNames, site.Aliases = "site", "web", "app", nil, nil
669 site.Knots = slices.Clone(site.Knots)
670 for i := range site.Knots {
671 site.Knots[i].Title = "Site: " + site.Knots[i].Title
672 }
673 e.Projects = append(e.Projects, site)
674 e.Groups = append(e.Groups, export.Group{ID: "web", Name: "docs"})
675 })
676 tip := h.tip()
677 if page := h.page("/tools/app/knots/oc-a000002"); !strings.Contains(page, "The plan page lists milestones") || strings.Contains(page, "Site: ") {
678 t.Errorf("/tools/app is not app:\n%s", page)
679 }
680 if page := h.page("/docs/app/knots/oc-a000002"); !strings.Contains(page, "Site: The plan page lists milestones") {
681 t.Errorf("/docs/app is not site:\n%s", page)
682 }
683 h.page("/docs/app/source/tree/" + tip + "/")
684 plan := h.page("/-/knots")
685 for _, link := range []string{`href="/tools/app/knots/oc-a000002"`, `href="/docs/app/knots/oc-a000002"`} {
686 if !strings.Contains(plan, link) {
687 t.Errorf("the plan page does not hold %s", link)
688 }
689 }
690 for _, target := range []string{"/docs/site/", "/docs/site/knots/oc-a000002", "/tools/site/"} {
691 if w := h.get(target); w.Code != http.StatusNotFound {
692 t.Errorf("GET %s answered %d, not 404", target, w.Code)
693 }
694 }
695}
696
697// A browser resolves a redirect's Location against the URL it asked for,
698// and removes the dot segments the server kept, "%2e" spelled ones too.
699// Every Location is a path on the server's own origin, whatever dot
700// segments, escaped slashes or empty segments the path held. Where the
701// browser goes answers as it does when asked for directly: a page of the
702// project, or the one 404.
703func TestRedirectsLeadWhereTheBrowserGoes(t *testing.T) {
704 h := newHarness(t)
705 tip := h.tip()
706 for from, c := range map[string]struct {
707 to string
708 code int
709 }{
710 "/app/source/blob/" + tip + "/docs/../README.md": {"/tools/app/source/blob/" + tip + "/README.md", http.StatusOK},
711 "/tools/old-app/source/blob/" + tip + "/docs/./guide.md": {"/tools/app/source/blob/" + tip + "/docs/guide.md", http.StatusOK},
712 "/t/app/source/blob/" + tip + "/docs/%2e%2E/README.md": {"/tools/app/source/blob/" + tip + "/README.md", http.StatusOK},
713 "/app/../site/": {"/tools/site/", http.StatusNotFound},
714 "/app/../../../-/": {"/-/", http.StatusNotFound},
715 "/t/../../..//example.net/": {"//example.net/", http.StatusNotFound},
716 "/t/..%2F..%2Fx": {"/tools/..%2F..%2Fx", http.StatusNotFound},
717 "/app/.%2E/x": {"/tools/x", http.StatusNotFound},
718 "/tools/old-app/..": {"/tools/", http.StatusNotFound},
719 "/tools/old-app/.%2e?": {"/tools/?", http.StatusNotFound},
720 } {
721 w := h.get(from)
722 if w.Code != http.StatusPermanentRedirect {
723 t.Errorf("GET %s answered %d, not a permanent redirect", from, w.Code)
724 continue
725 }
726 next := browserResolves(t, w.Header().Get("Location"))
727 if next != c.to {
728 t.Errorf("GET %s leads a browser to %s, not to %s", from, next, c.to)
729 continue
730 }
731 if got := h.get(next); got.Code != c.code {
732 t.Errorf("GET %s leads to %s, which answers %d, not %d", from, next, got.Code, c.code)
733 }
734 }
735}
736
737// browserResolves is the path and query a browser asks the same origin
738// for when a redirect's Location is location. location must be a path on
739// that origin: one "/", then a character a browser reads as neither "/"
740// nor "\", so no browser reads a host in it. The browser removes its dot
741// segments by the WHATWG URL standard's path parsing, which reads "%2e"
742// as a dot, ignoring case, and keeps empty segments.
743func browserResolves(t *testing.T, location string) string {
744 t.Helper()
745 if len(location) < 2 || location[0] != '/' || location[1] == '/' || location[1] == '\\' {
746 t.Fatalf("the Location %q is not a path on the server's origin", location)
747 }
748 path, query, queried := strings.Cut(location, "?")
749 if strings.ContainsAny(path, "\\#") {
750 t.Fatalf("the Location %q holds a character a browser reads apart from a path's", location)
751 }
752 segments := strings.Split(path[1:], "/")
753 var out []string
754 for i, segment := range segments {
755 last := i == len(segments)-1
756 switch strings.ToLower(segment) {
757 case "..", ".%2e", "%2e.", "%2e%2e":
758 if len(out) > 0 {
759 out = out[:len(out)-1]
760 }
761 if last {
762 out = append(out, "")
763 }
764 case ".", "%2e":
765 if last {
766 out = append(out, "")
767 }
768 default:
769 out = append(out, segment)
770 }
771 }
772 resolved := "/" + strings.Join(out, "/")
773 if queried {
774 resolved += "?" + query
775 }
776 return resolved
777}
778
779// Every 404 is the one page, made once: the box of text, whose last line
780// links to the plan, with no navigation, no export's age and no site name.
781// It stays the same byte for byte while the export changes.
782func TestNotFoundIsTheOnePage(t *testing.T) {
783 h := newHarness(t)
784 w := h.get("/tools/nosuch/")
785 if w.Code != http.StatusNotFound || w.Header().Get("Content-Type") != "text/html; charset=utf-8" {
786 t.Fatalf("a missing project answered %d, %q", w.Code, w.Header().Get("Content-Type"))
787 }
788 page := w.Body.String()
789 box := `<pre class="lost">
790╔═════════════════════════════════════╗
791║ ║
792║ THE WAY THAT CAN BE FOUND ║
793║ IS NOT THE ETERNAL WAY ║
794║ ║
795║ The page you seek exists ║
796║ only in non-existence. ║
797║ ║
798║ <a href="/">Return to the source</a> ║
799║ ║
800╚═════════════════════════════════════╝
801</pre>`
802 if !strings.Contains(page, box) {
803 t.Errorf("the 404 page does not hold the box:\n%s", page)
804 }
805 for _, unwanted := range []string{"<nav", "Collected", "app source", exporttest.Instance, exporttest.Destination, "tools"} {
806 if strings.Contains(page, unwanted) {
807 t.Errorf("the 404 page holds %q:\n%s", unwanted, page)
808 }
809 }
810 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
811 h.now = h.now.Add(time.Hour)
812 for _, target := range []string{"/nosuch", "/-/", "/tools/app/knots/oc-fffffff", "/tools/app/source/tree/" + strings.Repeat("0", 40) + "/"} {
813 if again := h.get(target); again.Code != http.StatusNotFound || again.Body.String() != page {
814 t.Errorf("GET %s answered %d with another page than the one 404", target, again.Code)
815 }
816 }
817}
818
819// A source route serves a commit only when main's published tip reaches
820// it, and refuses every other object ID or name with the one 404.
821func TestUnreachableCommitIsRefused(t *testing.T) {
822 h := newHarness(t)
823 repo, _ := h.active().Repo("app")
824 tip := h.tip()
825 tree := git(t, repo, nil, "rev-parse", tip+"^{tree}")
826 readme := git(t, repo, nil, "rev-parse", tip+":README.md")
827 side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach")
828 parent := git(t, repo, nil, "rev-parse", tip+"~2")
829 notFound := h.get("/tools/app/knots/oc-fffffff").Body.String()
830
831 for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} {
832 for _, route := range []string{"/tools/app/source/tree/%s/", "/tools/app/source/blob/%s/README.md", "/tools/app/source/log/%s",
833 "/tools/app/source/archive/%s.tar.gz"} {
834 if commit == "main" && strings.HasPrefix(route, "/tools/app/source/archive/") {
835 continue // main.tar.gz redirects to the archive of main's tip
836 }
837 target := fmt.Sprintf(route, commit)
838 w := h.get(target)
839 if w.Code != http.StatusNotFound || w.Body.String() != notFound {
840 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
841 }
842 }
843 }
844
845 // A commit the tip reaches is served, as that commit had it.
846 page := h.page("/tools/app/source/blob/" + parent + "/README.md")
847 if !strings.Contains(page, "A synthetic project for the web UI&#39;s tests.") || strings.Contains(page, "readme") {
848 t.Errorf("the first README is not served as the first commit had it:\n%s", page)
849 }
850}
851
852// The source browser lists a directory and its README, shows a file and
853// main's log, and every source link names its project, a full commit and
854// a path.
855func TestSourceBrowser(t *testing.T) {
856 h := newHarness(t)
857 tip := h.tip()
858
859 for _, path := range []string{"/tools/app/source", "/tools/app/source/"} {
860 w := h.get(path)
861 if w.Code != http.StatusFound || w.Header().Get("Location") != "/tools/app/source/tree/"+tip+"/" {
862 t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location"))
863 }
864 }
865
866 root := h.page("/tools/app/source/tree/" + tip + "/")
867 docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<")
868 if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs {
869 t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root)
870 }
871 if !strings.Contains(root, `<h1 id="app">app <a class="anchor" href="#app">#</a></h1>`) {
872 t.Error("the root does not show its README")
873 }
874 if dir := h.page("/tools/app/source/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") {
875 t.Error("docs/ does not list guide.md")
876 }
877 file := h.page("/tools/app/source/blob/" + tip + "/docs/guide.md?plain=1")
878 if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) {
879 t.Errorf("the file is not shown line by line:\n%s", file)
880 }
881 log := h.page("/tools/app/source/log/" + tip)
882 first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README")
883 if first < 0 || last < first {
884 t.Errorf("the log does not list main's commits newest first:\n%s", log)
885 }
886
887 links := regexp.MustCompile(`href="(/[^"]*/source/[^"]*)"`)
888 named := regexp.MustCompile(`^/tools/app/source/((tree|blob|log)/[0-9a-f]{40}(/|$)|archive/[0-9a-f]{40}\.tar\.gz$)`)
889 for _, page := range []string{root, file, log} {
890 for _, m := range links.FindAllStringSubmatch(page, -1) {
891 if !named.MatchString(m[1]) {
892 t.Errorf("the link %s names no commit", m[1])
893 }
894 }
895 }
896
897 for _, target := range []string{
898 "/tools/app/source/blob/" + tip + "/docs/guide.md/",
899 "/tools/app/source/blob/" + tip + "/docs/../README.md",
900 "/tools/app/source/blob/" + tip + "/docs%2Fguide.md",
901 "/tools/app/source/tree/" + tip + "//",
902 "/tools/app/source/log/" + tip + "?from=" + strings.ToUpper(tip),
903 } {
904 if w := h.get(target); w.Code != http.StatusNotFound {
905 t.Errorf("GET %s answered %d", target, w.Code)
906 }
907 }
908}
909
910// A tree page links the archive of its commit. The archive holds that
911// commit's files and directories, and only those, in the tree's order,
912// under one directory named for the project and the commit. Every entry
913// carries the commit's time, and the same commit gives the same bytes.
914// It carries every header a page carries, and its own. A name that is no
915// full ID of a commit main reaches, or a path of another shape, answers the
916// one 404, and a project the authorization does not name answers as its
917// tree page does.
918func TestSourceArchive(t *testing.T) {
919 h := newHarness(t)
920 repo, _ := h.active().Repo("app")
921 tip := h.tip()
922 parent := git(t, repo, nil, "rev-parse", tip+"~1")
923 at := func(commit string) string { return "/tools/app/source/archive/" + commit + ".tar.gz" }
924
925 for _, dir := range []string{tip + "/", tip + "/docs/", parent + "/"} {
926 if page := h.page("/tools/app/source/tree/" + dir); !strings.Contains(page, `<a href="`+at(dir[:40])+`">Download .tar.gz</a>`) {
927 t.Errorf("the tree page at %s does not link its commit's archive", dir)
928 }
929 }
930
931 for _, commit := range []string{tip, parent} {
932 w := h.get(at(commit))
933 if w.Code != http.StatusOK {
934 t.Fatalf("GET %s answered %d:\n%s", at(commit), w.Code, w.Body)
935 }
936 want := http.Header{}
937 setHeaders(want)
938 want.Set("Content-Type", "application/gzip")
939 want.Set("Content-Disposition", `attachment; filename="app-`+commit[:12]+`.tar.gz"`)
940 want.Set("Content-Length", strconv.Itoa(w.Body.Len()))
941 if fmt.Sprint(w.Header()) != fmt.Sprint(want) {
942 t.Errorf("the archive of %s answered with the headers\n%v\nnot\n%v", commit, w.Header(), want)
943 }
944 if head := h.do("HEAD", at(commit)); head.Code != http.StatusOK || fmt.Sprint(head.Header()) != fmt.Sprint(want) {
945 t.Errorf("HEAD %s answered %d with the headers\n%v", at(commit), head.Code, head.Header())
946 }
947 if again := h.get(at(commit)); !bytes.Equal(again.Body.Bytes(), w.Body.Bytes()) {
948 t.Errorf("two requests for the archive of %s gave other bytes", commit)
949 }
950 // The archive is its directory, then the commit's tree in git's
951 // order, each entry with its mode and the commit's time, each file
952 // as git holds it, and each header in the USTAR format.
953 when := git(t, repo, nil, "log", "-1", "--format=%ct", commit)
954 dir := "app-" + commit[:12] + "/"
955 describe := func(typ byte, mode int64, name, content string) string {
956 return fmt.Sprintf("%c %o %s %q %q", typ, mode, when, name, content)
957 }
958 tree := []string{describe(tar.TypeDir, 0o755, dir, "")}
959 for _, line := range strings.Split(git(t, repo, nil, "ls-tree", "-r", "-t", commit), "\n") {
960 meta, path, _ := strings.Cut(line, "\t")
961 switch f := strings.Fields(meta); f[0] {
962 case "040000":
963 tree = append(tree, describe(tar.TypeDir, 0o755, dir+path+"/", ""))
964 case "100644":
965 tree = append(tree, describe(tar.TypeReg, 0o644, dir+path, git(t, repo, nil, "cat-file", "blob", f[2])))
966 default:
967 t.Fatalf("the fixture's app holds %q", line)
968 }
969 }
970 var got []string
971 for _, e := range readArchive(t, w.Body.Bytes()) {
972 if e.hdr.Format != tar.FormatUSTAR {
973 t.Errorf("the archive of %s holds %q in the format %v", commit, e.hdr.Name, e.hdr.Format)
974 }
975 got = append(got, fmt.Sprintf("%c %o %d %q %q", e.hdr.Typeflag, e.hdr.Mode, e.hdr.ModTime.Unix(), e.hdr.Name, strings.TrimSpace(e.content)))
976 }
977 if !slices.Equal(got, tree) {
978 t.Errorf("the archive of %s holds\n%s\nnot\n%s", commit, strings.Join(got, "\n"), strings.Join(tree, "\n"))
979 }
980 }
981
982 notFound := h.get("/tools/app/knots/oc-fffffff").Body.String()
983 for _, target := range []string{
984 "/tools/app/source/archive/" + tip,
985 "/tools/app/source/archive/" + tip + ".tar",
986 "/tools/app/source/archive/" + tip + ".zip",
987 "/tools/app/source/archive/" + strings.ToUpper(tip) + ".tar.gz",
988 "/tools/app/source/archive/" + tip + ".tar.gz/",
989 "/tools/app/source/archive/" + tip + ".tar.gz/README.md",
990 "/tools/app/source/archive/" + tip + "/README.md",
991 "/tools/app/source/archive/.tar.gz",
992 "/tools/app/source/archive/",
993 "/tools/app/source/archive",
994 } {
995 if w := h.get(target); w.Code != http.StatusNotFound || w.Body.String() != notFound {
996 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
997 }
998 }
999
1000 a, _, err := h.store.Authorization()
1001 if err != nil {
1002 t.Fatal(err)
1003 }
1004 h.authorize(exporttest.Authorization(a.Sequence + 1))
1005 archive, tree := h.get(at(tip)), h.get("/tools/app/source/tree/"+tip+"/")
1006 if archive.Code != http.StatusNotFound || archive.Code != tree.Code || fmt.Sprint(archive.Header()) != fmt.Sprint(tree.Header()) ||
1007 !bytes.Equal(archive.Body.Bytes(), tree.Body.Bytes()) {
1008 t.Errorf("withdrawn, the archive answered %d and the tree page %d, or with other headers or bodies", archive.Code, tree.Code)
1009 }
1010 h.authorize(exporttest.Authorization(a.Sequence+2, "app"))
1011 if w := h.get(at(tip)); w.Code != http.StatusOK {
1012 t.Errorf("named again, the archive answered %d", w.Code)
1013 }
1014}
1015
1016// An archive that would pass MaxResponse answers with the short page that
1017// says the page is too large, and none of the archive, and the failure is
1018// logged. An archive within the bound is served.
1019func TestArchiveTooLarge(t *testing.T) {
1020 h := newHarness(t)
1021 var logged []string
1022 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1023 before := h.tip()
1024 var noise []byte
1025 for i := 0; len(noise) < 64<<10; i++ {
1026 sum := sha256.Sum256([]byte(fmt.Sprint(i)))
1027 noise = append(noise, sum[:]...)
1028 }
1029 tip, bundle := h.commitMain("app: a file gzip cannot shrink\n", file{"100644", "noise.bin", string(noise)})
1030 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1031
1032 h.srv.maxResponse = 32 << 10
1033 for _, method := range []string{"GET", "HEAD"} {
1034 w := h.do(method, "/tools/app/source/archive/"+tip+".tar.gz")
1035 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) ||
1036 w.Header().Get("Content-Type") != htmlType || w.Header().Get("Content-Disposition") != "" {
1037 t.Errorf("%s of an archive too large answered %d, %q, %q, with %d bytes", method, w.Code,
1038 w.Header().Get("Content-Type"), w.Header().Get("Content-Disposition"), w.Body.Len())
1039 }
1040 if n, _ := h.srv.holding(); n != 0 {
1041 t.Errorf("%s of an archive too large kept %d pieces of the budget", method, n)
1042 }
1043 }
1044 if w := h.get("/tools/app/source/archive/" + before + ".tar.gz"); w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/gzip" {
1045 t.Errorf("an archive within the bound answered %d, %q", w.Code, w.Header().Get("Content-Type"))
1046 }
1047 if len(logged) != 2 {
1048 t.Errorf("%d failures were logged for 2 archives too large: %q", len(logged), logged)
1049 }
1050 for _, l := range logged {
1051 if !strings.Contains(l, "larger than") {
1052 t.Errorf("the server logged %q", l)
1053 }
1054 }
1055}
1056
1057// An archive is the commit's tree byte for byte. It applies no attribute,
1058// from the commit's own .gitattributes or from the repository, so
1059// export-subst expands nothing and export-ignore leaves nothing out. One
1060// commit gives the same bytes once a ref is moved and attributes and
1061// configuration are added to the repository, though each would change an
1062// archive that applied attributes.
1063func TestArchiveAppliesNoAttributes(t *testing.T) {
1064 h := newHarness(t)
1065 subst := "$Format:%ar$ $Format:%d$ $Format:%H$\n"
1066 attributes := "* export-subst\nignored.txt export-ignore\ndocs export-ignore\n"
1067 tip, bundle := h.commitMain("app: attributes an archive does not apply\n",
1068 file{"100644", ".gitattributes", attributes},
1069 file{"100644", "subst.txt", subst},
1070 file{"100644", "ignored.txt", "ignored\n"})
1071 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1072 repo, _ := h.active().Repo("app")
1073 at := "/tools/app/source/archive/" + tip + ".tar.gz"
1074 first := h.get(at)
1075 if first.Code != http.StatusOK {
1076 t.Fatalf("GET %s answered %d:\n%s", at, first.Code, first.Body)
1077 }
1078 dir := "app-" + tip[:12] + "/"
1079 got := map[string]string{}
1080 for _, e := range readArchive(t, first.Body.Bytes()) {
1081 got[e.hdr.Name] = e.content
1082 }
1083 for name, want := range map[string]string{".gitattributes": attributes, "subst.txt": subst, "ignored.txt": "ignored\n", "docs/": ""} {
1084 if content, ok := got[dir+name]; !ok || content != want {
1085 t.Errorf("the archive holds %s as %q, %v, not %q", name, content, ok, want)
1086 }
1087 }
1088
1089 git(t, repo, nil, "branch", "side", tip)
1090 git(t, repo, nil, "tag", "v1", tip)
1091 if err := os.MkdirAll(filepath.Join(repo, "info"), 0o755); err != nil {
1092 t.Fatal(err)
1093 }
1094 if err := os.WriteFile(filepath.Join(repo, "info", "attributes"), []byte("* export-ignore\n"), 0o644); err != nil {
1095 t.Fatal(err)
1096 }
1097 git(t, repo, nil, "config", "tar.umask", "0")
1098 git(t, repo, nil, "config", "core.autocrlf", "true")
1099 h.now = h.now.Add(time.Hour)
1100 if again := h.get(at); again.Code != http.StatusOK || !bytes.Equal(again.Body.Bytes(), first.Body.Bytes()) {
1101 t.Errorf("with a ref moved, and attributes and configuration added, the archive answered %d with other bytes", again.Code)
1102 }
1103}
1104
1105// A symbolic link is a tar symbolic link to its blob's content, and is not
1106// followed. A submodule is an empty directory, and an executable file is
1107// 0755. A header is in the USTAR format unless its name or target is too
1108// long for it, and in the PAX format then.
1109func TestArchiveLinksAndSubmodules(t *testing.T) {
1110 h := newHarness(t)
1111 far := strings.Repeat("deep/", 40) + "target"
1112 long := strings.Repeat("n", 120) + ".txt"
1113 tip, bundle := h.commitMain("app: links, a submodule and long names\n",
1114 file{"120000", "link", "../../etc/passwd"},
1115 file{"120000", "far", far},
1116 file{"100755", "run.sh", "#!/bin/sh\n"},
1117 file{"160000", "vendor/lib", h.tip()},
1118 file{"100644", long, "long\n"})
1119 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1120 at := "/tools/app/source/archive/" + tip + ".tar.gz"
1121 w := h.get(at)
1122 if w.Code != http.StatusOK {
1123 t.Fatalf("GET %s answered %d:\n%s", at, w.Code, w.Body)
1124 }
1125 dir := "app-" + tip[:12] + "/"
1126 got := map[string]string{}
1127 var names []string
1128 for _, e := range readArchive(t, w.Body.Bytes()) {
1129 got[e.hdr.Name] = fmt.Sprintf("%c %o %d %q %q %v", e.hdr.Typeflag, e.hdr.Mode, e.hdr.Size, e.hdr.Linkname, e.content, e.hdr.Format)
1130 names = append(names, e.hdr.Name)
1131 }
1132 for name, want := range map[string]string{
1133 "link": fmt.Sprintf("%c 777 0 %q \"\" USTAR", tar.TypeSymlink, "../../etc/passwd"),
1134 "far": fmt.Sprintf("%c 777 0 %q \"\" PAX", tar.TypeSymlink, far),
1135 "run.sh": fmt.Sprintf("%c 755 10 \"\" %q USTAR", tar.TypeReg, "#!/bin/sh\n"),
1136 "vendor/": fmt.Sprintf("%c 755 0 \"\" \"\" USTAR", tar.TypeDir),
1137 "vendor/lib/": fmt.Sprintf("%c 755 0 \"\" \"\" USTAR", tar.TypeDir),
1138 long: fmt.Sprintf("%c 644 5 \"\" %q PAX", tar.TypeReg, "long\n"),
1139 } {
1140 if got[dir+name] != want {
1141 t.Errorf("the archive holds %s as %s, not %s", name, got[dir+name], want)
1142 }
1143 }
1144 for _, name := range names {
1145 if strings.HasPrefix(name, dir+"vendor/lib/") && name != dir+"vendor/lib/" {
1146 t.Errorf("the archive holds %s inside the submodule", name)
1147 }
1148 }
1149}
1150
1151// An archive whose files add up to more than MaxArchiveInput, or whose
1152// tree holds more than MaxArchiveEntries entries, is refused from its
1153// tree's listing, before any file is read: it answers with the short page
1154// that says the page is too large, holds none of the budget, and the
1155// refusal is logged. A file is counted once for each path that holds it,
1156// as the archive would hold it.
1157func TestArchiveInputBound(t *testing.T) {
1158 zeros := strings.Repeat("\x00", 1<<20)
1159 for _, c := range []struct {
1160 name, refused string
1161 files func() []file
1162 }{
1163 {"files", fmt.Sprintf("its files are larger than %d bytes", MaxArchiveInput), func() (files []file) {
1164 for i := range MaxArchiveInput >> 20 {
1165 files = append(files, file{"100644", fmt.Sprintf("big/%02d.bin", i), zeros})
1166 }
1167 return files
1168 }},
1169 {"entries", fmt.Sprintf("its tree holds more than %d entries", MaxArchiveEntries), func() (files []file) {
1170 for i := range MaxArchiveEntries {
1171 files = append(files, file{"100644", fmt.Sprintf("many/%05d", i), ""})
1172 }
1173 return files
1174 }},
1175 } {
1176 t.Run(c.name, func(t *testing.T) {
1177 h := newHarness(t)
1178 var logged []string
1179 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1180 tip, bundle := h.commitMain("app: a tree too large for an archive\n", c.files()...)
1181 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1182 w := h.get("/tools/app/source/archive/" + tip + ".tar.gz")
1183 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) ||
1184 w.Header().Get("Content-Type") != htmlType || w.Header().Get("Content-Disposition") != "" {
1185 t.Errorf("an archive too large answered %d, %q, %q, with %d bytes", w.Code,
1186 w.Header().Get("Content-Type"), w.Header().Get("Content-Disposition"), w.Body.Len())
1187 }
1188 if n, _ := h.srv.holding(); n != 0 {
1189 t.Errorf("an archive too large kept %d pieces of the budget", n)
1190 }
1191 if len(logged) != 1 || !strings.Contains(logged[0], "larger than the server sends: "+c.refused) {
1192 t.Errorf("the server logged %q, not that %s", logged, c.refused)
1193 }
1194 })
1195 }
1196}
1197
1198// A file far larger than MaxResponse that gzip shrinks to little is served
1199// whole. The server streams it through tar and gzip into the response
1200// body, and holds none of it whole: once the response is rendered, it
1201// holds the pieces of the budget that the gzipped archive fills, and no
1202// more.
1203func TestArchiveStreamsIntoTheBody(t *testing.T) {
1204 h := newHarness(t)
1205 zeros := strings.Repeat("\x00", 3*MaxResponse)
1206 tip, bundle := h.commitMain("app: a large file gzip shrinks\n", file{"100644", "zeros.bin", zeros})
1207 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1208 var held, large int
1209 h.srv.checked = func() { held, large = h.srv.holding() }
1210 at := "/tools/app/source/archive/" + tip + ".tar.gz"
1211 w := h.get(at)
1212 if w.Code != http.StatusOK {
1213 t.Fatalf("GET %s answered %d:\n%s", at, w.Code, w.Body)
1214 }
1215 if pieces := (w.Body.Len() + pieceSize - 1) / pieceSize; held != pieces || large != 0 || w.Body.Len() > SmallPage {
1216 t.Errorf("an archive of %d bytes held %d pieces of the budget and %d of the large budget, not %d and 0",
1217 w.Body.Len(), held, large, pieces)
1218 }
1219 if n, _ := h.srv.holding(); n != 0 {
1220 t.Errorf("once written, the archive kept %d pieces of the budget", n)
1221 }
1222 var content string
1223 for _, e := range readArchive(t, w.Body.Bytes()) {
1224 if e.hdr.Name == "app-"+tip[:12]+"/zeros.bin" {
1225 content = e.content
1226 }
1227 }
1228 if content != zeros {
1229 t.Errorf("the archive holds zeros.bin as %d bytes, not %d", len(content), len(zeros))
1230 }
1231}
1232
1233// /source/archive/main.tar.gz redirects to the archive of main's tip as
1234// /source/ redirects to the tree there: a temporary redirect, with the same
1235// headers, that takes no git slot, and that follows main when it moves.
1236// main is the one name the route takes in place of a full commit ID: HEAD,
1237// another branch's name, or main spelled another way answers the one 404.
1238func TestArchiveOfMainsTip(t *testing.T) {
1239 h := newHarness(t)
1240 repo, _ := h.active().Repo("app")
1241 git(t, repo, nil, "branch", "side", h.tip())
1242 var admitted atomic.Int32
1243 h.srv.admitted = func() { admitted.Add(1) }
1244 target := "/tools/app/source/archive/main.tar.gz"
1245 redirects := func(tip string) {
1246 t.Helper()
1247 admitted.Store(0)
1248 at := "/tools/app/source/archive/" + tip + ".tar.gz"
1249 for _, method := range []string{"GET", "HEAD"} {
1250 w, tree := h.do(method, target), h.do(method, "/tools/app/source/")
1251 want := tree.Header().Clone()
1252 want.Set("Location", at)
1253 if w.Code != http.StatusFound || w.Code != tree.Code || fmt.Sprint(w.Header()) != fmt.Sprint(want) {
1254 t.Errorf("%s %s answered %d with the headers\n%v\nnot %d with\n%v", method, target, w.Code, w.Header(), tree.Code, want)
1255 }
1256 }
1257 if n := admitted.Load(); n != 0 {
1258 t.Errorf("the redirect to the archive of main's tip took a git slot %d times", n)
1259 }
1260 if w := h.get(at); w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/gzip" {
1261 t.Errorf("the redirect leads to %s, which answers %d, %q", at, w.Code, w.Header().Get("Content-Type"))
1262 }
1263 }
1264 redirects(h.tip())
1265
1266 notFound := h.get("/tools/app/knots/oc-fffffff").Body.String()
1267 for _, name := range []string{"HEAD.tar.gz", "side.tar.gz", "MAIN.tar.gz", "main.tar", "main", "main.tar.gz/", "refs/heads/main.tar.gz"} {
1268 if w := h.get("/tools/app/source/archive/" + name); w.Code != http.StatusNotFound || w.Body.String() != notFound {
1269 t.Errorf("GET /tools/app/source/archive/%s answered %d, not the one 404", name, w.Code)
1270 }
1271 }
1272
1273 tip, bundle := h.commitMain("app: main moves on\n", file{"100644", "moved.txt", "moved\n"})
1274 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1275 redirects(tip)
1276}
1277
1278// archived is one entry of a gzipped tar archive: its header, and what it
1279// holds.
1280type archived struct {
1281 hdr *tar.Header
1282 content string
1283}
1284
1285// readArchive is the entries of a gzipped tar archive, in order. The gzip
1286// header must name no file and no time, and every entry must be a file, a
1287// symbolic link or a directory, with uid and gid 0 and no user or group
1288// name.
1289func readArchive(t *testing.T, data []byte) []archived {
1290 t.Helper()
1291 zr, err := gzip.NewReader(bytes.NewReader(data))
1292 if err != nil {
1293 t.Fatal(err)
1294 }
1295 if zr.Name != "" || !zr.ModTime.IsZero() {
1296 t.Errorf("the archive's gzip header names %q at %v", zr.Name, zr.ModTime)
1297 }
1298 tr := tar.NewReader(zr)
1299 var entries []archived
1300 for {
1301 hdr, err := tr.Next()
1302 if err == io.EOF {
1303 break
1304 }
1305 if err != nil {
1306 t.Fatal(err)
1307 }
1308 if !slices.Contains([]byte{tar.TypeReg, tar.TypeSymlink, tar.TypeDir}, hdr.Typeflag) ||
1309 hdr.Uid != 0 || hdr.Gid != 0 || hdr.Uname != "" || hdr.Gname != "" {
1310 t.Errorf("the archive holds %q of type %q, owned by %d:%d, %q:%q", hdr.Name, hdr.Typeflag, hdr.Uid, hdr.Gid, hdr.Uname, hdr.Gname)
1311 }
1312 content, err := io.ReadAll(tr)
1313 if err != nil {
1314 t.Fatal(err)
1315 }
1316 entries = append(entries, archived{hdr, string(content)})
1317 }
1318 if _, err := io.Copy(io.Discard, zr); err != nil {
1319 t.Fatal(err)
1320 }
1321 return entries
1322}
1323
1324// archiveEntries is the entries of a gzipped tar archive, by name: each
1325// file's content, without the white space that ends it, as git trims it,
1326// and "" for each directory.
1327func archiveEntries(t *testing.T, data []byte) map[string]string {
1328 t.Helper()
1329 entries := map[string]string{}
1330 for _, e := range readArchive(t, data) {
1331 entries[e.hdr.Name] = strings.TrimSpace(e.content)
1332 }
1333 return entries
1334}
1335
1336// Markdown files and READMEs render as documents: headings with anchors,
1337// a contents list for a long one, and relative links kept inside the
1338// source browser at the same commit. ?plain=1 shows the escaped text, and
1339// a path that names the other kind of entry redirects to its route.
1340// Hostile Markdown arrives inert. A document that renders larger than
1341// MaxShown shows its start, with a notice.
1342func TestMarkdownPages(t *testing.T) {
1343 h := newHarness(t)
1344 large := "# Large\n\n[a]: https://example.org/" + strings.Repeat("x", 4000) + "\n\n" + strings.Repeat("[a]\n\n", 600)
1345 tip, bundle := h.commitMain("docs: a long document\n",
1346 file{"100644", "large/README.md", large}, file{"100644", "docs/large.md", large},
1347 file{"100644", "docs/long.md", "# Long\n\n## One\n\nSee [the guide](guide.md#guide), [the README](../README.md),\n" +
1348 "[src](/src/), [docs](../docs), [here](#two), [above](../../x.md) and [js](javascript:alert(1)).\n\n" +
1349 "## Two\n\n### Three\n\n## Four\n\n| a | b |\n|---|--:|\n| 1 | 2 |\n"},
1350 file{"100644", "docs/hostile.MD", "<script>alert(1)</script>\n\n<svg onload=alert(2)><form action=x><input></form>\n\n" +
1351 "[x](javascript:alert(3)) [y](data:text/html,z) <img src=x onerror=alert(4)>\n"},
1352 )
1353 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1354 base := "/tools/app/source/"
1355 long := h.page(base + "blob/" + tip + "/docs/long.md")
1356 for _, want := range []string{
1357 `<h2 id="one">One <a class="anchor" href="#one">#</a></h2>`,
1358 `<details class="contents"><summary>Contents</summary><ul><li class="level2"><a href="#one">One</a></li>`,
1359 `<li class="level3"><a href="#three">Three</a></li>`,
1360 `<a href="` + base + `blob/` + tip + `/docs/guide.md#guide">the guide</a>`,
1361 `<a href="` + base + `blob/` + tip + `/README.md">the README</a>`,
1362 `<a href="` + base + `tree/` + tip + `/src/">src</a>`,
1363 `<a href="` + base + `blob/` + tip + `/docs">docs</a>`,
1364 `<a href="#two">here</a>`, ` above and js.`,
1365 `<th class="right">b</th>`,
1366 `<a href="` + base + `blob/` + tip + `/docs/long.md?plain=1">Plain text</a>`,
1367 } {
1368 if !strings.Contains(long, want) {
1369 t.Errorf("the rendered document lacks %s:\n%s", want, long)
1370 }
1371 }
1372 plain := h.page(base + "blob/" + tip + "/docs/long.md?plain=1")
1373 if !strings.Contains(plain, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Long</td></tr>`) ||
1374 !strings.Contains(plain, `<a href="`+base+`blob/`+tip+`/docs/long.md">Rendered</a>`) || strings.Contains(plain, "<h2") {
1375 t.Errorf("?plain=1 does not show the text line by line:\n%s", plain)
1376 }
1377 tree := h.page(base + "tree/" + tip + "/")
1378 if !strings.Contains(tree, `<h2 id="README">`) || !strings.Contains(tree, `<div class="markdown"><h1 id="app">`) {
1379 t.Errorf("the root does not render its README:\n%s", tree)
1380 }
1381 for from, to := range map[string]string{
1382 base + "blob/" + tip + "/docs": base + "tree/" + tip + "/docs/",
1383 base + "tree/" + tip + "/README.md/": base + "blob/" + tip + "/README.md",
1384 base + "tree/" + tip + "/docs/long.md": base + "blob/" + tip + "/docs/long.md",
1385 } {
1386 if w := h.get(from); w.Code != http.StatusFound || w.Header().Get("Location") != to {
1387 t.Errorf("GET %s answered %d to %q", from, w.Code, w.Header().Get("Location"))
1388 }
1389 }
1390 at := base + "blob/" + tip + "/docs/hostile.MD"
1391 page := h.page(at)
1392 for _, active := range []string{"<script", "<svg", "<form", "<input", "<img", "javascript:", "data:", "style="} {
1393 if strings.Contains(page, active) {
1394 t.Errorf("GET %s holds %q", at, active)
1395 }
1396 }
1397 for _, want := range []string{"<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>", "&lt;svg onload=alert(2)&gt;", "<p>x y &lt;img"} {
1398 if !strings.Contains(page, want) {
1399 t.Errorf("GET %s does not show %q:\n%s", at, want, page)
1400 }
1401 }
1402 if w := h.get(at); w.Header().Get("Content-Security-Policy") != csp {
1403 t.Errorf("a rendered page answered with policy %q", w.Header().Get("Content-Security-Policy"))
1404 }
1405 for target, notice := range map[string]string{
1406 base + "tree/" + tip + "/large/": "This README is longer than a page shows, and only its start is shown.",
1407 base + "blob/" + tip + "/docs/large.md": "This file is longer than a page shows, and only its start is shown.",
1408 } {
1409 page := h.page(target)
1410 if !strings.Contains(page, notice) || !strings.Contains(page, `<h1 id="large">`) ||
1411 strings.Count(page, "example.org/xxx") >= 600 || len(page) > MaxShown+64<<10 {
1412 t.Errorf("GET %s does not show the start of a large document with its notice:\n%.2000s", target, page)
1413 }
1414 }
1415}
1416
1417// file is one file a test commits: its mode, path and content. The
1418// content of a submodule, mode 160000, is the ID of its commit.
1419type file struct{ mode, path, content string }
1420
1421// commitMain writes a commit onto the fixture's app main, with message,
1422// that holds the files given beside what main holds. It returns the new
1423// tip and a bundle of it. Each content is written once, however many
1424// files hold it.
1425func (h *harness) commitMain(message string, files ...file) (tip, bundle string) {
1426 t := h.t
1427 t.Helper()
1428 repo := h.f.Repos["app"]
1429 var b bytes.Buffer
1430 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
1431 marks := map[string]int{}
1432 for _, f := range files {
1433 if _, ok := marks[f.content]; !ok && f.mode != "160000" {
1434 marks[f.content] = len(marks) + 1
1435 fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content])
1436 data(f.content)
1437 }
1438 }
1439 who := "Example Author <author@example.org> 1791190800 +0000"
1440 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
1441 data(message)
1442 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
1443 for _, f := range files {
1444 if f.mode == "160000" {
1445 fmt.Fprintf(&b, "M %s %s %s\n", f.mode, f.content, f.path)
1446 } else {
1447 fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path)
1448 }
1449 }
1450 git(t, repo, b.Bytes(), "fast-import", "--quiet")
1451 tip = git(t, repo, nil, "rev-parse", export.MainRef)
1452 bundle = filepath.Join(t.TempDir(), "app.bundle")
1453 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
1454 return tip, bundle
1455}
1456
1457// publishMain activates a generation whose app main is tip, carried by
1458// bundle.
1459func (h *harness) publishMain(at time.Time, tip, bundle string) {
1460 h.t.Helper()
1461 h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip })
1462}
1463
1464// hostileMain writes a commit onto the fixture's app main that holds a
1465// file of HTML, a file larger than a page shows, a binary file, a file
1466// whose name is HTML, and a symbolic link out of the repository. It
1467// returns the new tip and a bundle of it.
1468func (h *harness) hostileMain() (tip, bundle string) {
1469 return h.commitMain("hostile: <script>alert(\"subject\")</script>\n",
1470 file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"},
1471 file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)},
1472 file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"},
1473 file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"},
1474 file{"120000", "link", "../../etc/passwd"},
1475 )
1476}
1477
1478// HTML, scripts, large files and binary files from a repository or the
1479// plan render inert: escaped as text, or not shown.
1480func TestHostileContentRendersInert(t *testing.T) {
1481 h := newHarness(t)
1482 tip, bundle := h.hostileMain()
1483 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1484 e.Projects[0].SourceTip = tip
1485 })
1486
1487 inert := func(target, page string, wants ...string) {
1488 t.Helper()
1489 // Escaped, a tag is text; only a tag the page did not escape, or
1490 // an attribute it let a value break out into, is active.
1491 for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} {
1492 if strings.Contains(page, active) {
1493 t.Errorf("GET %s holds %q", target, active)
1494 }
1495 }
1496 for _, want := range wants {
1497 if !strings.Contains(page, want) {
1498 t.Errorf("GET %s does not show %q", target, want)
1499 }
1500 }
1501 }
1502 at := "/tools/app/source/tree/" + tip + "/"
1503 inert(at, h.page(at),
1504 `&lt;script&gt;alert(&#34;readme&#34;)&lt;/script&gt;`,
1505 `&lt;img src=x onerror=alert(3)&gt;.txt`,
1506 `href="/tools/app/source/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`)
1507 at = "/tools/app/source/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"
1508 inert(at, h.page(at), ">named<")
1509 at = "/tools/app/source/blob/" + tip + "/page.html"
1510 inert(at, h.page(at), `&lt;html&gt;&lt;script&gt;alert(&#34;file&#34;)&lt;/script&gt;&lt;img src=x onerror=alert(2)&gt;&lt;/html&gt;`)
1511 at = "/tools/app/source/blob/" + tip + "/big.txt"
1512 page := h.page(at)
1513 inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.")
1514 if len(page) > 64<<10 {
1515 t.Errorf("the large file's page is %d bytes", len(page))
1516 }
1517 at = "/tools/app/source/blob/" + tip + "/binary.bin"
1518 inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.")
1519 at = "/tools/app/source/blob/" + tip + "/link"
1520 inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.")
1521 at = "/tools/app/source/log/" + tip
1522 inert(at, h.page(at), "hostile: &lt;script&gt;alert(&#34;subject&#34;)&lt;/script&gt;")
1523
1524 at = "/tools/app/knots/bd-a000004"
1525 inert(at, h.page(at),
1526 `A README holding &lt;script&gt;alert(&#34;knot&#34;)&lt;/script&gt; must show as text.`,
1527 `Also &lt;img src=x onerror=alert(1)&gt; in a comment.`)
1528}
1529
1530// A directory larger than a page reads is listed in part, and a commit
1531// message larger than a page reads ends its page of history early. git
1532// is stopped once its listing passes MaxRead, and nothing past a record's
1533// bound is kept.
1534func TestOversizedTreeAndHistory(t *testing.T) {
1535 h := newHarness(t)
1536 // Each entry of huge/ takes 308 bytes of git ls-tree's output, so
1537 // 15,000 of them pass MaxRead at about entry 13,600.
1538 longest := "!" + strings.Repeat("l", 4095)
1539 files := []file{{"100644", "huge/" + longest, "x\n"}}
1540 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
1541 for i := range 15_000 {
1542 files = append(files, file{"100644", "huge/" + name(i), "x\n"})
1543 }
1544 if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead {
1545 t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n)
1546 }
1547 h.commitMain("app: a directory larger than a page reads\n", files...)
1548 h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n")
1549 tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n")
1550 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1551
1552 at := "/tools/app/source/tree/" + tip + "/huge/"
1553 page := h.page(at)
1554 if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") {
1555 t.Error("huge/ is not marked as listed in part")
1556 }
1557 if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries {
1558 t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries)
1559 }
1560 if !strings.Contains(page, `">`+longest+`</a>`) {
1561 t.Error("the entry with the longest name git accepts is not listed whole")
1562 }
1563 if len(page) > 1<<20 {
1564 t.Errorf("huge/'s page is %d bytes", len(page))
1565 }
1566 if w := h.get("/tools/app/source/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK {
1567 t.Errorf("an entry read before MaxRead answered %d", w.Code)
1568 }
1569 if w := h.get("/tools/app/source/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound {
1570 t.Errorf("an entry past MaxRead answered %d", w.Code)
1571 }
1572
1573 at = "/tools/app/source/log/" + tip
1574 page = h.page(at)
1575 if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") {
1576 t.Error("the page of history holding a 5 MiB message does not end early")
1577 }
1578 if n := strings.Count(page, `<tr><td class="name">`); n != 1 {
1579 t.Errorf("the page that ends early lists %d commits, not the one it cut", n)
1580 }
1581 if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText {
1582 t.Error("the cut commit's subject is not shown cut to maxLogText")
1583 }
1584 older := at + "?from=" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~1")
1585 if !strings.Contains(page, `href="`+older+`"`) {
1586 t.Error("the page that ends early does not link the commits after the one it cut")
1587 }
1588 page = h.page(older)
1589 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
1590 t.Errorf("the next page of history is not whole:\n%s", page)
1591 }
1592 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
1593 t.Error("a subject longer than a page shows is not cut")
1594 }
1595 for _, p := range []string{at, older} {
1596 if n := len(h.page(p)); n > 64<<10 {
1597 t.Errorf("GET %s is %d bytes", p, n)
1598 }
1599 }
1600}
1601
1602// The directories along a path share one budget of MaxRead bytes of git
1603// ls-tree's output. Each of big/ and big/zz/ lists about 3 MB before
1604// the entry the path names next, within MaxRead alone, so the directory
1605// big/zz/ is served. A path through both, to big/zz/zz/f, passes the
1606// budget and answers 404. The directory's own listing has a budget of
1607// its own.
1608func TestResolveSharesOneBudget(t *testing.T) {
1609 h := newHarness(t)
1610 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
1611 var files []file
1612 for i := range 10_000 {
1613 files = append(files, file{"100644", "big/" + name(i), "x\n"}, file{"100644", "big/zz/" + name(i), "x\n"})
1614 }
1615 files = append(files, file{"100644", "big/zz/zz/f", "the file\n"})
1616 if each := 6 + 1 + 4 + 1 + 40 + 1 + 246 + 1; 10_000*each > MaxRead || 2*10_000*each <= MaxRead {
1617 t.Fatalf("the listings take %d bytes each, not between half MaxRead and MaxRead", 10_000*each)
1618 }
1619 tip, bundle := h.commitMain("app: two large directories, one in the other\n", files...)
1620 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1621
1622 h.page("/tools/app/source/tree/" + tip + "/big/zz/")
1623 h.page("/tools/app/source/blob/" + tip + "/big/zz/" + name(0))
1624 for _, target := range []string{"/tools/app/source/tree/" + tip + "/big/zz/zz/", "/tools/app/source/blob/" + tip + "/big/zz/zz/f"} {
1625 if w := h.get(target); w.Code != http.StatusNotFound {
1626 t.Errorf("GET %s, through %d bytes of listings, answered %d", target, 2*10_000*300, w.Code)
1627 }
1628 }
1629}
1630
1631// lines writes onto the fixture's app main a merge of n lines of
1632// history, each of length commits, all from main's tip. The lines' commits
1633// are dated in turn, one line's after another's, so a log interleaves
1634// them, and each page ends with commits of every line still to show. The
1635// merge is an octopus when n is more than two. It returns the merge and a
1636// bundle of it.
1637func (h *harness) lines(n, length int) (tip, bundle string) {
1638 var commits []commit
1639 for i := range length {
1640 for l := range n {
1641 c := commit{message: fmt.Sprintf("line %d, commit %d\n", l, i), parents: []int{0}}
1642 if i > 0 {
1643 c.parents = []int{(i-1)*n + l + 1}
1644 }
1645 commits = append(commits, c)
1646 }
1647 }
1648 merge := commit{message: fmt.Sprintf("merge %d lines\n", n)}
1649 for l := range n {
1650 merge.parents = append(merge.parents, (length-1)*n+l+1)
1651 }
1652 return h.history(append(commits, merge)...)
1653}
1654
1655// commit is one commit history writes. Its parents are the numbers of
1656// commits written before it, counted from 1, or 0 for main's tip.
1657type commit struct {
1658 message string
1659 parents []int
1660}
1661
1662// history writes commits onto the fixture's app main, in order, and
1663// moves main to the last. Each commit is dated a second after the one
1664// before it. It returns the last commit and a bundle of it.
1665func (h *harness) history(commits ...commit) (tip, bundle string) {
1666 t := h.t
1667 t.Helper()
1668 repo := h.f.Repos["app"]
1669 base := git(t, repo, nil, "rev-parse", export.MainRef)
1670 var b bytes.Buffer
1671 for i, c := range commits {
1672 who := fmt.Sprintf("Example Author <author@example.org> %d +0000", 1791190800+i)
1673 fmt.Fprintf(&b, "commit refs/heads/main\nmark :%d\nauthor %s\ncommitter %s\ndata %d\n%s\n", i+1, who, who, len(c.message), c.message)
1674 for j, p := range c.parents {
1675 parent := base
1676 if p > 0 {
1677 parent = fmt.Sprintf(":%d", p)
1678 }
1679 if j == 0 {
1680 fmt.Fprintf(&b, "from %s\n", parent)
1681 } else {
1682 fmt.Fprintf(&b, "merge %s\n", parent)
1683 }
1684 }
1685 }
1686 git(t, repo, b.Bytes(), "fast-import", "--quiet")
1687 tip = git(t, repo, nil, "rev-parse", export.MainRef)
1688 bundle = filepath.Join(t.TempDir(), "app.bundle")
1689 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
1690 return tip, bundle
1691}
1692
1693// logged is the commits a page of history lists, in order.
1694var logged = regexp.MustCompile(`<td class="name"><a href="/tools/app/source/tree/([0-9a-f]+)/">`)
1695
1696// continued is the links a page of history has to older pages: its Older
1697// link, and a link for each other line it leaves to show.
1698var continued = regexp.MustCompile(`href="(/tools/app/source/log/[0-9a-f]+\?from=[0-9a-f,]+)"`)
1699
1700// reach follows every link to older pages from the page at target, and
1701// from each page it reaches, and counts how many of those pages show each
1702// commit. It fails once it has read more than most pages.
1703func (h *harness) reach(target string, most int) map[string]int {
1704 h.t.Helper()
1705 seen, read := map[string]int{}, map[string]bool{target: true}
1706 for next := []string{target}; len(next) > 0; next = next[1:] {
1707 if len(read) > most {
1708 h.t.Fatalf("the links from %s reach more than %d pages", target, most)
1709 }
1710 page := h.page(next[0])
1711 for _, m := range logged.FindAllStringSubmatch(page, -1) {
1712 seen[m[1]]++
1713 }
1714 for _, m := range continued.FindAllStringSubmatch(page, -1) {
1715 if !read[m[1]] {
1716 read[m[1]] = true
1717 next = append(next, m[1])
1718 }
1719 }
1720 }
1721 return seen
1722}
1723
1724// A page of history links the older page as the commits it leaves to
1725// show next, so the history of a merge whose lines run past a page is
1726// shown whole: following the older links from the tip shows every commit
1727// main reaches, each once. A page past the first links the newest page. A
1728// ?from= that is not ascending, names a commit the page's commit does
1729// not reach, or names more than MaxFrontier commits answers 404.
1730func TestHistoryAcrossMerges(t *testing.T) {
1731 h := newHarness(t)
1732 tip, bundle := h.lines(2, 60)
1733 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1734
1735 at := "/tools/app/source/log/" + tip
1736 seen := map[string]int{}
1737 merged := false
1738 for target, pages := at, 0; target != ""; pages++ {
1739 if pages > 10 {
1740 t.Fatal("the older links do not end")
1741 }
1742 page := h.page(target)
1743 for _, m := range logged.FindAllStringSubmatch(page, -1) {
1744 seen[m[1]]++
1745 }
1746 if target != at && !strings.Contains(page, `href="`+at+`">Newest`) {
1747 t.Errorf("%s does not link the newest page", target)
1748 }
1749 target = ""
1750 if m := regexp.MustCompile(`href="(/tools/app/source/log/[0-9a-f]+\?from=([0-9a-f,]+))">Older`).FindStringSubmatch(page); m != nil {
1751 target, merged = m[1], merged || strings.Contains(m[2], ",")
1752 }
1753 }
1754 all := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip))
1755 if len(seen) != len(all) {
1756 t.Errorf("the older links show %d commits of the %d main reaches", len(seen), len(all))
1757 }
1758 for _, id := range all {
1759 if seen[id] != 1 {
1760 t.Errorf("the older links show %s %d times", id, seen[id])
1761 }
1762 }
1763 if !merged {
1764 t.Error("no page ends with both lines still to show")
1765 }
1766
1767 line := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", "--max-count=2", tip+"^2"))
1768 slices.Sort(line)
1769 for _, from := range []string{
1770 line[1] + "," + line[0], // not ascending
1771 line[0] + "," + line[0], // twice
1772 tip, // not reached from the page's commit
1773 strings.Repeat("1", 40), // no object
1774 strings.Repeat(line[0]+",", MaxFrontier) + line[1],
1775 line[0][:12],
1776 "",
1777 } {
1778 target := "/tools/app/source/log/" + line[1] + "?from=" + from
1779 if w := h.get(target); w.Code != http.StatusNotFound {
1780 t.Errorf("GET %s answered %d", target, w.Code)
1781 }
1782 }
1783 if w := h.get(at + "?from=" + line[0] + "&from=" + line[1]); w.Code != http.StatusNotFound {
1784 t.Errorf("two from parameters answered %d", w.Code)
1785 }
1786}
1787
1788// A page that leaves more than MaxFrontier commits to show starts its
1789// Older link from MaxFrontier of them, links the history from each of the
1790// rest, and says how many lines continue: here a merge of 65 lines, each
1791// still to show once the first page ends. Following those links from the
1792// tip reaches every commit main reaches.
1793func TestWideHistoryStaysReachable(t *testing.T) {
1794 h := newHarness(t)
1795 tip, bundle := h.lines(MaxFrontier+1, 2)
1796 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1797 at := "/tools/app/source/log/" + tip
1798 page := h.page(at)
1799 if n := len(logged.FindAllString(page, -1)); n != LogPage {
1800 t.Errorf("the page shows %d commits", n)
1801 }
1802 m := regexp.MustCompile(`href="` + at + `\?from=([0-9a-f,]+)">Older`).FindStringSubmatch(page)
1803 if m == nil || len(strings.Split(m[1], ",")) != MaxFrontier {
1804 t.Errorf("the page's Older link does not start from MaxFrontier commits: %q", m)
1805 }
1806 if n := len(continued.FindAllString(page, -1)); n != 2 {
1807 t.Errorf("the page links %d older pages, not the Older one and one more", n)
1808 }
1809 if !strings.Contains(page, "Older history continues along 65 lines at once, more than the Older link follows. Each link below follows one of the remaining lines.") {
1810 t.Error("the page does not say how many lines continue")
1811 }
1812
1813 seen := h.reach(at, 20)
1814 for _, id := range strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) {
1815 if seen[id] == 0 {
1816 t.Errorf("no link from the tip's history reaches %s", id)
1817 }
1818 }
1819}
1820
1821// A page ends before a merge that would leave more than MaxLeftToShow
1822// commits to show, and says so. Here the tip merges another merge and 99
1823// lines, and the other merge, shown next, merges 100 lines more: 199
1824// left to show. Following the links from the tip still reaches every
1825// commit main reaches.
1826func TestCrowdedHistoryEndsEarly(t *testing.T) {
1827 h := newHarness(t)
1828 var commits []commit
1829 inner := commit{message: "merge 100 lines\n"}
1830 outer := commit{message: "merge a merge and 99 lines\n", parents: []int{200}}
1831 for l := range 199 {
1832 commits = append(commits, commit{message: fmt.Sprintf("line %d\n", l), parents: []int{0}})
1833 if l < 100 {
1834 inner.parents = append(inner.parents, l+1)
1835 } else {
1836 outer.parents = append(outer.parents, l+1)
1837 }
1838 }
1839 tip, bundle := h.history(append(commits, inner, outer)...)
1840 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1841 at := "/tools/app/source/log/" + tip
1842 page := h.page(at)
1843 if shown := logged.FindAllStringSubmatch(page, -1); len(shown) != 1 || shown[0][1] != tip {
1844 t.Errorf("the page shows %d commits, not the tip alone", len(shown))
1845 }
1846 if !strings.Contains(page, "This page ends early, before a commit that would leave more lines of history than one page can link to.") {
1847 t.Error("the page does not say it ends early")
1848 }
1849 if n := len(continued.FindAllString(page, -1)); n != 1+100-MaxFrontier {
1850 t.Errorf("the page links %d older pages, not one for each of the 100 lines past MaxFrontier and the Older one", n)
1851 }
1852
1853 seen := h.reach(at, 200)
1854 for _, id := range strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) {
1855 if seen[id] == 0 {
1856 t.Errorf("no link from the tip's history reaches %s", id)
1857 }
1858 }
1859}
1860
1861// A merge whose line of parents is longer than a record of git log keeps
1862// is shown, as the first commit of a page and further down. Its subject is
1863// shown, with a note that older pages follow its first MaxParents
1864// parents. Each of those is shown or linked, and none of the others is
1865// linked.
1866func TestMergeOfManyParents(t *testing.T) {
1867 h := newHarness(t)
1868 const lines = 420
1869 var commits []commit
1870 merge := commit{message: "merge 420 lines\n"}
1871 for l := range lines {
1872 commits = append(commits, commit{message: fmt.Sprintf("line %d\n", l), parents: []int{0}})
1873 merge.parents = append(merge.parents, l+1)
1874 }
1875 commits = append(commits, merge)
1876 for i := range LogPage {
1877 commits = append(commits, commit{message: fmt.Sprintf("after the merge, commit %d\n", i), parents: []int{len(commits)}})
1878 }
1879 tip, bundle := h.history(commits...)
1880 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1881 repo := h.f.Repos["app"]
1882 w := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, LogPage))
1883 parents := strings.Fields(git(t, repo, nil, "log", "-1", "--format=%P", w))
1884 if len(parents) != lines || len(w)+1+len(parents)*(len(w)+1) <= maxLogRecord {
1885 t.Fatalf("the merge's ID and %d parents fit in one record of git log", len(parents))
1886 }
1887
1888 at := "/tools/app/source/log/" + tip
1889 older := at + "?from=" + w
1890 if !strings.Contains(h.page(at), `href="`+older+`">Older`) {
1891 t.Fatal("the tip's page does not end before the merge")
1892 }
1893 note := fmt.Sprintf("merge 420 lines<p class=\"notice\">This merge has more than %d parents. Older pages follow its first %d.</p>", MaxParents, MaxParents)
1894 child := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, LogPage-1))
1895 // Where each page shows the merge: first on the tip page's older
1896 // page and on the merge's own history, second on its child's.
1897 for target, want := range map[string]int{older: 0, "/tools/app/source/log/" + w: 0, "/tools/app/source/log/" + child: 1} {
1898 page := h.page(target)
1899 shown := map[string]bool{}
1900 var order []string
1901 for _, m := range logged.FindAllStringSubmatch(page, -1) {
1902 shown[m[1]] = true
1903 order = append(order, m[1])
1904 }
1905 if len(order) != LogPage || order[want] != w {
1906 t.Errorf("GET %s does not show the merge as commit %d of %d", target, want+1, LogPage)
1907 continue
1908 }
1909 if strings.Count(page, note) != 1 {
1910 t.Errorf("GET %s does not show the merge's subject and its note once", target)
1911 }
1912 linked := map[string]bool{}
1913 for _, m := range continued.FindAllStringSubmatch(page, -1) {
1914 _, from, _ := strings.Cut(m[1], "?from=")
1915 for _, id := range strings.Split(from, ",") {
1916 linked[id] = true
1917 }
1918 }
1919 for i, id := range parents {
1920 switch {
1921 case i < MaxParents && !shown[id] && !linked[id]:
1922 t.Errorf("GET %s neither shows nor links the merge's parent %d", target, i+1)
1923 case i >= MaxParents && linked[id]:
1924 t.Errorf("GET %s links the merge's parent %d", target, i+1)
1925 }
1926 }
1927 }
1928}
1929
1930// A source request's git commands have a bound of their own, far within
1931// the request's time: a git that does not finish is stopped once it
1932// passes, and the request answers 503 and gives back its git slot. The
1933// failure is logged.
1934func TestSourceGitHasItsOwnBound(t *testing.T) {
1935 h := newHarness(t)
1936 real, err := exec.LookPath(export.GitProgram)
1937 if err != nil {
1938 t.Fatal(err)
1939 }
1940 if real, err = filepath.Abs(real); err != nil {
1941 t.Fatal(err)
1942 }
1943 slow := filepath.Join(t.TempDir(), "git")
1944 script := "#!/bin/sh\nfor a; do [ \"$a\" = ls-tree ] && exec sleep 60; done\nexec '" + real + "' \"$@\"\n"
1945 if err := os.WriteFile(slow, []byte(script), 0o755); err != nil {
1946 t.Fatal(err)
1947 }
1948 program := export.GitProgram
1949 export.GitProgram = slow
1950 t.Cleanup(func() { export.GitProgram = program })
1951 var logged []error
1952 var mu sync.Mutex
1953 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
1954 h.srv.gitTime = 300 * time.Millisecond
1955
1956 start := time.Now()
1957 w := h.get("/tools/app/source/tree/" + h.tip() + "/")
1958 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
1959 t.Errorf("a source request whose git does not finish answered %d after %v", w.Code, took)
1960 }
1961 if len(h.srv.slots) != 0 {
1962 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
1963 }
1964 mu.Lock()
1965 defer mu.Unlock()
1966 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") {
1967 t.Errorf("the server logged %v", logged)
1968 }
1969 if w := h.get("/tools/app/knots/oc-a000002"); w.Code != http.StatusOK {
1970 t.Errorf("a knot answered %d", w.Code)
1971 }
1972}
1973
1974// A source request's bound on its git slot runs from when it takes the
1975// slot, and covers its wait for its generation's export to be read. A
1976// source request whose export is read slowly answers 503 once the bound
1977// passes, gives back its slot, and is logged, while a request for the
1978// plan, which holds no slot, waits on for the same read and is served.
1979func TestGitSlotBoundCoversTheLoad(t *testing.T) {
1980 h := newHarness(t)
1981 var mu sync.Mutex
1982 var logged []error
1983 h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() }
1984 h.srv.gitTime = 300 * time.Millisecond
1985 hold := make(chan struct{})
1986 h.srv.loading = func(export.Generation) { <-hold }
1987
1988 plan := make(chan *httptest.ResponseRecorder, 1)
1989 go func() {
1990 w := httptest.NewRecorder()
1991 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/-/knots", nil))
1992 plan <- w
1993 }()
1994 eventually(t, "the plan waits for the export to be read", func() bool { return len(h.srv.loaders) == 1 })
1995 start := time.Now()
1996 w := h.get("/tools/app/source/tree/" + h.tip() + "/")
1997 if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second {
1998 t.Errorf("a source request whose export is read slowly answered %d after %v", w.Code, took)
1999 }
2000 if len(h.srv.slots) != 0 {
2001 t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots))
2002 }
2003 mu.Lock()
2004 if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") ||
2005 !strings.Contains(logged[0].Error(), "export to be read") {
2006 t.Errorf("the server logged %v", logged)
2007 }
2008 mu.Unlock()
2009
2010 close(hold)
2011 select {
2012 case w := <-plan:
2013 if w.Code != http.StatusOK {
2014 t.Errorf("the plan answered %d once its export was read", w.Code)
2015 }
2016 case <-time.After(10 * time.Second):
2017 t.Fatal("the plan was not served once its export was read")
2018 }
2019 h.page("/tools/app/source/tree/" + h.tip() + "/")
2020}
2021
2022// A source request gives back its git slot before it renders its page, so
2023// a page that renders slowly holds no slot, and is not held to the bound
2024// on holding one. While one renders, past that bound, another source
2025// request is served, and the first is served in full once it renders.
2026func TestRenderingHoldsNoGitSlot(t *testing.T) {
2027 h := newHarness(t)
2028 h.page("/-/knots")
2029 h.srv.gitTime = 300 * time.Millisecond
2030 rendering, hold := make(chan struct{}), make(chan struct{})
2031 var first atomic.Bool
2032 h.srv.rendering = func(name string) {
2033 if name == "tree" && first.CompareAndSwap(false, true) {
2034 close(rendering)
2035 <-hold
2036 }
2037 }
2038
2039 served := make(chan *httptest.ResponseRecorder, 1)
2040 go func() {
2041 w := httptest.NewRecorder()
2042 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/source/tree/"+h.tip()+"/", nil))
2043 served <- w
2044 }()
2045 select {
2046 case <-rendering:
2047 case <-time.After(10 * time.Second):
2048 t.Fatal("the source request did not render")
2049 }
2050 if len(h.srv.slots) != 0 {
2051 t.Errorf("a source request holds %d git slots while it renders", len(h.srv.slots))
2052 }
2053 h.page("/tools/app/source/blob/" + h.tip() + "/docs/guide.md")
2054 time.Sleep(2 * h.srv.gitTime)
2055 close(hold)
2056 select {
2057 case w := <-served:
2058 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "guide.md") {
2059 t.Errorf("a source request that rendered past the bound on its slot answered %d", w.Code)
2060 }
2061 case <-time.After(10 * time.Second):
2062 t.Fatal("the source request was not served once it rendered")
2063 }
2064}
2065
2066// A SHA-256 project's commits are served by their 64 hex digits alone.
2067// The first 40 of them, which git would read as an abbreviation, answer
2068// 404 on every source route, so each page has one address.
2069func TestSHA256CommitIDs(t *testing.T) {
2070 h := newHarness(t)
2071 repo := filepath.Join(t.TempDir(), "app.git")
2072 git(t, repo, nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", "--object-format=sha256")
2073 readme := "# app\n\nA SHA-256 repository.\n"
2074 who := "Example Author <author@example.org> 1791190800 +0000"
2075 stream := fmt.Sprintf("commit refs/heads/main\nauthor %s\ncommitter %s\ndata 7\nsha256\n\nM 100644 inline README.md\ndata %d\n%s\n",
2076 who, who, len(readme), readme)
2077 git(t, repo, []byte(stream), "fast-import", "--quiet")
2078 tip := git(t, repo, nil, "rev-parse", export.MainRef)
2079 if len(tip) != 64 {
2080 t.Fatalf("the tip is %q", tip)
2081 }
2082 bundle := filepath.Join(t.TempDir(), "app.bundle")
2083 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
2084 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
2085
2086 for _, route := range []string{"/tools/app/source/tree/%s/", "/tools/app/source/blob/%s/README.md", "/tools/app/source/log/%s"} {
2087 if page := h.page(fmt.Sprintf(route, tip)); !strings.Contains(page, tip[:12]) {
2088 t.Errorf("%s does not name the commit", fmt.Sprintf(route, tip))
2089 }
2090 if w := h.get(fmt.Sprintf(route, tip[:40])); w.Code != http.StatusNotFound {
2091 t.Errorf("%s answered %d", fmt.Sprintf(route, tip[:40]), w.Code)
2092 }
2093 }
2094 if w := h.get("/tools/app/source/"); w.Header().Get("Location") != "/tools/app/source/tree/"+tip+"/" {
2095 t.Errorf("/tools/app/source/ redirects to %q", w.Header().Get("Location"))
2096 }
2097 w := h.get("/tools/app/source/archive/" + tip + ".tar.gz")
2098 if w.Code != http.StatusOK || !strings.Contains(w.Header().Get("Content-Disposition"), `"app-`+tip[:12]+`.tar.gz"`) {
2099 t.Errorf("the archive answered %d, %q", w.Code, w.Header().Get("Content-Disposition"))
2100 }
2101 if _, ok := archiveEntries(t, w.Body.Bytes())["app-"+tip[:12]+"/README.md"]; !ok {
2102 t.Error("the archive does not hold README.md under its directory")
2103 }
2104 if w := h.get("/tools/app/source/archive/" + tip[:40] + ".tar.gz"); w.Code != http.StatusNotFound {
2105 t.Errorf("the archive of the tip's first 40 hex digits answered %d", w.Code)
2106 }
2107}
2108
2109// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
2110// and its page says where it stops. A README longer than a page shows is
2111// shown in part.
2112func TestLongFileIsShownInPart(t *testing.T) {
2113 h := newHarness(t)
2114 tip, bundle := h.commitMain("app: long files\n",
2115 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
2116 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
2117 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
2118 )
2119 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
2120
2121 page := h.page("/tools/app/source/blob/" + tip + "/newlines.txt")
2122 last := fmt.Sprintf(`id="L%d"`, MaxLines)
2123 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
2124 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
2125 }
2126 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
2127 t.Errorf("the page does not say %q", want)
2128 }
2129 if len(page) > MaxShown {
2130 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
2131 }
2132
2133 // One line of MaxFile characters that each escape to four bytes is
2134 // cut where MaxShown is reached.
2135 page = h.page("/tools/app/source/blob/" + tip + "/wide.txt")
2136 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
2137 t.Errorf("the page of one wide line is %d bytes", len(page))
2138 }
2139
2140 page = h.page("/tools/app/source/tree/" + tip + "/long/")
2141 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
2142 t.Error("the long README is not marked as shown in part")
2143 }
2144 if n := strings.Count(page, "a line of the README"); n != MaxLines {
2145 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
2146 }
2147}
2148
2149// A chain of knots as deep as the graph's knot limit allows renders its
2150// milestone to MaxPlanDepth levels, counts every knot under it, and
2151// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
2152// structure is built once for the generation. Siblings that block one
2153// another in a cycle share the last stage of their path.
2154func TestDeepPlan(t *testing.T) {
2155 h := newHarness(t)
2156 var chain []string
2157 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
2158 p := &e.Projects[0]
2159 for i := range knot.MaxKnots - len(p.Knots) - 3 {
2160 id := fmt.Sprintf("oc-c%06x", i)
2161 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
2162 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
2163 if i == 0 {
2164 p.Roots = append(p.Roots, id)
2165 } else {
2166 k.Parent = chain[i-1]
2167 p.Knots[len(p.Knots)-1].Children = []string{id}
2168 }
2169 chain = append(chain, id)
2170 p.Knots = append(p.Knots, k)
2171 }
2172 // Under the first link, a path whose two last siblings wait on
2173 // each other.
2174 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
2175 for _, k := range []export.Knot{
2176 {ID: free, BlockedBy: []string{}},
2177 {ID: a, BlockedBy: []string{free, b}},
2178 {ID: b, BlockedBy: []string{a}},
2179 } {
2180 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
2181 p.Knots = append(p.Knots, k)
2182 }
2183 for i := range p.Knots {
2184 if p.Knots[i].ID == chain[0] {
2185 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
2186 }
2187 }
2188 })
2189
2190 page := h.page("/-/knots")
2191 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
2192 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
2193 }
2194 if !strings.Contains(page, `href="/tools/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/tools/app/knots/`+chain[MaxPlanDepth+1]+`"`) {
2195 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
2196 }
2197 if n := strings.Count(page, ">more on its page<"); n != 1 {
2198 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
2199 }
2200 if len(page) > 256<<10 {
2201 t.Errorf("the plan page is %d bytes", len(page))
2202 }
2203 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
2204 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
2205 var stages []string
2206 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
2207 if strings.Contains(m[2], "Sibling") {
2208 var ids []string
2209 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
2210 ids = append(ids, id[1])
2211 }
2212 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
2213 }
2214 }
2215 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
2216 t.Errorf("the siblings' path has stages %q", got)
2217 }
2218
2219 h.srv.mu.Lock()
2220 plan := h.srv.cached.idx.plan
2221 h.srv.mu.Unlock()
2222 h.page("/-/knots")
2223 h.srv.mu.Lock()
2224 again := h.srv.cached.idx.plan
2225 h.srv.mu.Unlock()
2226 if plan != again {
2227 t.Error("the plan page's structure was built again for the same generation")
2228 }
2229
2230 deepest := chain[len(chain)-1]
2231 page = h.page("/tools/app/knots/" + deepest)
2232 trail := section(t, page, `<nav class="trail"`, `</nav>`)
2233 if n := strings.Count(trail, `<a href="/tools/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
2234 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
2235 }
2236 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/tools/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
2237 t.Error("the trail does not name the nearest parents alone")
2238 }
2239}
2240
2241// Every response carries the strict policy, and the policy admits the
2242// page's one inline stylesheet and one inline script by their hashes and
2243// nothing from another origin.
2244func TestEveryResponseCarriesTheCSP(t *testing.T) {
2245 h := newHarness(t)
2246 for _, c := range []struct{ method, target string }{
2247 {"GET", "/"},
2248 {"GET", "/-/knots"},
2249 {"GET", "/tools/app/knots/oc-a000002"},
2250 {"GET", "/tools/app/source/"},
2251 {"GET", "/tools/app/source/tree/" + h.tip() + "/"},
2252 {"GET", "/tools/app/source/blob/" + h.tip() + "/README.md"},
2253 {"GET", "/no/such/page"},
2254 {"POST", "/"},
2255 {"HEAD", "/"},
2256 {"HEAD", "/-/knots"},
2257 } {
2258 w := h.do(c.method, c.target)
2259 got := w.Header().Get("Content-Security-Policy")
2260 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
2261 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
2262 }
2263 }
2264 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
2265 if !strings.Contains(csp, directive) {
2266 t.Errorf("the policy lacks %s", directive)
2267 }
2268 }
2269 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
2270 if strings.Contains(csp, loose) {
2271 t.Errorf("the policy holds %q", loose)
2272 }
2273 }
2274
2275 page := h.page("/-/knots")
2276 inline := func(tag string) string {
2277 t.Helper()
2278 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
2279 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
2280 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
2281 }
2282 sum := sha256.Sum256([]byte(m[0][1]))
2283 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
2284 }
2285 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
2286 t.Errorf("the policy does not admit the page's script, %s", hash)
2287 }
2288 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
2289 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
2290 }
2291 for _, external := range []string{"<link", " src=", "@import", "url("} {
2292 if strings.Contains(page, external) {
2293 t.Errorf("the plan page holds %q", external)
2294 }
2295 }
2296}
2297
2298// A request serves everything from the generation it opened, though
2299// another activates while it runs, and that generation outlives the
2300// activation until the request releases it.
2301func TestARequestKeepsItsGeneration(t *testing.T) {
2302 h := newHarness(t)
2303 paused, resume := make(chan export.Generation), make(chan struct{})
2304 var once sync.Once
2305 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
2306 served := make(chan *httptest.ResponseRecorder)
2307 go func() {
2308 w := httptest.NewRecorder()
2309 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000001", nil))
2310 served <- w
2311 }()
2312 old := <-paused
2313
2314 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
2315 if next.Sequence == old.Sequence {
2316 t.Fatal("the publish did not activate a new generation")
2317 }
2318 if _, err := os.Stat(old.Dir); err != nil {
2319 t.Fatalf("the generation a request holds was deleted: %v", err)
2320 }
2321 close(resume)
2322 w := <-served
2323 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
2324 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
2325 }
2326 if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the second plan") {
2327 t.Error("the next request does not serve the new generation")
2328 }
2329
2330 // Released, the old generation goes with the next activation.
2331 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
2332 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2333 t.Errorf("the released generation is still on disk: %v", err)
2334 }
2335}
2336
2337// eventually waits up to ten seconds for cond to hold.
2338func eventually(t *testing.T, what string, cond func() bool) {
2339 t.Helper()
2340 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
2341 if time.Now().After(deadline) {
2342 t.Fatalf("timed out waiting until %s", what)
2343 }
2344 }
2345}
2346
2347// renamed changes the title of the fixture's first knot.
2348func renamed(title string) func(*export.Export) {
2349 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
2350}
2351
2352// Requests that wait for a generation together read its export once.
2353// While it is read, a newer generation is read on its own, and at most
2354// MaxLoads exports are read at once. A request whose load ends after a
2355// newer generation was activated waits for that one, so every request is
2356// served the generation active when its snapshot is ready, and an older
2357// read that finishes last does not displace the newest snapshot.
2358func TestExportLoadsCoalesce(t *testing.T) {
2359 h := newHarness(t)
2360 var mu sync.Mutex
2361 loads := map[int64]int{}
2362 holds := map[int64]chan struct{}{}
2363 hold := func(g export.Generation) chan struct{} {
2364 mu.Lock()
2365 defer mu.Unlock()
2366 if holds[g.Sequence] == nil {
2367 holds[g.Sequence] = make(chan struct{})
2368 }
2369 return holds[g.Sequence]
2370 }
2371 h.srv.loading = func(g export.Generation) {
2372 mu.Lock()
2373 loads[g.Sequence]++
2374 mu.Unlock()
2375 <-hold(g)
2376 }
2377 loaded := func(g export.Generation) int {
2378 mu.Lock()
2379 defer mu.Unlock()
2380 return loads[g.Sequence]
2381 }
2382 var opens atomic.Int32
2383 h.srv.opened = func(export.Generation) { opens.Add(1) }
2384 get := func(n int) chan *httptest.ResponseRecorder {
2385 served := make(chan *httptest.ResponseRecorder, n)
2386 for range n {
2387 go func() {
2388 w := httptest.NewRecorder()
2389 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000001", nil))
2390 served <- w
2391 }()
2392 }
2393 return served
2394 }
2395 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
2396 t.Helper()
2397 for range n {
2398 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
2399 t.Errorf("a request answered %d, not with %q", w.Code, title)
2400 }
2401 }
2402 }
2403 waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } }
2404
2405 first := h.active()
2406 firstServed := get(10)
2407 eventually(t, "ten requests wait for the first generation's read", func() bool {
2408 return loaded(first) == 1 && len(h.srv.loadWaiting) == 10
2409 })
2410 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
2411 secondServed := get(1)
2412 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
2413
2414 // Both loaders are taken, so the third generation waits for one.
2415 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
2416 thirdServed := get(1)
2417 eventually(t, "a request waits for the third generation", waiting(12))
2418 time.Sleep(20 * time.Millisecond)
2419 if n := loaded(third); n != 0 {
2420 t.Errorf("a third export was read while %d were", MaxLoads)
2421 }
2422 if n := opens.Load(); n != 0 {
2423 t.Errorf("%d requests opened a generation while they waited for its read", n)
2424 }
2425
2426 // The second read ends, and its request finds the third generation
2427 // active, and waits for that read with the third's request.
2428 close(hold(second))
2429 eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 })
2430 close(hold(third))
2431 expect(secondServed, 1, "Readers browse the third plan")
2432 expect(thirdServed, 1, "Readers browse the third plan")
2433 close(hold(first))
2434 expect(firstServed, 10, "Readers browse the third plan")
2435
2436 if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the third plan") {
2437 t.Error("the first generation's read displaced the third's")
2438 }
2439 for _, g := range []export.Generation{first, second, third} {
2440 if n := loaded(g); n != 1 {
2441 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
2442 }
2443 }
2444}
2445
2446// Source requests past MaxGit wait, MaxWaiting of them, and one more
2447// answers 503 at once. A waiting request holds no generation, so an
2448// activation while the server is saturated deletes the old generation,
2449// and every waiting request serves the new one. A request's time runs
2450// from its arrival, so one that waits past it answers 503.
2451func TestSourceAdmission(t *testing.T) {
2452 h := newHarness(t)
2453 // The requests that hold the slots wait for the test, not for git, so
2454 // the bound on holding a slot is no part of this test.
2455 h.srv.gitTime = time.Hour
2456 var admitted atomic.Int32
2457 release := make(chan struct{})
2458 h.srv.admitted = func() {
2459 admitted.Add(1)
2460 <-release
2461 }
2462 target := "/tools/app/source/tree/" + h.tip() + "/"
2463 get := func(n int) chan *httptest.ResponseRecorder {
2464 served := make(chan *httptest.ResponseRecorder, n)
2465 for range n {
2466 go func() {
2467 w := httptest.NewRecorder()
2468 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
2469 served <- w
2470 }()
2471 }
2472 return served
2473 }
2474
2475 old := h.active()
2476 served := get(MaxGit + MaxWaiting)
2477 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
2478 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
2479 })
2480 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2481 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
2482 }
2483 // A path through a group's alias or a project's former name that has
2484 // a source route's shape is admitted as one before the export is read,
2485 // so it answers 503 too. A project's short alias makes no such shape,
2486 // and redirects still.
2487 for _, alias := range []string{"/t/app/source/tree/" + h.tip() + "/", "/tools/old-app/source/tree/" + h.tip() + "/"} {
2488 if w := h.get(alias); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2489 t.Errorf("GET %s past MaxWaiting answered %d, Retry-After %q", alias, w.Code, w.Header().Get("Retry-After"))
2490 }
2491 }
2492 if w := h.get("/app/source/tree/" + h.tip() + "/"); w.Code != http.StatusPermanentRedirect {
2493 t.Errorf("a project's short alias answered %d while the server is saturated", w.Code)
2494 }
2495 h.page("/-/knots") // a page that runs no git is served still
2496
2497 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
2498 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
2499 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2500 t.Errorf("a generation no request had opened outlived the activation: %v", err)
2501 }
2502 close(release)
2503 for range MaxGit + MaxWaiting {
2504 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/tools/app/source/tree/"+tip+"/") {
2505 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
2506 }
2507 }
2508 // Once a slot is free, the alias's path redirects, and gives the slot
2509 // back.
2510 if w := h.get("/t/app/source/tree/" + tip + "/"); w.Code != http.StatusPermanentRedirect {
2511 t.Errorf("a group's alias answered %d once the server had a slot free", w.Code)
2512 }
2513 if len(h.srv.slots) != 0 {
2514 t.Errorf("a redirect kept %d git slots", len(h.srv.slots))
2515 }
2516
2517 // A request that waits past its time answers 503. Those that held
2518 // the slots meanwhile ran out of time too.
2519 h.srv.timeout = 200 * time.Millisecond
2520 h.srv.log = func(error) {}
2521 admitted.Store(0)
2522 release = make(chan struct{})
2523 held := get(MaxGit)
2524 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
2525 start := time.Now()
2526 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
2527 t.Errorf("a request that waited past its time answered %d", w.Code)
2528 }
2529 if waited := time.Since(start); waited > 5*time.Second {
2530 t.Errorf("a request waited %v past its time of 200ms", waited)
2531 }
2532 close(release)
2533 for range MaxGit {
2534 if w := <-held; w.Code != http.StatusServiceUnavailable {
2535 t.Errorf("a request that ran out of time answered %d", w.Code)
2536 }
2537 }
2538}
2539
2540// stallingListener accepts connections whose writes stall until release
2541// is closed, while stall is set. Each sends on stalled the first time one
2542// of its writes stalls.
2543type stallingListener struct {
2544 net.Listener
2545 stall atomic.Bool
2546 release chan struct{}
2547 stalled chan struct{}
2548}
2549
2550func (l *stallingListener) Accept() (net.Conn, error) {
2551 c, err := l.Listener.Accept()
2552 if err != nil || !l.stall.Load() {
2553 return c, err
2554 }
2555 return &stallingConn{Conn: c, l: l}, nil
2556}
2557
2558type stallingConn struct {
2559 net.Conn
2560 l *stallingListener
2561 once sync.Once
2562}
2563
2564func (c *stallingConn) Write(p []byte) (int, error) {
2565 c.once.Do(func() { c.l.stalled <- struct{}{} })
2566 <-c.l.release
2567 return c.Conn.Write(p)
2568}
2569
2570// Readers that never read their responses hold no git slot and no
2571// generation: more of them than MaxGit and MaxWaiting together are
2572// stalled writing, and a new reader is still served, and an activation
2573// deletes the generation they were served from.
2574func TestSlowReadersHoldNothing(t *testing.T) {
2575 h := newHarness(t)
2576 ln, err := net.Listen("tcp", "127.0.0.1:0")
2577 if err != nil {
2578 t.Fatal(err)
2579 }
2580 n := MaxGit + MaxWaiting + 4
2581 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
2582 sl.stall.Store(true)
2583 srv := &http.Server{Handler: h.srv}
2584 go srv.Serve(sl)
2585 var conns []net.Conn
2586 defer func() {
2587 close(sl.release)
2588 for _, c := range conns {
2589 c.Close()
2590 }
2591 srv.Close()
2592 }()
2593
2594 old := h.active()
2595 target := "/tools/app/source/blob/" + h.tip() + "/docs/guide.md"
2596 for range n {
2597 c, err := net.Dial("tcp", ln.Addr().String())
2598 if err != nil {
2599 t.Fatal(err)
2600 }
2601 conns = append(conns, c)
2602 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
2603 }
2604 for i := range n {
2605 select {
2606 case <-sl.stalled:
2607 case <-time.After(10 * time.Second):
2608 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
2609 }
2610 }
2611 sl.stall.Store(false)
2612 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
2613 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
2614 }
2615
2616 client := &http.Client{Timeout: 10 * time.Second}
2617 resp, err := client.Get("http://" + ln.Addr().String() + target)
2618 if err != nil {
2619 t.Fatal(err)
2620 }
2621 resp.Body.Close()
2622 if resp.StatusCode != http.StatusOK {
2623 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
2624 }
2625 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
2626 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
2627 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
2628 }
2629}
2630
2631// Before the first activation the server says nothing is published, and
2632// it answers GET and HEAD alone.
2633func TestNothingPublishedAndMethods(t *testing.T) {
2634 store, err := export.OpenStore(exporttest.StorePath(t), nil)
2635 if err != nil {
2636 t.Fatal(err)
2637 }
2638 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
2639 w := httptest.NewRecorder()
2640 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
2641 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
2642 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
2643 }
2644
2645 h := newHarness(t)
2646 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
2647 w := h.do(method, "/")
2648 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
2649 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
2650 }
2651 }
2652}
2653
2654// tooLarge checks that GET target answers with the one short page that
2655// says a page is too large.
2656func (h *harness) tooLarge(target string) {
2657 h.t.Helper()
2658 w := h.get(target)
2659 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
2660 h.t.Errorf("GET %s answered %d with %d bytes, not the page that says it is too large", target, w.Code, w.Body.Len())
2661 }
2662 if n, _ := h.srv.holding(); n != 0 {
2663 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
2664 }
2665}
2666
2667// A response's body is at most MaxResponse bytes. A page that would pass
2668// the bound answers with the one short page that says it is too large,
2669// and the failure is logged: a knot whose body passes MaxResponse, and,
2670// under a smaller bound, a file, a directory, a page of history and the
2671// plan page. A page within the bound is served on each route.
2672func TestPageTooLarge(t *testing.T) {
2673 h := newHarness(t)
2674 var logged []string
2675 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
2676 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
2677 for i := range 32 {
2678 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
2679 }
2680 h.commitMain("app: a wide file and a wide directory\n", files...)
2681 var tip, bundle string
2682 for i := range 8 {
2683 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
2684 }
2685 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
2686 p := &e.Projects[0]
2687 p.SourceTip = tip
2688 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
2689 for i := range 100 {
2690 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
2691 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
2692 }
2693 })
2694
2695 h.tooLarge("/tools/app/knots/" + h.f.Export.Projects[0].Knots[0].ID)
2696 h.page("/tools/app/knots/oc-a000002")
2697
2698 h.srv.maxResponse = 32 << 10
2699 at := "/tools/app/source/blob/" + tip + "/"
2700 h.tooLarge(at + "wide.txt")
2701 h.page(at + "docs/guide.md")
2702 at = "/tools/app/source/tree/" + tip + "/"
2703 h.tooLarge(at + "wide/")
2704 h.page(at + "docs/")
2705 h.tooLarge("/tools/app/source/log/" + tip)
2706 h.page("/tools/app/source/log/" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~8"))
2707 h.tooLarge("/-/knots")
2708
2709 if len(logged) != 5 {
2710 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
2711 }
2712 for _, l := range logged {
2713 if !strings.Contains(l, "larger than") {
2714 t.Errorf("the server logged %q", l)
2715 }
2716 }
2717 if len(tooLargePage) > 16<<10 {
2718 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
2719 }
2720}
2721
2722// holding is how many pieces of the budget responses hold, and how many
2723// of those the large budget counts.
2724func (s *Server) holding() (held, large int) {
2725 s.pieces.Lock()
2726 defer s.pieces.Unlock()
2727 return s.held, s.large
2728}
2729
2730// Rendered responses share a budget of MaxBuffered bytes, which each
2731// holds from when it starts rendering until it is written. Responses
2732// larger than SmallPage hold at most MaxLarge of it between them, their
2733// first SmallPage bytes counted. Readers that never read large pages ask
2734// for more than the whole budget, in pages of three sizes: one piece past
2735// SmallPage, 1 MiB, and 4 MiB. Without the first SmallPage bytes counted,
2736// 64 readers of the 1 MiB page would hold all of the budget. Once the
2737// readers' pages hold what fits in MaxLarge, a large page answers 503 at
2738// once, while small pages still render: the plan, a knot and a
2739// directory. The server's heap grows by no more than the budget, and the
2740// budget is whole again once the readers read.
2741func TestSlowReadersShareTheBudget(t *testing.T) {
2742 for _, pieces := range []int{smallPieces + 1, 16, 64} {
2743 t.Run(fmt.Sprintf("%d pieces", pieces), func(t *testing.T) { slowReadersOfPages(t, pieces) })
2744 }
2745}
2746
2747// slowReadersOfPages runs TestSlowReadersShareTheBudget with large pages
2748// of the number of pieces given.
2749func slowReadersOfPages(t *testing.T, pieces int) {
2750 h := newHarness(t)
2751 target := "/tools/app/knots/" + h.f.Export.Projects[0].Knots[0].ID
2752 body := func(at time.Duration, text string) {
2753 h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text })
2754 }
2755 body(time.Minute, "x")
2756 rest := len(h.page(target)) - 1
2757 body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22))
2758 size := len(h.page(target))
2759 if got := (size + pieceSize - 1) / pieceSize; got != pieces {
2760 t.Fatalf("the large page takes %d pieces, not %d", got, pieces)
2761 }
2762 fit := largePieces / pieces
2763 n := MaxBuffered/size + 2
2764
2765 ln, err := net.Listen("tcp", "127.0.0.1:0")
2766 if err != nil {
2767 t.Fatal(err)
2768 }
2769 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
2770 sl.stall.Store(true)
2771 srv := &http.Server{Handler: h.srv}
2772 go srv.Serve(sl)
2773 var conns []net.Conn
2774 released := false
2775 defer func() {
2776 if !released {
2777 close(sl.release)
2778 }
2779 for _, c := range conns {
2780 c.Close()
2781 }
2782 srv.Close()
2783 }()
2784
2785 var before runtime.MemStats
2786 runtime.GC()
2787 runtime.ReadMemStats(&before)
2788 // One reader at a time, each stalled before the next asks, so the
2789 // readers that fill the budget are the first fit of them.
2790 for i := range n {
2791 c, err := net.Dial("tcp", ln.Addr().String())
2792 if err != nil {
2793 t.Fatal(err)
2794 }
2795 conns = append(conns, c)
2796 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
2797 select {
2798 case <-sl.stalled:
2799 case <-time.After(10 * time.Second):
2800 t.Fatalf("reader %d of %d was not answered", i+1, n)
2801 }
2802 }
2803 sl.stall.Store(false)
2804 var after runtime.MemStats
2805 runtime.GC()
2806 runtime.ReadMemStats(&after)
2807 if held, large := h.srv.holding(); held != fit*pieces || large != fit*pieces {
2808 t.Errorf("slow readers hold %d pieces, %d of them counted as large; %d pages of %d pieces fit", held, large, fit, pieces)
2809 }
2810 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
2811 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
2812 }
2813
2814 client := &http.Client{Timeout: 10 * time.Second}
2815 get := func(target string) (int, string) {
2816 t.Helper()
2817 resp, err := client.Get("http://" + ln.Addr().String() + target)
2818 if err != nil {
2819 t.Fatal(err)
2820 }
2821 defer resp.Body.Close()
2822 io.Copy(io.Discard, resp.Body)
2823 return resp.StatusCode, resp.Header.Get("Retry-After")
2824 }
2825 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
2826 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
2827 }
2828 for _, small := range []string{"/", "/tools/app/knots/oc-a000002", "/tools/app/source/tree/" + h.tip() + "/"} {
2829 if code, _ := get(small); code != http.StatusOK {
2830 t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code)
2831 }
2832 }
2833
2834 close(sl.release)
2835 released = true
2836 codes := map[int]int{}
2837 for _, c := range conns {
2838 c.SetReadDeadline(time.Now().Add(10 * time.Second))
2839 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
2840 if err != nil {
2841 t.Fatal(err)
2842 }
2843 read, err := io.Copy(io.Discard, resp.Body)
2844 resp.Body.Close()
2845 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
2846 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
2847 }
2848 codes[resp.StatusCode]++
2849 }
2850 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
2851 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
2852 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
2853 }
2854 eventually(t, "the budget is whole again", func() bool { held, _ := h.srv.holding(); return held == 0 })
2855}
2856
2857// A load starts only once a request that waits for it takes a loader
2858// slot. While MaxLoads loads run, a request for a newer generation waits
2859// for a slot, holding no generation, until its time runs out, whatever
2860// its route, or its reader goes away. Neither leaves a load behind.
2861func TestExportLoadWaitsEnd(t *testing.T) {
2862 h := newHarness(t)
2863 var mu sync.Mutex
2864 var logged []string
2865 h.srv.log = func(err error) {
2866 mu.Lock()
2867 defer mu.Unlock()
2868 logged = append(logged, err.Error())
2869 }
2870 loads := map[int64]int{}
2871 hold := make(chan struct{})
2872 h.srv.loading = func(g export.Generation) {
2873 mu.Lock()
2874 loads[g.Sequence]++
2875 mu.Unlock()
2876 <-hold
2877 }
2878 loaded := func(g export.Generation) int {
2879 mu.Lock()
2880 defer mu.Unlock()
2881 return loads[g.Sequence]
2882 }
2883 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
2884 served := make(chan *httptest.ResponseRecorder, 1)
2885 go func() {
2886 w := httptest.NewRecorder()
2887 h.srv.ServeHTTP(w, r)
2888 served <- w
2889 }()
2890 return served
2891 }
2892 expect := func(served chan *httptest.ResponseRecorder, title string) {
2893 t.Helper()
2894 select {
2895 case w := <-served:
2896 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
2897 t.Errorf("a request answered %d, not with %q", w.Code, title)
2898 }
2899 case <-time.After(10 * time.Second):
2900 t.Fatalf("a request was not answered with %q", title)
2901 }
2902 }
2903
2904 first := h.active()
2905 firstServed := serve(httptest.NewRequest("GET", "/-/knots", nil))
2906 eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 })
2907 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
2908 secondServed := serve(httptest.NewRequest("GET", "/-/knots", nil))
2909 eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 })
2910
2911 // A request that runs no git runs out of time waiting, and answers
2912 // 503.
2913 h.srv.timeout = 200 * time.Millisecond
2914 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
2915 select {
2916 case w := <-serve(httptest.NewRequest("GET", "/tools/app/knots/oc-a000001", nil)):
2917 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
2918 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
2919 }
2920 case <-time.After(10 * time.Second):
2921 t.Fatal("a request waits for a read past its time of 200ms")
2922 }
2923
2924 // A request whose reader goes away stops waiting, and answers
2925 // nothing.
2926 h.srv.timeout = time.Hour
2927 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
2928 ctx, cancel := context.WithCancel(context.Background())
2929 defer cancel()
2930 gone := serve(httptest.NewRequest("GET", "/-/knots", nil).WithContext(ctx))
2931 eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 })
2932 cancel()
2933 select {
2934 case w := <-gone:
2935 if w.Body.Len() != 0 {
2936 t.Errorf("a request whose reader went away answered %d", w.Code)
2937 }
2938 case <-time.After(10 * time.Second):
2939 t.Fatal("a request whose reader went away still waits")
2940 }
2941
2942 h.srv.mu.Lock()
2943 left := len(h.srv.loads)
2944 h.srv.mu.Unlock()
2945 if left != MaxLoads {
2946 t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads)
2947 }
2948 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
2949 for _, g := range []export.Generation{third, fourth} {
2950 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
2951 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
2952 }
2953 }
2954
2955 // The first two reads end, and their requests are served the newest
2956 // generation.
2957 close(hold)
2958 expect(firstServed, "Readers browse the fifth plan")
2959 expect(secondServed, "Readers browse the fifth plan")
2960 for _, g := range []export.Generation{third, fourth} {
2961 if n := loaded(g); n != 0 {
2962 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
2963 }
2964 }
2965 mu.Lock()
2966 defer mu.Unlock()
2967 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
2968 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
2969 }
2970}
2971
2972// A load that reads slowly does not hold the request that waits for it:
2973// the request answers 503 at its deadline. With no request left waiting,
2974// the load stops reading part way through the export, caches nothing, and
2975// gives back its generation, which the next activation deletes. A load
2976// that ends is kept, and the requests after it are served without another
2977// read.
2978func TestSlowLoadEndsWithItsRequests(t *testing.T) {
2979 h := newHarness(t)
2980 h.srv.timeout = 200 * time.Millisecond
2981 var mu sync.Mutex
2982 var logged []string
2983 h.srv.log = func(err error) {
2984 mu.Lock()
2985 defer mu.Unlock()
2986 logged = append(logged, err.Error())
2987 }
2988 var reads atomic.Int32
2989 h.srv.loading = func(export.Generation) { reads.Add(1) }
2990
2991 // The active generation's export.json becomes a pipe the test writes
2992 // a few bytes at a time, as a slow disk would give it: all of it
2993 // takes about 4 seconds, twenty times the request's time.
2994 old := h.active()
2995 data, err := os.ReadFile(old.ExportPath())
2996 if err != nil {
2997 t.Fatal(err)
2998 }
2999 if err := os.Remove(old.ExportPath()); err != nil {
3000 t.Fatal(err)
3001 }
3002 if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil {
3003 t.Fatal(err)
3004 }
3005 piece := max(1, len(data)/200)
3006 wrote := make(chan error, 1)
3007 go func() {
3008 f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0)
3009 if err != nil {
3010 wrote <- err
3011 return
3012 }
3013 defer f.Close()
3014 for p := data; len(p) > 0; p = p[min(len(p), piece):] {
3015 if _, err := f.Write(p[:min(len(p), piece)]); err != nil {
3016 wrote <- err
3017 return
3018 }
3019 time.Sleep(20 * time.Millisecond)
3020 }
3021 wrote <- nil
3022 }()
3023
3024 start := time.Now()
3025 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
3026 t.Errorf("a request whose load ran past its time answered %d", w.Code)
3027 }
3028 if waited := time.Since(start); waited > 2*time.Second {
3029 t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited)
3030 }
3031 select {
3032 case err := <-wrote:
3033 if !errors.Is(err, syscall.EPIPE) {
3034 t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err)
3035 }
3036 case <-time.After(10 * time.Second):
3037 t.Fatal("the load still reads the export")
3038 }
3039 eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 })
3040 h.srv.mu.Lock()
3041 cached, loads := h.srv.cached, len(h.srv.loads)
3042 h.srv.mu.Unlock()
3043 if cached != nil || loads != 0 {
3044 t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads)
3045 }
3046 // The store reads the active export.json when it takes an upload.
3047 if err := os.Remove(old.ExportPath()); err != nil {
3048 t.Fatal(err)
3049 }
3050 if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil {
3051 t.Fatal(err)
3052 }
3053 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
3054 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
3055 t.Errorf("the generation a stopped load opened outlived an activation: %v", err)
3056 }
3057
3058 h.srv.timeout = requestTimeout
3059 for range 3 {
3060 if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the second plan") {
3061 t.Error("a request after the stopped load is not served the new generation")
3062 }
3063 }
3064 if n := reads.Load(); n != 2 {
3065 t.Errorf("exports were read %d times: once in part, and once for the new generation", n)
3066 }
3067 mu.Lock()
3068 defer mu.Unlock()
3069 if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") {
3070 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
3071 }
3072}
3073
3074// openFiles is the number of files the process holds open, and false
3075// where the system does not list them.
3076func openFiles(t *testing.T) (int, bool) {
3077 t.Helper()
3078 entries, err := os.ReadDir("/proc/self/fd")
3079 if err != nil {
3080 return 0, false
3081 }
3082 return len(entries), true
3083}
3084
3085// A flood of requests while a load runs: MaxLoadWaiting of them wait, and
3086// the rest answer 503 at once, unlogged. A waiting request holds no
3087// generation, so the goroutines and files the server holds stay within a
3088// bound however large the flood. Once the load ends, every request that
3089// waited is served from its one read.
3090func TestLoadFlood(t *testing.T) {
3091 h := newHarness(t)
3092 var reads atomic.Int32
3093 reading, hold := make(chan struct{}, 1), make(chan struct{})
3094 h.srv.loading = func(export.Generation) {
3095 reads.Add(1)
3096 reading <- struct{}{}
3097 <-hold
3098 }
3099 get := func(n int) chan *httptest.ResponseRecorder {
3100 served := make(chan *httptest.ResponseRecorder, n)
3101 for range n {
3102 go func() {
3103 w := httptest.NewRecorder()
3104 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/-/knots", nil))
3105 served <- w
3106 }()
3107 }
3108 return served
3109 }
3110
3111 first := get(1)
3112 select {
3113 case <-reading:
3114 case <-time.After(10 * time.Second):
3115 t.Fatal("no load started")
3116 }
3117 goroutines := runtime.NumGoroutine()
3118 files, listed := openFiles(t)
3119
3120 flood := 4 * MaxLoadWaiting
3121 served := get(flood)
3122 refused := flood - (MaxLoadWaiting - 1)
3123 for range refused {
3124 if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
3125 t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code)
3126 }
3127 }
3128 if n := len(h.srv.loadWaiting); n != MaxLoadWaiting {
3129 t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting)
3130 }
3131 const slack = 8
3132 eventually(t, "the refused requests' goroutines end", func() bool {
3133 return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack
3134 })
3135 if n, _ := openFiles(t); listed && n > files+slack {
3136 t.Errorf("the flood holds %d files open, %d more than before it", n, n-files)
3137 }
3138
3139 close(hold)
3140 for range MaxLoadWaiting - 1 {
3141 if w := <-served; w.Code != http.StatusOK {
3142 t.Errorf("a request that waited for the load answered %d", w.Code)
3143 }
3144 }
3145 if w := <-first; w.Code != http.StatusOK {
3146 t.Errorf("the request that started the load answered %d", w.Code)
3147 }
3148 if n := reads.Load(); n != 1 {
3149 t.Errorf("the export was read %d times for one generation", n)
3150 }
3151 if n := len(h.srv.loadWaiting); n != 0 {
3152 t.Errorf("%d requests still hold a place among those that wait", n)
3153 }
3154}
3155
3156// A request's time runs from its arrival through its rendering: a request
3157// for a page that runs no git, held past its time before it renders,
3158// answers 503, and the server logs it.
3159func TestRenderingIsWithinTheDeadline(t *testing.T) {
3160 h := newHarness(t)
3161 h.page("/-/knots")
3162 h.srv.timeout = 50 * time.Millisecond
3163 var logged []string
3164 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
3165 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
3166 if w := h.get("/-/knots"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
3167 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
3168 }
3169 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
3170 t.Errorf("the server logged %q", logged)
3171 }
3172 if n, _ := h.srv.holding(); n != 0 {
3173 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
3174 }
3175}
3176
3177// A FIFO with a writer that sends no bytes keeps Read blocked until the
3178// request deadline. A FIFO without a writer must not block Open.
3179func TestStalledLoadReleasesGeneration(t *testing.T) {
3180 for _, writer := range []bool{false, true} {
3181 t.Run(fmt.Sprint(writer), func(t *testing.T) {
3182 h := newHarness(t)
3183 h.srv.timeout = 100 * time.Millisecond
3184 h.srv.log = func(error) {}
3185 old := h.active()
3186 data, err := os.ReadFile(old.ExportPath())
3187 if err != nil {
3188 t.Fatal(err)
3189 }
3190 if err := os.Remove(old.ExportPath()); err != nil {
3191 t.Fatal(err)
3192 }
3193 if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil {
3194 t.Fatal(err)
3195 }
3196 if writer {
3197 f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0)
3198 if err != nil {
3199 t.Fatal(err)
3200 }
3201 defer f.Close()
3202 if _, err := f.Write([]byte("{")); err != nil {
3203 t.Fatal(err)
3204 }
3205 }
3206 if w := h.get("/"); w.Code != http.StatusServiceUnavailable {
3207 t.Fatalf("status = %d", w.Code)
3208 }
3209 eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 })
3210 h.srv.mu.Lock()
3211 cached := h.srv.cached
3212 h.srv.mu.Unlock()
3213 if cached != nil {
3214 t.Fatal("stalled load cached a snapshot")
3215 }
3216 if err := os.Remove(old.ExportPath()); err != nil {
3217 t.Fatal(err)
3218 }
3219 if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil {
3220 t.Fatal(err)
3221 }
3222 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
3223 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
3224 t.Fatalf("generation retained: %v", err)
3225 }
3226 h.srv.timeout = requestTimeout
3227 if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "The second plan") {
3228 t.Fatal("loader slot is not reusable")
3229 }
3230 })
3231 }
3232}
3233
3234// cancelInPhase cancels a real context on the cancellation check numbered
3235// at, or the third when at is 0, inside a named processing function. It
3236// makes cancellation during CPU work deterministic without replacing
3237// decoding or graph traversal. With a nil cancel it counts alone.
3238type cancelInPhase struct {
3239 context.Context
3240 cancel context.CancelFunc
3241 phase string
3242 at int
3243 checks int
3244}
3245
3246func (c *cancelInPhase) Err() error {
3247 var pcs [32]uintptr
3248 n := runtime.Callers(2, pcs[:])
3249 frames := runtime.CallersFrames(pcs[:n])
3250 for {
3251 frame, more := frames.Next()
3252 if strings.HasSuffix(frame.Function, c.phase) {
3253 c.checks++
3254 at := c.at
3255 if at == 0 {
3256 at = 3
3257 }
3258 if c.checks == at && c.cancel != nil {
3259 c.cancel()
3260 }
3261 break
3262 }
3263 if !more {
3264 break
3265 }
3266 }
3267 return c.Context.Err()
3268}
3269
3270func TestProcessingCancellationReleasesGeneration(t *testing.T) {
3271 for _, phase := range []string{".decodeValue", "exactjson.(*checker).check", ".(*Export).ValidateContext", ".CheckNames", ".(*Export).checkGroups",
3272 ".(*index).place", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} {
3273 t.Run(phase, func(t *testing.T) {
3274 h := newHarness(t)
3275 old := h.active()
3276 base, cancel := context.WithCancel(context.Background())
3277 defer cancel()
3278 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase}
3279 l := &load{done: make(chan struct{}), cancel: cancel}
3280 h.srv.loads[l] = struct{}{}
3281 h.srv.loaders <- struct{}{}
3282 finished := make(chan struct{})
3283 go func() { h.srv.run(ctx, l); close(finished) }()
3284 select {
3285 case <-finished:
3286 case <-time.After(2 * time.Second):
3287 t.Fatal("processing did not stop")
3288 }
3289 if ctx.checks < 3 {
3290 t.Fatalf("phase was not reached: %d checks", ctx.checks)
3291 }
3292 if !errors.Is(l.err, context.Canceled) {
3293 t.Fatalf("load error = %v", l.err)
3294 }
3295 if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 {
3296 t.Fatal("cancelled processing retained load state")
3297 }
3298 h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan"))
3299 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
3300 t.Fatalf("generation retained: %v", err)
3301 }
3302 if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "The second plan") {
3303 t.Fatal("loader slot is not reusable")
3304 }
3305 })
3306 }
3307}
3308
3309// Indexing where each public project's pages are, and where each alias
3310// and former name redirects to, stops when the load is cancelled, inside
3311// each of its loops: over the groups and their aliases, and over the
3312// projects and their former names and aliases. It checks before each name
3313// it indexes, so a long list of names keeps no cancelled load at work.
3314func TestPlacingStopsWhenCancelled(t *testing.T) {
3315 f := exporttest.New(t)
3316 e, err := export.Decode(f.ExportJSON)
3317 if err != nil {
3318 t.Fatal(err)
3319 }
3320 e.Groups[0].Aliases = []string{"t", "u", "v"}
3321 app := &e.Projects[0]
3322 app.FormerNames, app.Aliases = []string{"old-app", "older-app", "oldest-app"}, []string{"app", "a", "b"}
3323 if err := e.Validate(); err != nil {
3324 t.Fatal(err)
3325 }
3326 count := &cancelInPhase{Context: context.Background(), phase: ".(*index).place"}
3327 if _, err := newIndex(count, e, map[string]bool{"app": true}); err != nil {
3328 t.Fatal(err)
3329 }
3330 if names := 3 + 3 + 3; count.checks < names {
3331 t.Errorf("placing indexed %d names and checked the context %d times", names, count.checks)
3332 }
3333 for at := 1; at <= count.checks; at++ {
3334 base, cancel := context.WithCancel(context.Background())
3335 ctx := &cancelInPhase{Context: base, cancel: cancel, phase: ".(*index).place", at: at}
3336 idx, err := newIndex(ctx, e, map[string]bool{"app": true})
3337 cancel()
3338 if idx != nil || !errors.Is(err, context.Canceled) || ctx.checks != at {
3339 t.Errorf("cancelled at check %d of %d, newIndex returned %v after %d checks", at, count.checks, err, ctx.checks)
3340 }
3341 }
3342}
3343
3344// The server reads the stored authorization on every request. One that
3345// withdraws app takes it off every page at the next request, with no
3346// restart; one that names it again serves it again; and with none stored,
3347// nothing is served, though the export is indexed already.
3348func TestAuthorizationIsReadOnEveryRequest(t *testing.T) {
3349 h := newHarness(t)
3350 h.srv.log = func(error) {}
3351 app := "/tools/app/knots/oc-a000002"
3352 if w := h.get(app); w.Code != http.StatusOK {
3353 t.Fatalf("GET %s answered %d", app, w.Code)
3354 }
3355 a, _, err := h.store.Authorization()
3356 if err != nil {
3357 t.Fatal(err)
3358 }
3359 withdrawn := exporttest.Authorization(a.Sequence + 1)
3360 h.authorize(withdrawn)
3361 for _, path := range []string{app, "/tools/app/", "/t/app/", "/app/", "/tools/old-app/"} {
3362 if w := h.get(path); w.Code != http.StatusNotFound {
3363 t.Errorf("after the withdrawal GET %s answered %d, want 404", path, w.Code)
3364 }
3365 }
3366 if page := h.page("/-/knots"); strings.Contains(page, "/tools/app") {
3367 t.Error("after the withdrawal the plan page links app")
3368 }
3369 h.authorize(exporttest.Authorization(a.Sequence+2, "app"))
3370 if w := h.get(app); w.Code != http.StatusOK {
3371 t.Errorf("named again, GET %s answered %d", app, w.Code)
3372 }
3373 if err := os.Remove(filepath.Join(h.store.Dir(), "authorization")); err != nil {
3374 t.Fatal(err)
3375 }
3376 for _, path := range []string{"/", app, "/tools/app/"} {
3377 w := h.get(path)
3378 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") || strings.Contains(w.Body.String(), "oc-a000002") {
3379 t.Errorf("with no authorization GET %s answered %d:\n%s", path, w.Code, w.Body)
3380 }
3381 }
3382}
3383
3384// A response is written only under the authorization it was rendered
3385// under. One the authorization withdraws while it renders, a page or a
3386// redirect, is rendered again under the new one, and the reader gets the
3387// 404 the new one gives.
3388func TestAResponseIsHeldToTheAuthorizationWhenWritten(t *testing.T) {
3389 for _, path := range []string{"/tools/app/knots/oc-a000002", "/tools/app/", "/app/knots/oc-a000002"} {
3390 t.Run(path, func(t *testing.T) {
3391 h := newHarness(t)
3392 a, _, err := h.store.Authorization()
3393 if err != nil {
3394 t.Fatal(err)
3395 }
3396 renders := 0
3397 h.srv.checked = func() {
3398 if renders++; renders == 1 {
3399 h.authorize(exporttest.Authorization(a.Sequence + 1))
3400 }
3401 }
3402 if w := h.get(path); w.Code != http.StatusNotFound || w.Header().Get("Location") != "" {
3403 t.Errorf("GET %s withdrawn while it rendered answered %d, to %q", path, w.Code, w.Header().Get("Location"))
3404 }
3405 if renders != 2 {
3406 t.Errorf("GET %s rendered %d times, want twice", path, renders)
3407 }
3408 })
3409 }
3410}
3411
3412// headerClock is a response recorder that notes when the headers were
3413// written.
3414type headerClock struct {
3415 *httptest.ResponseRecorder
3416 at time.Time
3417}
3418
3419func (h *headerClock) WriteHeader(status int) {
3420 h.at = time.Now()
3421 h.ResponseRecorder.WriteHeader(status)
3422}
3423
3424// A withdrawal stored between a response's last read of the authorization
3425// and its headers waits for the headers: Authorize renames the record
3426// under the serving lock, which the response holds shared until its
3427// headers are written. So the response the old authorization allowed is
3428// one whose headers were written before the withdrawal returned, and the
3429// next request is refused.
3430func TestAWithdrawalWaitsForAResponseItsCheckAdmitted(t *testing.T) {
3431 h := newHarness(t)
3432 a, _, err := h.store.Authorization()
3433 if err != nil {
3434 t.Fatal(err)
3435 }
3436 withdrawal := exporttest.Authorization(a.Sequence + 1)
3437 signed := exporttest.SignAuthorization(t, withdrawal)
3438 stored := make(chan time.Time, 1)
3439 h.srv.starting = func() {
3440 h.srv.starting = nil
3441 go func() {
3442 if err := h.store.Authorize(context.Background(), withdrawal, signed); err != nil {
3443 t.Error(err)
3444 }
3445 stored <- time.Now()
3446 }()
3447 select {
3448 case at := <-stored:
3449 t.Error("the withdrawal was stored while a response held the serving lock")
3450 stored <- at
3451 case <-time.After(200 * time.Millisecond):
3452 }
3453 }
3454 w := &headerClock{ResponseRecorder: httptest.NewRecorder()}
3455 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000002", nil))
3456 if w.Code != http.StatusOK {
3457 t.Fatalf("the response admitted before the withdrawal answered %d", w.Code)
3458 }
3459 at := <-stored
3460 if !at.After(w.at) {
3461 t.Errorf("the withdrawal returned at %v, before the response's headers at %v", at, w.at)
3462 }
3463 if w := h.get("/tools/app/knots/oc-a000002"); w.Code != http.StatusNotFound {
3464 t.Errorf("after the withdrawal returned the next request answered %d, want 404", w.Code)
3465 }
3466}
3467
3468// holdEnv names the serving lock TestHoldTheServingLock holds, when the
3469// test binary runs as that helper.
3470const holdEnv = "VALLEY_WEB_SERVER_TEST_HOLD"
3471
3472// TestHoldTheServingLock is a process of its own when holdEnv is set: it
3473// holds the serving lock exclusively, as a receiver renaming an
3474// authorization does, says so on stdout, and holds it until its stdin
3475// closes.
3476func TestHoldTheServingLock(t *testing.T) {
3477 path := os.Getenv(holdEnv)
3478 if path == "" {
3479 t.Skip("a helper process of TestAServingLockWaitEndsWithTheRequest")
3480 }
3481 f, err := os.OpenFile(path, os.O_RDWR, 0)
3482 if err != nil {
3483 t.Fatal(err)
3484 }
3485 if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
3486 t.Fatal(err)
3487 }
3488 fmt.Println("held")
3489 io.Copy(io.Discard, os.Stdin)
3490}
3491
3492// lockProbe is a response writer that notes when the headers were
3493// written, and whether the serving lock was free when the body was.
3494type lockProbe struct {
3495 *httptest.ResponseRecorder
3496 lock string
3497 wrote bool
3498 freeAtBody bool
3499 bodyAttempted bool
3500}
3501
3502func (p *lockProbe) WriteHeader(status int) {
3503 p.wrote = true
3504 p.ResponseRecorder.WriteHeader(status)
3505}
3506
3507func (p *lockProbe) Write(b []byte) (int, error) {
3508 if !p.bodyAttempted {
3509 p.bodyAttempted = true
3510 if f, err := os.OpenFile(p.lock, os.O_RDWR, 0); err == nil {
3511 if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil {
3512 p.freeAtBody = true
3513 }
3514 f.Close()
3515 }
3516 }
3517 return p.ResponseRecorder.Write(b)
3518}
3519
3520// A request waits for the serving lock only until its deadline, or until
3521// its reader goes away. While another process holds the lock
3522// exclusively, a request whose deadline passes answers 503 and writes
3523// nothing it rendered, and one whose reader goes away writes nothing at
3524// all. With the lock free, a page and a redirect write their bodies after
3525// the lock is let go.
3526func TestAServingLockWaitEndsWithTheRequest(t *testing.T) {
3527 h := newHarness(t)
3528 lock := filepath.Join(h.store.Dir(), "serving.lock")
3529 for _, path := range []string{"/tools/app/knots/oc-a000002", "/tools/app/"} {
3530 w := &lockProbe{ResponseRecorder: httptest.NewRecorder(), lock: lock}
3531 h.srv.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
3532 if !w.bodyAttempted || !w.freeAtBody {
3533 t.Errorf("GET %s wrote its body with the serving lock held (body written: %v)", path, w.bodyAttempted)
3534 }
3535 }
3536
3537 cmd := exec.Command(os.Args[0], "-test.run=^TestHoldTheServingLock$")
3538 cmd.Env = append(os.Environ(), holdEnv+"="+lock)
3539 stdin, err := cmd.StdinPipe()
3540 if err != nil {
3541 t.Fatal(err)
3542 }
3543 stdout, err := cmd.StdoutPipe()
3544 if err != nil {
3545 t.Fatal(err)
3546 }
3547 if err := cmd.Start(); err != nil {
3548 t.Fatal(err)
3549 }
3550 defer func() {
3551 stdin.Close()
3552 cmd.Wait()
3553 }()
3554 line, err := bufio.NewReader(stdout).ReadString('\n')
3555 if err != nil || line != "held\n" {
3556 t.Fatalf("the helper said %q, %v", line, err)
3557 }
3558
3559 h.srv.timeout = 300 * time.Millisecond
3560 began := time.Now()
3561 w := &lockProbe{ResponseRecorder: httptest.NewRecorder(), lock: lock}
3562 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/", nil))
3563 if took := time.Since(began); took > 3*time.Second {
3564 t.Errorf("a request waited %v for a held serving lock, past its deadline", took)
3565 }
3566 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Location") != "" || strings.Contains(w.Body.String(), "oc-a000002") {
3567 t.Errorf("a request past its deadline answered %d, to %q:\n%s", w.Code, w.Header().Get("Location"), w.Body)
3568 }
3569
3570 h.srv.timeout = time.Minute
3571 ctx, cancel := context.WithCancel(context.Background())
3572 time.AfterFunc(200*time.Millisecond, cancel)
3573 began = time.Now()
3574 w = &lockProbe{ResponseRecorder: httptest.NewRecorder(), lock: lock}
3575 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000002", nil).WithContext(ctx))
3576 if took := time.Since(began); took > 3*time.Second {
3577 t.Errorf("a request whose reader went away waited %v for a held serving lock", took)
3578 }
3579 if w.wrote || w.bodyAttempted {
3580 t.Errorf("a request whose reader went away wrote a response: %d\n%s", w.Code, w.Body)
3581 }
3582}