gunk-dev/the-valley

server_test.go

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