gunk-dev/the-valley

server_test.go

sourcea9ea3ba977damain's published tip history
53.8 KiB
1package server
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/base64"
9 "fmt"
10 "io"
11 "net"
12 "net/http"
13 "net/http/httptest"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "strings"
20 "sync"
21 "sync/atomic"
22 "testing"
23 "time"
24
25 "the-valley/knot"
26 "the-valley/webui/export"
27 "the-valley/webui/export/exporttest"
28)
29
30// harness is a server over a real store that the fixture's export was
31// uploaded to, with a clock the test sets.
32type harness struct {
33 t *testing.T
34 f *exporttest.Fixture
35 store *export.Store
36 srv *Server
37 now time.Time
38}
39
40// newHarness serves the fixture's export, two minutes after it was
41// collected.
42func newHarness(t *testing.T) *harness {
43 t.Helper()
44 f := exporttest.New(t)
45 store, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) })
46 if err != nil {
47 t.Fatal(err)
48 }
49 f.Upload(t, store)
50 h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)}
51 h.srv = New(Config{Store: store, Now: func() time.Time { return h.now },
52 Log: func(err error) { t.Errorf("the server logged: %v", err) }})
53 return h
54}
55
56func (h *harness) do(method, target string) *httptest.ResponseRecorder {
57 h.t.Helper()
58 w := httptest.NewRecorder()
59 h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil))
60 return w
61}
62
63func (h *harness) get(target string) *httptest.ResponseRecorder {
64 h.t.Helper()
65 return h.do("GET", target)
66}
67
68// page is the body of a GET that must answer 200.
69func (h *harness) page(target string) string {
70 h.t.Helper()
71 w := h.get(target)
72 if w.Code != http.StatusOK {
73 h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body)
74 }
75 return w.Body.String()
76}
77
78// tip is the fixture's published source tip of app.
79func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip }
80
81// publish activates a new generation, signed at: the fixture's export
82// changed by change, with the bundles given in place of the fixture's.
83func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation {
84 t := h.t
85 t.Helper()
86 e, err := export.Decode(h.f.ExportJSON)
87 if err != nil {
88 t.Fatal(err)
89 }
90 change(e)
91 data, err := e.Encode()
92 if err != nil {
93 t.Fatal(err)
94 }
95 paths := map[string]string{}
96 for name, path := range h.f.Bundles {
97 paths[name] = path
98 }
99 for name, path := range bundles {
100 paths[name] = path
101 }
102 bodies := map[string]export.Body{}
103 for name, path := range paths {
104 if bodies[name], err = export.FileBody(name, path); err != nil {
105 t.Fatal(err)
106 }
107 }
108 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies)
109 if err != nil {
110 t.Fatal(err)
111 }
112 hw, err := h.store.HighWater()
113 if err != nil {
114 t.Fatal(err)
115 }
116 a := h.f.Admission()
117 a.Now, a.HighWater = at.Add(time.Second), hw
118 if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil {
119 t.Fatal(err)
120 }
121 st, err := h.store.Stage(m)
122 if err != nil {
123 t.Fatal(err)
124 }
125 inv, err := h.store.Inventory(st)
126 if err != nil {
127 t.Fatal(err)
128 }
129 for _, need := range inv.Needs {
130 body := data
131 if need.Name != export.ExportFile {
132 if body, err = os.ReadFile(paths[need.Name]); err != nil {
133 t.Fatal(err)
134 }
135 }
136 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body))
137 if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil {
138 t.Fatal(err)
139 }
140 }
141 g, err := h.store.Activate(context.Background(), st)
142 if err != nil {
143 t.Fatal(err)
144 }
145 return g
146}
147
148// active is the generation the store serves.
149func (h *harness) active() export.Generation {
150 h.t.Helper()
151 g, release, err := h.store.Open()
152 if err != nil {
153 h.t.Fatal(err)
154 }
155 release()
156 return g
157}
158
159// git runs git on the repository at repo, with no configuration of the
160// caller's and a fixed identity for the commits it writes.
161func git(t *testing.T, repo string, stdin []byte, args ...string) string {
162 t.Helper()
163 cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...)
164 for _, kv := range os.Environ() {
165 if !strings.HasPrefix(kv, "GIT_") {
166 cmd.Env = append(cmd.Env, kv)
167 }
168 }
169 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
170 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000",
171 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000")
172 if stdin != nil {
173 cmd.Stdin = bytes.NewReader(stdin)
174 }
175 var stderr bytes.Buffer
176 cmd.Stderr = &stderr
177 out, err := cmd.Output()
178 if err != nil {
179 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
180 }
181 return strings.TrimSpace(string(out))
182}
183
184// section is the part of a page from one marker up to the next.
185func section(t *testing.T, page, from, to string) string {
186 t.Helper()
187 i := strings.Index(page, from)
188 j := strings.Index(page[max(i, 0):], to)
189 if i < 0 || j < 0 {
190 t.Fatalf("the page has no section from %q to %q", from, to)
191 }
192 return page[i : i+j]
193}
194
195// The plan page keeps the template's reading order, says what free to
196// start means, shows the ready changes as one card in no order, and
197// shows how old the export is.
198func TestPlanPage(t *testing.T) {
199 h := newHarness(t)
200 page := h.page("/")
201
202 at := -1
203 for _, heading := range []string{">Waiting on you<", ">In flight<", ">Paths<", ">Milestones<"} {
204 i := strings.Index(page, heading)
205 if i <= at {
206 t.Fatalf("%s is not where the reading order puts it", heading)
207 }
208 at = i
209 }
210 for _, want := range []string{
211 "free to start: an open, unclaimed, unblocked outcome or bug",
212 "Nothing here waits on you.",
213 "Ready changes — order not assessed",
214 `<span class="handle">kmno</span>`, "plan: list the milestones", "app v2", "approved · integrator: stale",
215 "Collected 2026-10-25 12:00 UTC, 2 minutes ago",
216 "claimed by agent 2 hours ago",
217 "in progress, unclaimed",
218 "Readers browse the app&#39;s plan", "1 of 5 done",
219 "Unfiled", "Render Markdown in a later slice",
220 "waits on oc-a000002",
221 } {
222 if !strings.Contains(page, want) {
223 t.Errorf("the plan page does not show %q", want)
224 }
225 }
226 if strings.Count(page, "Ready changes") != 1 {
227 t.Error("the ready changes are not one card")
228 }
229
230 // The bug nobody claims and nothing blocks is free to start.
231 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="/knots/app/bd-a000004">`) {
232 t.Error("bd-a000004 is not shown as free to start")
233 }
234
235 // The milestone's path puts oc-a000003 after the knot it waits on.
236 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
237 second := strings.Index(paths, `<span class="stage-num">2</span>`)
238 if second < 0 || strings.Index(paths, "oc-a000002") > second || strings.Index(paths, "oc-a000003") < second {
239 t.Errorf("the path does not order oc-a000003 after oc-a000002:\n%s", paths)
240 }
241
242 // Nothing of the hidden project is linked or named, and nothing is
243 // fetched from another origin.
244 for _, want := range []string{"lands in an unpublished project", "lands in a knot in an unpublished project"} {
245 if !strings.Contains(page, want) {
246 t.Errorf("the plan page does not show %q", want)
247 }
248 }
249 for _, unwanted := range append([]string{"/knots/site/", "/source/site/", "http://", "https://", `class="chip stale"`}, unpublishedText...) {
250 if strings.Contains(page, unwanted) {
251 t.Errorf("the plan page holds %q", unwanted)
252 }
253 }
254
255 h.now = exporttest.Collected.Add(6 * time.Minute)
256 page = h.page("/")
257 if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) {
258 t.Error("an export six minutes old is not marked stale")
259 }
260}
261
262// unpublishedText is what of the hidden project site the fixture's
263// references hold: its name and its knots' IDs. No page shows any of it.
264var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"}
265
266// A knot's page shows its body and comments, and marks the edited
267// comment. A reference into a hidden project is shown as unpublished,
268// with nothing of its text, and a missing knot of a public project is
269// named as missing.
270func TestKnotPage(t *testing.T) {
271 h := newHarness(t)
272 page := h.page("/knots/app/oc-a000002")
273 for _, want := range []string{
274 "Each milestone is listed with its progress.",
275 "Start with the milestones that have open children.",
276 "Claimed; the change is ready for approval.",
277 `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`,
278 `<a href="/knots/app/oc-a000001">Readers browse the app&#39;s plan</a>`,
279 } {
280 if !strings.Contains(page, want) {
281 t.Errorf("the knot's page does not show %q", want)
282 }
283 }
284 if n := strings.Count(page, ">edited<"); n != 1 {
285 t.Errorf("%d comments are marked edited; one was edited", n)
286 }
287
288 page = h.page("/knots/app/oc-a000003")
289 if !strings.Contains(page, `<a href="/knots/app/oc-a000002">The plan page lists milestones</a>`) {
290 t.Error("the local blocker is not linked")
291 }
292 for _, want := range []string{
293 `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`,
294 "<dt>Lands in</dt><dd>an unpublished project</dd>",
295 } {
296 if !strings.Contains(page, want) {
297 t.Errorf("the knot's page does not show %q", want)
298 }
299 }
300 page += h.page("/knots/app/bd-a000004")
301 if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") {
302 t.Error("a target in the hidden project is not shown as unpublished")
303 }
304 for _, unwanted := range append([]string{"/knots/site/", "/source/site/"}, unpublishedText...) {
305 if strings.Contains(page, unwanted) {
306 t.Errorf("the knot's page shows %q", unwanted)
307 }
308 }
309 if w := h.get("/knots/app/oc-fffffff"); w.Code != http.StatusNotFound {
310 t.Errorf("a missing knot answered %d", w.Code)
311 }
312
313 // A knot of a public project the graph does not hold, and a local
314 // knot that is not there, are named as missing. A change of the
315 // hidden project is not named.
316 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
317 for i := range e.Projects[0].Knots {
318 if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" {
319 k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee")
320 k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling})
321 k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm")
322 }
323 }
324 })
325 page = h.page("/knots/app/oc-a000003")
326 for _, want := range []string{
327 `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`,
328 `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`,
329 `<li class="mono">a change in an unpublished project</li>`,
330 `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`,
331 } {
332 if !strings.Contains(page, want) {
333 t.Errorf("the knot's page does not show %q", want)
334 }
335 }
336 for _, unwanted := range unpublishedText {
337 if strings.Contains(page, unwanted) {
338 t.Errorf("the knot's page shows %q", unwanted)
339 }
340 }
341}
342
343// A project the export does not hold as public answers every route
344// exactly as a project that does not exist, even when its repository is
345// in the generation's directory.
346func TestHiddenProjectAnswersLikeMissing(t *testing.T) {
347 h := newHarness(t)
348 g := h.active()
349 if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil {
350 t.Fatal(err)
351 }
352 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
353 notFound := h.get("/knots/app/oc-fffffff")
354 for _, route := range []string{
355 "/knots/%s/oc-b000001",
356 "/source/%s",
357 "/source/%s/",
358 "/source/%s/tree/" + siteTip + "/",
359 "/source/%s/blob/" + siteTip + "/README.md",
360 "/source/%s/log/" + siteTip,
361 "/source/%s/tree/" + siteTip + "/no/such/path/",
362 "/source/%s/anything",
363 } {
364 hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch"))
365 if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound {
366 t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code)
367 }
368 if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) {
369 t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header())
370 }
371 if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) {
372 t.Errorf("%s answered with another page hidden than missing", route)
373 }
374 }
375}
376
377// A source route serves a commit only when main's published tip reaches
378// it, and refuses every other object ID or name with the one 404.
379func TestUnreachableCommitIsRefused(t *testing.T) {
380 h := newHarness(t)
381 repo, _ := h.active().Repo("app")
382 tip := h.tip()
383 tree := git(t, repo, nil, "rev-parse", tip+"^{tree}")
384 readme := git(t, repo, nil, "rev-parse", tip+":README.md")
385 side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach")
386 parent := git(t, repo, nil, "rev-parse", tip+"~2")
387 notFound := h.get("/knots/app/oc-fffffff").Body.String()
388
389 for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} {
390 for _, route := range []string{"/source/app/tree/%s/", "/source/app/blob/%s/README.md", "/source/app/log/%s"} {
391 target := fmt.Sprintf(route, commit)
392 w := h.get(target)
393 if w.Code != http.StatusNotFound || w.Body.String() != notFound {
394 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
395 }
396 }
397 }
398
399 // A commit the tip reaches is served, as that commit had it.
400 page := h.page("/source/app/blob/" + parent + "/README.md")
401 if !strings.Contains(page, "A synthetic project for the web UI&#39;s tests.") || strings.Contains(page, "readme") {
402 t.Errorf("the first README is not served as the first commit had it:\n%s", page)
403 }
404}
405
406// The source browser lists a directory and its README, shows a file and
407// main's log, and every source link names its project, a full commit and
408// a path.
409func TestSourceBrowser(t *testing.T) {
410 h := newHarness(t)
411 tip := h.tip()
412
413 w := h.get("/source/app/")
414 if w.Code != http.StatusFound || w.Header().Get("Location") != "/source/app/tree/"+tip+"/" {
415 t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location"))
416 }
417
418 root := h.page("/source/app/tree/" + tip + "/")
419 docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<")
420 if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs {
421 t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root)
422 }
423 if !strings.Contains(root, `<pre class="text"># app`) {
424 t.Error("the root does not show its README")
425 }
426 if dir := h.page("/source/app/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") {
427 t.Error("docs/ does not list guide.md")
428 }
429 file := h.page("/source/app/blob/" + tip + "/docs/guide.md")
430 if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) {
431 t.Errorf("the file is not shown line by line:\n%s", file)
432 }
433 log := h.page("/source/app/log/" + tip)
434 first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README")
435 if first < 0 || last < first {
436 t.Errorf("the log does not list main's commits newest first:\n%s", log)
437 }
438
439 links := regexp.MustCompile(`href="(/source/[^"]*)"`)
440 named := regexp.MustCompile(`^/source/app/(tree|blob|log)/[0-9a-f]{40}(/|$)`)
441 for _, page := range []string{root, file, log} {
442 for _, m := range links.FindAllStringSubmatch(page, -1) {
443 if !named.MatchString(m[1]) {
444 t.Errorf("the link %s names no commit", m[1])
445 }
446 }
447 }
448
449 for _, target := range []string{
450 "/source/app/tree/" + tip + "/README.md/",
451 "/source/app/blob/" + tip + "/docs",
452 "/source/app/blob/" + tip + "/docs/guide.md/",
453 "/source/app/blob/" + tip + "/docs/../README.md",
454 "/source/app/blob/" + tip + "/docs%2Fguide.md",
455 "/source/app/tree/" + tip + "//",
456 "/source/app/log/" + tip + "?skip=-1",
457 } {
458 if w := h.get(target); w.Code != http.StatusNotFound {
459 t.Errorf("GET %s answered %d", target, w.Code)
460 }
461 }
462}
463
464// file is one file a test commits: its mode, path and content.
465type file struct{ mode, path, content string }
466
467// commitMain writes a commit onto the fixture's app main, with message,
468// that holds the files given beside what main holds. It returns the new
469// tip and a bundle of it. Each content is written once, however many
470// files hold it.
471func (h *harness) commitMain(message string, files ...file) (tip, bundle string) {
472 t := h.t
473 t.Helper()
474 repo := h.f.Repos["app"]
475 var b bytes.Buffer
476 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
477 marks := map[string]int{}
478 for _, f := range files {
479 if _, ok := marks[f.content]; !ok {
480 marks[f.content] = len(marks) + 1
481 fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content])
482 data(f.content)
483 }
484 }
485 who := "Example Author <author@example.org> 1791190800 +0000"
486 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
487 data(message)
488 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
489 for _, f := range files {
490 fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path)
491 }
492 git(t, repo, b.Bytes(), "fast-import", "--quiet")
493 tip = git(t, repo, nil, "rev-parse", export.MainRef)
494 bundle = filepath.Join(t.TempDir(), "app.bundle")
495 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
496 return tip, bundle
497}
498
499// publishMain activates a generation whose app main is tip, carried by
500// bundle.
501func (h *harness) publishMain(at time.Time, tip, bundle string) {
502 h.t.Helper()
503 h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip })
504}
505
506// hostileMain writes a commit onto the fixture's app main that holds a
507// file of HTML, a file larger than a page shows, a binary file, a file
508// whose name is HTML, and a symbolic link out of the repository. It
509// returns the new tip and a bundle of it.
510func (h *harness) hostileMain() (tip, bundle string) {
511 return h.commitMain("hostile: <script>alert(\"subject\")</script>\n",
512 file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"},
513 file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)},
514 file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"},
515 file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"},
516 file{"120000", "link", "../../etc/passwd"},
517 )
518}
519
520// HTML, scripts, large files and binary files from a repository or the
521// plan render inert: escaped as text, or not shown.
522func TestHostileContentRendersInert(t *testing.T) {
523 h := newHarness(t)
524 tip, bundle := h.hostileMain()
525 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
526 e.Projects[0].SourceTip = tip
527 })
528
529 inert := func(target, page string, wants ...string) {
530 t.Helper()
531 // Escaped, a tag is text; only a tag the page did not escape, or
532 // an attribute it let a value break out into, is active.
533 for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} {
534 if strings.Contains(page, active) {
535 t.Errorf("GET %s holds %q", target, active)
536 }
537 }
538 for _, want := range wants {
539 if !strings.Contains(page, want) {
540 t.Errorf("GET %s does not show %q", target, want)
541 }
542 }
543 }
544 at := "/source/app/tree/" + tip + "/"
545 inert(at, h.page(at),
546 `&lt;script&gt;alert(&#34;readme&#34;)&lt;/script&gt;`,
547 `&lt;img src=x onerror=alert(3)&gt;.txt`,
548 `href="/source/app/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`)
549 at = "/source/app/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"
550 inert(at, h.page(at), ">named<")
551 at = "/source/app/blob/" + tip + "/page.html"
552 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;`)
553 at = "/source/app/blob/" + tip + "/big.txt"
554 page := h.page(at)
555 inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.")
556 if len(page) > 64<<10 {
557 t.Errorf("the large file's page is %d bytes", len(page))
558 }
559 at = "/source/app/blob/" + tip + "/binary.bin"
560 inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.")
561 at = "/source/app/blob/" + tip + "/link"
562 inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.")
563 at = "/source/app/log/" + tip
564 inert(at, h.page(at), "hostile: &lt;script&gt;alert(&#34;subject&#34;)&lt;/script&gt;")
565
566 at = "/knots/app/bd-a000004"
567 inert(at, h.page(at),
568 `A README holding &lt;script&gt;alert(&#34;knot&#34;)&lt;/script&gt; must show as text.`,
569 `Also &lt;img src=x onerror=alert(1)&gt; in a comment.`)
570}
571
572// A directory larger than a page reads is listed in part, and a commit
573// message larger than a page reads ends its page of history early. git
574// is stopped once its listing passes MaxRead, and nothing past a record's
575// bound is kept.
576func TestOversizedTreeAndHistory(t *testing.T) {
577 h := newHarness(t)
578 // Each entry of huge/ takes 308 bytes of git ls-tree's output, so
579 // 15,000 of them pass MaxRead at about entry 13,600.
580 longest := "!" + strings.Repeat("l", 4095)
581 files := []file{{"100644", "huge/" + longest, "x\n"}}
582 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
583 for i := range 15_000 {
584 files = append(files, file{"100644", "huge/" + name(i), "x\n"})
585 }
586 if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead {
587 t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n)
588 }
589 h.commitMain("app: a directory larger than a page reads\n", files...)
590 h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n")
591 tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n")
592 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
593
594 at := "/source/app/tree/" + tip + "/huge/"
595 page := h.page(at)
596 if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") {
597 t.Error("huge/ is not marked as listed in part")
598 }
599 if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries {
600 t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries)
601 }
602 if !strings.Contains(page, `">`+longest+`</a>`) {
603 t.Error("the entry with the longest name git accepts is not listed whole")
604 }
605 if len(page) > 1<<20 {
606 t.Errorf("huge/'s page is %d bytes", len(page))
607 }
608 if w := h.get("/source/app/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK {
609 t.Errorf("an entry read before MaxRead answered %d", w.Code)
610 }
611 if w := h.get("/source/app/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound {
612 t.Errorf("an entry past MaxRead answered %d", w.Code)
613 }
614
615 at = "/source/app/log/" + tip
616 page = h.page(at)
617 if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") {
618 t.Error("the page of history holding a 5 MiB message does not end early")
619 }
620 if n := strings.Count(page, `<tr><td class="name">`); n != 1 {
621 t.Errorf("the page that ends early lists %d commits, not the one it cut", n)
622 }
623 if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText {
624 t.Error("the cut commit's subject is not shown cut to maxLogText")
625 }
626 if !strings.Contains(page, `href="/source/app/log/`+tip+`?skip=1"`) {
627 t.Error("the page that ends early does not link the commits after the one it cut")
628 }
629 page = h.page(at + "?skip=1")
630 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
631 t.Errorf("the next page of history is not whole:\n%s", page)
632 }
633 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
634 t.Error("a subject longer than a page shows is not cut")
635 }
636 for _, p := range []string{at, at + "?skip=1"} {
637 if n := len(h.page(p)); n > 64<<10 {
638 t.Errorf("GET %s is %d bytes", p, n)
639 }
640 }
641}
642
643// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
644// and its page says where it stops. A README longer than a page shows is
645// shown in part.
646func TestLongFileIsShownInPart(t *testing.T) {
647 h := newHarness(t)
648 tip, bundle := h.commitMain("app: long files\n",
649 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
650 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
651 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
652 )
653 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
654
655 page := h.page("/source/app/blob/" + tip + "/newlines.txt")
656 last := fmt.Sprintf(`id="L%d"`, MaxLines)
657 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
658 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
659 }
660 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
661 t.Errorf("the page does not say %q", want)
662 }
663 if len(page) > MaxShown {
664 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
665 }
666
667 // One line of MaxFile characters that each escape to four bytes is
668 // cut where MaxShown is reached.
669 page = h.page("/source/app/blob/" + tip + "/wide.txt")
670 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
671 t.Errorf("the page of one wide line is %d bytes", len(page))
672 }
673
674 page = h.page("/source/app/tree/" + tip + "/long/")
675 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
676 t.Error("the long README is not marked as shown in part")
677 }
678 if n := strings.Count(page, "a line of the README"); n != MaxLines {
679 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
680 }
681}
682
683// A chain of knots as deep as the graph's knot limit allows renders its
684// milestone to MaxPlanDepth levels, counts every knot under it, and
685// names MaxPlanDepth parents in the deepest knot's trail. The plan page's
686// structure is built once for the generation. Siblings that block one
687// another in a cycle share the last stage of their path.
688func TestDeepPlan(t *testing.T) {
689 h := newHarness(t)
690 var chain []string
691 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
692 p := &e.Projects[0]
693 for i := range knot.MaxKnots - len(p.Knots) - 3 {
694 id := fmt.Sprintf("oc-c%06x", i)
695 k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready",
696 Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"}
697 if i == 0 {
698 p.Roots = append(p.Roots, id)
699 } else {
700 k.Parent = chain[i-1]
701 p.Knots[len(p.Knots)-1].Children = []string{id}
702 }
703 chain = append(chain, id)
704 p.Knots = append(p.Knots, k)
705 }
706 // Under the first link, a path whose two last siblings wait on
707 // each other.
708 free, a, b := "oc-d000001", "oc-d000002", "oc-d000003"
709 for _, k := range []export.Knot{
710 {ID: free, BlockedBy: []string{}},
711 {ID: a, BlockedBy: []string{free, b}},
712 {ID: b, BlockedBy: []string{a}},
713 } {
714 k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0]
715 p.Knots = append(p.Knots, k)
716 }
717 for i := range p.Knots {
718 if p.Knots[i].ID == chain[0] {
719 p.Knots[i].Children = append(p.Knots[i].Children, free, a, b)
720 }
721 }
722 })
723
724 page := h.page("/")
725 if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) {
726 t.Errorf("the chain's milestone does not count every knot under it as %q", want)
727 }
728 if !strings.Contains(page, `href="/knots/app/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/knots/app/`+chain[MaxPlanDepth+1]+`"`) {
729 t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth)
730 }
731 if n := strings.Count(page, ">more on its page<"); n != 1 {
732 t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n)
733 }
734 if len(page) > 256<<10 {
735 t.Errorf("the plan page is %d bytes", len(page))
736 }
737 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
738 stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`)
739 var stages []string
740 for _, m := range stage.FindAllStringSubmatch(paths, -1) {
741 if strings.Contains(m[2], "Sibling") {
742 var ids []string
743 for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) {
744 ids = append(ids, id[1])
745 }
746 stages = append(stages, m[1]+":"+strings.Join(ids, ","))
747 }
748 }
749 if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" {
750 t.Errorf("the siblings' path has stages %q", got)
751 }
752
753 h.srv.mu.Lock()
754 plan := h.srv.cached.idx.plan
755 h.srv.mu.Unlock()
756 h.page("/")
757 h.srv.mu.Lock()
758 again := h.srv.cached.idx.plan
759 h.srv.mu.Unlock()
760 if plan != again {
761 t.Error("the plan page's structure was built again for the same generation")
762 }
763
764 deepest := chain[len(chain)-1]
765 page = h.page("/knots/app/" + deepest)
766 trail := section(t, page, `<nav class="trail"`, `</nav>`)
767 if n := strings.Count(trail, `<a href="/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") {
768 t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n)
769 }
770 if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/knots/app/`+chain[len(chain)-2-MaxPlanDepth]+`"`) {
771 t.Error("the trail does not name the nearest parents alone")
772 }
773}
774
775// Every response carries the strict policy, and the policy admits the
776// page's one inline stylesheet and one inline script by their hashes and
777// nothing from another origin.
778func TestEveryResponseCarriesTheCSP(t *testing.T) {
779 h := newHarness(t)
780 for _, c := range []struct{ method, target string }{
781 {"GET", "/"},
782 {"GET", "/knots/app/oc-a000002"},
783 {"GET", "/source/app/"},
784 {"GET", "/source/app/tree/" + h.tip() + "/"},
785 {"GET", "/source/app/blob/" + h.tip() + "/README.md"},
786 {"GET", "/no/such/page"},
787 {"POST", "/"},
788 {"HEAD", "/"},
789 } {
790 w := h.do(c.method, c.target)
791 got := w.Header().Get("Content-Security-Policy")
792 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
793 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
794 }
795 }
796 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
797 if !strings.Contains(csp, directive) {
798 t.Errorf("the policy lacks %s", directive)
799 }
800 }
801 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
802 if strings.Contains(csp, loose) {
803 t.Errorf("the policy holds %q", loose)
804 }
805 }
806
807 page := h.page("/")
808 inline := func(tag string) string {
809 t.Helper()
810 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
811 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
812 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
813 }
814 sum := sha256.Sum256([]byte(m[0][1]))
815 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
816 }
817 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
818 t.Errorf("the policy does not admit the page's script, %s", hash)
819 }
820 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
821 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
822 }
823 for _, external := range []string{"<link", " src=", "@import", "url("} {
824 if strings.Contains(page, external) {
825 t.Errorf("the plan page holds %q", external)
826 }
827 }
828}
829
830// A request serves everything from the generation it opened, though
831// another activates while it runs, and that generation outlives the
832// activation until the request releases it.
833func TestARequestKeepsItsGeneration(t *testing.T) {
834 h := newHarness(t)
835 paused, resume := make(chan export.Generation), make(chan struct{})
836 var once sync.Once
837 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
838 served := make(chan *httptest.ResponseRecorder)
839 go func() {
840 w := httptest.NewRecorder()
841 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil))
842 served <- w
843 }()
844 old := <-paused
845
846 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
847 if next.Sequence == old.Sequence {
848 t.Fatal("the publish did not activate a new generation")
849 }
850 if _, err := os.Stat(old.Dir); err != nil {
851 t.Fatalf("the generation a request holds was deleted: %v", err)
852 }
853 close(resume)
854 w := <-served
855 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
856 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
857 }
858 if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the second plan") {
859 t.Error("the next request does not serve the new generation")
860 }
861
862 // Released, the old generation goes with the next activation.
863 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
864 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
865 t.Errorf("the released generation is still on disk: %v", err)
866 }
867}
868
869// eventually waits up to ten seconds for cond to hold.
870func eventually(t *testing.T, what string, cond func() bool) {
871 t.Helper()
872 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) {
873 if time.Now().After(deadline) {
874 t.Fatalf("timed out waiting until %s", what)
875 }
876 }
877}
878
879// renamed changes the title of the fixture's first knot.
880func renamed(title string) func(*export.Export) {
881 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
882}
883
884// Requests that open a generation together read its export once. While
885// it is read, a newer generation is read and served on its own, at most
886// MaxLoads exports are read at once, and an older read that finishes
887// last does not displace the newest generation's snapshot.
888func TestExportLoadsCoalesce(t *testing.T) {
889 h := newHarness(t)
890 var mu sync.Mutex
891 loads := map[int64]int{}
892 holds := map[int64]chan struct{}{}
893 hold := func(g export.Generation) chan struct{} {
894 mu.Lock()
895 defer mu.Unlock()
896 if holds[g.Sequence] == nil {
897 holds[g.Sequence] = make(chan struct{})
898 }
899 return holds[g.Sequence]
900 }
901 h.srv.loading = func(g export.Generation) {
902 mu.Lock()
903 loads[g.Sequence]++
904 mu.Unlock()
905 <-hold(g)
906 }
907 loaded := func(g export.Generation) int {
908 mu.Lock()
909 defer mu.Unlock()
910 return loads[g.Sequence]
911 }
912 var opens atomic.Int32
913 h.srv.opened = func(export.Generation) { opens.Add(1) }
914 get := func(n int) chan *httptest.ResponseRecorder {
915 served := make(chan *httptest.ResponseRecorder, n)
916 for range n {
917 go func() {
918 w := httptest.NewRecorder()
919 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil))
920 served <- w
921 }()
922 }
923 return served
924 }
925 expect := func(served chan *httptest.ResponseRecorder, n int, title string) {
926 t.Helper()
927 for range n {
928 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
929 t.Errorf("a request answered %d, not with %q", w.Code, title)
930 }
931 }
932 }
933
934 first := h.active()
935 firstServed := get(10)
936 eventually(t, "ten requests open the first generation", func() bool { return opens.Load() == 10 })
937 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
938 secondServed := get(1)
939 eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 })
940
941 // Both loaders are taken, so the third generation waits for one.
942 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
943 thirdServed := get(1)
944 eventually(t, "a request opens the third generation", func() bool { return opens.Load() == 12 })
945 time.Sleep(20 * time.Millisecond)
946 if n := loaded(third); n != 0 {
947 t.Errorf("a third export was read while %d were", MaxLoads)
948 }
949 close(hold(second))
950 expect(secondServed, 1, "Readers browse the second plan")
951 close(hold(third))
952 expect(thirdServed, 1, "Readers browse the third plan")
953 close(hold(first))
954 expect(firstServed, 10, "Readers browse the app&#39;s plan")
955
956 if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the third plan") {
957 t.Error("the first generation's read displaced the third's")
958 }
959 for _, g := range []export.Generation{first, second, third} {
960 if n := loaded(g); n != 1 {
961 t.Errorf("generation %d's export was read %d times", g.Sequence, n)
962 }
963 }
964}
965
966// Source requests past MaxGit wait, MaxWaiting of them, and one more
967// answers 503 at once. A waiting request holds no generation, so an
968// activation while the server is saturated deletes the old generation,
969// and every waiting request serves the new one. A request's time runs
970// from its arrival, so one that waits past it answers 503.
971func TestSourceAdmission(t *testing.T) {
972 h := newHarness(t)
973 var admitted atomic.Int32
974 release := make(chan struct{})
975 h.srv.admitted = func() {
976 admitted.Add(1)
977 <-release
978 }
979 target := "/source/app/tree/" + h.tip() + "/"
980 get := func(n int) chan *httptest.ResponseRecorder {
981 served := make(chan *httptest.ResponseRecorder, n)
982 for range n {
983 go func() {
984 w := httptest.NewRecorder()
985 h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
986 served <- w
987 }()
988 }
989 return served
990 }
991
992 old := h.active()
993 served := get(MaxGit + MaxWaiting)
994 eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool {
995 return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting
996 })
997 if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
998 t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After"))
999 }
1000 h.page("/") // a page that runs no git is served still
1001
1002 tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"})
1003 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
1004 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1005 t.Errorf("a generation no request had opened outlived the activation: %v", err)
1006 }
1007 close(release)
1008 for range MaxGit + MaxWaiting {
1009 if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/source/app/tree/"+tip+"/") {
1010 t.Errorf("a waiting request answered %d, not from the new generation", w.Code)
1011 }
1012 }
1013
1014 // A request that waits past its time answers 503. Those that held
1015 // the slots meanwhile ran out of time too.
1016 h.srv.timeout = 200 * time.Millisecond
1017 h.srv.log = func(error) {}
1018 admitted.Store(0)
1019 release = make(chan struct{})
1020 held := get(MaxGit)
1021 eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit })
1022 start := time.Now()
1023 if w := h.get(target); w.Code != http.StatusServiceUnavailable {
1024 t.Errorf("a request that waited past its time answered %d", w.Code)
1025 }
1026 if waited := time.Since(start); waited > 5*time.Second {
1027 t.Errorf("a request waited %v past its time of 200ms", waited)
1028 }
1029 close(release)
1030 for range MaxGit {
1031 if w := <-held; w.Code != http.StatusServiceUnavailable {
1032 t.Errorf("a request that ran out of time answered %d", w.Code)
1033 }
1034 }
1035}
1036
1037// stallingListener accepts connections whose writes stall until release
1038// is closed, while stall is set. Each sends on stalled the first time one
1039// of its writes stalls.
1040type stallingListener struct {
1041 net.Listener
1042 stall atomic.Bool
1043 release chan struct{}
1044 stalled chan struct{}
1045}
1046
1047func (l *stallingListener) Accept() (net.Conn, error) {
1048 c, err := l.Listener.Accept()
1049 if err != nil || !l.stall.Load() {
1050 return c, err
1051 }
1052 return &stallingConn{Conn: c, l: l}, nil
1053}
1054
1055type stallingConn struct {
1056 net.Conn
1057 l *stallingListener
1058 once sync.Once
1059}
1060
1061func (c *stallingConn) Write(p []byte) (int, error) {
1062 c.once.Do(func() { c.l.stalled <- struct{}{} })
1063 <-c.l.release
1064 return c.Conn.Write(p)
1065}
1066
1067// Readers that never read their responses hold no git slot and no
1068// generation: more of them than MaxGit and MaxWaiting together are
1069// stalled writing, and a new reader is still served, and an activation
1070// deletes the generation they were served from.
1071func TestSlowReadersHoldNothing(t *testing.T) {
1072 h := newHarness(t)
1073 ln, err := net.Listen("tcp", "127.0.0.1:0")
1074 if err != nil {
1075 t.Fatal(err)
1076 }
1077 n := MaxGit + MaxWaiting + 4
1078 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1079 sl.stall.Store(true)
1080 srv := &http.Server{Handler: h.srv}
1081 go srv.Serve(sl)
1082 var conns []net.Conn
1083 defer func() {
1084 close(sl.release)
1085 for _, c := range conns {
1086 c.Close()
1087 }
1088 srv.Close()
1089 }()
1090
1091 old := h.active()
1092 target := "/source/app/blob/" + h.tip() + "/docs/guide.md"
1093 for range n {
1094 c, err := net.Dial("tcp", ln.Addr().String())
1095 if err != nil {
1096 t.Fatal(err)
1097 }
1098 conns = append(conns, c)
1099 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1100 }
1101 for i := range n {
1102 select {
1103 case <-sl.stalled:
1104 case <-time.After(10 * time.Second):
1105 t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n)
1106 }
1107 }
1108 sl.stall.Store(false)
1109 if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 {
1110 t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting))
1111 }
1112
1113 client := &http.Client{Timeout: 10 * time.Second}
1114 resp, err := client.Get("http://" + ln.Addr().String() + target)
1115 if err != nil {
1116 t.Fatal(err)
1117 }
1118 resp.Body.Close()
1119 if resp.StatusCode != http.StatusOK {
1120 t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode)
1121 }
1122 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {})
1123 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
1124 t.Errorf("the generation slow readers were served from outlived the activation: %v", err)
1125 }
1126}
1127
1128// Before the first activation the server says nothing is published, and
1129// it answers GET and HEAD alone.
1130func TestNothingPublishedAndMethods(t *testing.T) {
1131 store, err := export.OpenStore(t.TempDir(), nil)
1132 if err != nil {
1133 t.Fatal(err)
1134 }
1135 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
1136 w := httptest.NewRecorder()
1137 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
1138 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
1139 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
1140 }
1141
1142 h := newHarness(t)
1143 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
1144 w := h.do(method, "/")
1145 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
1146 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
1147 }
1148 }
1149}
1150
1151// tooLarge checks that GET target answers with the one short page that
1152// says a page is too large.
1153func (h *harness) tooLarge(target string) {
1154 h.t.Helper()
1155 w := h.get(target)
1156 if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) {
1157 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())
1158 }
1159 if n := len(h.srv.budget); n != 0 {
1160 h.t.Errorf("GET %s kept %d pieces of the budget", target, n)
1161 }
1162}
1163
1164// A response's body is at most MaxResponse bytes. A page that would pass
1165// the bound answers with the one short page that says it is too large,
1166// and the failure is logged: a knot whose body passes MaxResponse, and,
1167// under a smaller bound, a file, a directory, a page of history and the
1168// plan page. A page within the bound is served on each route.
1169func TestPageTooLarge(t *testing.T) {
1170 h := newHarness(t)
1171 var logged []string
1172 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1173 files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}}
1174 for i := range 32 {
1175 files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"})
1176 }
1177 h.commitMain("app: a wide file and a wide directory\n", files...)
1178 var tip, bundle string
1179 for i := range 8 {
1180 tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText)))
1181 }
1182 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
1183 p := &e.Projects[0]
1184 p.SourceTip = tip
1185 p.Knots[0].Body = strings.Repeat("a", MaxResponse)
1186 for i := range 100 {
1187 p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open",
1188 Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"})
1189 }
1190 })
1191
1192 h.tooLarge("/knots/app/" + h.f.Export.Projects[0].Knots[0].ID)
1193 h.page("/knots/app/oc-a000002")
1194
1195 h.srv.maxResponse = 32 << 10
1196 at := "/source/app/blob/" + tip + "/"
1197 h.tooLarge(at + "wide.txt")
1198 h.page(at + "docs/guide.md")
1199 at = "/source/app/tree/" + tip + "/"
1200 h.tooLarge(at + "wide/")
1201 h.page(at + "docs/")
1202 h.tooLarge("/source/app/log/" + tip)
1203 h.page("/source/app/log/" + tip + "?skip=8")
1204 h.tooLarge("/")
1205
1206 if len(logged) != 5 {
1207 t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged)
1208 }
1209 for _, l := range logged {
1210 if !strings.Contains(l, "larger than") {
1211 t.Errorf("the server logged %q", l)
1212 }
1213 }
1214 if len(tooLargePage) > 16<<10 {
1215 t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage))
1216 }
1217}
1218
1219// Rendered responses share a budget of MaxBuffered bytes, which each
1220// holds from when it starts rendering until it is written. Readers that
1221// never read, asking for twice the budget in all, hold no more than it:
1222// once their pages fill it, a page it has no room for answers 503 at
1223// once, and a small page that fits is still served. The server's heap
1224// grows by no more than the budget, and the budget is whole again once
1225// the readers read.
1226func TestSlowReadersShareTheBudget(t *testing.T) {
1227 h := newHarness(t)
1228 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
1229 e.Projects[0].Knots[0].Body = strings.Repeat("a line of a long body\n", (4<<20)/22)
1230 })
1231 target := "/knots/app/" + h.f.Export.Projects[0].Knots[0].ID
1232 size := len(h.page(target))
1233 pieces := (size + pieceSize - 1) / pieceSize
1234 fit := cap(h.srv.budget) / pieces
1235 n := 2*MaxBuffered/size + 1
1236
1237 ln, err := net.Listen("tcp", "127.0.0.1:0")
1238 if err != nil {
1239 t.Fatal(err)
1240 }
1241 sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)}
1242 sl.stall.Store(true)
1243 srv := &http.Server{Handler: h.srv}
1244 go srv.Serve(sl)
1245 var conns []net.Conn
1246 released := false
1247 defer func() {
1248 if !released {
1249 close(sl.release)
1250 }
1251 for _, c := range conns {
1252 c.Close()
1253 }
1254 srv.Close()
1255 }()
1256
1257 var before runtime.MemStats
1258 runtime.GC()
1259 runtime.ReadMemStats(&before)
1260 // One reader at a time, each stalled before the next asks, so the
1261 // readers that fill the budget are the first fit of them.
1262 for i := range n {
1263 c, err := net.Dial("tcp", ln.Addr().String())
1264 if err != nil {
1265 t.Fatal(err)
1266 }
1267 conns = append(conns, c)
1268 fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target)
1269 select {
1270 case <-sl.stalled:
1271 case <-time.After(10 * time.Second):
1272 t.Fatalf("reader %d of %d was not answered", i+1, n)
1273 }
1274 }
1275 sl.stall.Store(false)
1276 var after runtime.MemStats
1277 runtime.GC()
1278 runtime.ReadMemStats(&after)
1279 if held := len(h.srv.budget); held != fit*pieces {
1280 t.Errorf("slow readers hold %d pieces; %d pages of %d pieces fit", held, fit, pieces)
1281 }
1282 if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 {
1283 t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew)
1284 }
1285
1286 client := &http.Client{Timeout: 10 * time.Second}
1287 get := func(target string) (int, string) {
1288 t.Helper()
1289 resp, err := client.Get("http://" + ln.Addr().String() + target)
1290 if err != nil {
1291 t.Fatal(err)
1292 }
1293 defer resp.Body.Close()
1294 io.Copy(io.Discard, resp.Body)
1295 return resp.StatusCode, resp.Header.Get("Retry-After")
1296 }
1297 if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" {
1298 t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry)
1299 }
1300 if code, _ := get("/knots/app/oc-a000002"); code != http.StatusOK {
1301 t.Errorf("a small page answered %d while slow readers hold most of the budget", code)
1302 }
1303
1304 close(sl.release)
1305 released = true
1306 codes := map[int]int{}
1307 for _, c := range conns {
1308 c.SetReadDeadline(time.Now().Add(10 * time.Second))
1309 resp, err := http.ReadResponse(bufio.NewReader(c), nil)
1310 if err != nil {
1311 t.Fatal(err)
1312 }
1313 read, err := io.Copy(io.Discard, resp.Body)
1314 resp.Body.Close()
1315 if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) {
1316 t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err)
1317 }
1318 codes[resp.StatusCode]++
1319 }
1320 if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit {
1321 t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget",
1322 n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit)
1323 }
1324 eventually(t, "the budget is whole again", func() bool { return len(h.srv.budget) == 0 })
1325}
1326
1327// A read of an export starts only in a request that holds a loader slot.
1328// While MaxLoads reads run, a request for a newer generation waits for a
1329// slot, holding its generation, until its time runs out, whatever its
1330// route, or its reader goes away. Neither leaves a read behind, and
1331// neither holds its generation once it has answered.
1332func TestExportLoadWaitsEnd(t *testing.T) {
1333 h := newHarness(t)
1334 var mu sync.Mutex
1335 var logged []string
1336 h.srv.log = func(err error) {
1337 mu.Lock()
1338 defer mu.Unlock()
1339 logged = append(logged, err.Error())
1340 }
1341 loads := map[int64]int{}
1342 hold := make(chan struct{})
1343 h.srv.loading = func(g export.Generation) {
1344 mu.Lock()
1345 loads[g.Sequence]++
1346 mu.Unlock()
1347 <-hold
1348 }
1349 loaded := func(g export.Generation) int {
1350 mu.Lock()
1351 defer mu.Unlock()
1352 return loads[g.Sequence]
1353 }
1354 var opened atomic.Int64
1355 h.srv.opened = func(g export.Generation) { opened.Store(g.Sequence) }
1356 serve := func(r *http.Request) chan *httptest.ResponseRecorder {
1357 served := make(chan *httptest.ResponseRecorder, 1)
1358 go func() {
1359 w := httptest.NewRecorder()
1360 h.srv.ServeHTTP(w, r)
1361 served <- w
1362 }()
1363 return served
1364 }
1365 expect := func(served chan *httptest.ResponseRecorder, title string) {
1366 t.Helper()
1367 select {
1368 case w := <-served:
1369 if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) {
1370 t.Errorf("a request answered %d, not with %q", w.Code, title)
1371 }
1372 case <-time.After(10 * time.Second):
1373 t.Fatalf("a request was not answered with %q", title)
1374 }
1375 }
1376
1377 first := h.active()
1378 firstServed := serve(httptest.NewRequest("GET", "/", nil))
1379 second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
1380 secondServed := serve(httptest.NewRequest("GET", "/", nil))
1381 eventually(t, "both loader slots are taken", func() bool { return loaded(first) == 1 && loaded(second) == 1 })
1382
1383 // A request that runs no git runs out of time waiting, and answers
1384 // 503.
1385 h.srv.timeout = 200 * time.Millisecond
1386 third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
1387 select {
1388 case w := <-serve(httptest.NewRequest("GET", "/knots/app/oc-a000001", nil)):
1389 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {
1390 t.Errorf("a request that waited past its time for a read answered %d", w.Code)
1391 }
1392 case <-time.After(10 * time.Second):
1393 t.Fatal("a request waits for a read past its time of 200ms")
1394 }
1395
1396 // A request whose reader goes away stops waiting, and answers
1397 // nothing.
1398 h.srv.timeout = time.Hour
1399 fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan"))
1400 ctx, cancel := context.WithCancel(context.Background())
1401 defer cancel()
1402 gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx))
1403 eventually(t, "a request opens the fourth generation", func() bool { return opened.Load() == fourth.Sequence })
1404 cancel()
1405 select {
1406 case w := <-gone:
1407 if w.Body.Len() != 0 {
1408 t.Errorf("a request whose reader went away answered %d", w.Code)
1409 }
1410 case <-time.After(10 * time.Second):
1411 t.Fatal("a request whose reader went away still waits")
1412 }
1413
1414 h.srv.mu.Lock()
1415 _, thirdLoad := h.srv.loads[third.Sequence]
1416 _, fourthLoad := h.srv.loads[fourth.Sequence]
1417 h.srv.mu.Unlock()
1418 if thirdLoad || fourthLoad {
1419 t.Error("a read no request waits for is left behind")
1420 }
1421 h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan"))
1422 for _, g := range []export.Generation{third, fourth} {
1423 if _, err := os.Stat(g.Dir); !os.IsNotExist(err) {
1424 t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err)
1425 }
1426 }
1427
1428 close(hold)
1429 expect(firstServed, "Readers browse the app&#39;s plan")
1430 expect(secondServed, "Readers browse the second plan")
1431 if !strings.Contains(h.page("/"), "Readers browse the fifth plan") {
1432 t.Error("the newest generation is not served once the reads end")
1433 }
1434 for _, g := range []export.Generation{third, fourth} {
1435 if n := loaded(g); n != 0 {
1436 t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n)
1437 }
1438 }
1439 mu.Lock()
1440 defer mu.Unlock()
1441 if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") {
1442 t.Errorf("the server logged %q; it logs the one request that ran out of time", logged)
1443 }
1444}
1445
1446// A request's time runs from its arrival through its rendering: a request
1447// for a page that runs no git, held past its time before it renders,
1448// answers 503, and the server logs it.
1449func TestRenderingIsWithinTheDeadline(t *testing.T) {
1450 h := newHarness(t)
1451 h.page("/")
1452 h.srv.timeout = 50 * time.Millisecond
1453 var logged []string
1454 h.srv.log = func(err error) { logged = append(logged, err.Error()) }
1455 h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) }
1456 if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) {
1457 t.Errorf("a request that ran out of time before it rendered answered %d", w.Code)
1458 }
1459 if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") {
1460 t.Errorf("the server logged %q", logged)
1461 }
1462 if n := len(h.srv.budget); n != 0 {
1463 t.Errorf("a page that stopped rendering kept %d pieces of the budget", n)
1464 }
1465}