gunk-dev/the-valley

server_test.go

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