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