gunk-dev/the-valley

server_test.go

source026c37612e61main's published tip history
28.0 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, and nothing is fetched
237 // from another origin.
238 for _, unwanted := range []string{"/knots/site/", "/source/site/", "http://", "https://", `class="chip stale"`} {
239 if strings.Contains(page, unwanted) {
240 t.Errorf("the plan page holds %q", unwanted)
241 }
242 }
243
244 h.now = exporttest.Collected.Add(6 * time.Minute)
245 page = h.page("/")
246 if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) {
247 t.Error("an export six minutes old is not marked stale")
248 }
249}
250
251// A knot's page shows its body and comments, marks the edited comment,
252// and names a blocker in a hidden project without linking it.
253func TestKnotPage(t *testing.T) {
254 h := newHarness(t)
255 page := h.page("/knots/app/oc-a000002")
256 for _, want := range []string{
257 "Each milestone is listed with its progress.",
258 "Start with the milestones that have open children.",
259 "Claimed; the change is ready for approval.",
260 `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`,
261 `<a href="/knots/app/oc-a000001">Readers browse the app&#39;s plan</a>`,
262 } {
263 if !strings.Contains(page, want) {
264 t.Errorf("the knot's page does not show %q", want)
265 }
266 }
267 if n := strings.Count(page, ">edited<"); n != 1 {
268 t.Errorf("%d comments are marked edited; one was edited", n)
269 }
270
271 page = h.page("/knots/app/oc-a000003")
272 if !strings.Contains(page, `<a href="/knots/app/oc-a000002">The plan page lists milestones</a>`) {
273 t.Error("the local blocker is not linked")
274 }
275 if !strings.Contains(page, `<span class="mono">site:oc-b000001</span> <span class="muted">not published</span>`) {
276 t.Error("the hidden blocker is not named as not published")
277 }
278 if strings.Contains(page, "/knots/site/") || strings.Contains(page, "/source/site/") {
279 t.Error("the knot's page links into the hidden project")
280 }
281 if w := h.get("/knots/app/oc-fffffff"); w.Code != http.StatusNotFound {
282 t.Errorf("a missing knot answered %d", w.Code)
283 }
284}
285
286// A project the export does not hold as public answers every route
287// exactly as a project that does not exist, even when its repository is
288// in the generation's directory.
289func TestHiddenProjectAnswersLikeMissing(t *testing.T) {
290 h := newHarness(t)
291 g := h.active()
292 if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil {
293 t.Fatal(err)
294 }
295 siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef)
296 notFound := h.get("/knots/app/oc-fffffff")
297 for _, route := range []string{
298 "/knots/%s/oc-b000001",
299 "/source/%s",
300 "/source/%s/",
301 "/source/%s/tree/" + siteTip + "/",
302 "/source/%s/blob/" + siteTip + "/README.md",
303 "/source/%s/log/" + siteTip,
304 "/source/%s/tree/" + siteTip + "/no/such/path/",
305 "/source/%s/anything",
306 } {
307 hidden, missing := h.get(fmt.Sprintf(route, "site")), h.get(fmt.Sprintf(route, "nosuch"))
308 if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound {
309 t.Errorf("%s answered %d hidden and %d missing", route, hidden.Code, missing.Code)
310 }
311 if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) {
312 t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", route, hidden.Header(), missing.Header())
313 }
314 if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) {
315 t.Errorf("%s answered with another page hidden than missing", route)
316 }
317 }
318}
319
320// A source route serves a commit only when main's published tip reaches
321// it, and refuses every other object ID or name with the one 404.
322func TestUnreachableCommitIsRefused(t *testing.T) {
323 h := newHarness(t)
324 repo, _ := h.active().Repo("app")
325 tip := h.tip()
326 tree := git(t, repo, nil, "rev-parse", tip+"^{tree}")
327 readme := git(t, repo, nil, "rev-parse", tip+":README.md")
328 side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach")
329 parent := git(t, repo, nil, "rev-parse", tip+"~2")
330 notFound := h.get("/knots/app/oc-fffffff").Body.String()
331
332 for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} {
333 for _, route := range []string{"/source/app/tree/%s/", "/source/app/blob/%s/README.md", "/source/app/log/%s"} {
334 target := fmt.Sprintf(route, commit)
335 w := h.get(target)
336 if w.Code != http.StatusNotFound || w.Body.String() != notFound {
337 t.Errorf("GET %s answered %d, not the one 404", target, w.Code)
338 }
339 }
340 }
341
342 // A commit the tip reaches is served, as that commit had it.
343 page := h.page("/source/app/blob/" + parent + "/README.md")
344 if !strings.Contains(page, "A synthetic project for the web UI&#39;s tests.") || strings.Contains(page, "readme") {
345 t.Errorf("the first README is not served as the first commit had it:\n%s", page)
346 }
347}
348
349// The source browser lists a directory and its README, shows a file and
350// main's log, and every source link names its project, a full commit and
351// a path.
352func TestSourceBrowser(t *testing.T) {
353 h := newHarness(t)
354 tip := h.tip()
355
356 w := h.get("/source/app/")
357 if w.Code != http.StatusFound || w.Header().Get("Location") != "/source/app/tree/"+tip+"/" {
358 t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location"))
359 }
360
361 root := h.page("/source/app/tree/" + tip + "/")
362 docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<")
363 if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs {
364 t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root)
365 }
366 if !strings.Contains(root, `<pre class="text"># app`) {
367 t.Error("the root does not show its README")
368 }
369 if dir := h.page("/source/app/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") {
370 t.Error("docs/ does not list guide.md")
371 }
372 file := h.page("/source/app/blob/" + tip + "/docs/guide.md")
373 if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) {
374 t.Errorf("the file is not shown line by line:\n%s", file)
375 }
376 log := h.page("/source/app/log/" + tip)
377 first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README")
378 if first < 0 || last < first {
379 t.Errorf("the log does not list main's commits newest first:\n%s", log)
380 }
381
382 links := regexp.MustCompile(`href="(/source/[^"]*)"`)
383 named := regexp.MustCompile(`^/source/app/(tree|blob|log)/[0-9a-f]{40}(/|$)`)
384 for _, page := range []string{root, file, log} {
385 for _, m := range links.FindAllStringSubmatch(page, -1) {
386 if !named.MatchString(m[1]) {
387 t.Errorf("the link %s names no commit", m[1])
388 }
389 }
390 }
391
392 for _, target := range []string{
393 "/source/app/tree/" + tip + "/README.md/",
394 "/source/app/blob/" + tip + "/docs",
395 "/source/app/blob/" + tip + "/docs/guide.md/",
396 "/source/app/blob/" + tip + "/docs/../README.md",
397 "/source/app/blob/" + tip + "/docs%2Fguide.md",
398 "/source/app/tree/" + tip + "//",
399 "/source/app/log/" + tip + "?skip=-1",
400 } {
401 if w := h.get(target); w.Code != http.StatusNotFound {
402 t.Errorf("GET %s answered %d", target, w.Code)
403 }
404 }
405}
406
407// file is one file a test commits: its mode, path and content.
408type file struct{ mode, path, content string }
409
410// commitMain writes a commit onto the fixture's app main, with message,
411// that holds the files given beside what main holds. It returns the new
412// tip and a bundle of it. Each content is written once, however many
413// files hold it.
414func (h *harness) commitMain(message string, files ...file) (tip, bundle string) {
415 t := h.t
416 t.Helper()
417 repo := h.f.Repos["app"]
418 var b bytes.Buffer
419 data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) }
420 marks := map[string]int{}
421 for _, f := range files {
422 if _, ok := marks[f.content]; !ok {
423 marks[f.content] = len(marks) + 1
424 fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content])
425 data(f.content)
426 }
427 }
428 who := "Example Author <author@example.org> 1791190800 +0000"
429 fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who)
430 data(message)
431 fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef))
432 for _, f := range files {
433 fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path)
434 }
435 git(t, repo, b.Bytes(), "fast-import", "--quiet")
436 tip = git(t, repo, nil, "rev-parse", export.MainRef)
437 bundle = filepath.Join(t.TempDir(), "app.bundle")
438 git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main")
439 return tip, bundle
440}
441
442// publishMain activates a generation whose app main is tip, carried by
443// bundle.
444func (h *harness) publishMain(at time.Time, tip, bundle string) {
445 h.t.Helper()
446 h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip })
447}
448
449// hostileMain writes a commit onto the fixture's app main that holds a
450// file of HTML, a file larger than a page shows, a binary file, a file
451// whose name is HTML, and a symbolic link out of the repository. It
452// returns the new tip and a bundle of it.
453func (h *harness) hostileMain() (tip, bundle string) {
454 return h.commitMain("hostile: <script>alert(\"subject\")</script>\n",
455 file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"},
456 file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)},
457 file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"},
458 file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"},
459 file{"120000", "link", "../../etc/passwd"},
460 )
461}
462
463// HTML, scripts, large files and binary files from a repository or the
464// plan render inert: escaped as text, or not shown.
465func TestHostileContentRendersInert(t *testing.T) {
466 h := newHarness(t)
467 tip, bundle := h.hostileMain()
468 h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) {
469 e.Projects[0].SourceTip = tip
470 })
471
472 inert := func(target, page string, wants ...string) {
473 t.Helper()
474 // Escaped, a tag is text; only a tag the page did not escape, or
475 // an attribute it let a value break out into, is active.
476 for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} {
477 if strings.Contains(page, active) {
478 t.Errorf("GET %s holds %q", target, active)
479 }
480 }
481 for _, want := range wants {
482 if !strings.Contains(page, want) {
483 t.Errorf("GET %s does not show %q", target, want)
484 }
485 }
486 }
487 at := "/source/app/tree/" + tip + "/"
488 inert(at, h.page(at),
489 `&lt;script&gt;alert(&#34;readme&#34;)&lt;/script&gt;`,
490 `&lt;img src=x onerror=alert(3)&gt;.txt`,
491 `href="/source/app/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`)
492 at = "/source/app/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"
493 inert(at, h.page(at), ">named<")
494 at = "/source/app/blob/" + tip + "/page.html"
495 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;`)
496 at = "/source/app/blob/" + tip + "/big.txt"
497 page := h.page(at)
498 inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.")
499 if len(page) > 64<<10 {
500 t.Errorf("the large file's page is %d bytes", len(page))
501 }
502 at = "/source/app/blob/" + tip + "/binary.bin"
503 inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.")
504 at = "/source/app/blob/" + tip + "/link"
505 inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.")
506 at = "/source/app/log/" + tip
507 inert(at, h.page(at), "hostile: &lt;script&gt;alert(&#34;subject&#34;)&lt;/script&gt;")
508
509 at = "/knots/app/bd-a000004"
510 inert(at, h.page(at),
511 `A README holding &lt;script&gt;alert(&#34;knot&#34;)&lt;/script&gt; must show as text.`,
512 `Also &lt;img src=x onerror=alert(1)&gt; in a comment.`)
513}
514
515// A directory larger than a page reads is listed in part, and a commit
516// message larger than a page reads ends its page of history early. git
517// is stopped once its listing passes MaxRead, and nothing past a record's
518// bound is kept.
519func TestOversizedTreeAndHistory(t *testing.T) {
520 h := newHarness(t)
521 // Each entry of huge/ takes 308 bytes of git ls-tree's output, so
522 // 15,000 of them pass MaxRead at about entry 13,600.
523 longest := "!" + strings.Repeat("l", 4095)
524 files := []file{{"100644", "huge/" + longest, "x\n"}}
525 name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) }
526 for i := range 15_000 {
527 files = append(files, file{"100644", "huge/" + name(i), "x\n"})
528 }
529 if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead {
530 t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n)
531 }
532 h.commitMain("app: a directory larger than a page reads\n", files...)
533 h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n")
534 tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n")
535 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
536
537 at := "/source/app/tree/" + tip + "/huge/"
538 page := h.page(at)
539 if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") {
540 t.Error("huge/ is not marked as listed in part")
541 }
542 if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries {
543 t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries)
544 }
545 if !strings.Contains(page, `">`+longest+`</a>`) {
546 t.Error("the entry with the longest name git accepts is not listed whole")
547 }
548 if len(page) > 1<<20 {
549 t.Errorf("huge/'s page is %d bytes", len(page))
550 }
551 if w := h.get("/source/app/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK {
552 t.Errorf("an entry read before MaxRead answered %d", w.Code)
553 }
554 if w := h.get("/source/app/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound {
555 t.Errorf("an entry past MaxRead answered %d", w.Code)
556 }
557
558 at = "/source/app/log/" + tip
559 page = h.page(at)
560 if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") {
561 t.Error("the page of history holding a 5 MiB message does not end early")
562 }
563 if n := strings.Count(page, `<tr><td class="name">`); n != 1 {
564 t.Errorf("the page that ends early lists %d commits, not the one it cut", n)
565 }
566 if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText {
567 t.Error("the cut commit's subject is not shown cut to maxLogText")
568 }
569 if !strings.Contains(page, `href="/source/app/log/`+tip+`?skip=1"`) {
570 t.Error("the page that ends early does not link the commits after the one it cut")
571 }
572 page = h.page(at + "?skip=1")
573 if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") {
574 t.Errorf("the next page of history is not whole:\n%s", page)
575 }
576 if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) {
577 t.Error("a subject longer than a page shows is not cut")
578 }
579 for _, p := range []string{at, at + "?skip=1"} {
580 if n := len(h.page(p)); n > 64<<10 {
581 t.Errorf("GET %s is %d bytes", p, n)
582 }
583 }
584}
585
586// A file of exactly MaxFile bytes of newlines is shown to MaxLines lines,
587// and its page says where it stops. A README longer than a page shows is
588// shown in part.
589func TestLongFileIsShownInPart(t *testing.T) {
590 h := newHarness(t)
591 tip, bundle := h.commitMain("app: long files\n",
592 file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)},
593 file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)},
594 file{"100644", "wide.txt", strings.Repeat("<", MaxFile)},
595 )
596 h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle)
597
598 page := h.page("/source/app/blob/" + tip + "/newlines.txt")
599 last := fmt.Sprintf(`id="L%d"`, MaxLines)
600 if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) {
601 t.Errorf("the file of newlines is not shown to line %d", MaxLines)
602 }
603 if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) {
604 t.Errorf("the page does not say %q", want)
605 }
606 if len(page) > MaxShown {
607 t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page))
608 }
609
610 // One line of MaxFile characters that each escape to four bytes is
611 // cut where MaxShown is reached.
612 page = h.page("/source/app/blob/" + tip + "/wide.txt")
613 if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 {
614 t.Errorf("the page of one wide line is %d bytes", len(page))
615 }
616
617 page = h.page("/source/app/tree/" + tip + "/long/")
618 if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") {
619 t.Error("the long README is not marked as shown in part")
620 }
621 if n := strings.Count(page, "a line of the README"); n != MaxLines {
622 t.Errorf("the long README shows %d lines, not %d", n, MaxLines)
623 }
624}
625
626// Every response carries the strict policy, and the policy admits the
627// page's one inline stylesheet and one inline script by their hashes and
628// nothing from another origin.
629func TestEveryResponseCarriesTheCSP(t *testing.T) {
630 h := newHarness(t)
631 for _, c := range []struct{ method, target string }{
632 {"GET", "/"},
633 {"GET", "/knots/app/oc-a000002"},
634 {"GET", "/source/app/"},
635 {"GET", "/source/app/tree/" + h.tip() + "/"},
636 {"GET", "/source/app/blob/" + h.tip() + "/README.md"},
637 {"GET", "/no/such/page"},
638 {"POST", "/"},
639 {"HEAD", "/"},
640 } {
641 w := h.do(c.method, c.target)
642 got := w.Header().Get("Content-Security-Policy")
643 if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" {
644 t.Errorf("%s %s answered with policy %q", c.method, c.target, got)
645 }
646 }
647 for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} {
648 if !strings.Contains(csp, directive) {
649 t.Errorf("the policy lacks %s", directive)
650 }
651 }
652 for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} {
653 if strings.Contains(csp, loose) {
654 t.Errorf("the policy holds %q", loose)
655 }
656 }
657
658 page := h.page("/")
659 inline := func(tag string) string {
660 t.Helper()
661 m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1)
662 if len(m) != 1 || strings.Count(page, "<"+tag) != 1 {
663 t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag)
664 }
665 sum := sha256.Sum256([]byte(m[0][1]))
666 return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'"
667 }
668 if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") {
669 t.Errorf("the policy does not admit the page's script, %s", hash)
670 }
671 if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") {
672 t.Errorf("the policy does not admit the page's stylesheet, %s", hash)
673 }
674 for _, external := range []string{"<link", " src=", "@import", "url("} {
675 if strings.Contains(page, external) {
676 t.Errorf("the plan page holds %q", external)
677 }
678 }
679}
680
681// A request serves everything from the generation it opened, though
682// another activates while it runs, and that generation outlives the
683// activation until the request releases it.
684func TestARequestKeepsItsGeneration(t *testing.T) {
685 h := newHarness(t)
686 paused, resume := make(chan export.Generation), make(chan struct{})
687 var once sync.Once
688 h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) }
689 served := make(chan *httptest.ResponseRecorder)
690 go func() {
691 w := httptest.NewRecorder()
692 h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil))
693 served <- w
694 }()
695 old := <-paused
696
697 renamed := func(title string) func(*export.Export) {
698 return func(e *export.Export) { e.Projects[0].Knots[0].Title = title }
699 }
700 next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan"))
701 if next.Sequence == old.Sequence {
702 t.Fatal("the publish did not activate a new generation")
703 }
704 if _, err := os.Stat(old.Dir); err != nil {
705 t.Fatalf("the generation a request holds was deleted: %v", err)
706 }
707 close(resume)
708 w := <-served
709 if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app&#39;s plan") || strings.Contains(body, "second plan") {
710 t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body)
711 }
712 if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the second plan") {
713 t.Error("the next request does not serve the new generation")
714 }
715
716 // Released, the old generation goes with the next activation.
717 h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan"))
718 if _, err := os.Stat(old.Dir); !os.IsNotExist(err) {
719 t.Errorf("the released generation is still on disk: %v", err)
720 }
721}
722
723// Before the first activation the server says nothing is published, and
724// it answers GET and HEAD alone.
725func TestNothingPublishedAndMethods(t *testing.T) {
726 store, err := export.OpenStore(t.TempDir(), nil)
727 if err != nil {
728 t.Fatal(err)
729 }
730 srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
731 w := httptest.NewRecorder()
732 srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
733 if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") {
734 t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body)
735 }
736
737 h := newHarness(t)
738 for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} {
739 w := h.do(method, "/")
740 if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" {
741 t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow"))
742 }
743 }
744}