gunk-dev/the-valley

server_test.go

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