| 1 | package server |
| 2 | |
| 3 | import ( |
| 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. |
| 26 | type 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. |
| 36 | func 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 | |
| 50 | func (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 | |
| 57 | func (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. |
| 63 | func (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. |
| 73 | func (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. |
| 77 | func (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. |
| 143 | func (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. |
| 155 | func 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. |
| 179 | func 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. |
| 192 | func 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'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. |
| 253 | func 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'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. |
| 289 | func 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. |
| 322 | func 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'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. |
| 352 | func 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 | // hostileMain writes a commit onto the fixture's app main that holds a |
| 408 | // file of HTML, a file larger than a page shows, a binary file, a file |
| 409 | // whose name is HTML, and a symbolic link out of the repository. It |
| 410 | // returns the new tip and a bundle of it. |
| 411 | func (h *harness) hostileMain() (tip, bundle string) { |
| 412 | t := h.t |
| 413 | repo := h.f.Repos["app"] |
| 414 | var b bytes.Buffer |
| 415 | data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) } |
| 416 | who := "Example Author <author@example.org> 1791190800 +0000" |
| 417 | fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who) |
| 418 | data("hostile: <script>alert(\"subject\")</script>\n") |
| 419 | fmt.Fprintf(&b, "from %s\n", h.tip()) |
| 420 | for _, f := range []struct{ mode, path, content string }{ |
| 421 | {"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"}, |
| 422 | {"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)}, |
| 423 | {"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"}, |
| 424 | {"100644", "<img src=x onerror=alert(3)>.txt", "named\n"}, |
| 425 | {"120000", "link", "../../etc/passwd"}, |
| 426 | } { |
| 427 | fmt.Fprintf(&b, "M %s inline %s\n", f.mode, f.path) |
| 428 | data(f.content) |
| 429 | } |
| 430 | git(t, repo, b.Bytes(), "fast-import", "--quiet") |
| 431 | tip = git(t, repo, nil, "rev-parse", export.MainRef) |
| 432 | bundle = filepath.Join(t.TempDir(), "app.bundle") |
| 433 | git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main") |
| 434 | return tip, bundle |
| 435 | } |
| 436 | |
| 437 | // HTML, scripts, large files and binary files from a repository or the |
| 438 | // plan render inert: escaped as text, or not shown. |
| 439 | func TestHostileContentRendersInert(t *testing.T) { |
| 440 | h := newHarness(t) |
| 441 | tip, bundle := h.hostileMain() |
| 442 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 443 | e.Projects[0].SourceTip = tip |
| 444 | }) |
| 445 | |
| 446 | inert := func(target, page string, wants ...string) { |
| 447 | t.Helper() |
| 448 | // Escaped, a tag is text; only a tag the page did not escape, or |
| 449 | // an attribute it let a value break out into, is active. |
| 450 | for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} { |
| 451 | if strings.Contains(page, active) { |
| 452 | t.Errorf("GET %s holds %q", target, active) |
| 453 | } |
| 454 | } |
| 455 | for _, want := range wants { |
| 456 | if !strings.Contains(page, want) { |
| 457 | t.Errorf("GET %s does not show %q", target, want) |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | at := "/source/app/tree/" + tip + "/" |
| 462 | inert(at, h.page(at), |
| 463 | `<script>alert("readme")</script>`, |
| 464 | `<img src=x onerror=alert(3)>.txt`, |
| 465 | `href="/source/app/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`) |
| 466 | at = "/source/app/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt" |
| 467 | inert(at, h.page(at), ">named<") |
| 468 | at = "/source/app/blob/" + tip + "/page.html" |
| 469 | inert(at, h.page(at), `<html><script>alert("file")</script><img src=x onerror=alert(2)></html>`) |
| 470 | at = "/source/app/blob/" + tip + "/big.txt" |
| 471 | page := h.page(at) |
| 472 | inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.") |
| 473 | if len(page) > 64<<10 { |
| 474 | t.Errorf("the large file's page is %d bytes", len(page)) |
| 475 | } |
| 476 | at = "/source/app/blob/" + tip + "/binary.bin" |
| 477 | inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.") |
| 478 | at = "/source/app/blob/" + tip + "/link" |
| 479 | inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.") |
| 480 | at = "/source/app/log/" + tip |
| 481 | inert(at, h.page(at), "hostile: <script>alert("subject")</script>") |
| 482 | |
| 483 | at = "/knots/app/bd-a000004" |
| 484 | inert(at, h.page(at), |
| 485 | `A README holding <script>alert("knot")</script> must show as text.`, |
| 486 | `Also <img src=x onerror=alert(1)> in a comment.`) |
| 487 | } |
| 488 | |
| 489 | // Every response carries the strict policy, and the policy admits the |
| 490 | // page's one inline stylesheet and one inline script by their hashes and |
| 491 | // nothing from another origin. |
| 492 | func TestEveryResponseCarriesTheCSP(t *testing.T) { |
| 493 | h := newHarness(t) |
| 494 | for _, c := range []struct{ method, target string }{ |
| 495 | {"GET", "/"}, |
| 496 | {"GET", "/knots/app/oc-a000002"}, |
| 497 | {"GET", "/source/app/"}, |
| 498 | {"GET", "/source/app/tree/" + h.tip() + "/"}, |
| 499 | {"GET", "/source/app/blob/" + h.tip() + "/README.md"}, |
| 500 | {"GET", "/no/such/page"}, |
| 501 | {"POST", "/"}, |
| 502 | {"HEAD", "/"}, |
| 503 | } { |
| 504 | w := h.do(c.method, c.target) |
| 505 | got := w.Header().Get("Content-Security-Policy") |
| 506 | if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" { |
| 507 | t.Errorf("%s %s answered with policy %q", c.method, c.target, got) |
| 508 | } |
| 509 | } |
| 510 | for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} { |
| 511 | if !strings.Contains(csp, directive) { |
| 512 | t.Errorf("the policy lacks %s", directive) |
| 513 | } |
| 514 | } |
| 515 | for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} { |
| 516 | if strings.Contains(csp, loose) { |
| 517 | t.Errorf("the policy holds %q", loose) |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | page := h.page("/") |
| 522 | inline := func(tag string) string { |
| 523 | t.Helper() |
| 524 | m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1) |
| 525 | if len(m) != 1 || strings.Count(page, "<"+tag) != 1 { |
| 526 | t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag) |
| 527 | } |
| 528 | sum := sha256.Sum256([]byte(m[0][1])) |
| 529 | return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" |
| 530 | } |
| 531 | if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") { |
| 532 | t.Errorf("the policy does not admit the page's script, %s", hash) |
| 533 | } |
| 534 | if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") { |
| 535 | t.Errorf("the policy does not admit the page's stylesheet, %s", hash) |
| 536 | } |
| 537 | for _, external := range []string{"<link", " src=", "@import", "url("} { |
| 538 | if strings.Contains(page, external) { |
| 539 | t.Errorf("the plan page holds %q", external) |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | // A request serves everything from the generation it opened, though |
| 545 | // another activates while it runs, and that generation outlives the |
| 546 | // activation until the request releases it. |
| 547 | func TestARequestKeepsItsGeneration(t *testing.T) { |
| 548 | h := newHarness(t) |
| 549 | paused, resume := make(chan export.Generation), make(chan struct{}) |
| 550 | var once sync.Once |
| 551 | h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) } |
| 552 | served := make(chan *httptest.ResponseRecorder) |
| 553 | go func() { |
| 554 | w := httptest.NewRecorder() |
| 555 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/knots/app/oc-a000001", nil)) |
| 556 | served <- w |
| 557 | }() |
| 558 | old := <-paused |
| 559 | |
| 560 | renamed := func(title string) func(*export.Export) { |
| 561 | return func(e *export.Export) { e.Projects[0].Knots[0].Title = title } |
| 562 | } |
| 563 | next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 564 | if next.Sequence == old.Sequence { |
| 565 | t.Fatal("the publish did not activate a new generation") |
| 566 | } |
| 567 | if _, err := os.Stat(old.Dir); err != nil { |
| 568 | t.Fatalf("the generation a request holds was deleted: %v", err) |
| 569 | } |
| 570 | close(resume) |
| 571 | w := <-served |
| 572 | if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app's plan") || strings.Contains(body, "second plan") { |
| 573 | t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body) |
| 574 | } |
| 575 | if !strings.Contains(h.page("/knots/app/oc-a000001"), "Readers browse the second plan") { |
| 576 | t.Error("the next request does not serve the new generation") |
| 577 | } |
| 578 | |
| 579 | // Released, the old generation goes with the next activation. |
| 580 | h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 581 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 582 | t.Errorf("the released generation is still on disk: %v", err) |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | // Before the first activation the server says nothing is published, and |
| 587 | // it answers GET and HEAD alone. |
| 588 | func TestNothingPublishedAndMethods(t *testing.T) { |
| 589 | store, err := export.OpenStore(t.TempDir(), nil) |
| 590 | if err != nil { |
| 591 | t.Fatal(err) |
| 592 | } |
| 593 | srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }}) |
| 594 | w := httptest.NewRecorder() |
| 595 | srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 596 | if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") { |
| 597 | t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body) |
| 598 | } |
| 599 | |
| 600 | h := newHarness(t) |
| 601 | for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} { |
| 602 | w := h.do(method, "/") |
| 603 | if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" { |
| 604 | t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow")) |
| 605 | } |
| 606 | } |
| 607 | } |