gunk-dev/the-valley

server_test.go

source7964e6acfb7fmain's published tip history
30.3 KiB
1package server
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/base64"
8 "fmt"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "regexp"
15 "strings"
16 "sync"
17 "testing"
18 "time"
19
20 "the-valley/webui/export"
21 "the-valley/webui/export/exporttest"
22)
23
24// harness is a server over a real store that the fixture's export was
25// uploaded to, with a clock the test sets.
26type harness struct {
27 t *testing.T
28 f *exporttest.Fixture
29 store *export.Store
30 srv *Server
31 now time.Time
32}
33
34// newHarness serves the fixture's export, two minutes after it was
35// collected.
36func newHarness(t *testing.T) *harness {
37 t.Helper()
38 f := exporttest.New(t)
39 store, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) })
40 if err != nil {
41 t.Fatal(err)
42 }
43 f.Upload(t, store)
44 h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)}
45 h.srv = New(Config{Store: store, Now: func() time.Time { return h.now },
46 Log: func(err error) { t.Errorf("the server logged: %v", err) }})
47 return h
48}
49
50func (h *harness) do(method, target string) *httptest.ResponseRecorder {
51 h.t.Helper()
52 w := httptest.NewRecorder()
53 h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil))
54 return w
55}
56
57func (h *harness) get(target string) *httptest.ResponseRecorder {
58 h.t.Helper()
59 return h.do("GET", target)
60}
61
62// page is the body of a GET that must answer 200.
63func (h *harness) page(target string) string {
64 h.t.Helper()
65 w := h.get(target)
66 if w.Code != http.StatusOK {
67 h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body)
68 }
69 return w.Body.String()
70}
71
72// tip is the fixture's published source tip of app.
73func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip }
74
75// publish activates a new generation, signed at: the fixture's export
76// changed by change, with the bundles given in place of the fixture's.
77func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation {
78 t := h.t
79 t.Helper()
80 e, err := export.Decode(h.f.ExportJSON)
81 if err != nil {
82 t.Fatal(err)
83 }
84 change(e)
85 data, err := e.Encode()
86 if err != nil {
87 t.Fatal(err)
88 }
89 paths := map[string]string{}
90 for name, path := range h.f.Bundles {
91 paths[name] = path
92 }
93 for name, path := range bundles {
94 paths[name] = path
95 }
96 bodies := map[string]export.Body{}
97 for name, path := range paths {
98 if bodies[name], err = export.FileBody(name, path); err != nil {
99 t.Fatal(err)
100 }
101 }
102 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies)
103 if err != nil {
104 t.Fatal(err)
105 }
106 hw, err := h.store.HighWater()
107 if err != nil {
108 t.Fatal(err)
109 }
110 a := h.f.Admission()
111 a.Now, a.HighWater = at.Add(time.Second), hw
112 if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil {
113 t.Fatal(err)
114 }
115 st, err := h.store.Stage(m)
116 if err != nil {
117 t.Fatal(err)
118 }
119 inv, err := h.store.Inventory(st)
120 if err != nil {
121 t.Fatal(err)
122 }
123 for _, need := range inv.Needs {
124 body := data
125 if need.Name != export.ExportFile {
126 if body, err = os.ReadFile(paths[need.Name]); err != nil {
127 t.Fatal(err)
128 }
129 }
130 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body))
131 if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil {
132 t.Fatal(err)
133 }
134 }
135 g, err := h.store.Activate(context.Background(), st)
136 if err != nil {
137 t.Fatal(err)
138 }
139 return g
140}
141
142// active is the generation the store serves.
143func (h *harness) active() export.Generation {
144 h.t.Helper()
145 g, release, err := h.store.Open()
146 if err != nil {
147 h.t.Fatal(err)
148 }
149 release()
150 return g
151}
152
153// git runs git on the repository at repo, with no configuration of the
154// caller's and a fixed identity for the commits it writes.
155func git(t *testing.T, repo string, stdin []byte, args ...string) string {
156 t.Helper()
157 cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...)
158 for _, kv := range os.Environ() {
159 if !strings.HasPrefix(kv, "GIT_") {
160 cmd.Env = append(cmd.Env, kv)
161 }
162 }
163 cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
164 "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000",
165 "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000")
166 if stdin != nil {
167 cmd.Stdin = bytes.NewReader(stdin)
168 }
169 var stderr bytes.Buffer
170 cmd.Stderr = &stderr
171 out, err := cmd.Output()
172 if err != nil {
173 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String())
174 }
175 return strings.TrimSpace(string(out))
176}
177
178// section is the part of a page from one marker up to the next.
179func section(t *testing.T, page, from, to string) string {
180 t.Helper()
181 i := strings.Index(page, from)
182 j := strings.Index(page[max(i, 0):], to)
183 if i < 0 || j < 0 {
184 t.Fatalf("the page has no section from %q to %q", from, to)
185 }
186 return page[i : i+j]
187}
188
189// The plan page keeps the template's reading order, says what free to
190// start means, shows the ready changes as one card in no order, and
191// shows how old the export is.
192func TestPlanPage(t *testing.T) {
193 h := newHarness(t)
194 page := h.page("/")
195
196 at := -1
197 for _, heading := range []string{">Waiting on you<", ">In flight<", ">Paths<", ">Milestones<"} {
198 i := strings.Index(page, heading)
199 if i <= at {
200 t.Fatalf("%s is not where the reading order puts it", heading)
201 }
202 at = i
203 }
204 for _, want := range []string{
205 "free to start: an open, unclaimed, unblocked outcome or bug",
206 "Nothing here waits on you.",
207 "Ready changes — order not assessed",
208 `<span class="handle">kmno</span>`, "plan: list the milestones", "app v2", "approved · integrator: stale",
209 "Collected 2026-10-25 12:00 UTC, 2 minutes ago",
210 "claimed by agent 2 hours ago",
211 "in progress, unclaimed",
212 "Readers browse the app&#39;s plan", "1 of 5 done",
213 "Unfiled", "Render Markdown in a later slice",
214 "waits on oc-a000002",
215 } {
216 if !strings.Contains(page, want) {
217 t.Errorf("the plan page does not show %q", want)
218 }
219 }
220 if strings.Count(page, "Ready changes") != 1 {
221 t.Error("the ready changes are not one card")
222 }
223
224 // The bug nobody claims and nothing blocks is free to start.
225 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">`) {
226 t.Error("bd-a000004 is not shown as free to start")
227 }
228
229 // The milestone's path puts oc-a000003 after the knot it waits on.
230 paths := section(t, page, `id="paths-h"`, `id="ms-h"`)
231 second := strings.Index(paths, `<span class="stage-num">2</span>`)
232 if second < 0 || strings.Index(paths, "oc-a000002") > second || strings.Index(paths, "oc-a000003") < second {
233 t.Errorf("the path does not order oc-a000003 after oc-a000002:\n%s", paths)
234 }
235
236 // Nothing of the hidden project is linked or named, and nothing is
237 // fetched from another origin.
238 for _, want := range []string{"lands in an unpublished project", "lands in a knot in an unpublished project"} {
239 if !strings.Contains(page, want) {
240 t.Errorf("the plan page does not show %q", want)
241 }
242 }
243 for _, unwanted := range append([]string{"/knots/site/", "/source/site/", "http://", "https://", `class="chip stale"`}, unpublishedText...) {
244 if strings.Contains(page, unwanted) {
245 t.Errorf("the plan page holds %q", unwanted)
246 }
247 }
248
249 h.now = exporttest.Collected.Add(6 * time.Minute)
250 page = h.page("/")
251 if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) {
252 t.Error("an export six minutes old is not marked stale")
253 }
254}
255
256// unpublishedText is what of the hidden project site the fixture's
257// references hold: its name and its knots' IDs. No page shows any of it.
258var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"}
259
260// A knot's page shows its body and comments, and marks the edited
261// comment. A reference into a hidden project is shown as unpublished,
262// with nothing of its text, and a missing knot of a public project is
263// named as missing.
264func TestKnotPage(t *testing.T) {
265 h := newHarness(t)
266 page := h.page("/knots/app/oc-a000002")
267 for _, want := range []string{
268 "Each milestone is listed with its progress.",
269 "Start with the milestones that have open children.",
270 "Claimed; the change is ready for approval.",
271 `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`,
272 `<a href="/knots/app/oc-a000001">Readers browse the app&#39;s plan</a>`,
273 } {
274 if !strings.Contains(page, want) {
275 t.Errorf("the knot's page does not show %q", want)
276 }
277 }
278 if n := strings.Count(page, ">edited<"); n != 1 {
279 t.Errorf("%d comments are marked edited; one was edited", n)
280 }
281
282 page = h.page("/knots/app/oc-a000003")
283 if !strings.Contains(page, `<a href="/knots/app/oc-a000002">The plan page lists milestones</a>`) {
284 t.Error("the local blocker is not linked")
285 }
286 for _, want := range []string{
287 `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`,
288 "<dt>Lands in</dt><dd>an unpublished project</dd>",
289 } {
290 if !strings.Contains(page, want) {
291 t.Errorf("the knot's page does not show %q", want)
292 }
293 }
294 page += h.page("/knots/app/bd-a000004")
295 if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") {
296 t.Error("a target in the hidden project is not shown as unpublished")
297 }
298 for _, unwanted := range append([]string{"/knots/site/", "/source/site/"}, unpublishedText...) {
299 if strings.Contains(page, unwanted) {
300 t.Errorf("the knot's page shows %q", unwanted)
301 }
302 }
303 if w := h.get("/knots/app/oc-fffffff"); w.Code != http.StatusNotFound {
304 t.Errorf("a missing knot answered %d", w.Code)
305 }
306
307 // A knot of a public project the graph does not hold, and a local
308 // knot that is not there, are named as missing. A change of the
309 // hidden project is not named.
310 h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) {
311 for i := range e.Projects[0].Knots {
312 if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" {
313 k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee")
314 k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling})
315 k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm")
316 }
317 }
318 })
319 page = h.page("/knots/app/oc-a000003")
320 for _, want := range []string{
321 `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`,
322 `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`,
323 `<li class="mono">a change in an unpublished project</li>`,
324 `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`,
325 } {
326 if !strings.Contains(page, want) {
327 t.Errorf("the knot's page does not show %q", want)
328 }
329 }
330 for _, unwanted := range unpublishedText {
331 if strings.Contains(page, unwanted) {
332 t.Errorf("the knot's page shows %q", unwanted)
333 }
334 }
335}
336
337// A project the export does not hold as public answers every route
338// exactly as a project that does not exist, even when its repository is
339// in the generation's directory.
340func TestHiddenProjectAnswersLikeMissing(t *testing.T) {
341 h := newHarness(t)
342 g := h.active()
343 if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil {
344 t.Fatal(err)
345 }
346 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
347 notFound := h.get("/knots/app/oc-fffffff")
348 for _, route := range []string{
349 "/knots/%s/oc-b000001",
350 "/source/%s",
351 "/source/%s/",
352 "/source/%s/tree/" + siteTip + "/",
353 "/source/%s/blob/" + siteTip + "/README.md",
354 "/source/%s/log/" + siteTip,
355 "/source/%s/tree/" + siteTip + "/no/such/path/",
356 "/source/%s/anything",
357 } {
358 hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch"))
359 if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound {
360 t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code)
361 }
362 if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) {
363 t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header())
364 }
365 if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) {
366 t.Errorf("%s answered with another page hidden than missing", route)
367 }
368 }
369}
370
371// A source route serves a commit only when main's published tip reaches
372// it, and refuses every other object ID or name with the one 404.
373func TestUnreachableCommitIsRefused(t *testing.T) {
374 h := newHarness(t)
375 repo, _ := h.active().Repo("app")
376 tip := h.tip()
377 tree := git(t, repo, nil, "rev-parse", tip+"^{tree}")
378 readme := git(t, repo, nil, "rev-parse", tip+":README.md")
379 side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach")
380 parent := git(t, repo, nil, "rev-parse", tip+"~2")
381 notFound := h.get("/knots/app/oc-fffffff").Body.String()
382
383 for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} {
384 for _, route := range []string{"/source/app/tree/%s/", "/source/app/blob/%s/README.md", "/source/app/log/%s"} {
385 target := fmt.Sprintf(route, commit)
386 w := h.get(target)
387 if w.Code != http.StatusNotFound || w.Body.String() != notFound {
388 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
389 }
390 }
391 }
392
393 // A commit the tip reaches is served, as that commit had it.
394 page := h.page("/source/app/blob/" + parent + "/README.md")
395 if !strings.Contains(page, "A synthetic project for the web UI&#39;s tests.") || strings.Contains(page, "readme") {
396 t.Errorf("the first README is not served as the first commit had it:\n%s", page)
397 }
398}
399
400// The source browser lists a directory and its README, shows a file and
401// main's log, and every source link names its project, a full commit and
402// a path.
403func TestSourceBrowser(t *testing.T) {
404 h := newHarness(t)
405 tip := h.tip()
406
407 w := h.get("/source/app/")
408 if w.Code != http.StatusFound || w.Header().Get("Location") != "/source/app/tree/"+tip+"/" {
409 t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location"))
410 }
411
412 root := h.page("/source/app/tree/" + tip + "/")
413 docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<")
414 if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs {
415 t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root)
416 }
417 if !strings.Contains(root, `<pre class="text"># app`) {
418 t.Error("the root does not show its README")
419 }
420 if dir := h.page("/source/app/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") {
421 t.Error("docs/ does not list guide.md")
422 }
423 file := h.page("/source/app/blob/" + tip + "/docs/guide.md")
424 if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) {
425 t.Errorf("the file is not shown line by line:\n%s", file)
426 }
427 log := h.page("/source/app/log/" + tip)
428 first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README")
429 if first < 0 || last < first {
430 t.Errorf("the log does not list main's commits newest first:\n%s", log)
431 }
432
433 links := regexp.MustCompile(`href="(/source/[^"]*)"`)
434 named := regexp.MustCompile(`^/source/app/(tree|blob|log)/[0-9a-f]{40}(/|$)`)
435 for _, page := range []string{root, file, log} {
436 for _, m := range links.FindAllStringSubmatch(page, -1) {
437 if !named.MatchString(m[1]) {
438 t.Errorf("the link %s names no commit", m[1])
439 }
440 }
441 }
442
443 for _, target := range []string{
444 "/source/app/tree/" + tip + "/README.md/",
445 "/source/app/blob/" + tip + "/docs",
446 "/source/app/blob/" + tip + "/docs/guide.md/",
447 "/source/app/blob/" + tip + "/docs/../README.md",
448 "/source/app/blob/" + tip + "/docs%2Fguide.md",
449 "/source/app/tree/" + tip + "//",
450 "/source/app/log/" + tip + "?skip=-1",
451 } {
452 if w := h.get(target); w.Code != http.StatusNotFound {
453 t.Errorf("GET %s answered %d", target, w.Code)
454 }
455 }
456}
457
458// file is one file a test commits: its mode, path and content.
459type file struct{ mode, path, content string }
460
461// commitMain writes a commit onto the fixture's app main, with message,
462// that holds the files given beside what main holds. It returns the new
463// tip and a bundle of it. Each content is written once, however many
464// files hold it.
465func (h *harness) commitMain(message string, files ...file) (tip, bundle string) {
466 t := h.t
467 t.Helper()
468 repo := h.f.Repos["app"]
469 var b bytes.Buffer
470 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
471 marks := map[string]int{}
472 for _, f := range files {
473 if _, ok := marks[f.content]; !ok {
474 marks[f.content] = len(marks) + 1
475 fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content])
476 data(f.content)
477 }
478 }
479 who := "Example Author <author@example.org> 1791190800 +0000"
480 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
481 data(message)
482 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
483 for _, f := range files {
484 fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path)
485 }
486 git(t, repo, b.Bytes(), "fast-import", "--quiet")
487 tip = git(t, repo, nil, "rev-parse", export.MainRef)
488 bundle = filepath.Join(t.TempDir(), "app.bundle")
489 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
490 return tip, bundle
491}
492
493// publishMain activates a generation whose app main is tip, carried by
494// bundle.
495func (h *harness) publishMain(at time.Time, tip, bundle string) {
496 h.t.Helper()
497 h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip })
498}
499
500// hostileMain writes a commit onto the fixture's app main that holds a
501// file of HTML, a file larger than a page shows, a binary file, a file
502// whose name is HTML, and a symbolic link out of the repository. It
503// returns the new tip and a bundle of it.
504func (h *harness) hostileMain() (tip, bundle string) {
505 return h.commitMain("hostile: <script>alert(\"subject\")</script>\n",
506 file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"},
507 file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)},
508 file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"},
509 file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"},
510 file{"120000", "link", "../../etc/passwd"},
511 )
512}
513
514// HTML, scripts, large files and binary files from a repository or the
515// plan render inert: escaped as text, or not shown.
516func TestHostileContentRendersInert(t *testing.T) {
517 h := newHarness(t)
518 tip, bundle := h.hostileMain()
519 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
520 e.Projects[0].SourceTip = tip
521 })
522
523 inert := func(target, page string, wants ...string) {
524 t.Helper()
525 // Escaped, a tag is text; only a tag the page did not escape, or
526 // an attribute it let a value break out into, is active.
527 for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} {
528 if strings.Contains(page, active) {
529 t.Errorf("GET %s holds %q", target, active)
530 }
531 }
532 for _, want := range wants {
533 if !strings.Contains(page, want) {
534 t.Errorf("GET %s does not show %q", target, want)
535 }
536 }
537 }
538 at := "/source/app/tree/" + tip + "/"
539 inert(at, h.page(at),
540 `&lt;script&gt;alert(&#34;readme&#34;)&lt;/script&gt;`,
541 `&lt;img src=x onerror=alert(3)&gt;.txt`,
542 `href="/source/app/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`)
543 at = "/source/app/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"
544 inert(at, h.page(at), ">named<")
545 at = "/source/app/blob/" + tip + "/page.html"
546 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;`)
547 at = "/source/app/blob/" + tip + "/big.txt"
548 page := h.page(at)
549 inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.")
550 if len(page) > 64<<10 {
551 t.Errorf("the large file's page is %d bytes", len(page))
552 }
553 at = "/source/app/blob/" + tip + "/binary.bin"
554 inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.")
555 at = "/source/app/blob/" + tip + "/link"
556 inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.")
557 at = "/source/app/log/" + tip
558 inert(at, h.page(at), "hostile: &lt;script&gt;alert(&#34;subject&#34;)&lt;/script&gt;")
559
560 at = "/knots/app/bd-a000004"
561 inert(at, h.page(at),
562 `A README holding &lt;script&gt;alert(&#34;knot&#34;)&lt;/script&gt; must show as text.`,
563 `Also &lt;img src=x onerror=alert(1)&gt; in a comment.`)
564}
565
566// A directory larger than a page reads is listed in part, and a commit
567// message larger than a page reads ends its page of history early. git
568// is stopped once its listing passes MaxRead, and nothing past a record's
569// bound is kept.
570func TestOversizedTreeAndHistory(t *testing.T) {
571 h := newHarness(t)
572 // Each entry of huge/ takes 308 bytes of git ls-tree's output, so
573 // 15,000 of them pass MaxRead at about entry 13,600.
574 longest := "!" + strings.Repeat("l", 4095)
575 files := []file{{"100644", "huge/" + longest, "x\n"}}
576 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
577 for i := range 15_000 {
578 files = append(files, file{"100644", "huge/" + name(i), "x\n"})
579 }
580 if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead {
581 t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n)
582 }
583 h.commitMain("app: a directory larger than a page reads\n", files...)
584 h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n")
585 tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n")
586 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
587
588 at := "/source/app/tree/" + tip + "/huge/"
589 page := h.page(at)
590 if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") {
591 t.Error("huge/ is not marked as listed in part")
592 }
593 if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries {
594 t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries)
595 }
596 if !strings.Contains(page, `">`+longest+`</a>`) {
597 t.Error("the entry with the longest name git accepts is not listed whole")
598 }
599 if len(page) > 1<<20 {
600 t.Errorf("huge/'s page is %d bytes", len(page))
601 }
602 if w := h.get("/source/app/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK {
603 t.Errorf("an entry read before MaxRead answered %d", w.Code)
604 }
605 if w := h.get("/source/app/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound {
606 t.Errorf("an entry past MaxRead answered %d", w.Code)
607 }
608
609 at = "/source/app/log/" + tip
610 page = h.page(at)
611 if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") {
612 t.Error("the page of history holding a 5 MiB message does not end early")
613 }
614 if n := strings.Count(page, `<tr><td class="name">`); n != 1 {
615 t.Errorf("the page that ends early lists %d commits, not the one it cut", n)
616 }
617 if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText {
618 t.Error("the cut commit's subject is not shown cut to maxLogText")
619 }
620 if !strings.Contains(page, `href="/source/app/log/`+tip+`?skip=1"`) {
621 t.Error("the page that ends early does not link the commits after the one it cut")
622 }
623 page = h.page(at + "?skip=1")
624 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
625 t.Errorf("the next page of history is not whole:\n%s", page)
626 }
627 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
628 t.Error("a subject longer than a page shows is not cut")
629 }
630 for _, p := range []string{at, at + "?skip=1"} {
631 if n := len(h.page(p)); n > 64<<10 {
632 t.Errorf("GET %s is %d bytes", p, n)
633 }
634 }
635}
636
637// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
638// and its page says where it stops. A README longer than a page shows is
639// shown in part.
640func TestLongFileIsShownInPart(t *testing.T) {
641 h := newHarness(t)
642 tip, bundle := h.commitMain("app: long files\n",
643 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
644 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
645 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
646 )
647 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
648
649 page := h.page("/source/app/blob/" + tip + "/newlines.txt")
650 last := fmt.Sprintf(`id="L%d"`, MaxLines)
651 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
652 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
653 }
654 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
655 t.Errorf("the page does not say %q", want)
656 }
657 if len(page) > MaxShown {
658 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
659 }
660
661 // One line of MaxFile characters that each escape to four bytes is
662 // cut where MaxShown is reached.
663 page = h.page("/source/app/blob/" + tip + "/wide.txt")
664 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
665 t.Errorf("the page of one wide line is %d bytes", len(page))
666 }
667
668 page = h.page("/source/app/tree/" + tip + "/long/")
669 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
670 t.Error("the long README is not marked as shown in part")
671 }
672 if n := strings.Count(page, "a line of the README"); n != MaxLines {
673 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
674 }
675}
676
677// Every response carries the strict policy, and the policy admits the
678// page's one inline stylesheet and one inline script by their hashes and
679// nothing from another origin.
680func TestEveryResponseCarriesTheCSP(t *testing.T) {
681 h := newHarness(t)
682 for _, c := range []struct{ method, target string }{
683 {"GET", "/"},
684 {"GET", "/knots/app/oc-a000002"},
685 {"GET", "/source/app/"},
686 {"GET", "/source/app/tree/" + h.tip() + "/"},
687 {"GET", "/source/app/blob/" + h.tip() + "/README.md"},
688 {"GET", "/no/such/page"},
689 {"POST", "/"},
690 {"HEAD", "/"},
691 } {
692 w := h.do(c.method, c.target)
693 got := w.Header().Get("Content-Security-Policy")
694 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
695 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
696 }
697 }
698 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
699 if !strings.Contains(csp, directive) {
700 t.Errorf("the policy lacks %s", directive)
701 }
702 }
703 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
704 if strings.Contains(csp, loose) {
705 t.Errorf("the policy holds %q", loose)
706 }
707 }
708
709 page := h.page("/")
710 inline := func(tag string) string {
711 t.Helper()
712 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
713 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
714 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
715 }
716 sum := sha256.Sum256([]byte(m[0][1]))
717 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
718 }
719 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
720 t.Errorf("the policy does not admit the page's script, %s", hash)
721 }
722 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
723 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
724 }
725 for _, external := range []string{"<link", " src=", "@import", "url("} {
726 if strings.Contains(page, external) {
727 t.Errorf("the plan page holds %q", external)
728 }
729 }
730}
731
732// A request serves everything from the generation it opened, though
733// another activates while it runs, and that generation outlives the
734// activation until the request releases it.
735func TestARequestKeepsItsGeneration(t *testing.T) {
736 h := newHarness(t)
737 paused, resume := make(chan export.Generation), make(chan struct{})
738 var once sync.Once
739 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
740 served := make(chan *httptest.ResponseRecorder)
741 go func() {
742 w := httptest.NewRecorder()
743 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil))
744 served <- w
745 }()
746 old := <-paused
747
748 renamed := func(title string) func(*export.Export) {
749 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
750 }
751 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
752 if next.Sequence == old.Sequence {
753 t.Fatal("the publish did not activate a new generation")
754 }
755 if _, err := os.Stat(old.Dir); err != nil {
756 t.Fatalf("the generation a request holds was deleted: %v", err)
757 }
758 close(resume)
759 w := <-served
760 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
761 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
762 }
763 if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the second plan") {
764 t.Error("the next request does not serve the new generation")
765 }
766
767 // Released, the old generation goes with the next activation.
768 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
769 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
770 t.Errorf("the released generation is still on disk: %v", err)
771 }
772}
773
774// Before the first activation the server says nothing is published, and
775// it answers GET and HEAD alone.
776func TestNothingPublishedAndMethods(t *testing.T) {
777 store, err := export.OpenStore(t.TempDir(), nil)
778 if err != nil {
779 t.Fatal(err)
780 }
781 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
782 w := httptest.NewRecorder()
783 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
784 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
785 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
786 }
787
788 h := newHarness(t)
789 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
790 w := h.do(method, "/")
791 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
792 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
793 }
794 }
795}