| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "archive/tar" |
| 5 | "bufio" |
| 6 | "bytes" |
| 7 | "compress/gzip" |
| 8 | "context" |
| 9 | "crypto/sha256" |
| 10 | "encoding/base64" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "io" |
| 14 | "net" |
| 15 | "net/http" |
| 16 | "net/http/httptest" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "path/filepath" |
| 20 | "regexp" |
| 21 | "runtime" |
| 22 | "slices" |
| 23 | "strconv" |
| 24 | "strings" |
| 25 | "sync" |
| 26 | "sync/atomic" |
| 27 | "syscall" |
| 28 | "testing" |
| 29 | "time" |
| 30 | |
| 31 | "the-valley/knot" |
| 32 | "the-valley/web/export" |
| 33 | "the-valley/web/export/exporttest" |
| 34 | ) |
| 35 | |
| 36 | // harness is a server over a real store that the fixture's export was |
| 37 | // uploaded to, with a clock the test sets. |
| 38 | type harness struct { |
| 39 | t *testing.T |
| 40 | f *exporttest.Fixture |
| 41 | store *export.Store |
| 42 | srv *Server |
| 43 | now time.Time |
| 44 | } |
| 45 | |
| 46 | // newHarness serves the fixture's export, two minutes after it was |
| 47 | // collected. |
| 48 | func newHarness(t *testing.T) *harness { |
| 49 | t.Helper() |
| 50 | f := exporttest.New(t) |
| 51 | store, err := export.OpenStore(exporttest.StorePath(t), func(err error) { t.Errorf("the store reported: %v", err) }) |
| 52 | if err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | f.Upload(t, store) |
| 56 | h := &harness{t: t, f: f, store: store, now: exporttest.Collected.Add(2 * time.Minute)} |
| 57 | h.srv = New(Config{Store: store, Now: func() time.Time { return h.now }, |
| 58 | Log: func(err error) { t.Errorf("the server logged: %v", err) }}) |
| 59 | return h |
| 60 | } |
| 61 | |
| 62 | func (h *harness) do(method, target string) *httptest.ResponseRecorder { |
| 63 | h.t.Helper() |
| 64 | w := httptest.NewRecorder() |
| 65 | h.srv.ServeHTTP(w, httptest.NewRequest(method, target, nil)) |
| 66 | return w |
| 67 | } |
| 68 | |
| 69 | func (h *harness) get(target string) *httptest.ResponseRecorder { |
| 70 | h.t.Helper() |
| 71 | return h.do("GET", target) |
| 72 | } |
| 73 | |
| 74 | // page is the body of a GET that must answer 200. |
| 75 | func (h *harness) page(target string) string { |
| 76 | h.t.Helper() |
| 77 | w := h.get(target) |
| 78 | if w.Code != http.StatusOK { |
| 79 | h.t.Fatalf("GET %s answered %d:\n%s", target, w.Code, w.Body) |
| 80 | } |
| 81 | return w.Body.String() |
| 82 | } |
| 83 | |
| 84 | // tip is the fixture's published source tip of app. |
| 85 | func (h *harness) tip() string { return h.f.Export.Projects[0].SourceTip } |
| 86 | |
| 87 | // publish activates a new generation, signed at: the fixture's export |
| 88 | // changed by change, with the bundles given, by project, in place of the |
| 89 | // fixture's. |
| 90 | func (h *harness) publish(at time.Time, bundles map[string]string, change func(*export.Export)) export.Generation { |
| 91 | t := h.t |
| 92 | t.Helper() |
| 93 | e, err := export.Decode(h.f.ExportJSON) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | change(e) |
| 98 | h.authorizeAll(e) |
| 99 | data, err := e.Encode() |
| 100 | if err != nil { |
| 101 | t.Fatal(err) |
| 102 | } |
| 103 | paths := map[string]string{} |
| 104 | for _, p := range e.Projects { |
| 105 | if paths[p.Name] = bundles[p.Name]; paths[p.Name] == "" { |
| 106 | paths[p.Name] = h.f.Bundles[p.Name] |
| 107 | } |
| 108 | } |
| 109 | bodies := map[string]export.Body{} |
| 110 | for name, path := range paths { |
| 111 | if bodies[name], err = export.FileBody(name, path); err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | } |
| 115 | m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, at.UnixNano(), e, data, bodies) |
| 116 | if err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | hw, err := h.store.HighWater() |
| 120 | if err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | a := h.f.Admission() |
| 124 | a.Now, a.HighWater = at.Add(time.Second), hw |
| 125 | if m, err = export.VerifyManifest(bytes.NewReader(h.f.Sign(t, m)), a); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | st, err := h.store.Stage(context.Background(), m) |
| 129 | if err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | inv, err := h.store.Inventory(st) |
| 133 | if err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | for _, need := range inv.Needs { |
| 137 | body := data |
| 138 | if need.Name != export.ExportFile { |
| 139 | if body, err = os.ReadFile(paths[need.Name]); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | } |
| 143 | req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(body)) |
| 144 | if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | } |
| 148 | g, err := h.store.Activate(context.Background(), st) |
| 149 | if err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | return g |
| 153 | } |
| 154 | |
| 155 | // authorizeAll stores an authorization that lets anyone read every |
| 156 | // project of e, unless the stored one does already. |
| 157 | func (h *harness) authorizeAll(e *export.Export) { |
| 158 | h.t.Helper() |
| 159 | a, _, err := h.store.Authorization() |
| 160 | if err != nil { |
| 161 | h.t.Fatal(err) |
| 162 | } |
| 163 | all := true |
| 164 | for _, p := range e.Projects { |
| 165 | all = all && a.Allows(export.Anyone, p.Name, p.Identity) |
| 166 | } |
| 167 | if all { |
| 168 | return |
| 169 | } |
| 170 | next := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, |
| 171 | Sequence: a.Sequence + 1, Checked: a.Checked} |
| 172 | for _, p := range e.Projects { |
| 173 | next.Projects = append(next.Projects, export.AuthorizedProject{Name: p.Name, Identity: p.Identity, Readers: []string{export.Anyone}}) |
| 174 | } |
| 175 | h.authorize(next) |
| 176 | } |
| 177 | |
| 178 | // authorize stores the authorization a, as the receiver does. |
| 179 | func (h *harness) authorize(a *export.Authorization) { |
| 180 | h.t.Helper() |
| 181 | if err := h.store.Authorize(context.Background(), a, exporttest.SignAuthorization(h.t, a)); err != nil { |
| 182 | h.t.Fatal(err) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // active is the generation the store serves. |
| 187 | func (h *harness) active() export.Generation { |
| 188 | h.t.Helper() |
| 189 | g, release, err := h.store.Open() |
| 190 | if err != nil { |
| 191 | h.t.Fatal(err) |
| 192 | } |
| 193 | release() |
| 194 | return g |
| 195 | } |
| 196 | |
| 197 | // git runs git on the repository at repo, with no configuration of the |
| 198 | // caller's and a fixed identity for the commits it writes. |
| 199 | func git(t *testing.T, repo string, stdin []byte, args ...string) string { |
| 200 | t.Helper() |
| 201 | cmd := exec.Command(export.GitProgram, append([]string{"--git-dir=" + repo}, args...)...) |
| 202 | for _, kv := range os.Environ() { |
| 203 | if !strings.HasPrefix(kv, "GIT_") { |
| 204 | cmd.Env = append(cmd.Env, kv) |
| 205 | } |
| 206 | } |
| 207 | cmd.Env = append(cmd.Env, "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", |
| 208 | "GIT_AUTHOR_NAME=Example Author", "GIT_AUTHOR_EMAIL=author@example.org", "GIT_AUTHOR_DATE=1791190800 +0000", |
| 209 | "GIT_COMMITTER_NAME=Example Author", "GIT_COMMITTER_EMAIL=author@example.org", "GIT_COMMITTER_DATE=1791190800 +0000") |
| 210 | if stdin != nil { |
| 211 | cmd.Stdin = bytes.NewReader(stdin) |
| 212 | } |
| 213 | var out, stderr bytes.Buffer |
| 214 | cmd.Stdout, cmd.Stderr = &out, &stderr |
| 215 | if err := exporttest.Run(t, cmd, 2*time.Minute); err != nil { |
| 216 | t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr.String()) |
| 217 | } |
| 218 | return strings.TrimSpace(out.String()) |
| 219 | } |
| 220 | |
| 221 | // section is the part of a page from one marker up to the next. |
| 222 | func section(t *testing.T, page, from, to string) string { |
| 223 | t.Helper() |
| 224 | i := strings.Index(page, from) |
| 225 | j := strings.Index(page[max(i, 0):], to) |
| 226 | if i < 0 || j < 0 { |
| 227 | t.Fatalf("the page has no section from %q to %q", from, to) |
| 228 | } |
| 229 | return page[i : i+j] |
| 230 | } |
| 231 | |
| 232 | // The plan page keeps the template's reading order, says what free to |
| 233 | // start means, shows the ready changes as one card in no order, and |
| 234 | // shows how old the export is. |
| 235 | func TestPlanPage(t *testing.T) { |
| 236 | h := newHarness(t) |
| 237 | page := h.page("/") |
| 238 | |
| 239 | at := -1 |
| 240 | for _, heading := range []string{">Waiting on you<", ">In flight<", ">Paths<", ">Milestones<"} { |
| 241 | i := strings.Index(page, heading) |
| 242 | if i <= at { |
| 243 | t.Fatalf("%s is not where the reading order puts it", heading) |
| 244 | } |
| 245 | at = i |
| 246 | } |
| 247 | for _, want := range []string{ |
| 248 | "free to start: an open, unclaimed, unblocked outcome or bug", |
| 249 | "Nothing here waits on you.", |
| 250 | "Ready changes — order not assessed", |
| 251 | `<span class="handle">kmno</span>`, "plan: list the milestones", "app v2", "approved · integrator: stale", |
| 252 | "Collected 2026-10-25 12:00 UTC. Policy last checked 2026-10-25 12:00 UTC, 2 minutes ago", |
| 253 | "claimed by agent 2 hours ago", |
| 254 | "in progress, unclaimed", |
| 255 | "Readers browse the app's plan", "1 of 5 done", |
| 256 | "Unfiled", "Render Markdown in a later slice", |
| 257 | `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`, |
| 258 | } { |
| 259 | if !strings.Contains(page, want) { |
| 260 | t.Errorf("the plan page does not show %q", want) |
| 261 | } |
| 262 | } |
| 263 | if strings.Count(page, "Ready changes") != 1 { |
| 264 | t.Error("the ready changes are not one card") |
| 265 | } |
| 266 | |
| 267 | // The bug nobody claims and nothing blocks is free to start. |
| 268 | 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="/tools/app/knots/bd-a000004">`) { |
| 269 | t.Error("bd-a000004 is not shown as free to start") |
| 270 | } |
| 271 | |
| 272 | // The milestone's path puts oc-a000003 after the knot it waits on. |
| 273 | paths := section(t, page, `id="paths-h"`, `id="ms-h"`) |
| 274 | second := strings.Index(paths, `<span class="stage-num">2</span>`) |
| 275 | if second < 0 || strings.Index(paths, "oc-a000002") > second || strings.Index(paths, "oc-a000003") < second { |
| 276 | t.Errorf("the path does not order oc-a000003 after oc-a000002:\n%s", paths) |
| 277 | } |
| 278 | |
| 279 | // Nothing of the hidden project is linked or named, and nothing is |
| 280 | // fetched from another origin. |
| 281 | for _, want := range []string{"lands in an unpublished project", "lands in a knot in an unpublished project"} { |
| 282 | if !strings.Contains(page, want) { |
| 283 | t.Errorf("the plan page does not show %q", want) |
| 284 | } |
| 285 | } |
| 286 | for _, unwanted := range append([]string{"/tools/site/knots/", "/tools/site/source/", "/site/knots/", "/site/source/", "http://", "https://", `class="chip stale"`}, unpublishedText...) { |
| 287 | if strings.Contains(page, unwanted) { |
| 288 | t.Errorf("the plan page holds %q", unwanted) |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | h.now = exporttest.Collected.Add(6 * time.Minute) |
| 293 | page = h.page("/") |
| 294 | if !strings.Contains(page, `Collected 2026-10-25 12:00 UTC. Policy last checked 2026-10-25 12:00 UTC, 6 minutes ago <span class="chip stale">stale</span>`) { |
| 295 | t.Error("a policy check six minutes old is not marked stale") |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | // A blocked knot's chip names the published knots it waits on, and says |
| 300 | // once that it also waits on unpublished work, naming nothing of it: |
| 301 | // oc-a000003 waits on oc-a000002 and on a knot of the hidden site, which |
| 302 | // the export leaves out of waiting_on and marks with waiting_on_hidden. |
| 303 | // A knot waiting on unpublished work alone says only that. An export |
| 304 | // without the field, as v1 exports before it, is read, and its chip |
| 305 | // names what waiting_on holds. |
| 306 | func TestWaitsOnChip(t *testing.T) { |
| 307 | h := newHarness(t) |
| 308 | chip := func(text string) string { return `<span class="chip blocked">waits on ` + text + `</span>` } |
| 309 | cases := []struct { |
| 310 | name string |
| 311 | change func(*export.Knot) |
| 312 | want string |
| 313 | }{ |
| 314 | {"a published and an unpublished blocker", func(*export.Knot) {}, "oc-a000002, a knot in an unpublished project"}, |
| 315 | {"two published blockers and an unpublished one", func(k *export.Knot) { k.WaitingOn = append(k.WaitingOn, "oc-a000006") }, |
| 316 | "oc-a000002, oc-a000006, a knot in an unpublished project"}, |
| 317 | {"an unpublished blocker alone", func(k *export.Knot) { k.WaitingOn = []string{} }, "a knot in an unpublished project"}, |
| 318 | {"an export without waiting_on_hidden", func(k *export.Knot) { k.WaitingOnHidden = false }, "oc-a000002"}, |
| 319 | } |
| 320 | for i, c := range cases { |
| 321 | t.Run(c.name, func(t *testing.T) { |
| 322 | h.publish(exporttest.SignedAt.Add(time.Duration(i+1)*time.Minute), nil, func(e *export.Export) { |
| 323 | for j := range e.Projects[0].Knots { |
| 324 | if k := &e.Projects[0].Knots[j]; k.ID == "oc-a000003" { |
| 325 | if !k.WaitingOnHidden { |
| 326 | t.Fatal("the fixture's oc-a000003 does not carry waiting_on_hidden") |
| 327 | } |
| 328 | c.change(k) |
| 329 | } |
| 330 | } |
| 331 | }) |
| 332 | page := h.page("/") |
| 333 | if !strings.Contains(page, chip(c.want)) { |
| 334 | t.Errorf("the plan page does not show %q:\n%s", chip(c.want), section(t, page, `id="ms-h"`, "</body>")) |
| 335 | } |
| 336 | if n := strings.Count(page, `<span class="chip blocked">`); n != 1 { |
| 337 | t.Errorf("the plan page shows %d blocked chips", n) |
| 338 | } |
| 339 | for _, unwanted := range unpublishedText { |
| 340 | if strings.Contains(page, unwanted) { |
| 341 | t.Errorf("the plan page holds %q", unwanted) |
| 342 | } |
| 343 | } |
| 344 | }) |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // unpublishedText is what of the hidden project site the fixture's |
| 349 | // references hold: its name and its knots' IDs. No page shows any of it. |
| 350 | var unpublishedText = []string{"site:", "oc-b000001", "oc-b000002", "lands in site", ">site<", "valley:site"} |
| 351 | |
| 352 | // A knot's page shows its body and comments, and marks the edited |
| 353 | // comment. A reference into a hidden project is shown as unpublished, |
| 354 | // with nothing of its text, and a missing knot of a public project is |
| 355 | // named as missing. |
| 356 | func TestKnotPage(t *testing.T) { |
| 357 | h := newHarness(t) |
| 358 | page := h.page("/tools/app/knots/oc-a000002") |
| 359 | for _, want := range []string{ |
| 360 | "Each milestone is listed with its progress.", |
| 361 | "Start with the milestones that have open children.", |
| 362 | "Claimed; the change is ready for approval.", |
| 363 | `<span class="chip quiet">edited</span><span>2026-10-25 10:30 UTC by agent</span>`, |
| 364 | `<a href="/tools/app/knots/oc-a000001">Readers browse the app's plan</a>`, |
| 365 | } { |
| 366 | if !strings.Contains(page, want) { |
| 367 | t.Errorf("the knot's page does not show %q", want) |
| 368 | } |
| 369 | } |
| 370 | if n := strings.Count(page, ">edited<"); n != 1 { |
| 371 | t.Errorf("%d comments are marked edited; one was edited", n) |
| 372 | } |
| 373 | |
| 374 | page = h.page("/tools/app/knots/oc-a000003") |
| 375 | if !strings.Contains(page, `<a href="/tools/app/knots/oc-a000002">The plan page lists milestones</a>`) { |
| 376 | t.Error("the local blocker is not linked") |
| 377 | } |
| 378 | for _, want := range []string{ |
| 379 | `<span class="nochild"></span><span class="t"><span class="muted">a knot in an unpublished project</span></span>`, |
| 380 | "<dt>Lands in</dt><dd>an unpublished project</dd>", |
| 381 | } { |
| 382 | if !strings.Contains(page, want) { |
| 383 | t.Errorf("the knot's page does not show %q", want) |
| 384 | } |
| 385 | } |
| 386 | page += h.page("/tools/app/knots/bd-a000004") |
| 387 | if !strings.Contains(page, "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>") { |
| 388 | t.Error("a target in the hidden project is not shown as unpublished") |
| 389 | } |
| 390 | for _, unwanted := range append([]string{"/tools/site/knots/", "/tools/site/source/", "/site/knots/", "/site/source/"}, unpublishedText...) { |
| 391 | if strings.Contains(page, unwanted) { |
| 392 | t.Errorf("the knot's page shows %q", unwanted) |
| 393 | } |
| 394 | } |
| 395 | if w := h.get("/tools/app/knots/oc-fffffff"); w.Code != http.StatusNotFound { |
| 396 | t.Errorf("a missing knot answered %d", w.Code) |
| 397 | } |
| 398 | |
| 399 | // A knot of a public project the graph does not hold, and a local |
| 400 | // knot that is not there, are named as missing. A change of the |
| 401 | // hidden project is not named. |
| 402 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) { |
| 403 | for i := range e.Projects[0].Knots { |
| 404 | if k := &e.Projects[0].Knots[i]; k.ID == "oc-a000003" { |
| 405 | k.BlockedBy = append(k.BlockedBy, "app:oc-fffffff", "oc-eeeeeee") |
| 406 | k.Edges = append(k.Edges, export.Edge{Field: "blocked_by", Ref: "app:oc-fffffff", Project: "app", ID: "oc-fffffff", State: export.EdgeDangling}) |
| 407 | k.Changes = append(k.Changes, "valley:site/kmnopqrstuvwxyzkmnopqrstuvwxyzkm", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm") |
| 408 | } |
| 409 | } |
| 410 | }) |
| 411 | page = h.page("/tools/app/knots/oc-a000003") |
| 412 | for _, want := range []string{ |
| 413 | `<span class="mono">app:oc-fffffff</span> <span class="muted">not found in its graph</span>`, |
| 414 | `<span class="mono">oc-eeeeeee</span> <span class="muted">not found</span>`, |
| 415 | `<li class="mono">a change in an unpublished project</li>`, |
| 416 | `<li class="mono">valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm</li>`, |
| 417 | } { |
| 418 | if !strings.Contains(page, want) { |
| 419 | t.Errorf("the knot's page does not show %q", want) |
| 420 | } |
| 421 | } |
| 422 | for _, unwanted := range unpublishedText { |
| 423 | if strings.Contains(page, unwanted) { |
| 424 | t.Errorf("the knot's page shows %q", unwanted) |
| 425 | } |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | // A project the export does not hold as public answers every route |
| 430 | // exactly as a project that does not exist, even when its repository is |
| 431 | // in the generation's directory: under its group's name, under a group |
| 432 | // that does not exist, and under the short alias and the former name the |
| 433 | // instance gives it, which the export does not carry. Through the group's |
| 434 | // alias, both answer with the same redirect. |
| 435 | func TestHiddenProjectAnswersLikeMissing(t *testing.T) { |
| 436 | h := newHarness(t) |
| 437 | g := h.active() |
| 438 | if err := os.CopyFS(filepath.Join(g.Dir, "repos", "site.git"), os.DirFS(h.f.Repos["site"])); err != nil { |
| 439 | t.Fatal(err) |
| 440 | } |
| 441 | siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef) |
| 442 | notFound := h.get("/tools/app/knots/oc-fffffff") |
| 443 | for _, route := range []string{ |
| 444 | "", |
| 445 | "/", |
| 446 | "/knots/oc-b000001", |
| 447 | "/source", |
| 448 | "/source/", |
| 449 | "/source/tree/" + siteTip + "/", |
| 450 | "/source/blob/" + siteTip + "/README.md", |
| 451 | "/source/log/" + siteTip, |
| 452 | "/source/archive/" + siteTip + ".tar.gz", |
| 453 | "/source/archive/main.tar.gz", |
| 454 | "/source/tree/" + siteTip + "/no/such/path/", |
| 455 | "/source/anything", |
| 456 | } { |
| 457 | for _, pair := range [][2]string{ |
| 458 | {"/tools/site" + route, "/tools/nosuch" + route}, |
| 459 | {"/core/site" + route, "/nosuch/site" + route}, |
| 460 | {"/site" + route, "/nosuch" + route}, |
| 461 | {"/tools/old-site" + route, "/tools/nosuch" + route}, |
| 462 | } { |
| 463 | hidden, missing := h.get(pair[0]), h.get(pair[1]) |
| 464 | if hidden.Code != http.StatusNotFound || missing.Code != http.StatusNotFound { |
| 465 | t.Errorf("%s answered %d hidden, and %s %d missing", pair[0], hidden.Code, pair[1], missing.Code) |
| 466 | } |
| 467 | if fmt.Sprint(hidden.Header()) != fmt.Sprint(missing.Header()) { |
| 468 | t.Errorf("%s answered with other headers hidden than missing:\n%v\n%v", pair[0], hidden.Header(), missing.Header()) |
| 469 | } |
| 470 | if !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) || !bytes.Equal(hidden.Body.Bytes(), notFound.Body.Bytes()) { |
| 471 | t.Errorf("%s answered with another page hidden than missing", pair[0]) |
| 472 | } |
| 473 | } |
| 474 | for _, name := range []string{"site", "old-site"} { |
| 475 | hidden, missing := h.get("/t/"+name+route), h.get("/t/nosuch"+route) |
| 476 | if hidden.Code != http.StatusPermanentRedirect || hidden.Header().Get("Location") != "/tools/"+name+route || |
| 477 | missing.Code != http.StatusPermanentRedirect || missing.Header().Get("Location") != "/tools/nosuch"+route || |
| 478 | !bytes.Equal(hidden.Body.Bytes(), missing.Body.Bytes()) { |
| 479 | t.Errorf("/t/%s%s answered %d to %q, and /t/nosuch%s %d to %q", name, route, hidden.Code, hidden.Header().Get("Location"), |
| 480 | route, missing.Code, missing.Header().Get("Location")) |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | // A group's or a project's name may be any word the server's routes use: |
| 487 | // source, knots, or web-export, the receiver's first segment. A project |
| 488 | // so named, in a group so named, is served on every route, and |
| 489 | // /<group>/<project>/ redirects to its tree. The server's own paths, under |
| 490 | // /-/, are never a group's, and a project's path without its group is no |
| 491 | // route. |
| 492 | func TestProjectNamesBesideTheServersPaths(t *testing.T) { |
| 493 | for _, name := range []string{"source", "knots", "web-export"} { |
| 494 | t.Run(name, func(t *testing.T) { |
| 495 | h := newHarness(t) |
| 496 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{name: h.f.Bundles["app"]}, |
| 497 | func(e *export.Export) { |
| 498 | e.Groups[0].Name = name |
| 499 | e.Projects[0].Name, e.Projects[0].WebName = name, name |
| 500 | }) |
| 501 | tip := h.tip() |
| 502 | base := "/" + name + "/" + name |
| 503 | tree := base + "/source/tree/" + tip + "/" |
| 504 | if plan := h.page("/"); !strings.Contains(plan, `href="`+base+`/knots/oc-a000002"`) { |
| 505 | t.Errorf("the plan page does not link %s's knots", name) |
| 506 | } |
| 507 | for _, target := range []string{ |
| 508 | base + "/knots/oc-a000002", |
| 509 | tree, |
| 510 | base + "/source/blob/" + tip + "/docs/guide.md", |
| 511 | base + "/source/log/" + tip, |
| 512 | } { |
| 513 | h.page(target) |
| 514 | } |
| 515 | for _, target := range []string{base + "/", base, base + "/source/"} { |
| 516 | if w := h.get(target); w.Code != http.StatusFound || w.Header().Get("Location") != tree { |
| 517 | t.Errorf("GET %s answered %d to %q, not a redirect to %s", target, w.Code, w.Header().Get("Location"), tree) |
| 518 | } |
| 519 | } |
| 520 | for _, target := range []string{ |
| 521 | "/-", "/-/", "/-/" + name + "/", "/-/knots/oc-a000002", "/-/source/tree/" + tip + "/", |
| 522 | "/-/" + name + "/" + name + "/source/tree/" + tip + "/", "/-" + base + "/", |
| 523 | "/" + name + "/source/tree/" + tip + "/", "/" + name + "/knots/oc-a000002", |
| 524 | "/" + name, "/" + name + "/", "/tools/app/", "/core/" + name + "/", "/site/", "/site", |
| 525 | } { |
| 526 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 527 | t.Errorf("GET %s answered %d, not 404", target, w.Code) |
| 528 | } |
| 529 | } |
| 530 | }) |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | // An alias answers with a permanent redirect to the same path under what |
| 535 | // it stands for: a group's alias to the group's name, a project's former |
| 536 | // name to its web name in its group, and a project's short alias to |
| 537 | // /<group>/<project>. The rest of the path and the query are kept as they |
| 538 | // were sent, escapes, dot segments and a bare "?" too, and the redirect |
| 539 | // leads to the page. A group's identifier, a name in another case, and a |
| 540 | // group with no project named answer 404. |
| 541 | func TestAliasesRedirectPermanently(t *testing.T) { |
| 542 | h := newHarness(t) |
| 543 | tip := h.tip() |
| 544 | for from, to := range map[string]string{ |
| 545 | "/t": "/tools", |
| 546 | "/t/": "/tools/", |
| 547 | "/t/app/knots/oc-a000002": "/tools/app/knots/oc-a000002", |
| 548 | "/t/old-app/knots/oc-a000002": "/tools/old-app/knots/oc-a000002", |
| 549 | "/tools/old-app": "/tools/app", |
| 550 | "/tools/old-app/": "/tools/app/", |
| 551 | "/tools/old-app/knots/oc-a000002": "/tools/app/knots/oc-a000002", |
| 552 | "/tools/old-app/source/log/" + tip: "/tools/app/source/log/" + tip, |
| 553 | "/app": "/tools/app", |
| 554 | "/app/": "/tools/app/", |
| 555 | "/app/knots/oc-a000002": "/tools/app/knots/oc-a000002", |
| 556 | "/app/source/log/" + tip + "?from=" + tip: "/tools/app/source/log/" + tip + "?from=" + tip, |
| 557 | "/app/source/log/" + tip + "?": "/tools/app/source/log/" + tip + "?", |
| 558 | "/tools/old-app/knots/oc-a000002?": "/tools/app/knots/oc-a000002?", |
| 559 | "/app/source/blob/" + tip + "/docs%2Fguide.md": "/tools/app/source/blob/" + tip + "/docs%2Fguide.md", |
| 560 | "/app/source/blob/" + tip + "/docs/../README.md": "/tools/app/source/blob/" + tip + "/docs/../README.md", |
| 561 | "/t/app/source/tree/" + tip + "/docs/": "/tools/app/source/tree/" + tip + "/docs/", |
| 562 | "/app//knots": "/tools/app//knots", |
| 563 | } { |
| 564 | for _, method := range []string{"GET", "HEAD"} { |
| 565 | w := h.do(method, from) |
| 566 | if w.Code != http.StatusPermanentRedirect || w.Header().Get("Location") != to { |
| 567 | t.Errorf("%s %s answered %d to %q, not a permanent redirect to %s", method, from, w.Code, w.Header().Get("Location"), to) |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | for _, target := range []string{"/tools/app/knots/oc-a000002", "/tools/app/source/tree/" + tip + "/docs/"} { |
| 572 | h.page(target) |
| 573 | } |
| 574 | if w := h.get("/app/"); w.Code == http.StatusPermanentRedirect { |
| 575 | if next := h.get(w.Header().Get("Location")); next.Code != http.StatusFound || |
| 576 | next.Header().Get("Location") != "/tools/app/source/tree/"+tip+"/" { |
| 577 | t.Errorf("/app/ leads to %d %q, not to app's tree", next.Code, next.Header().Get("Location")) |
| 578 | } |
| 579 | } |
| 580 | for _, target := range []string{"/tools", "/tools/", "/core/app/", "/Tools/app/", "/T/app/", "/App/", "/tools/App/", |
| 581 | "/tools/Old-app/", "/old-app/", "/core/old-app/"} { |
| 582 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 583 | t.Errorf("GET %s answered %d, not 404", target, w.Code) |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | // A project's web name is its own within its group, and need not be its |
| 589 | // identifier. Two projects that are each app on the web, in two groups, |
| 590 | // are served apart, each under its group's name, while the plan page |
| 591 | // links each. A project's identifier is no web name of its own. |
| 592 | func TestTwoGroupsEachHoldAnApp(t *testing.T) { |
| 593 | h := newHarness(t) |
| 594 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"site": h.f.Bundles["app"]}, func(e *export.Export) { |
| 595 | site := e.Projects[0] |
| 596 | site.Name, site.Group, site.WebName, site.FormerNames, site.Aliases = "site", "web", "app", nil, nil |
| 597 | site.Knots = slices.Clone(site.Knots) |
| 598 | for i := range site.Knots { |
| 599 | site.Knots[i].Title = "Site: " + site.Knots[i].Title |
| 600 | } |
| 601 | e.Projects = append(e.Projects, site) |
| 602 | e.Groups = append(e.Groups, export.Group{ID: "web", Name: "docs"}) |
| 603 | }) |
| 604 | tip := h.tip() |
| 605 | if page := h.page("/tools/app/knots/oc-a000002"); !strings.Contains(page, "The plan page lists milestones") || strings.Contains(page, "Site: ") { |
| 606 | t.Errorf("/tools/app is not app:\n%s", page) |
| 607 | } |
| 608 | if page := h.page("/docs/app/knots/oc-a000002"); !strings.Contains(page, "Site: The plan page lists milestones") { |
| 609 | t.Errorf("/docs/app is not site:\n%s", page) |
| 610 | } |
| 611 | h.page("/docs/app/source/tree/" + tip + "/") |
| 612 | plan := h.page("/") |
| 613 | for _, link := range []string{`href="/tools/app/knots/oc-a000002"`, `href="/docs/app/knots/oc-a000002"`} { |
| 614 | if !strings.Contains(plan, link) { |
| 615 | t.Errorf("the plan page does not hold %s", link) |
| 616 | } |
| 617 | } |
| 618 | for _, target := range []string{"/docs/site/", "/docs/site/knots/oc-a000002", "/tools/site/"} { |
| 619 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 620 | t.Errorf("GET %s answered %d, not 404", target, w.Code) |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | // A browser resolves a redirect's Location against the URL it asked for, |
| 626 | // and removes the dot segments the server kept, "%2e" spelled ones too. |
| 627 | // Every Location is a path on the server's own origin, whatever dot |
| 628 | // segments, escaped slashes or empty segments the path held. Where the |
| 629 | // browser goes answers as it does when asked for directly: a page of the |
| 630 | // project, or the one 404. |
| 631 | func TestRedirectsLeadWhereTheBrowserGoes(t *testing.T) { |
| 632 | h := newHarness(t) |
| 633 | tip := h.tip() |
| 634 | for from, c := range map[string]struct { |
| 635 | to string |
| 636 | code int |
| 637 | }{ |
| 638 | "/app/source/blob/" + tip + "/docs/../README.md": {"/tools/app/source/blob/" + tip + "/README.md", http.StatusOK}, |
| 639 | "/tools/old-app/source/blob/" + tip + "/docs/./guide.md": {"/tools/app/source/blob/" + tip + "/docs/guide.md", http.StatusOK}, |
| 640 | "/t/app/source/blob/" + tip + "/docs/%2e%2E/README.md": {"/tools/app/source/blob/" + tip + "/README.md", http.StatusOK}, |
| 641 | "/app/../site/": {"/tools/site/", http.StatusNotFound}, |
| 642 | "/app/../../../-/": {"/-/", http.StatusNotFound}, |
| 643 | "/t/../../..//example.net/": {"//example.net/", http.StatusNotFound}, |
| 644 | "/t/..%2F..%2Fx": {"/tools/..%2F..%2Fx", http.StatusNotFound}, |
| 645 | "/app/.%2E/x": {"/tools/x", http.StatusNotFound}, |
| 646 | "/tools/old-app/..": {"/tools/", http.StatusNotFound}, |
| 647 | "/tools/old-app/.%2e?": {"/tools/?", http.StatusNotFound}, |
| 648 | } { |
| 649 | w := h.get(from) |
| 650 | if w.Code != http.StatusPermanentRedirect { |
| 651 | t.Errorf("GET %s answered %d, not a permanent redirect", from, w.Code) |
| 652 | continue |
| 653 | } |
| 654 | next := browserResolves(t, w.Header().Get("Location")) |
| 655 | if next != c.to { |
| 656 | t.Errorf("GET %s leads a browser to %s, not to %s", from, next, c.to) |
| 657 | continue |
| 658 | } |
| 659 | if got := h.get(next); got.Code != c.code { |
| 660 | t.Errorf("GET %s leads to %s, which answers %d, not %d", from, next, got.Code, c.code) |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | // browserResolves is the path and query a browser asks the same origin |
| 666 | // for when a redirect's Location is location. location must be a path on |
| 667 | // that origin: one "/", then a character a browser reads as neither "/" |
| 668 | // nor "\", so no browser reads a host in it. The browser removes its dot |
| 669 | // segments by the WHATWG URL standard's path parsing, which reads "%2e" |
| 670 | // as a dot, ignoring case, and keeps empty segments. |
| 671 | func browserResolves(t *testing.T, location string) string { |
| 672 | t.Helper() |
| 673 | if len(location) < 2 || location[0] != '/' || location[1] == '/' || location[1] == '\\' { |
| 674 | t.Fatalf("the Location %q is not a path on the server's origin", location) |
| 675 | } |
| 676 | path, query, queried := strings.Cut(location, "?") |
| 677 | if strings.ContainsAny(path, "\\#") { |
| 678 | t.Fatalf("the Location %q holds a character a browser reads apart from a path's", location) |
| 679 | } |
| 680 | segments := strings.Split(path[1:], "/") |
| 681 | var out []string |
| 682 | for i, segment := range segments { |
| 683 | last := i == len(segments)-1 |
| 684 | switch strings.ToLower(segment) { |
| 685 | case "..", ".%2e", "%2e.", "%2e%2e": |
| 686 | if len(out) > 0 { |
| 687 | out = out[:len(out)-1] |
| 688 | } |
| 689 | if last { |
| 690 | out = append(out, "") |
| 691 | } |
| 692 | case ".", "%2e": |
| 693 | if last { |
| 694 | out = append(out, "") |
| 695 | } |
| 696 | default: |
| 697 | out = append(out, segment) |
| 698 | } |
| 699 | } |
| 700 | resolved := "/" + strings.Join(out, "/") |
| 701 | if queried { |
| 702 | resolved += "?" + query |
| 703 | } |
| 704 | return resolved |
| 705 | } |
| 706 | |
| 707 | // Every 404 is the one page, made once: the box of text, whose last line |
| 708 | // links to the plan, with no navigation, no export's age and no site name. |
| 709 | // It stays the same byte for byte while the export changes. |
| 710 | func TestNotFoundIsTheOnePage(t *testing.T) { |
| 711 | h := newHarness(t) |
| 712 | w := h.get("/tools/nosuch/") |
| 713 | if w.Code != http.StatusNotFound || w.Header().Get("Content-Type") != "text/html; charset=utf-8" { |
| 714 | t.Fatalf("a missing project answered %d, %q", w.Code, w.Header().Get("Content-Type")) |
| 715 | } |
| 716 | page := w.Body.String() |
| 717 | box := `<pre class="lost"> |
| 718 | ╔═════════════════════════════════════╗ |
| 719 | ║ ║ |
| 720 | ║ THE WAY THAT CAN BE FOUND ║ |
| 721 | ║ IS NOT THE ETERNAL WAY ║ |
| 722 | ║ ║ |
| 723 | ║ The page you seek exists ║ |
| 724 | ║ only in non-existence. ║ |
| 725 | ║ ║ |
| 726 | ║ <a href="/">Return to the source</a> ║ |
| 727 | ║ ║ |
| 728 | ╚═════════════════════════════════════╝ |
| 729 | </pre>` |
| 730 | if !strings.Contains(page, box) { |
| 731 | t.Errorf("the 404 page does not hold the box:\n%s", page) |
| 732 | } |
| 733 | for _, unwanted := range []string{"<nav", "Collected", "app source", exporttest.Instance, exporttest.Destination, "tools"} { |
| 734 | if strings.Contains(page, unwanted) { |
| 735 | t.Errorf("the 404 page holds %q:\n%s", unwanted, page) |
| 736 | } |
| 737 | } |
| 738 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 739 | h.now = h.now.Add(time.Hour) |
| 740 | for _, target := range []string{"/nosuch", "/-/", "/tools/app/knots/oc-fffffff", "/tools/app/source/tree/" + strings.Repeat("0", 40) + "/"} { |
| 741 | if again := h.get(target); again.Code != http.StatusNotFound || again.Body.String() != page { |
| 742 | t.Errorf("GET %s answered %d with another page than the one 404", target, again.Code) |
| 743 | } |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | // A source route serves a commit only when main's published tip reaches |
| 748 | // it, and refuses every other object ID or name with the one 404. |
| 749 | func TestUnreachableCommitIsRefused(t *testing.T) { |
| 750 | h := newHarness(t) |
| 751 | repo, _ := h.active().Repo("app") |
| 752 | tip := h.tip() |
| 753 | tree := git(t, repo, nil, "rev-parse", tip+"^{tree}") |
| 754 | readme := git(t, repo, nil, "rev-parse", tip+":README.md") |
| 755 | side := git(t, repo, nil, "commit-tree", tree, "-p", tip, "-m", "a commit main does not reach") |
| 756 | parent := git(t, repo, nil, "rev-parse", tip+"~2") |
| 757 | notFound := h.get("/tools/app/knots/oc-fffffff").Body.String() |
| 758 | |
| 759 | for _, commit := range []string{side, tree, readme, tip[:12], "main", "HEAD", strings.Repeat("0", 40), tip + "~1"} { |
| 760 | for _, route := range []string{"/tools/app/source/tree/%s/", "/tools/app/source/blob/%s/README.md", "/tools/app/source/log/%s", |
| 761 | "/tools/app/source/archive/%s.tar.gz"} { |
| 762 | if commit == "main" && strings.HasPrefix(route, "/tools/app/source/archive/") { |
| 763 | continue // main.tar.gz redirects to the archive of main's tip |
| 764 | } |
| 765 | target := fmt.Sprintf(route, commit) |
| 766 | w := h.get(target) |
| 767 | if w.Code != http.StatusNotFound || w.Body.String() != notFound { |
| 768 | t.Errorf("GET %s answered %d, not the one 404", target, w.Code) |
| 769 | } |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | // A commit the tip reaches is served, as that commit had it. |
| 774 | page := h.page("/tools/app/source/blob/" + parent + "/README.md") |
| 775 | if !strings.Contains(page, "A synthetic project for the web UI's tests.") || strings.Contains(page, "readme") { |
| 776 | t.Errorf("the first README is not served as the first commit had it:\n%s", page) |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | // The source browser lists a directory and its README, shows a file and |
| 781 | // main's log, and every source link names its project, a full commit and |
| 782 | // a path. |
| 783 | func TestSourceBrowser(t *testing.T) { |
| 784 | h := newHarness(t) |
| 785 | tip := h.tip() |
| 786 | |
| 787 | for _, path := range []string{"/tools/app/source", "/tools/app/source/"} { |
| 788 | w := h.get(path) |
| 789 | if w.Code != http.StatusFound || w.Header().Get("Location") != "/tools/app/source/tree/"+tip+"/" { |
| 790 | t.Fatalf("the project's source answered %d to %q", w.Code, w.Header().Get("Location")) |
| 791 | } |
| 792 | } |
| 793 | |
| 794 | root := h.page("/tools/app/source/tree/" + tip + "/") |
| 795 | docs, src, readme := strings.Index(root, ">docs/<"), strings.Index(root, ">src/<"), strings.Index(root, ">README.md<") |
| 796 | if docs < 0 || src < 0 || readme < 0 || readme < src || src < docs { |
| 797 | t.Errorf("the root does not list docs/ and src/ before README.md:\n%s", root) |
| 798 | } |
| 799 | if !strings.Contains(root, `<h1 id="app">app <a class="anchor" href="#app">#</a></h1>`) { |
| 800 | t.Error("the root does not show its README") |
| 801 | } |
| 802 | if dir := h.page("/tools/app/source/tree/" + tip + "/docs/"); !strings.Contains(dir, ">guide.md<") { |
| 803 | t.Error("docs/ does not list guide.md") |
| 804 | } |
| 805 | file := h.page("/tools/app/source/blob/" + tip + "/docs/guide.md?plain=1") |
| 806 | if !strings.Contains(file, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Guide</td></tr>`) { |
| 807 | t.Errorf("the file is not shown line by line:\n%s", file) |
| 808 | } |
| 809 | log := h.page("/tools/app/source/log/" + tip) |
| 810 | first, last := strings.Index(log, "docs: a guide, and the README names it"), strings.Index(log, "app: the first README") |
| 811 | if first < 0 || last < first { |
| 812 | t.Errorf("the log does not list main's commits newest first:\n%s", log) |
| 813 | } |
| 814 | |
| 815 | links := regexp.MustCompile(`href="(/[^"]*/source/[^"]*)"`) |
| 816 | named := regexp.MustCompile(`^/tools/app/source/((tree|blob|log)/[0-9a-f]{40}(/|$)|archive/[0-9a-f]{40}\.tar\.gz$)`) |
| 817 | for _, page := range []string{root, file, log} { |
| 818 | for _, m := range links.FindAllStringSubmatch(page, -1) { |
| 819 | if !named.MatchString(m[1]) { |
| 820 | t.Errorf("the link %s names no commit", m[1]) |
| 821 | } |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | for _, target := range []string{ |
| 826 | "/tools/app/source/blob/" + tip + "/docs/guide.md/", |
| 827 | "/tools/app/source/blob/" + tip + "/docs/../README.md", |
| 828 | "/tools/app/source/blob/" + tip + "/docs%2Fguide.md", |
| 829 | "/tools/app/source/tree/" + tip + "//", |
| 830 | "/tools/app/source/log/" + tip + "?from=" + strings.ToUpper(tip), |
| 831 | } { |
| 832 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 833 | t.Errorf("GET %s answered %d", target, w.Code) |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | // A tree page links the archive of its commit. The archive holds that |
| 839 | // commit's files and directories, and only those, in the tree's order, |
| 840 | // under one directory named for the project and the commit. Every entry |
| 841 | // carries the commit's time, and the same commit gives the same bytes. |
| 842 | // It carries every header a page carries, and its own. A name that is no |
| 843 | // full ID of a commit main reaches, or a path of another shape, answers the |
| 844 | // one 404, and a project the authorization does not name answers as its |
| 845 | // tree page does. |
| 846 | func TestSourceArchive(t *testing.T) { |
| 847 | h := newHarness(t) |
| 848 | repo, _ := h.active().Repo("app") |
| 849 | tip := h.tip() |
| 850 | parent := git(t, repo, nil, "rev-parse", tip+"~1") |
| 851 | at := func(commit string) string { return "/tools/app/source/archive/" + commit + ".tar.gz" } |
| 852 | |
| 853 | for _, dir := range []string{tip + "/", tip + "/docs/", parent + "/"} { |
| 854 | if page := h.page("/tools/app/source/tree/" + dir); !strings.Contains(page, `<a href="`+at(dir[:40])+`">Download .tar.gz</a>`) { |
| 855 | t.Errorf("the tree page at %s does not link its commit's archive", dir) |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | for _, commit := range []string{tip, parent} { |
| 860 | w := h.get(at(commit)) |
| 861 | if w.Code != http.StatusOK { |
| 862 | t.Fatalf("GET %s answered %d:\n%s", at(commit), w.Code, w.Body) |
| 863 | } |
| 864 | want := http.Header{} |
| 865 | setHeaders(want) |
| 866 | want.Set("Content-Type", "application/gzip") |
| 867 | want.Set("Content-Disposition", `attachment; filename="app-`+commit[:12]+`.tar.gz"`) |
| 868 | want.Set("Content-Length", strconv.Itoa(w.Body.Len())) |
| 869 | if fmt.Sprint(w.Header()) != fmt.Sprint(want) { |
| 870 | t.Errorf("the archive of %s answered with the headers\n%v\nnot\n%v", commit, w.Header(), want) |
| 871 | } |
| 872 | if head := h.do("HEAD", at(commit)); head.Code != http.StatusOK || fmt.Sprint(head.Header()) != fmt.Sprint(want) { |
| 873 | t.Errorf("HEAD %s answered %d with the headers\n%v", at(commit), head.Code, head.Header()) |
| 874 | } |
| 875 | if again := h.get(at(commit)); !bytes.Equal(again.Body.Bytes(), w.Body.Bytes()) { |
| 876 | t.Errorf("two requests for the archive of %s gave other bytes", commit) |
| 877 | } |
| 878 | // The archive is its directory, then the commit's tree in git's |
| 879 | // order, each entry with its mode and the commit's time, each file |
| 880 | // as git holds it, and each header in the USTAR format. |
| 881 | when := git(t, repo, nil, "log", "-1", "--format=%ct", commit) |
| 882 | dir := "app-" + commit[:12] + "/" |
| 883 | describe := func(typ byte, mode int64, name, content string) string { |
| 884 | return fmt.Sprintf("%c %o %s %q %q", typ, mode, when, name, content) |
| 885 | } |
| 886 | tree := []string{describe(tar.TypeDir, 0o755, dir, "")} |
| 887 | for _, line := range strings.Split(git(t, repo, nil, "ls-tree", "-r", "-t", commit), "\n") { |
| 888 | meta, path, _ := strings.Cut(line, "\t") |
| 889 | switch f := strings.Fields(meta); f[0] { |
| 890 | case "040000": |
| 891 | tree = append(tree, describe(tar.TypeDir, 0o755, dir+path+"/", "")) |
| 892 | case "100644": |
| 893 | tree = append(tree, describe(tar.TypeReg, 0o644, dir+path, git(t, repo, nil, "cat-file", "blob", f[2]))) |
| 894 | default: |
| 895 | t.Fatalf("the fixture's app holds %q", line) |
| 896 | } |
| 897 | } |
| 898 | var got []string |
| 899 | for _, e := range readArchive(t, w.Body.Bytes()) { |
| 900 | if e.hdr.Format != tar.FormatUSTAR { |
| 901 | t.Errorf("the archive of %s holds %q in the format %v", commit, e.hdr.Name, e.hdr.Format) |
| 902 | } |
| 903 | got = append(got, fmt.Sprintf("%c %o %d %q %q", e.hdr.Typeflag, e.hdr.Mode, e.hdr.ModTime.Unix(), e.hdr.Name, strings.TrimSpace(e.content))) |
| 904 | } |
| 905 | if !slices.Equal(got, tree) { |
| 906 | t.Errorf("the archive of %s holds\n%s\nnot\n%s", commit, strings.Join(got, "\n"), strings.Join(tree, "\n")) |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | notFound := h.get("/tools/app/knots/oc-fffffff").Body.String() |
| 911 | for _, target := range []string{ |
| 912 | "/tools/app/source/archive/" + tip, |
| 913 | "/tools/app/source/archive/" + tip + ".tar", |
| 914 | "/tools/app/source/archive/" + tip + ".zip", |
| 915 | "/tools/app/source/archive/" + strings.ToUpper(tip) + ".tar.gz", |
| 916 | "/tools/app/source/archive/" + tip + ".tar.gz/", |
| 917 | "/tools/app/source/archive/" + tip + ".tar.gz/README.md", |
| 918 | "/tools/app/source/archive/" + tip + "/README.md", |
| 919 | "/tools/app/source/archive/.tar.gz", |
| 920 | "/tools/app/source/archive/", |
| 921 | "/tools/app/source/archive", |
| 922 | } { |
| 923 | if w := h.get(target); w.Code != http.StatusNotFound || w.Body.String() != notFound { |
| 924 | t.Errorf("GET %s answered %d, not the one 404", target, w.Code) |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | a, _, err := h.store.Authorization() |
| 929 | if err != nil { |
| 930 | t.Fatal(err) |
| 931 | } |
| 932 | h.authorize(exporttest.Authorization(a.Sequence + 1)) |
| 933 | archive, tree := h.get(at(tip)), h.get("/tools/app/source/tree/"+tip+"/") |
| 934 | if archive.Code != http.StatusNotFound || archive.Code != tree.Code || fmt.Sprint(archive.Header()) != fmt.Sprint(tree.Header()) || |
| 935 | !bytes.Equal(archive.Body.Bytes(), tree.Body.Bytes()) { |
| 936 | t.Errorf("withdrawn, the archive answered %d and the tree page %d, or with other headers or bodies", archive.Code, tree.Code) |
| 937 | } |
| 938 | h.authorize(exporttest.Authorization(a.Sequence+2, "app")) |
| 939 | if w := h.get(at(tip)); w.Code != http.StatusOK { |
| 940 | t.Errorf("named again, the archive answered %d", w.Code) |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | // An archive that would pass MaxResponse answers with the short page that |
| 945 | // says the page is too large, and none of the archive, and the failure is |
| 946 | // logged. An archive within the bound is served. |
| 947 | func TestArchiveTooLarge(t *testing.T) { |
| 948 | h := newHarness(t) |
| 949 | var logged []string |
| 950 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 951 | before := h.tip() |
| 952 | var noise []byte |
| 953 | for i := 0; len(noise) < 64<<10; i++ { |
| 954 | sum := sha256.Sum256([]byte(fmt.Sprint(i))) |
| 955 | noise = append(noise, sum[:]...) |
| 956 | } |
| 957 | tip, bundle := h.commitMain("app: a file gzip cannot shrink\n", file{"100644", "noise.bin", string(noise)}) |
| 958 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 959 | |
| 960 | h.srv.maxResponse = 32 << 10 |
| 961 | for _, method := range []string{"GET", "HEAD"} { |
| 962 | w := h.do(method, "/tools/app/source/archive/"+tip+".tar.gz") |
| 963 | if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) || |
| 964 | w.Header().Get("Content-Type") != htmlType || w.Header().Get("Content-Disposition") != "" { |
| 965 | t.Errorf("%s of an archive too large answered %d, %q, %q, with %d bytes", method, w.Code, |
| 966 | w.Header().Get("Content-Type"), w.Header().Get("Content-Disposition"), w.Body.Len()) |
| 967 | } |
| 968 | if n, _ := h.srv.holding(); n != 0 { |
| 969 | t.Errorf("%s of an archive too large kept %d pieces of the budget", method, n) |
| 970 | } |
| 971 | } |
| 972 | if w := h.get("/tools/app/source/archive/" + before + ".tar.gz"); w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/gzip" { |
| 973 | t.Errorf("an archive within the bound answered %d, %q", w.Code, w.Header().Get("Content-Type")) |
| 974 | } |
| 975 | if len(logged) != 2 { |
| 976 | t.Errorf("%d failures were logged for 2 archives too large: %q", len(logged), logged) |
| 977 | } |
| 978 | for _, l := range logged { |
| 979 | if !strings.Contains(l, "larger than") { |
| 980 | t.Errorf("the server logged %q", l) |
| 981 | } |
| 982 | } |
| 983 | } |
| 984 | |
| 985 | // An archive is the commit's tree byte for byte. It applies no attribute, |
| 986 | // from the commit's own .gitattributes or from the repository, so |
| 987 | // export-subst expands nothing and export-ignore leaves nothing out. One |
| 988 | // commit gives the same bytes once a ref is moved and attributes and |
| 989 | // configuration are added to the repository, though each would change an |
| 990 | // archive that applied attributes. |
| 991 | func TestArchiveAppliesNoAttributes(t *testing.T) { |
| 992 | h := newHarness(t) |
| 993 | subst := "$Format:%ar$ $Format:%d$ $Format:%H$\n" |
| 994 | attributes := "* export-subst\nignored.txt export-ignore\ndocs export-ignore\n" |
| 995 | tip, bundle := h.commitMain("app: attributes an archive does not apply\n", |
| 996 | file{"100644", ".gitattributes", attributes}, |
| 997 | file{"100644", "subst.txt", subst}, |
| 998 | file{"100644", "ignored.txt", "ignored\n"}) |
| 999 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1000 | repo, _ := h.active().Repo("app") |
| 1001 | at := "/tools/app/source/archive/" + tip + ".tar.gz" |
| 1002 | first := h.get(at) |
| 1003 | if first.Code != http.StatusOK { |
| 1004 | t.Fatalf("GET %s answered %d:\n%s", at, first.Code, first.Body) |
| 1005 | } |
| 1006 | dir := "app-" + tip[:12] + "/" |
| 1007 | got := map[string]string{} |
| 1008 | for _, e := range readArchive(t, first.Body.Bytes()) { |
| 1009 | got[e.hdr.Name] = e.content |
| 1010 | } |
| 1011 | for name, want := range map[string]string{".gitattributes": attributes, "subst.txt": subst, "ignored.txt": "ignored\n", "docs/": ""} { |
| 1012 | if content, ok := got[dir+name]; !ok || content != want { |
| 1013 | t.Errorf("the archive holds %s as %q, %v, not %q", name, content, ok, want) |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | git(t, repo, nil, "branch", "side", tip) |
| 1018 | git(t, repo, nil, "tag", "v1", tip) |
| 1019 | if err := os.MkdirAll(filepath.Join(repo, "info"), 0o755); err != nil { |
| 1020 | t.Fatal(err) |
| 1021 | } |
| 1022 | if err := os.WriteFile(filepath.Join(repo, "info", "attributes"), []byte("* export-ignore\n"), 0o644); err != nil { |
| 1023 | t.Fatal(err) |
| 1024 | } |
| 1025 | git(t, repo, nil, "config", "tar.umask", "0") |
| 1026 | git(t, repo, nil, "config", "core.autocrlf", "true") |
| 1027 | h.now = h.now.Add(time.Hour) |
| 1028 | if again := h.get(at); again.Code != http.StatusOK || !bytes.Equal(again.Body.Bytes(), first.Body.Bytes()) { |
| 1029 | t.Errorf("with a ref moved, and attributes and configuration added, the archive answered %d with other bytes", again.Code) |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | // A symbolic link is a tar symbolic link to its blob's content, and is not |
| 1034 | // followed. A submodule is an empty directory, and an executable file is |
| 1035 | // 0755. A header is in the USTAR format unless its name or target is too |
| 1036 | // long for it, and in the PAX format then. |
| 1037 | func TestArchiveLinksAndSubmodules(t *testing.T) { |
| 1038 | h := newHarness(t) |
| 1039 | far := strings.Repeat("deep/", 40) + "target" |
| 1040 | long := strings.Repeat("n", 120) + ".txt" |
| 1041 | tip, bundle := h.commitMain("app: links, a submodule and long names\n", |
| 1042 | file{"120000", "link", "../../etc/passwd"}, |
| 1043 | file{"120000", "far", far}, |
| 1044 | file{"100755", "run.sh", "#!/bin/sh\n"}, |
| 1045 | file{"160000", "vendor/lib", h.tip()}, |
| 1046 | file{"100644", long, "long\n"}) |
| 1047 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1048 | at := "/tools/app/source/archive/" + tip + ".tar.gz" |
| 1049 | w := h.get(at) |
| 1050 | if w.Code != http.StatusOK { |
| 1051 | t.Fatalf("GET %s answered %d:\n%s", at, w.Code, w.Body) |
| 1052 | } |
| 1053 | dir := "app-" + tip[:12] + "/" |
| 1054 | got := map[string]string{} |
| 1055 | var names []string |
| 1056 | for _, e := range readArchive(t, w.Body.Bytes()) { |
| 1057 | got[e.hdr.Name] = fmt.Sprintf("%c %o %d %q %q %v", e.hdr.Typeflag, e.hdr.Mode, e.hdr.Size, e.hdr.Linkname, e.content, e.hdr.Format) |
| 1058 | names = append(names, e.hdr.Name) |
| 1059 | } |
| 1060 | for name, want := range map[string]string{ |
| 1061 | "link": fmt.Sprintf("%c 777 0 %q \"\" USTAR", tar.TypeSymlink, "../../etc/passwd"), |
| 1062 | "far": fmt.Sprintf("%c 777 0 %q \"\" PAX", tar.TypeSymlink, far), |
| 1063 | "run.sh": fmt.Sprintf("%c 755 10 \"\" %q USTAR", tar.TypeReg, "#!/bin/sh\n"), |
| 1064 | "vendor/": fmt.Sprintf("%c 755 0 \"\" \"\" USTAR", tar.TypeDir), |
| 1065 | "vendor/lib/": fmt.Sprintf("%c 755 0 \"\" \"\" USTAR", tar.TypeDir), |
| 1066 | long: fmt.Sprintf("%c 644 5 \"\" %q PAX", tar.TypeReg, "long\n"), |
| 1067 | } { |
| 1068 | if got[dir+name] != want { |
| 1069 | t.Errorf("the archive holds %s as %s, not %s", name, got[dir+name], want) |
| 1070 | } |
| 1071 | } |
| 1072 | for _, name := range names { |
| 1073 | if strings.HasPrefix(name, dir+"vendor/lib/") && name != dir+"vendor/lib/" { |
| 1074 | t.Errorf("the archive holds %s inside the submodule", name) |
| 1075 | } |
| 1076 | } |
| 1077 | } |
| 1078 | |
| 1079 | // An archive whose files add up to more than MaxArchiveInput, or whose |
| 1080 | // tree holds more than MaxArchiveEntries entries, is refused from its |
| 1081 | // tree's listing, before any file is read: it answers with the short page |
| 1082 | // that says the page is too large, holds none of the budget, and the |
| 1083 | // refusal is logged. A file is counted once for each path that holds it, |
| 1084 | // as the archive would hold it. |
| 1085 | func TestArchiveInputBound(t *testing.T) { |
| 1086 | zeros := strings.Repeat("\x00", 1<<20) |
| 1087 | for _, c := range []struct { |
| 1088 | name, refused string |
| 1089 | files func() []file |
| 1090 | }{ |
| 1091 | {"files", fmt.Sprintf("its files are larger than %d bytes", MaxArchiveInput), func() (files []file) { |
| 1092 | for i := range MaxArchiveInput >> 20 { |
| 1093 | files = append(files, file{"100644", fmt.Sprintf("big/%02d.bin", i), zeros}) |
| 1094 | } |
| 1095 | return files |
| 1096 | }}, |
| 1097 | {"entries", fmt.Sprintf("its tree holds more than %d entries", MaxArchiveEntries), func() (files []file) { |
| 1098 | for i := range MaxArchiveEntries { |
| 1099 | files = append(files, file{"100644", fmt.Sprintf("many/%05d", i), ""}) |
| 1100 | } |
| 1101 | return files |
| 1102 | }}, |
| 1103 | } { |
| 1104 | t.Run(c.name, func(t *testing.T) { |
| 1105 | h := newHarness(t) |
| 1106 | var logged []string |
| 1107 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 1108 | tip, bundle := h.commitMain("app: a tree too large for an archive\n", c.files()...) |
| 1109 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1110 | w := h.get("/tools/app/source/archive/" + tip + ".tar.gz") |
| 1111 | if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) || |
| 1112 | w.Header().Get("Content-Type") != htmlType || w.Header().Get("Content-Disposition") != "" { |
| 1113 | t.Errorf("an archive too large answered %d, %q, %q, with %d bytes", w.Code, |
| 1114 | w.Header().Get("Content-Type"), w.Header().Get("Content-Disposition"), w.Body.Len()) |
| 1115 | } |
| 1116 | if n, _ := h.srv.holding(); n != 0 { |
| 1117 | t.Errorf("an archive too large kept %d pieces of the budget", n) |
| 1118 | } |
| 1119 | if len(logged) != 1 || !strings.Contains(logged[0], "larger than the server sends: "+c.refused) { |
| 1120 | t.Errorf("the server logged %q, not that %s", logged, c.refused) |
| 1121 | } |
| 1122 | }) |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | // A file far larger than MaxResponse that gzip shrinks to little is served |
| 1127 | // whole. The server streams it through tar and gzip into the response |
| 1128 | // body, and holds none of it whole: once the response is rendered, it |
| 1129 | // holds the pieces of the budget that the gzipped archive fills, and no |
| 1130 | // more. |
| 1131 | func TestArchiveStreamsIntoTheBody(t *testing.T) { |
| 1132 | h := newHarness(t) |
| 1133 | zeros := strings.Repeat("\x00", 3*MaxResponse) |
| 1134 | tip, bundle := h.commitMain("app: a large file gzip shrinks\n", file{"100644", "zeros.bin", zeros}) |
| 1135 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1136 | var held, large int |
| 1137 | h.srv.checked = func() { held, large = h.srv.holding() } |
| 1138 | at := "/tools/app/source/archive/" + tip + ".tar.gz" |
| 1139 | w := h.get(at) |
| 1140 | if w.Code != http.StatusOK { |
| 1141 | t.Fatalf("GET %s answered %d:\n%s", at, w.Code, w.Body) |
| 1142 | } |
| 1143 | if pieces := (w.Body.Len() + pieceSize - 1) / pieceSize; held != pieces || large != 0 || w.Body.Len() > SmallPage { |
| 1144 | t.Errorf("an archive of %d bytes held %d pieces of the budget and %d of the large budget, not %d and 0", |
| 1145 | w.Body.Len(), held, large, pieces) |
| 1146 | } |
| 1147 | if n, _ := h.srv.holding(); n != 0 { |
| 1148 | t.Errorf("once written, the archive kept %d pieces of the budget", n) |
| 1149 | } |
| 1150 | var content string |
| 1151 | for _, e := range readArchive(t, w.Body.Bytes()) { |
| 1152 | if e.hdr.Name == "app-"+tip[:12]+"/zeros.bin" { |
| 1153 | content = e.content |
| 1154 | } |
| 1155 | } |
| 1156 | if content != zeros { |
| 1157 | t.Errorf("the archive holds zeros.bin as %d bytes, not %d", len(content), len(zeros)) |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | // /source/archive/main.tar.gz redirects to the archive of main's tip as |
| 1162 | // /source/ redirects to the tree there: a temporary redirect, with the same |
| 1163 | // headers, that takes no git slot, and that follows main when it moves. |
| 1164 | // main is the one name the route takes in place of a full commit ID: HEAD, |
| 1165 | // another branch's name, or main spelled another way answers the one 404. |
| 1166 | func TestArchiveOfMainsTip(t *testing.T) { |
| 1167 | h := newHarness(t) |
| 1168 | repo, _ := h.active().Repo("app") |
| 1169 | git(t, repo, nil, "branch", "side", h.tip()) |
| 1170 | var admitted atomic.Int32 |
| 1171 | h.srv.admitted = func() { admitted.Add(1) } |
| 1172 | target := "/tools/app/source/archive/main.tar.gz" |
| 1173 | redirects := func(tip string) { |
| 1174 | t.Helper() |
| 1175 | admitted.Store(0) |
| 1176 | at := "/tools/app/source/archive/" + tip + ".tar.gz" |
| 1177 | for _, method := range []string{"GET", "HEAD"} { |
| 1178 | w, tree := h.do(method, target), h.do(method, "/tools/app/source/") |
| 1179 | want := tree.Header().Clone() |
| 1180 | want.Set("Location", at) |
| 1181 | if w.Code != http.StatusFound || w.Code != tree.Code || fmt.Sprint(w.Header()) != fmt.Sprint(want) { |
| 1182 | t.Errorf("%s %s answered %d with the headers\n%v\nnot %d with\n%v", method, target, w.Code, w.Header(), tree.Code, want) |
| 1183 | } |
| 1184 | } |
| 1185 | if n := admitted.Load(); n != 0 { |
| 1186 | t.Errorf("the redirect to the archive of main's tip took a git slot %d times", n) |
| 1187 | } |
| 1188 | if w := h.get(at); w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/gzip" { |
| 1189 | t.Errorf("the redirect leads to %s, which answers %d, %q", at, w.Code, w.Header().Get("Content-Type")) |
| 1190 | } |
| 1191 | } |
| 1192 | redirects(h.tip()) |
| 1193 | |
| 1194 | notFound := h.get("/tools/app/knots/oc-fffffff").Body.String() |
| 1195 | for _, name := range []string{"HEAD.tar.gz", "side.tar.gz", "MAIN.tar.gz", "main.tar", "main", "main.tar.gz/", "refs/heads/main.tar.gz"} { |
| 1196 | if w := h.get("/tools/app/source/archive/" + name); w.Code != http.StatusNotFound || w.Body.String() != notFound { |
| 1197 | t.Errorf("GET /tools/app/source/archive/%s answered %d, not the one 404", name, w.Code) |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | tip, bundle := h.commitMain("app: main moves on\n", file{"100644", "moved.txt", "moved\n"}) |
| 1202 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1203 | redirects(tip) |
| 1204 | } |
| 1205 | |
| 1206 | // archived is one entry of a gzipped tar archive: its header, and what it |
| 1207 | // holds. |
| 1208 | type archived struct { |
| 1209 | hdr *tar.Header |
| 1210 | content string |
| 1211 | } |
| 1212 | |
| 1213 | // readArchive is the entries of a gzipped tar archive, in order. The gzip |
| 1214 | // header must name no file and no time, and every entry must be a file, a |
| 1215 | // symbolic link or a directory, with uid and gid 0 and no user or group |
| 1216 | // name. |
| 1217 | func readArchive(t *testing.T, data []byte) []archived { |
| 1218 | t.Helper() |
| 1219 | zr, err := gzip.NewReader(bytes.NewReader(data)) |
| 1220 | if err != nil { |
| 1221 | t.Fatal(err) |
| 1222 | } |
| 1223 | if zr.Name != "" || !zr.ModTime.IsZero() { |
| 1224 | t.Errorf("the archive's gzip header names %q at %v", zr.Name, zr.ModTime) |
| 1225 | } |
| 1226 | tr := tar.NewReader(zr) |
| 1227 | var entries []archived |
| 1228 | for { |
| 1229 | hdr, err := tr.Next() |
| 1230 | if err == io.EOF { |
| 1231 | break |
| 1232 | } |
| 1233 | if err != nil { |
| 1234 | t.Fatal(err) |
| 1235 | } |
| 1236 | if !slices.Contains([]byte{tar.TypeReg, tar.TypeSymlink, tar.TypeDir}, hdr.Typeflag) || |
| 1237 | hdr.Uid != 0 || hdr.Gid != 0 || hdr.Uname != "" || hdr.Gname != "" { |
| 1238 | t.Errorf("the archive holds %q of type %q, owned by %d:%d, %q:%q", hdr.Name, hdr.Typeflag, hdr.Uid, hdr.Gid, hdr.Uname, hdr.Gname) |
| 1239 | } |
| 1240 | content, err := io.ReadAll(tr) |
| 1241 | if err != nil { |
| 1242 | t.Fatal(err) |
| 1243 | } |
| 1244 | entries = append(entries, archived{hdr, string(content)}) |
| 1245 | } |
| 1246 | if _, err := io.Copy(io.Discard, zr); err != nil { |
| 1247 | t.Fatal(err) |
| 1248 | } |
| 1249 | return entries |
| 1250 | } |
| 1251 | |
| 1252 | // archiveEntries is the entries of a gzipped tar archive, by name: each |
| 1253 | // file's content, without the white space that ends it, as git trims it, |
| 1254 | // and "" for each directory. |
| 1255 | func archiveEntries(t *testing.T, data []byte) map[string]string { |
| 1256 | t.Helper() |
| 1257 | entries := map[string]string{} |
| 1258 | for _, e := range readArchive(t, data) { |
| 1259 | entries[e.hdr.Name] = strings.TrimSpace(e.content) |
| 1260 | } |
| 1261 | return entries |
| 1262 | } |
| 1263 | |
| 1264 | // Markdown files and READMEs render as documents: headings with anchors, |
| 1265 | // a contents list for a long one, and relative links kept inside the |
| 1266 | // source browser at the same commit. ?plain=1 shows the escaped text, and |
| 1267 | // a path that names the other kind of entry redirects to its route. |
| 1268 | // Hostile Markdown arrives inert. A document that renders larger than |
| 1269 | // MaxShown shows its start, with a notice. |
| 1270 | func TestMarkdownPages(t *testing.T) { |
| 1271 | h := newHarness(t) |
| 1272 | large := "# Large\n\n[a]: https://example.org/" + strings.Repeat("x", 4000) + "\n\n" + strings.Repeat("[a]\n\n", 600) |
| 1273 | tip, bundle := h.commitMain("docs: a long document\n", |
| 1274 | file{"100644", "large/README.md", large}, file{"100644", "docs/large.md", large}, |
| 1275 | file{"100644", "docs/long.md", "# Long\n\n## One\n\nSee [the guide](guide.md#guide), [the README](../README.md),\n" + |
| 1276 | "[src](/src/), [docs](../docs), [here](#two), [above](../../x.md) and [js](javascript:alert(1)).\n\n" + |
| 1277 | "## Two\n\n### Three\n\n## Four\n\n| a | b |\n|---|--:|\n| 1 | 2 |\n"}, |
| 1278 | file{"100644", "docs/hostile.MD", "<script>alert(1)</script>\n\n<svg onload=alert(2)><form action=x><input></form>\n\n" + |
| 1279 | "[x](javascript:alert(3)) [y](data:text/html,z) <img src=x onerror=alert(4)>\n"}, |
| 1280 | ) |
| 1281 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1282 | base := "/tools/app/source/" |
| 1283 | long := h.page(base + "blob/" + tip + "/docs/long.md") |
| 1284 | for _, want := range []string{ |
| 1285 | `<h2 id="one">One <a class="anchor" href="#one">#</a></h2>`, |
| 1286 | `<details class="contents"><summary>Contents</summary><ul><li class="level2"><a href="#one">One</a></li>`, |
| 1287 | `<li class="level3"><a href="#three">Three</a></li>`, |
| 1288 | `<a href="` + base + `blob/` + tip + `/docs/guide.md#guide">the guide</a>`, |
| 1289 | `<a href="` + base + `blob/` + tip + `/README.md">the README</a>`, |
| 1290 | `<a href="` + base + `tree/` + tip + `/src/">src</a>`, |
| 1291 | `<a href="` + base + `blob/` + tip + `/docs">docs</a>`, |
| 1292 | `<a href="#two">here</a>`, ` above and js.`, |
| 1293 | `<th class="right">b</th>`, |
| 1294 | `<a href="` + base + `blob/` + tip + `/docs/long.md?plain=1">Plain text</a>`, |
| 1295 | } { |
| 1296 | if !strings.Contains(long, want) { |
| 1297 | t.Errorf("the rendered document lacks %s:\n%s", want, long) |
| 1298 | } |
| 1299 | } |
| 1300 | plain := h.page(base + "blob/" + tip + "/docs/long.md?plain=1") |
| 1301 | if !strings.Contains(plain, `<tr id="L1"><td class="ln"><a href="#L1">1</a></td><td class="src"># Long</td></tr>`) || |
| 1302 | !strings.Contains(plain, `<a href="`+base+`blob/`+tip+`/docs/long.md">Rendered</a>`) || strings.Contains(plain, "<h2") { |
| 1303 | t.Errorf("?plain=1 does not show the text line by line:\n%s", plain) |
| 1304 | } |
| 1305 | tree := h.page(base + "tree/" + tip + "/") |
| 1306 | if !strings.Contains(tree, `<h2 id="README">`) || !strings.Contains(tree, `<div class="markdown"><h1 id="app">`) { |
| 1307 | t.Errorf("the root does not render its README:\n%s", tree) |
| 1308 | } |
| 1309 | for from, to := range map[string]string{ |
| 1310 | base + "blob/" + tip + "/docs": base + "tree/" + tip + "/docs/", |
| 1311 | base + "tree/" + tip + "/README.md/": base + "blob/" + tip + "/README.md", |
| 1312 | base + "tree/" + tip + "/docs/long.md": base + "blob/" + tip + "/docs/long.md", |
| 1313 | } { |
| 1314 | if w := h.get(from); w.Code != http.StatusFound || w.Header().Get("Location") != to { |
| 1315 | t.Errorf("GET %s answered %d to %q", from, w.Code, w.Header().Get("Location")) |
| 1316 | } |
| 1317 | } |
| 1318 | at := base + "blob/" + tip + "/docs/hostile.MD" |
| 1319 | page := h.page(at) |
| 1320 | for _, active := range []string{"<script", "<svg", "<form", "<input", "<img", "javascript:", "data:", "style="} { |
| 1321 | if strings.Contains(page, active) { |
| 1322 | t.Errorf("GET %s holds %q", at, active) |
| 1323 | } |
| 1324 | } |
| 1325 | for _, want := range []string{"<p><script>alert(1)</script></p>", "<svg onload=alert(2)>", "<p>x y <img"} { |
| 1326 | if !strings.Contains(page, want) { |
| 1327 | t.Errorf("GET %s does not show %q:\n%s", at, want, page) |
| 1328 | } |
| 1329 | } |
| 1330 | if w := h.get(at); w.Header().Get("Content-Security-Policy") != csp { |
| 1331 | t.Errorf("a rendered page answered with policy %q", w.Header().Get("Content-Security-Policy")) |
| 1332 | } |
| 1333 | for target, notice := range map[string]string{ |
| 1334 | base + "tree/" + tip + "/large/": "This README is longer than a page shows, and only its start is shown.", |
| 1335 | base + "blob/" + tip + "/docs/large.md": "This file is longer than a page shows, and only its start is shown.", |
| 1336 | } { |
| 1337 | page := h.page(target) |
| 1338 | if !strings.Contains(page, notice) || !strings.Contains(page, `<h1 id="large">`) || |
| 1339 | strings.Count(page, "example.org/xxx") >= 600 || len(page) > MaxShown+64<<10 { |
| 1340 | t.Errorf("GET %s does not show the start of a large document with its notice:\n%.2000s", target, page) |
| 1341 | } |
| 1342 | } |
| 1343 | } |
| 1344 | |
| 1345 | // file is one file a test commits: its mode, path and content. The |
| 1346 | // content of a submodule, mode 160000, is the ID of its commit. |
| 1347 | type file struct{ mode, path, content string } |
| 1348 | |
| 1349 | // commitMain writes a commit onto the fixture's app main, with message, |
| 1350 | // that holds the files given beside what main holds. It returns the new |
| 1351 | // tip and a bundle of it. Each content is written once, however many |
| 1352 | // files hold it. |
| 1353 | func (h *harness) commitMain(message string, files ...file) (tip, bundle string) { |
| 1354 | t := h.t |
| 1355 | t.Helper() |
| 1356 | repo := h.f.Repos["app"] |
| 1357 | var b bytes.Buffer |
| 1358 | data := func(s string) { fmt.Fprintf(&b, "data %d\n%s\n", len(s), s) } |
| 1359 | marks := map[string]int{} |
| 1360 | for _, f := range files { |
| 1361 | if _, ok := marks[f.content]; !ok && f.mode != "160000" { |
| 1362 | marks[f.content] = len(marks) + 1 |
| 1363 | fmt.Fprintf(&b, "blob\nmark :%d\n", marks[f.content]) |
| 1364 | data(f.content) |
| 1365 | } |
| 1366 | } |
| 1367 | who := "Example Author <author@example.org> 1791190800 +0000" |
| 1368 | fmt.Fprintf(&b, "commit refs/heads/main\nauthor %s\ncommitter %s\n", who, who) |
| 1369 | data(message) |
| 1370 | fmt.Fprintf(&b, "from %s\n", git(t, repo, nil, "rev-parse", export.MainRef)) |
| 1371 | for _, f := range files { |
| 1372 | if f.mode == "160000" { |
| 1373 | fmt.Fprintf(&b, "M %s %s %s\n", f.mode, f.content, f.path) |
| 1374 | } else { |
| 1375 | fmt.Fprintf(&b, "M %s :%d %s\n", f.mode, marks[f.content], f.path) |
| 1376 | } |
| 1377 | } |
| 1378 | git(t, repo, b.Bytes(), "fast-import", "--quiet") |
| 1379 | tip = git(t, repo, nil, "rev-parse", export.MainRef) |
| 1380 | bundle = filepath.Join(t.TempDir(), "app.bundle") |
| 1381 | git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main") |
| 1382 | return tip, bundle |
| 1383 | } |
| 1384 | |
| 1385 | // publishMain activates a generation whose app main is tip, carried by |
| 1386 | // bundle. |
| 1387 | func (h *harness) publishMain(at time.Time, tip, bundle string) { |
| 1388 | h.t.Helper() |
| 1389 | h.publish(at, map[string]string{"app": bundle}, func(e *export.Export) { e.Projects[0].SourceTip = tip }) |
| 1390 | } |
| 1391 | |
| 1392 | // hostileMain writes a commit onto the fixture's app main that holds a |
| 1393 | // file of HTML, a file larger than a page shows, a binary file, a file |
| 1394 | // whose name is HTML, and a symbolic link out of the repository. It |
| 1395 | // returns the new tip and a bundle of it. |
| 1396 | func (h *harness) hostileMain() (tip, bundle string) { |
| 1397 | return h.commitMain("hostile: <script>alert(\"subject\")</script>\n", |
| 1398 | file{"100644", "page.html", "<html><script>alert(\"file\")</script><img src=x onerror=alert(2)></html>\n"}, |
| 1399 | file{"100644", "big.txt", strings.Repeat("big\n", (MaxFile/4)+1)}, |
| 1400 | file{"100644", "binary.bin", "\x7fELF\x00\x01\x02<script>alert(\"binary\")</script>"}, |
| 1401 | file{"100644", "<img src=x onerror=alert(3)>.txt", "named\n"}, |
| 1402 | file{"120000", "link", "../../etc/passwd"}, |
| 1403 | ) |
| 1404 | } |
| 1405 | |
| 1406 | // HTML, scripts, large files and binary files from a repository or the |
| 1407 | // plan render inert: escaped as text, or not shown. |
| 1408 | func TestHostileContentRendersInert(t *testing.T) { |
| 1409 | h := newHarness(t) |
| 1410 | tip, bundle := h.hostileMain() |
| 1411 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 1412 | e.Projects[0].SourceTip = tip |
| 1413 | }) |
| 1414 | |
| 1415 | inert := func(target, page string, wants ...string) { |
| 1416 | t.Helper() |
| 1417 | // Escaped, a tag is text; only a tag the page did not escape, or |
| 1418 | // an attribute it let a value break out into, is active. |
| 1419 | for _, active := range []string{"<script", "<img", `" onerror`, "\x00"} { |
| 1420 | if strings.Contains(page, active) { |
| 1421 | t.Errorf("GET %s holds %q", target, active) |
| 1422 | } |
| 1423 | } |
| 1424 | for _, want := range wants { |
| 1425 | if !strings.Contains(page, want) { |
| 1426 | t.Errorf("GET %s does not show %q", target, want) |
| 1427 | } |
| 1428 | } |
| 1429 | } |
| 1430 | at := "/tools/app/source/tree/" + tip + "/" |
| 1431 | inert(at, h.page(at), |
| 1432 | `<script>alert("readme")</script>`, |
| 1433 | `<img src=x onerror=alert(3)>.txt`, |
| 1434 | `href="/tools/app/source/blob/`+tip+`/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt"`) |
| 1435 | at = "/tools/app/source/blob/" + tip + "/%3Cimg%20src=x%20onerror=alert%283%29%3E.txt" |
| 1436 | inert(at, h.page(at), ">named<") |
| 1437 | at = "/tools/app/source/blob/" + tip + "/page.html" |
| 1438 | inert(at, h.page(at), `<html><script>alert("file")</script><img src=x onerror=alert(2)></html>`) |
| 1439 | at = "/tools/app/source/blob/" + tip + "/big.txt" |
| 1440 | page := h.page(at) |
| 1441 | inert(at, page, "This file is 1.0 MiB, larger than the 1.0 MiB a page shows.") |
| 1442 | if len(page) > 64<<10 { |
| 1443 | t.Errorf("the large file's page is %d bytes", len(page)) |
| 1444 | } |
| 1445 | at = "/tools/app/source/blob/" + tip + "/binary.bin" |
| 1446 | inert(at, h.page(at), "This file is binary, 39 bytes, and is not shown.") |
| 1447 | at = "/tools/app/source/blob/" + tip + "/link" |
| 1448 | inert(at, h.page(at), "A symbolic link to ../../etc/passwd. It is not followed.") |
| 1449 | at = "/tools/app/source/log/" + tip |
| 1450 | inert(at, h.page(at), "hostile: <script>alert("subject")</script>") |
| 1451 | |
| 1452 | at = "/tools/app/knots/bd-a000004" |
| 1453 | inert(at, h.page(at), |
| 1454 | `A README holding <script>alert("knot")</script> must show as text.`, |
| 1455 | `Also <img src=x onerror=alert(1)> in a comment.`) |
| 1456 | } |
| 1457 | |
| 1458 | // A directory larger than a page reads is listed in part, and a commit |
| 1459 | // message larger than a page reads ends its page of history early. git |
| 1460 | // is stopped once its listing passes MaxRead, and nothing past a record's |
| 1461 | // bound is kept. |
| 1462 | func TestOversizedTreeAndHistory(t *testing.T) { |
| 1463 | h := newHarness(t) |
| 1464 | // Each entry of huge/ takes 308 bytes of git ls-tree's output, so |
| 1465 | // 15,000 of them pass MaxRead at about entry 13,600. |
| 1466 | longest := "!" + strings.Repeat("l", 4095) |
| 1467 | files := []file{{"100644", "huge/" + longest, "x\n"}} |
| 1468 | name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) } |
| 1469 | for i := range 15_000 { |
| 1470 | files = append(files, file{"100644", "huge/" + name(i), "x\n"}) |
| 1471 | } |
| 1472 | if n := 15_000 * (6 + 1 + 4 + 1 + 40 + 1 + 7 + 1 + 246 + 1); n <= MaxRead { |
| 1473 | t.Fatalf("the listing of huge/ is %d bytes, within MaxRead", n) |
| 1474 | } |
| 1475 | h.commitMain("app: a directory larger than a page reads\n", files...) |
| 1476 | h.commitMain("long: " + strings.Repeat("a long subject ", (100<<10)/15) + "\n") |
| 1477 | tip, bundle := h.commitMain("longer: " + strings.Repeat("a subject past the bound ", (5<<20)/25) + "\n") |
| 1478 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1479 | |
| 1480 | at := "/tools/app/source/tree/" + tip + "/huge/" |
| 1481 | page := h.page(at) |
| 1482 | if !strings.Contains(page, "This directory is larger than a page reads, so only part of it is listed.") { |
| 1483 | t.Error("huge/ is not marked as listed in part") |
| 1484 | } |
| 1485 | if n := strings.Count(page, `<tr><td class="name">`); n != MaxEntries { |
| 1486 | t.Errorf("huge/ lists %d entries, not %d", n, MaxEntries) |
| 1487 | } |
| 1488 | if !strings.Contains(page, `">`+longest+`</a>`) { |
| 1489 | t.Error("the entry with the longest name git accepts is not listed whole") |
| 1490 | } |
| 1491 | if len(page) > 1<<20 { |
| 1492 | t.Errorf("huge/'s page is %d bytes", len(page)) |
| 1493 | } |
| 1494 | if w := h.get("/tools/app/source/blob/" + tip + "/huge/" + name(0)); w.Code != http.StatusOK { |
| 1495 | t.Errorf("an entry read before MaxRead answered %d", w.Code) |
| 1496 | } |
| 1497 | if w := h.get("/tools/app/source/blob/" + tip + "/huge/" + name(14_999)); w.Code != http.StatusNotFound { |
| 1498 | t.Errorf("an entry past MaxRead answered %d", w.Code) |
| 1499 | } |
| 1500 | |
| 1501 | at = "/tools/app/source/log/" + tip |
| 1502 | page = h.page(at) |
| 1503 | if !strings.Contains(page, "This page ends early: its commits are larger than a page reads.") { |
| 1504 | t.Error("the page of history holding a 5 MiB message does not end early") |
| 1505 | } |
| 1506 | if n := strings.Count(page, `<tr><td class="name">`); n != 1 { |
| 1507 | t.Errorf("the page that ends early lists %d commits, not the one it cut", n) |
| 1508 | } |
| 1509 | if m := regexp.MustCompile(`<td>(longer: a subject past the bound[^<]*)…</td>`).FindStringSubmatch(page); m == nil || len(m[1]) > maxLogText { |
| 1510 | t.Error("the cut commit's subject is not shown cut to maxLogText") |
| 1511 | } |
| 1512 | older := at + "?from=" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~1") |
| 1513 | if !strings.Contains(page, `href="`+older+`"`) { |
| 1514 | t.Error("the page that ends early does not link the commits after the one it cut") |
| 1515 | } |
| 1516 | page = h.page(older) |
| 1517 | if strings.Contains(page, "ends early") || !strings.Contains(page, "long: a long subject") || !strings.Contains(page, "app: the first README") { |
| 1518 | t.Errorf("the next page of history is not whole:\n%s", page) |
| 1519 | } |
| 1520 | if strings.Contains(page, strings.Repeat("a long subject ", (maxLogText/15)+1)) { |
| 1521 | t.Error("a subject longer than a page shows is not cut") |
| 1522 | } |
| 1523 | for _, p := range []string{at, older} { |
| 1524 | if n := len(h.page(p)); n > 64<<10 { |
| 1525 | t.Errorf("GET %s is %d bytes", p, n) |
| 1526 | } |
| 1527 | } |
| 1528 | } |
| 1529 | |
| 1530 | // The directories along a path share one budget of MaxRead bytes of git |
| 1531 | // ls-tree's output. Each of big/ and big/zz/ lists about 3 MB before |
| 1532 | // the entry the path names next, within MaxRead alone, so the directory |
| 1533 | // big/zz/ is served. A path through both, to big/zz/zz/f, passes the |
| 1534 | // budget and answers 404. The directory's own listing has a budget of |
| 1535 | // its own. |
| 1536 | func TestResolveSharesOneBudget(t *testing.T) { |
| 1537 | h := newHarness(t) |
| 1538 | name := func(i int) string { return fmt.Sprintf("%05d-%s", i, strings.Repeat("n", 240)) } |
| 1539 | var files []file |
| 1540 | for i := range 10_000 { |
| 1541 | files = append(files, file{"100644", "big/" + name(i), "x\n"}, file{"100644", "big/zz/" + name(i), "x\n"}) |
| 1542 | } |
| 1543 | files = append(files, file{"100644", "big/zz/zz/f", "the file\n"}) |
| 1544 | if each := 6 + 1 + 4 + 1 + 40 + 1 + 246 + 1; 10_000*each > MaxRead || 2*10_000*each <= MaxRead { |
| 1545 | t.Fatalf("the listings take %d bytes each, not between half MaxRead and MaxRead", 10_000*each) |
| 1546 | } |
| 1547 | tip, bundle := h.commitMain("app: two large directories, one in the other\n", files...) |
| 1548 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1549 | |
| 1550 | h.page("/tools/app/source/tree/" + tip + "/big/zz/") |
| 1551 | h.page("/tools/app/source/blob/" + tip + "/big/zz/" + name(0)) |
| 1552 | for _, target := range []string{"/tools/app/source/tree/" + tip + "/big/zz/zz/", "/tools/app/source/blob/" + tip + "/big/zz/zz/f"} { |
| 1553 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 1554 | t.Errorf("GET %s, through %d bytes of listings, answered %d", target, 2*10_000*300, w.Code) |
| 1555 | } |
| 1556 | } |
| 1557 | } |
| 1558 | |
| 1559 | // lines writes onto the fixture's app main a merge of n lines of |
| 1560 | // history, each of length commits, all from main's tip. The lines' commits |
| 1561 | // are dated in turn, one line's after another's, so a log interleaves |
| 1562 | // them, and each page ends with commits of every line still to show. The |
| 1563 | // merge is an octopus when n is more than two. It returns the merge and a |
| 1564 | // bundle of it. |
| 1565 | func (h *harness) lines(n, length int) (tip, bundle string) { |
| 1566 | var commits []commit |
| 1567 | for i := range length { |
| 1568 | for l := range n { |
| 1569 | c := commit{message: fmt.Sprintf("line %d, commit %d\n", l, i), parents: []int{0}} |
| 1570 | if i > 0 { |
| 1571 | c.parents = []int{(i-1)*n + l + 1} |
| 1572 | } |
| 1573 | commits = append(commits, c) |
| 1574 | } |
| 1575 | } |
| 1576 | merge := commit{message: fmt.Sprintf("merge %d lines\n", n)} |
| 1577 | for l := range n { |
| 1578 | merge.parents = append(merge.parents, (length-1)*n+l+1) |
| 1579 | } |
| 1580 | return h.history(append(commits, merge)...) |
| 1581 | } |
| 1582 | |
| 1583 | // commit is one commit history writes. Its parents are the numbers of |
| 1584 | // commits written before it, counted from 1, or 0 for main's tip. |
| 1585 | type commit struct { |
| 1586 | message string |
| 1587 | parents []int |
| 1588 | } |
| 1589 | |
| 1590 | // history writes commits onto the fixture's app main, in order, and |
| 1591 | // moves main to the last. Each commit is dated a second after the one |
| 1592 | // before it. It returns the last commit and a bundle of it. |
| 1593 | func (h *harness) history(commits ...commit) (tip, bundle string) { |
| 1594 | t := h.t |
| 1595 | t.Helper() |
| 1596 | repo := h.f.Repos["app"] |
| 1597 | base := git(t, repo, nil, "rev-parse", export.MainRef) |
| 1598 | var b bytes.Buffer |
| 1599 | for i, c := range commits { |
| 1600 | who := fmt.Sprintf("Example Author <author@example.org> %d +0000", 1791190800+i) |
| 1601 | fmt.Fprintf(&b, "commit refs/heads/main\nmark :%d\nauthor %s\ncommitter %s\ndata %d\n%s\n", i+1, who, who, len(c.message), c.message) |
| 1602 | for j, p := range c.parents { |
| 1603 | parent := base |
| 1604 | if p > 0 { |
| 1605 | parent = fmt.Sprintf(":%d", p) |
| 1606 | } |
| 1607 | if j == 0 { |
| 1608 | fmt.Fprintf(&b, "from %s\n", parent) |
| 1609 | } else { |
| 1610 | fmt.Fprintf(&b, "merge %s\n", parent) |
| 1611 | } |
| 1612 | } |
| 1613 | } |
| 1614 | git(t, repo, b.Bytes(), "fast-import", "--quiet") |
| 1615 | tip = git(t, repo, nil, "rev-parse", export.MainRef) |
| 1616 | bundle = filepath.Join(t.TempDir(), "app.bundle") |
| 1617 | git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main") |
| 1618 | return tip, bundle |
| 1619 | } |
| 1620 | |
| 1621 | // logged is the commits a page of history lists, in order. |
| 1622 | var logged = regexp.MustCompile(`<td class="name"><a href="/tools/app/source/tree/([0-9a-f]+)/">`) |
| 1623 | |
| 1624 | // continued is the links a page of history has to older pages: its Older |
| 1625 | // link, and a link for each other line it leaves to show. |
| 1626 | var continued = regexp.MustCompile(`href="(/tools/app/source/log/[0-9a-f]+\?from=[0-9a-f,]+)"`) |
| 1627 | |
| 1628 | // reach follows every link to older pages from the page at target, and |
| 1629 | // from each page it reaches, and counts how many of those pages show each |
| 1630 | // commit. It fails once it has read more than most pages. |
| 1631 | func (h *harness) reach(target string, most int) map[string]int { |
| 1632 | h.t.Helper() |
| 1633 | seen, read := map[string]int{}, map[string]bool{target: true} |
| 1634 | for next := []string{target}; len(next) > 0; next = next[1:] { |
| 1635 | if len(read) > most { |
| 1636 | h.t.Fatalf("the links from %s reach more than %d pages", target, most) |
| 1637 | } |
| 1638 | page := h.page(next[0]) |
| 1639 | for _, m := range logged.FindAllStringSubmatch(page, -1) { |
| 1640 | seen[m[1]]++ |
| 1641 | } |
| 1642 | for _, m := range continued.FindAllStringSubmatch(page, -1) { |
| 1643 | if !read[m[1]] { |
| 1644 | read[m[1]] = true |
| 1645 | next = append(next, m[1]) |
| 1646 | } |
| 1647 | } |
| 1648 | } |
| 1649 | return seen |
| 1650 | } |
| 1651 | |
| 1652 | // A page of history links the older page as the commits it leaves to |
| 1653 | // show next, so the history of a merge whose lines run past a page is |
| 1654 | // shown whole: following the older links from the tip shows every commit |
| 1655 | // main reaches, each once. A page past the first links the newest page. A |
| 1656 | // ?from= that is not ascending, names a commit the page's commit does |
| 1657 | // not reach, or names more than MaxFrontier commits answers 404. |
| 1658 | func TestHistoryAcrossMerges(t *testing.T) { |
| 1659 | h := newHarness(t) |
| 1660 | tip, bundle := h.lines(2, 60) |
| 1661 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1662 | |
| 1663 | at := "/tools/app/source/log/" + tip |
| 1664 | seen := map[string]int{} |
| 1665 | merged := false |
| 1666 | for target, pages := at, 0; target != ""; pages++ { |
| 1667 | if pages > 10 { |
| 1668 | t.Fatal("the older links do not end") |
| 1669 | } |
| 1670 | page := h.page(target) |
| 1671 | for _, m := range logged.FindAllStringSubmatch(page, -1) { |
| 1672 | seen[m[1]]++ |
| 1673 | } |
| 1674 | if target != at && !strings.Contains(page, `href="`+at+`">Newest`) { |
| 1675 | t.Errorf("%s does not link the newest page", target) |
| 1676 | } |
| 1677 | target = "" |
| 1678 | if m := regexp.MustCompile(`href="(/tools/app/source/log/[0-9a-f]+\?from=([0-9a-f,]+))">Older`).FindStringSubmatch(page); m != nil { |
| 1679 | target, merged = m[1], merged || strings.Contains(m[2], ",") |
| 1680 | } |
| 1681 | } |
| 1682 | all := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) |
| 1683 | if len(seen) != len(all) { |
| 1684 | t.Errorf("the older links show %d commits of the %d main reaches", len(seen), len(all)) |
| 1685 | } |
| 1686 | for _, id := range all { |
| 1687 | if seen[id] != 1 { |
| 1688 | t.Errorf("the older links show %s %d times", id, seen[id]) |
| 1689 | } |
| 1690 | } |
| 1691 | if !merged { |
| 1692 | t.Error("no page ends with both lines still to show") |
| 1693 | } |
| 1694 | |
| 1695 | line := strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", "--max-count=2", tip+"^2")) |
| 1696 | slices.Sort(line) |
| 1697 | for _, from := range []string{ |
| 1698 | line[1] + "," + line[0], // not ascending |
| 1699 | line[0] + "," + line[0], // twice |
| 1700 | tip, // not reached from the page's commit |
| 1701 | strings.Repeat("1", 40), // no object |
| 1702 | strings.Repeat(line[0]+",", MaxFrontier) + line[1], |
| 1703 | line[0][:12], |
| 1704 | "", |
| 1705 | } { |
| 1706 | target := "/tools/app/source/log/" + line[1] + "?from=" + from |
| 1707 | if w := h.get(target); w.Code != http.StatusNotFound { |
| 1708 | t.Errorf("GET %s answered %d", target, w.Code) |
| 1709 | } |
| 1710 | } |
| 1711 | if w := h.get(at + "?from=" + line[0] + "&from=" + line[1]); w.Code != http.StatusNotFound { |
| 1712 | t.Errorf("two from parameters answered %d", w.Code) |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | // A page that leaves more than MaxFrontier commits to show starts its |
| 1717 | // Older link from MaxFrontier of them, links the history from each of the |
| 1718 | // rest, and says how many lines continue: here a merge of 65 lines, each |
| 1719 | // still to show once the first page ends. Following those links from the |
| 1720 | // tip reaches every commit main reaches. |
| 1721 | func TestWideHistoryStaysReachable(t *testing.T) { |
| 1722 | h := newHarness(t) |
| 1723 | tip, bundle := h.lines(MaxFrontier+1, 2) |
| 1724 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1725 | at := "/tools/app/source/log/" + tip |
| 1726 | page := h.page(at) |
| 1727 | if n := len(logged.FindAllString(page, -1)); n != LogPage { |
| 1728 | t.Errorf("the page shows %d commits", n) |
| 1729 | } |
| 1730 | m := regexp.MustCompile(`href="` + at + `\?from=([0-9a-f,]+)">Older`).FindStringSubmatch(page) |
| 1731 | if m == nil || len(strings.Split(m[1], ",")) != MaxFrontier { |
| 1732 | t.Errorf("the page's Older link does not start from MaxFrontier commits: %q", m) |
| 1733 | } |
| 1734 | if n := len(continued.FindAllString(page, -1)); n != 2 { |
| 1735 | t.Errorf("the page links %d older pages, not the Older one and one more", n) |
| 1736 | } |
| 1737 | if !strings.Contains(page, "Older history continues along 65 lines at once, more than the Older link follows. Each link below follows one of the remaining lines.") { |
| 1738 | t.Error("the page does not say how many lines continue") |
| 1739 | } |
| 1740 | |
| 1741 | seen := h.reach(at, 20) |
| 1742 | for _, id := range strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) { |
| 1743 | if seen[id] == 0 { |
| 1744 | t.Errorf("no link from the tip's history reaches %s", id) |
| 1745 | } |
| 1746 | } |
| 1747 | } |
| 1748 | |
| 1749 | // A page ends before a merge that would leave more than MaxLeftToShow |
| 1750 | // commits to show, and says so. Here the tip merges another merge and 99 |
| 1751 | // lines, and the other merge, shown next, merges 100 lines more: 199 |
| 1752 | // left to show. Following the links from the tip still reaches every |
| 1753 | // commit main reaches. |
| 1754 | func TestCrowdedHistoryEndsEarly(t *testing.T) { |
| 1755 | h := newHarness(t) |
| 1756 | var commits []commit |
| 1757 | inner := commit{message: "merge 100 lines\n"} |
| 1758 | outer := commit{message: "merge a merge and 99 lines\n", parents: []int{200}} |
| 1759 | for l := range 199 { |
| 1760 | commits = append(commits, commit{message: fmt.Sprintf("line %d\n", l), parents: []int{0}}) |
| 1761 | if l < 100 { |
| 1762 | inner.parents = append(inner.parents, l+1) |
| 1763 | } else { |
| 1764 | outer.parents = append(outer.parents, l+1) |
| 1765 | } |
| 1766 | } |
| 1767 | tip, bundle := h.history(append(commits, inner, outer)...) |
| 1768 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1769 | at := "/tools/app/source/log/" + tip |
| 1770 | page := h.page(at) |
| 1771 | if shown := logged.FindAllStringSubmatch(page, -1); len(shown) != 1 || shown[0][1] != tip { |
| 1772 | t.Errorf("the page shows %d commits, not the tip alone", len(shown)) |
| 1773 | } |
| 1774 | if !strings.Contains(page, "This page ends early, before a commit that would leave more lines of history than one page can link to.") { |
| 1775 | t.Error("the page does not say it ends early") |
| 1776 | } |
| 1777 | if n := len(continued.FindAllString(page, -1)); n != 1+100-MaxFrontier { |
| 1778 | t.Errorf("the page links %d older pages, not one for each of the 100 lines past MaxFrontier and the Older one", n) |
| 1779 | } |
| 1780 | |
| 1781 | seen := h.reach(at, 200) |
| 1782 | for _, id := range strings.Fields(git(t, h.f.Repos["app"], nil, "rev-list", tip)) { |
| 1783 | if seen[id] == 0 { |
| 1784 | t.Errorf("no link from the tip's history reaches %s", id) |
| 1785 | } |
| 1786 | } |
| 1787 | } |
| 1788 | |
| 1789 | // A merge whose line of parents is longer than a record of git log keeps |
| 1790 | // is shown, as the first commit of a page and further down. Its subject is |
| 1791 | // shown, with a note that older pages follow its first MaxParents |
| 1792 | // parents. Each of those is shown or linked, and none of the others is |
| 1793 | // linked. |
| 1794 | func TestMergeOfManyParents(t *testing.T) { |
| 1795 | h := newHarness(t) |
| 1796 | const lines = 420 |
| 1797 | var commits []commit |
| 1798 | merge := commit{message: "merge 420 lines\n"} |
| 1799 | for l := range lines { |
| 1800 | commits = append(commits, commit{message: fmt.Sprintf("line %d\n", l), parents: []int{0}}) |
| 1801 | merge.parents = append(merge.parents, l+1) |
| 1802 | } |
| 1803 | commits = append(commits, merge) |
| 1804 | for i := range LogPage { |
| 1805 | commits = append(commits, commit{message: fmt.Sprintf("after the merge, commit %d\n", i), parents: []int{len(commits)}}) |
| 1806 | } |
| 1807 | tip, bundle := h.history(commits...) |
| 1808 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 1809 | repo := h.f.Repos["app"] |
| 1810 | w := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, LogPage)) |
| 1811 | parents := strings.Fields(git(t, repo, nil, "log", "-1", "--format=%P", w)) |
| 1812 | if len(parents) != lines || len(w)+1+len(parents)*(len(w)+1) <= maxLogRecord { |
| 1813 | t.Fatalf("the merge's ID and %d parents fit in one record of git log", len(parents)) |
| 1814 | } |
| 1815 | |
| 1816 | at := "/tools/app/source/log/" + tip |
| 1817 | older := at + "?from=" + w |
| 1818 | if !strings.Contains(h.page(at), `href="`+older+`">Older`) { |
| 1819 | t.Fatal("the tip's page does not end before the merge") |
| 1820 | } |
| 1821 | note := fmt.Sprintf("merge 420 lines<p class=\"notice\">This merge has more than %d parents. Older pages follow its first %d.</p>", MaxParents, MaxParents) |
| 1822 | child := git(t, repo, nil, "rev-parse", fmt.Sprintf("%s~%d", tip, LogPage-1)) |
| 1823 | // Where each page shows the merge: first on the tip page's older |
| 1824 | // page and on the merge's own history, second on its child's. |
| 1825 | for target, want := range map[string]int{older: 0, "/tools/app/source/log/" + w: 0, "/tools/app/source/log/" + child: 1} { |
| 1826 | page := h.page(target) |
| 1827 | shown := map[string]bool{} |
| 1828 | var order []string |
| 1829 | for _, m := range logged.FindAllStringSubmatch(page, -1) { |
| 1830 | shown[m[1]] = true |
| 1831 | order = append(order, m[1]) |
| 1832 | } |
| 1833 | if len(order) != LogPage || order[want] != w { |
| 1834 | t.Errorf("GET %s does not show the merge as commit %d of %d", target, want+1, LogPage) |
| 1835 | continue |
| 1836 | } |
| 1837 | if strings.Count(page, note) != 1 { |
| 1838 | t.Errorf("GET %s does not show the merge's subject and its note once", target) |
| 1839 | } |
| 1840 | linked := map[string]bool{} |
| 1841 | for _, m := range continued.FindAllStringSubmatch(page, -1) { |
| 1842 | _, from, _ := strings.Cut(m[1], "?from=") |
| 1843 | for _, id := range strings.Split(from, ",") { |
| 1844 | linked[id] = true |
| 1845 | } |
| 1846 | } |
| 1847 | for i, id := range parents { |
| 1848 | switch { |
| 1849 | case i < MaxParents && !shown[id] && !linked[id]: |
| 1850 | t.Errorf("GET %s neither shows nor links the merge's parent %d", target, i+1) |
| 1851 | case i >= MaxParents && linked[id]: |
| 1852 | t.Errorf("GET %s links the merge's parent %d", target, i+1) |
| 1853 | } |
| 1854 | } |
| 1855 | } |
| 1856 | } |
| 1857 | |
| 1858 | // A source request's git commands have a bound of their own, far within |
| 1859 | // the request's time: a git that does not finish is stopped once it |
| 1860 | // passes, and the request answers 503 and gives back its git slot. The |
| 1861 | // failure is logged. |
| 1862 | func TestSourceGitHasItsOwnBound(t *testing.T) { |
| 1863 | h := newHarness(t) |
| 1864 | real, err := exec.LookPath(export.GitProgram) |
| 1865 | if err != nil { |
| 1866 | t.Fatal(err) |
| 1867 | } |
| 1868 | if real, err = filepath.Abs(real); err != nil { |
| 1869 | t.Fatal(err) |
| 1870 | } |
| 1871 | slow := filepath.Join(t.TempDir(), "git") |
| 1872 | script := "#!/bin/sh\nfor a; do [ \"$a\" = ls-tree ] && exec sleep 60; done\nexec '" + real + "' \"$@\"\n" |
| 1873 | if err := os.WriteFile(slow, []byte(script), 0o755); err != nil { |
| 1874 | t.Fatal(err) |
| 1875 | } |
| 1876 | program := export.GitProgram |
| 1877 | export.GitProgram = slow |
| 1878 | t.Cleanup(func() { export.GitProgram = program }) |
| 1879 | var logged []error |
| 1880 | var mu sync.Mutex |
| 1881 | h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() } |
| 1882 | h.srv.gitTime = 300 * time.Millisecond |
| 1883 | |
| 1884 | start := time.Now() |
| 1885 | w := h.get("/tools/app/source/tree/" + h.tip() + "/") |
| 1886 | if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second { |
| 1887 | t.Errorf("a source request whose git does not finish answered %d after %v", w.Code, took) |
| 1888 | } |
| 1889 | if len(h.srv.slots) != 0 { |
| 1890 | t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots)) |
| 1891 | } |
| 1892 | mu.Lock() |
| 1893 | defer mu.Unlock() |
| 1894 | if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") { |
| 1895 | t.Errorf("the server logged %v", logged) |
| 1896 | } |
| 1897 | if w := h.get("/tools/app/knots/oc-a000002"); w.Code != http.StatusOK { |
| 1898 | t.Errorf("a knot answered %d", w.Code) |
| 1899 | } |
| 1900 | } |
| 1901 | |
| 1902 | // A source request's bound on its git slot runs from when it takes the |
| 1903 | // slot, and covers its wait for its generation's export to be read. A |
| 1904 | // source request whose export is read slowly answers 503 once the bound |
| 1905 | // passes, gives back its slot, and is logged, while a request for the |
| 1906 | // plan, which holds no slot, waits on for the same read and is served. |
| 1907 | func TestGitSlotBoundCoversTheLoad(t *testing.T) { |
| 1908 | h := newHarness(t) |
| 1909 | var mu sync.Mutex |
| 1910 | var logged []error |
| 1911 | h.srv.log = func(err error) { mu.Lock(); logged = append(logged, err); mu.Unlock() } |
| 1912 | h.srv.gitTime = 300 * time.Millisecond |
| 1913 | hold := make(chan struct{}) |
| 1914 | h.srv.loading = func(export.Generation) { <-hold } |
| 1915 | |
| 1916 | plan := make(chan *httptest.ResponseRecorder, 1) |
| 1917 | go func() { |
| 1918 | w := httptest.NewRecorder() |
| 1919 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 1920 | plan <- w |
| 1921 | }() |
| 1922 | eventually(t, "the plan waits for the export to be read", func() bool { return len(h.srv.loaders) == 1 }) |
| 1923 | start := time.Now() |
| 1924 | w := h.get("/tools/app/source/tree/" + h.tip() + "/") |
| 1925 | if took := time.Since(start); w.Code != http.StatusServiceUnavailable || took > 5*time.Second { |
| 1926 | t.Errorf("a source request whose export is read slowly answered %d after %v", w.Code, took) |
| 1927 | } |
| 1928 | if len(h.srv.slots) != 0 { |
| 1929 | t.Errorf("the request holds %d git slots once it answered", len(h.srv.slots)) |
| 1930 | } |
| 1931 | mu.Lock() |
| 1932 | if len(logged) != 1 || !strings.Contains(logged[0].Error(), "the request held its git slot past 300ms") || |
| 1933 | !strings.Contains(logged[0].Error(), "export to be read") { |
| 1934 | t.Errorf("the server logged %v", logged) |
| 1935 | } |
| 1936 | mu.Unlock() |
| 1937 | |
| 1938 | close(hold) |
| 1939 | select { |
| 1940 | case w := <-plan: |
| 1941 | if w.Code != http.StatusOK { |
| 1942 | t.Errorf("the plan answered %d once its export was read", w.Code) |
| 1943 | } |
| 1944 | case <-time.After(10 * time.Second): |
| 1945 | t.Fatal("the plan was not served once its export was read") |
| 1946 | } |
| 1947 | h.page("/tools/app/source/tree/" + h.tip() + "/") |
| 1948 | } |
| 1949 | |
| 1950 | // A source request gives back its git slot before it renders its page, so |
| 1951 | // a page that renders slowly holds no slot, and is not held to the bound |
| 1952 | // on holding one. While one renders, past that bound, another source |
| 1953 | // request is served, and the first is served in full once it renders. |
| 1954 | func TestRenderingHoldsNoGitSlot(t *testing.T) { |
| 1955 | h := newHarness(t) |
| 1956 | h.page("/") |
| 1957 | h.srv.gitTime = 300 * time.Millisecond |
| 1958 | rendering, hold := make(chan struct{}), make(chan struct{}) |
| 1959 | var first atomic.Bool |
| 1960 | h.srv.rendering = func(name string) { |
| 1961 | if name == "tree" && first.CompareAndSwap(false, true) { |
| 1962 | close(rendering) |
| 1963 | <-hold |
| 1964 | } |
| 1965 | } |
| 1966 | |
| 1967 | served := make(chan *httptest.ResponseRecorder, 1) |
| 1968 | go func() { |
| 1969 | w := httptest.NewRecorder() |
| 1970 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/source/tree/"+h.tip()+"/", nil)) |
| 1971 | served <- w |
| 1972 | }() |
| 1973 | select { |
| 1974 | case <-rendering: |
| 1975 | case <-time.After(10 * time.Second): |
| 1976 | t.Fatal("the source request did not render") |
| 1977 | } |
| 1978 | if len(h.srv.slots) != 0 { |
| 1979 | t.Errorf("a source request holds %d git slots while it renders", len(h.srv.slots)) |
| 1980 | } |
| 1981 | h.page("/tools/app/source/blob/" + h.tip() + "/docs/guide.md") |
| 1982 | time.Sleep(2 * h.srv.gitTime) |
| 1983 | close(hold) |
| 1984 | select { |
| 1985 | case w := <-served: |
| 1986 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "guide.md") { |
| 1987 | t.Errorf("a source request that rendered past the bound on its slot answered %d", w.Code) |
| 1988 | } |
| 1989 | case <-time.After(10 * time.Second): |
| 1990 | t.Fatal("the source request was not served once it rendered") |
| 1991 | } |
| 1992 | } |
| 1993 | |
| 1994 | // A SHA-256 project's commits are served by their 64 hex digits alone. |
| 1995 | // The first 40 of them, which git would read as an abbreviation, answer |
| 1996 | // 404 on every source route, so each page has one address. |
| 1997 | func TestSHA256CommitIDs(t *testing.T) { |
| 1998 | h := newHarness(t) |
| 1999 | repo := filepath.Join(t.TempDir(), "app.git") |
| 2000 | git(t, repo, nil, "init", "--quiet", "--bare", "--template=", "--initial-branch=main", "--object-format=sha256") |
| 2001 | readme := "# app\n\nA SHA-256 repository.\n" |
| 2002 | who := "Example Author <author@example.org> 1791190800 +0000" |
| 2003 | stream := fmt.Sprintf("commit refs/heads/main\nauthor %s\ncommitter %s\ndata 7\nsha256\n\nM 100644 inline README.md\ndata %d\n%s\n", |
| 2004 | who, who, len(readme), readme) |
| 2005 | git(t, repo, []byte(stream), "fast-import", "--quiet") |
| 2006 | tip := git(t, repo, nil, "rev-parse", export.MainRef) |
| 2007 | if len(tip) != 64 { |
| 2008 | t.Fatalf("the tip is %q", tip) |
| 2009 | } |
| 2010 | bundle := filepath.Join(t.TempDir(), "app.bundle") |
| 2011 | git(t, repo, nil, "bundle", "create", "--quiet", bundle, "main") |
| 2012 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 2013 | |
| 2014 | for _, route := range []string{"/tools/app/source/tree/%s/", "/tools/app/source/blob/%s/README.md", "/tools/app/source/log/%s"} { |
| 2015 | if page := h.page(fmt.Sprintf(route, tip)); !strings.Contains(page, tip[:12]) { |
| 2016 | t.Errorf("%s does not name the commit", fmt.Sprintf(route, tip)) |
| 2017 | } |
| 2018 | if w := h.get(fmt.Sprintf(route, tip[:40])); w.Code != http.StatusNotFound { |
| 2019 | t.Errorf("%s answered %d", fmt.Sprintf(route, tip[:40]), w.Code) |
| 2020 | } |
| 2021 | } |
| 2022 | if w := h.get("/tools/app/source/"); w.Header().Get("Location") != "/tools/app/source/tree/"+tip+"/" { |
| 2023 | t.Errorf("/tools/app/source/ redirects to %q", w.Header().Get("Location")) |
| 2024 | } |
| 2025 | w := h.get("/tools/app/source/archive/" + tip + ".tar.gz") |
| 2026 | if w.Code != http.StatusOK || !strings.Contains(w.Header().Get("Content-Disposition"), `"app-`+tip[:12]+`.tar.gz"`) { |
| 2027 | t.Errorf("the archive answered %d, %q", w.Code, w.Header().Get("Content-Disposition")) |
| 2028 | } |
| 2029 | if _, ok := archiveEntries(t, w.Body.Bytes())["app-"+tip[:12]+"/README.md"]; !ok { |
| 2030 | t.Error("the archive does not hold README.md under its directory") |
| 2031 | } |
| 2032 | if w := h.get("/tools/app/source/archive/" + tip[:40] + ".tar.gz"); w.Code != http.StatusNotFound { |
| 2033 | t.Errorf("the archive of the tip's first 40 hex digits answered %d", w.Code) |
| 2034 | } |
| 2035 | } |
| 2036 | |
| 2037 | // A file of exactly MaxFile bytes of newlines is shown to MaxLines lines, |
| 2038 | // and its page says where it stops. A README longer than a page shows is |
| 2039 | // shown in part. |
| 2040 | func TestLongFileIsShownInPart(t *testing.T) { |
| 2041 | h := newHarness(t) |
| 2042 | tip, bundle := h.commitMain("app: long files\n", |
| 2043 | file{"100644", "newlines.txt", strings.Repeat("\n", MaxFile)}, |
| 2044 | file{"100644", "long/README.md", strings.Repeat("a line of the README\n", 2*MaxLines)}, |
| 2045 | file{"100644", "wide.txt", strings.Repeat("<", MaxFile)}, |
| 2046 | ) |
| 2047 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 2048 | |
| 2049 | page := h.page("/tools/app/source/blob/" + tip + "/newlines.txt") |
| 2050 | last := fmt.Sprintf(`id="L%d"`, MaxLines) |
| 2051 | if !strings.Contains(page, last) || strings.Contains(page, fmt.Sprintf(`id="L%d"`, MaxLines+1)) { |
| 2052 | t.Errorf("the file of newlines is not shown to line %d", MaxLines) |
| 2053 | } |
| 2054 | if want := fmt.Sprintf("The page stops at line %d of %d.", MaxLines, MaxFile); !strings.Contains(page, want) { |
| 2055 | t.Errorf("the page does not say %q", want) |
| 2056 | } |
| 2057 | if len(page) > MaxShown { |
| 2058 | t.Errorf("the page of a file of newlines is %d bytes, past MaxShown", len(page)) |
| 2059 | } |
| 2060 | |
| 2061 | // One line of MaxFile characters that each escape to four bytes is |
| 2062 | // cut where MaxShown is reached. |
| 2063 | page = h.page("/tools/app/source/blob/" + tip + "/wide.txt") |
| 2064 | if !strings.Contains(page, "The page stops at line 1 of 1.") || len(page) > MaxShown+64<<10 { |
| 2065 | t.Errorf("the page of one wide line is %d bytes", len(page)) |
| 2066 | } |
| 2067 | |
| 2068 | page = h.page("/tools/app/source/tree/" + tip + "/long/") |
| 2069 | if !strings.Contains(page, "This README is longer than a page shows, and only its start is shown.") { |
| 2070 | t.Error("the long README is not marked as shown in part") |
| 2071 | } |
| 2072 | if n := strings.Count(page, "a line of the README"); n != MaxLines { |
| 2073 | t.Errorf("the long README shows %d lines, not %d", n, MaxLines) |
| 2074 | } |
| 2075 | } |
| 2076 | |
| 2077 | // A chain of knots as deep as the graph's knot limit allows renders its |
| 2078 | // milestone to MaxPlanDepth levels, counts every knot under it, and |
| 2079 | // names MaxPlanDepth parents in the deepest knot's trail. The plan page's |
| 2080 | // structure is built once for the generation. Siblings that block one |
| 2081 | // another in a cycle share the last stage of their path. |
| 2082 | func TestDeepPlan(t *testing.T) { |
| 2083 | h := newHarness(t) |
| 2084 | var chain []string |
| 2085 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(e *export.Export) { |
| 2086 | p := &e.Projects[0] |
| 2087 | for i := range knot.MaxKnots - len(p.Knots) - 3 { |
| 2088 | id := fmt.Sprintf("oc-c%06x", i) |
| 2089 | k := export.Knot{ID: id, Type: "outcome", Status: "open", Active: true, State: "ready", |
| 2090 | Title: fmt.Sprintf("Level %d of the chain", i), Created: "2026-10-01", CreatedBy: "operator"} |
| 2091 | if i == 0 { |
| 2092 | p.Roots = append(p.Roots, id) |
| 2093 | } else { |
| 2094 | k.Parent = chain[i-1] |
| 2095 | p.Knots[len(p.Knots)-1].Children = []string{id} |
| 2096 | } |
| 2097 | chain = append(chain, id) |
| 2098 | p.Knots = append(p.Knots, k) |
| 2099 | } |
| 2100 | // Under the first link, a path whose two last siblings wait on |
| 2101 | // each other. |
| 2102 | free, a, b := "oc-d000001", "oc-d000002", "oc-d000003" |
| 2103 | for _, k := range []export.Knot{ |
| 2104 | {ID: free, BlockedBy: []string{}}, |
| 2105 | {ID: a, BlockedBy: []string{free, b}}, |
| 2106 | {ID: b, BlockedBy: []string{a}}, |
| 2107 | } { |
| 2108 | k.Type, k.Status, k.State, k.Title, k.Parent = "outcome", "open", "blocked", "Sibling "+k.ID, chain[0] |
| 2109 | p.Knots = append(p.Knots, k) |
| 2110 | } |
| 2111 | for i := range p.Knots { |
| 2112 | if p.Knots[i].ID == chain[0] { |
| 2113 | p.Knots[i].Children = append(p.Knots[i].Children, free, a, b) |
| 2114 | } |
| 2115 | } |
| 2116 | }) |
| 2117 | |
| 2118 | page := h.page("/") |
| 2119 | if want := fmt.Sprintf("%d of %d done", 0, len(chain)-1+3); !strings.Contains(page, want) { |
| 2120 | t.Errorf("the chain's milestone does not count every knot under it as %q", want) |
| 2121 | } |
| 2122 | if !strings.Contains(page, `href="/tools/app/knots/`+chain[MaxPlanDepth]+`"`) || strings.Contains(page, `href="/tools/app/knots/`+chain[MaxPlanDepth+1]+`"`) { |
| 2123 | t.Errorf("the chain's tree is not shown to %d levels", MaxPlanDepth) |
| 2124 | } |
| 2125 | if n := strings.Count(page, ">more on its page<"); n != 1 { |
| 2126 | t.Errorf("%d rows say there is more on their page; the chain's deepest shown row does", n) |
| 2127 | } |
| 2128 | if len(page) > 256<<10 { |
| 2129 | t.Errorf("the plan page is %d bytes", len(page)) |
| 2130 | } |
| 2131 | paths := section(t, page, `id="paths-h"`, `id="ms-h"`) |
| 2132 | stage := regexp.MustCompile(`<span class="stage-num">(\d+)</span><ul class="plain">(.*?)</ul>`) |
| 2133 | var stages []string |
| 2134 | for _, m := range stage.FindAllStringSubmatch(paths, -1) { |
| 2135 | if strings.Contains(m[2], "Sibling") { |
| 2136 | var ids []string |
| 2137 | for _, id := range regexp.MustCompile(`"mono muted">(oc-d00000\d)<`).FindAllStringSubmatch(m[2], -1) { |
| 2138 | ids = append(ids, id[1]) |
| 2139 | } |
| 2140 | stages = append(stages, m[1]+":"+strings.Join(ids, ",")) |
| 2141 | } |
| 2142 | } |
| 2143 | if got := strings.Join(stages, " "); got != "1:oc-d000001 2:oc-d000002,oc-d000003" { |
| 2144 | t.Errorf("the siblings' path has stages %q", got) |
| 2145 | } |
| 2146 | |
| 2147 | h.srv.mu.Lock() |
| 2148 | plan := h.srv.cached.idx.plan |
| 2149 | h.srv.mu.Unlock() |
| 2150 | h.page("/") |
| 2151 | h.srv.mu.Lock() |
| 2152 | again := h.srv.cached.idx.plan |
| 2153 | h.srv.mu.Unlock() |
| 2154 | if plan != again { |
| 2155 | t.Error("the plan page's structure was built again for the same generation") |
| 2156 | } |
| 2157 | |
| 2158 | deepest := chain[len(chain)-1] |
| 2159 | page = h.page("/tools/app/knots/" + deepest) |
| 2160 | trail := section(t, page, `<nav class="trail"`, `</nav>`) |
| 2161 | if n := strings.Count(trail, `<a href="/tools/app/knots/`); n != MaxPlanDepth || !strings.Contains(trail, "<span>…</span>") { |
| 2162 | t.Errorf("the deepest knot's trail names %d parents, or does not mark those above them", n) |
| 2163 | } |
| 2164 | if !strings.Contains(trail, chain[len(chain)-2]) || strings.Contains(trail, `"/tools/app/knots/`+chain[len(chain)-2-MaxPlanDepth]+`"`) { |
| 2165 | t.Error("the trail does not name the nearest parents alone") |
| 2166 | } |
| 2167 | } |
| 2168 | |
| 2169 | // Every response carries the strict policy, and the policy admits the |
| 2170 | // page's one inline stylesheet and one inline script by their hashes and |
| 2171 | // nothing from another origin. |
| 2172 | func TestEveryResponseCarriesTheCSP(t *testing.T) { |
| 2173 | h := newHarness(t) |
| 2174 | for _, c := range []struct{ method, target string }{ |
| 2175 | {"GET", "/"}, |
| 2176 | {"GET", "/tools/app/knots/oc-a000002"}, |
| 2177 | {"GET", "/tools/app/source/"}, |
| 2178 | {"GET", "/tools/app/source/tree/" + h.tip() + "/"}, |
| 2179 | {"GET", "/tools/app/source/blob/" + h.tip() + "/README.md"}, |
| 2180 | {"GET", "/no/such/page"}, |
| 2181 | {"POST", "/"}, |
| 2182 | {"HEAD", "/"}, |
| 2183 | } { |
| 2184 | w := h.do(c.method, c.target) |
| 2185 | got := w.Header().Get("Content-Security-Policy") |
| 2186 | if got != csp || w.Header().Get("X-Content-Type-Options") != "nosniff" { |
| 2187 | t.Errorf("%s %s answered with policy %q", c.method, c.target, got) |
| 2188 | } |
| 2189 | } |
| 2190 | for _, directive := range []string{"default-src 'self'", "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'"} { |
| 2191 | if !strings.Contains(csp, directive) { |
| 2192 | t.Errorf("the policy lacks %s", directive) |
| 2193 | } |
| 2194 | } |
| 2195 | for _, loose := range []string{"unsafe-inline", "unsafe-eval", "http", "*", "data:"} { |
| 2196 | if strings.Contains(csp, loose) { |
| 2197 | t.Errorf("the policy holds %q", loose) |
| 2198 | } |
| 2199 | } |
| 2200 | |
| 2201 | page := h.page("/") |
| 2202 | inline := func(tag string) string { |
| 2203 | t.Helper() |
| 2204 | m := regexp.MustCompile(`(?s)<`+tag+`>(.*?)</`+tag+`>`).FindAllStringSubmatch(page, -1) |
| 2205 | if len(m) != 1 || strings.Count(page, "<"+tag) != 1 { |
| 2206 | t.Fatalf("the plan page has %d %s elements; it has one", len(m), tag) |
| 2207 | } |
| 2208 | sum := sha256.Sum256([]byte(m[0][1])) |
| 2209 | return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" |
| 2210 | } |
| 2211 | if hash := inline("script"); !strings.Contains(csp, "script-src "+hash+";") { |
| 2212 | t.Errorf("the policy does not admit the page's script, %s", hash) |
| 2213 | } |
| 2214 | if hash := inline("style"); !strings.Contains(csp, "style-src "+hash+";") { |
| 2215 | t.Errorf("the policy does not admit the page's stylesheet, %s", hash) |
| 2216 | } |
| 2217 | for _, external := range []string{"<link", " src=", "@import", "url("} { |
| 2218 | if strings.Contains(page, external) { |
| 2219 | t.Errorf("the plan page holds %q", external) |
| 2220 | } |
| 2221 | } |
| 2222 | } |
| 2223 | |
| 2224 | // A request serves everything from the generation it opened, though |
| 2225 | // another activates while it runs, and that generation outlives the |
| 2226 | // activation until the request releases it. |
| 2227 | func TestARequestKeepsItsGeneration(t *testing.T) { |
| 2228 | h := newHarness(t) |
| 2229 | paused, resume := make(chan export.Generation), make(chan struct{}) |
| 2230 | var once sync.Once |
| 2231 | h.srv.opened = func(g export.Generation) { once.Do(func() { paused <- g; <-resume }) } |
| 2232 | served := make(chan *httptest.ResponseRecorder) |
| 2233 | go func() { |
| 2234 | w := httptest.NewRecorder() |
| 2235 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000001", nil)) |
| 2236 | served <- w |
| 2237 | }() |
| 2238 | old := <-paused |
| 2239 | |
| 2240 | next := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 2241 | if next.Sequence == old.Sequence { |
| 2242 | t.Fatal("the publish did not activate a new generation") |
| 2243 | } |
| 2244 | if _, err := os.Stat(old.Dir); err != nil { |
| 2245 | t.Fatalf("the generation a request holds was deleted: %v", err) |
| 2246 | } |
| 2247 | close(resume) |
| 2248 | w := <-served |
| 2249 | if body := w.Body.String(); w.Code != http.StatusOK || !strings.Contains(body, "Readers browse the app's plan") || strings.Contains(body, "second plan") { |
| 2250 | t.Errorf("the request did not serve the generation it opened: %d\n%s", w.Code, body) |
| 2251 | } |
| 2252 | if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the second plan") { |
| 2253 | t.Error("the next request does not serve the new generation") |
| 2254 | } |
| 2255 | |
| 2256 | // Released, the old generation goes with the next activation. |
| 2257 | h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 2258 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 2259 | t.Errorf("the released generation is still on disk: %v", err) |
| 2260 | } |
| 2261 | } |
| 2262 | |
| 2263 | // eventually waits up to ten seconds for cond to hold. |
| 2264 | func eventually(t *testing.T, what string, cond func() bool) { |
| 2265 | t.Helper() |
| 2266 | for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(time.Millisecond) { |
| 2267 | if time.Now().After(deadline) { |
| 2268 | t.Fatalf("timed out waiting until %s", what) |
| 2269 | } |
| 2270 | } |
| 2271 | } |
| 2272 | |
| 2273 | // renamed changes the title of the fixture's first knot. |
| 2274 | func renamed(title string) func(*export.Export) { |
| 2275 | return func(e *export.Export) { e.Projects[0].Knots[0].Title = title } |
| 2276 | } |
| 2277 | |
| 2278 | // Requests that wait for a generation together read its export once. |
| 2279 | // While it is read, a newer generation is read on its own, and at most |
| 2280 | // MaxLoads exports are read at once. A request whose load ends after a |
| 2281 | // newer generation was activated waits for that one, so every request is |
| 2282 | // served the generation active when its snapshot is ready, and an older |
| 2283 | // read that finishes last does not displace the newest snapshot. |
| 2284 | func TestExportLoadsCoalesce(t *testing.T) { |
| 2285 | h := newHarness(t) |
| 2286 | var mu sync.Mutex |
| 2287 | loads := map[int64]int{} |
| 2288 | holds := map[int64]chan struct{}{} |
| 2289 | hold := func(g export.Generation) chan struct{} { |
| 2290 | mu.Lock() |
| 2291 | defer mu.Unlock() |
| 2292 | if holds[g.Sequence] == nil { |
| 2293 | holds[g.Sequence] = make(chan struct{}) |
| 2294 | } |
| 2295 | return holds[g.Sequence] |
| 2296 | } |
| 2297 | h.srv.loading = func(g export.Generation) { |
| 2298 | mu.Lock() |
| 2299 | loads[g.Sequence]++ |
| 2300 | mu.Unlock() |
| 2301 | <-hold(g) |
| 2302 | } |
| 2303 | loaded := func(g export.Generation) int { |
| 2304 | mu.Lock() |
| 2305 | defer mu.Unlock() |
| 2306 | return loads[g.Sequence] |
| 2307 | } |
| 2308 | var opens atomic.Int32 |
| 2309 | h.srv.opened = func(export.Generation) { opens.Add(1) } |
| 2310 | get := func(n int) chan *httptest.ResponseRecorder { |
| 2311 | served := make(chan *httptest.ResponseRecorder, n) |
| 2312 | for range n { |
| 2313 | go func() { |
| 2314 | w := httptest.NewRecorder() |
| 2315 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000001", nil)) |
| 2316 | served <- w |
| 2317 | }() |
| 2318 | } |
| 2319 | return served |
| 2320 | } |
| 2321 | expect := func(served chan *httptest.ResponseRecorder, n int, title string) { |
| 2322 | t.Helper() |
| 2323 | for range n { |
| 2324 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 2325 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 2326 | } |
| 2327 | } |
| 2328 | } |
| 2329 | waiting := func(n int) func() bool { return func() bool { return len(h.srv.loadWaiting) == n } } |
| 2330 | |
| 2331 | first := h.active() |
| 2332 | firstServed := get(10) |
| 2333 | eventually(t, "ten requests wait for the first generation's read", func() bool { |
| 2334 | return loaded(first) == 1 && len(h.srv.loadWaiting) == 10 |
| 2335 | }) |
| 2336 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 2337 | secondServed := get(1) |
| 2338 | eventually(t, "the second generation is read", func() bool { return loaded(second) == 1 }) |
| 2339 | |
| 2340 | // Both loaders are taken, so the third generation waits for one. |
| 2341 | third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 2342 | thirdServed := get(1) |
| 2343 | eventually(t, "a request waits for the third generation", waiting(12)) |
| 2344 | time.Sleep(20 * time.Millisecond) |
| 2345 | if n := loaded(third); n != 0 { |
| 2346 | t.Errorf("a third export was read while %d were", MaxLoads) |
| 2347 | } |
| 2348 | if n := opens.Load(); n != 0 { |
| 2349 | t.Errorf("%d requests opened a generation while they waited for its read", n) |
| 2350 | } |
| 2351 | |
| 2352 | // The second read ends, and its request finds the third generation |
| 2353 | // active, and waits for that read with the third's request. |
| 2354 | close(hold(second)) |
| 2355 | eventually(t, "the third generation is read", func() bool { return loaded(third) == 1 }) |
| 2356 | close(hold(third)) |
| 2357 | expect(secondServed, 1, "Readers browse the third plan") |
| 2358 | expect(thirdServed, 1, "Readers browse the third plan") |
| 2359 | close(hold(first)) |
| 2360 | expect(firstServed, 10, "Readers browse the third plan") |
| 2361 | |
| 2362 | if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the third plan") { |
| 2363 | t.Error("the first generation's read displaced the third's") |
| 2364 | } |
| 2365 | for _, g := range []export.Generation{first, second, third} { |
| 2366 | if n := loaded(g); n != 1 { |
| 2367 | t.Errorf("generation %d's export was read %d times", g.Sequence, n) |
| 2368 | } |
| 2369 | } |
| 2370 | } |
| 2371 | |
| 2372 | // Source requests past MaxGit wait, MaxWaiting of them, and one more |
| 2373 | // answers 503 at once. A waiting request holds no generation, so an |
| 2374 | // activation while the server is saturated deletes the old generation, |
| 2375 | // and every waiting request serves the new one. A request's time runs |
| 2376 | // from its arrival, so one that waits past it answers 503. |
| 2377 | func TestSourceAdmission(t *testing.T) { |
| 2378 | h := newHarness(t) |
| 2379 | // The requests that hold the slots wait for the test, not for git, so |
| 2380 | // the bound on holding a slot is no part of this test. |
| 2381 | h.srv.gitTime = time.Hour |
| 2382 | var admitted atomic.Int32 |
| 2383 | release := make(chan struct{}) |
| 2384 | h.srv.admitted = func() { |
| 2385 | admitted.Add(1) |
| 2386 | <-release |
| 2387 | } |
| 2388 | target := "/tools/app/source/tree/" + h.tip() + "/" |
| 2389 | get := func(n int) chan *httptest.ResponseRecorder { |
| 2390 | served := make(chan *httptest.ResponseRecorder, n) |
| 2391 | for range n { |
| 2392 | go func() { |
| 2393 | w := httptest.NewRecorder() |
| 2394 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", target, nil)) |
| 2395 | served <- w |
| 2396 | }() |
| 2397 | } |
| 2398 | return served |
| 2399 | } |
| 2400 | |
| 2401 | old := h.active() |
| 2402 | served := get(MaxGit + MaxWaiting) |
| 2403 | eventually(t, "every slot is taken and MaxWaiting requests wait", func() bool { |
| 2404 | return admitted.Load() == MaxGit && len(h.srv.waiting) == MaxWaiting |
| 2405 | }) |
| 2406 | if w := h.get(target); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 2407 | t.Errorf("a source request past MaxWaiting answered %d, Retry-After %q", w.Code, w.Header().Get("Retry-After")) |
| 2408 | } |
| 2409 | // A path through a group's alias or a project's former name that has |
| 2410 | // a source route's shape is admitted as one before the export is read, |
| 2411 | // so it answers 503 too. A project's short alias makes no such shape, |
| 2412 | // and redirects still. |
| 2413 | for _, alias := range []string{"/t/app/source/tree/" + h.tip() + "/", "/tools/old-app/source/tree/" + h.tip() + "/"} { |
| 2414 | if w := h.get(alias); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 2415 | t.Errorf("GET %s past MaxWaiting answered %d, Retry-After %q", alias, w.Code, w.Header().Get("Retry-After")) |
| 2416 | } |
| 2417 | } |
| 2418 | if w := h.get("/app/source/tree/" + h.tip() + "/"); w.Code != http.StatusPermanentRedirect { |
| 2419 | t.Errorf("a project's short alias answered %d while the server is saturated", w.Code) |
| 2420 | } |
| 2421 | h.page("/") // a page that runs no git is served still |
| 2422 | |
| 2423 | tip, bundle := h.commitMain("app: a commit while the server is saturated\n", file{"100644", "saturated.txt", "saturated\n"}) |
| 2424 | h.publishMain(exporttest.SignedAt.Add(time.Minute), tip, bundle) |
| 2425 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 2426 | t.Errorf("a generation no request had opened outlived the activation: %v", err) |
| 2427 | } |
| 2428 | close(release) |
| 2429 | for range MaxGit + MaxWaiting { |
| 2430 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/tools/app/source/tree/"+tip+"/") { |
| 2431 | t.Errorf("a waiting request answered %d, not from the new generation", w.Code) |
| 2432 | } |
| 2433 | } |
| 2434 | // Once a slot is free, the alias's path redirects, and gives the slot |
| 2435 | // back. |
| 2436 | if w := h.get("/t/app/source/tree/" + tip + "/"); w.Code != http.StatusPermanentRedirect { |
| 2437 | t.Errorf("a group's alias answered %d once the server had a slot free", w.Code) |
| 2438 | } |
| 2439 | if len(h.srv.slots) != 0 { |
| 2440 | t.Errorf("a redirect kept %d git slots", len(h.srv.slots)) |
| 2441 | } |
| 2442 | |
| 2443 | // A request that waits past its time answers 503. Those that held |
| 2444 | // the slots meanwhile ran out of time too. |
| 2445 | h.srv.timeout = 200 * time.Millisecond |
| 2446 | h.srv.log = func(error) {} |
| 2447 | admitted.Store(0) |
| 2448 | release = make(chan struct{}) |
| 2449 | held := get(MaxGit) |
| 2450 | eventually(t, "every slot is taken", func() bool { return admitted.Load() == MaxGit }) |
| 2451 | start := time.Now() |
| 2452 | if w := h.get(target); w.Code != http.StatusServiceUnavailable { |
| 2453 | t.Errorf("a request that waited past its time answered %d", w.Code) |
| 2454 | } |
| 2455 | if waited := time.Since(start); waited > 5*time.Second { |
| 2456 | t.Errorf("a request waited %v past its time of 200ms", waited) |
| 2457 | } |
| 2458 | close(release) |
| 2459 | for range MaxGit { |
| 2460 | if w := <-held; w.Code != http.StatusServiceUnavailable { |
| 2461 | t.Errorf("a request that ran out of time answered %d", w.Code) |
| 2462 | } |
| 2463 | } |
| 2464 | } |
| 2465 | |
| 2466 | // stallingListener accepts connections whose writes stall until release |
| 2467 | // is closed, while stall is set. Each sends on stalled the first time one |
| 2468 | // of its writes stalls. |
| 2469 | type stallingListener struct { |
| 2470 | net.Listener |
| 2471 | stall atomic.Bool |
| 2472 | release chan struct{} |
| 2473 | stalled chan struct{} |
| 2474 | } |
| 2475 | |
| 2476 | func (l *stallingListener) Accept() (net.Conn, error) { |
| 2477 | c, err := l.Listener.Accept() |
| 2478 | if err != nil || !l.stall.Load() { |
| 2479 | return c, err |
| 2480 | } |
| 2481 | return &stallingConn{Conn: c, l: l}, nil |
| 2482 | } |
| 2483 | |
| 2484 | type stallingConn struct { |
| 2485 | net.Conn |
| 2486 | l *stallingListener |
| 2487 | once sync.Once |
| 2488 | } |
| 2489 | |
| 2490 | func (c *stallingConn) Write(p []byte) (int, error) { |
| 2491 | c.once.Do(func() { c.l.stalled <- struct{}{} }) |
| 2492 | <-c.l.release |
| 2493 | return c.Conn.Write(p) |
| 2494 | } |
| 2495 | |
| 2496 | // Readers that never read their responses hold no git slot and no |
| 2497 | // generation: more of them than MaxGit and MaxWaiting together are |
| 2498 | // stalled writing, and a new reader is still served, and an activation |
| 2499 | // deletes the generation they were served from. |
| 2500 | func TestSlowReadersHoldNothing(t *testing.T) { |
| 2501 | h := newHarness(t) |
| 2502 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 2503 | if err != nil { |
| 2504 | t.Fatal(err) |
| 2505 | } |
| 2506 | n := MaxGit + MaxWaiting + 4 |
| 2507 | sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)} |
| 2508 | sl.stall.Store(true) |
| 2509 | srv := &http.Server{Handler: h.srv} |
| 2510 | go srv.Serve(sl) |
| 2511 | var conns []net.Conn |
| 2512 | defer func() { |
| 2513 | close(sl.release) |
| 2514 | for _, c := range conns { |
| 2515 | c.Close() |
| 2516 | } |
| 2517 | srv.Close() |
| 2518 | }() |
| 2519 | |
| 2520 | old := h.active() |
| 2521 | target := "/tools/app/source/blob/" + h.tip() + "/docs/guide.md" |
| 2522 | for range n { |
| 2523 | c, err := net.Dial("tcp", ln.Addr().String()) |
| 2524 | if err != nil { |
| 2525 | t.Fatal(err) |
| 2526 | } |
| 2527 | conns = append(conns, c) |
| 2528 | fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target) |
| 2529 | } |
| 2530 | for i := range n { |
| 2531 | select { |
| 2532 | case <-sl.stalled: |
| 2533 | case <-time.After(10 * time.Second): |
| 2534 | t.Fatalf("%d of %d slow readers' responses were written; the rest wait", i, n) |
| 2535 | } |
| 2536 | } |
| 2537 | sl.stall.Store(false) |
| 2538 | if len(h.srv.slots) != 0 || len(h.srv.waiting) != 0 { |
| 2539 | t.Errorf("slow readers hold %d git slots, and %d requests wait", len(h.srv.slots), len(h.srv.waiting)) |
| 2540 | } |
| 2541 | |
| 2542 | client := &http.Client{Timeout: 10 * time.Second} |
| 2543 | resp, err := client.Get("http://" + ln.Addr().String() + target) |
| 2544 | if err != nil { |
| 2545 | t.Fatal(err) |
| 2546 | } |
| 2547 | resp.Body.Close() |
| 2548 | if resp.StatusCode != http.StatusOK { |
| 2549 | t.Errorf("a new reader answered %d while slow readers stall", resp.StatusCode) |
| 2550 | } |
| 2551 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, func(*export.Export) {}) |
| 2552 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 2553 | t.Errorf("the generation slow readers were served from outlived the activation: %v", err) |
| 2554 | } |
| 2555 | } |
| 2556 | |
| 2557 | // Before the first activation the server says nothing is published, and |
| 2558 | // it answers GET and HEAD alone. |
| 2559 | func TestNothingPublishedAndMethods(t *testing.T) { |
| 2560 | store, err := export.OpenStore(exporttest.StorePath(t), nil) |
| 2561 | if err != nil { |
| 2562 | t.Fatal(err) |
| 2563 | } |
| 2564 | srv := New(Config{Store: store, Log: func(err error) { t.Errorf("the server logged: %v", err) }}) |
| 2565 | w := httptest.NewRecorder() |
| 2566 | srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 2567 | if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") { |
| 2568 | t.Errorf("an empty store answered %d:\n%s", w.Code, w.Body) |
| 2569 | } |
| 2570 | |
| 2571 | h := newHarness(t) |
| 2572 | for _, method := range []string{"POST", "PUT", "DELETE", "OPTIONS"} { |
| 2573 | w := h.do(method, "/") |
| 2574 | if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "GET, HEAD" { |
| 2575 | t.Errorf("%s answered %d, allowing %q", method, w.Code, w.Header().Get("Allow")) |
| 2576 | } |
| 2577 | } |
| 2578 | } |
| 2579 | |
| 2580 | // tooLarge checks that GET target answers with the one short page that |
| 2581 | // says a page is too large. |
| 2582 | func (h *harness) tooLarge(target string) { |
| 2583 | h.t.Helper() |
| 2584 | w := h.get(target) |
| 2585 | if w.Code != http.StatusInternalServerError || !bytes.Equal(w.Body.Bytes(), tooLargePage) { |
| 2586 | h.t.Errorf("GET %s answered %d with %d bytes, not the page that says it is too large", target, w.Code, w.Body.Len()) |
| 2587 | } |
| 2588 | if n, _ := h.srv.holding(); n != 0 { |
| 2589 | h.t.Errorf("GET %s kept %d pieces of the budget", target, n) |
| 2590 | } |
| 2591 | } |
| 2592 | |
| 2593 | // A response's body is at most MaxResponse bytes. A page that would pass |
| 2594 | // the bound answers with the one short page that says it is too large, |
| 2595 | // and the failure is logged: a knot whose body passes MaxResponse, and, |
| 2596 | // under a smaller bound, a file, a directory, a page of history and the |
| 2597 | // plan page. A page within the bound is served on each route. |
| 2598 | func TestPageTooLarge(t *testing.T) { |
| 2599 | h := newHarness(t) |
| 2600 | var logged []string |
| 2601 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 2602 | files := []file{{"100644", "wide.txt", strings.Repeat("<", 16<<10)}} |
| 2603 | for i := range 32 { |
| 2604 | files = append(files, file{"100644", fmt.Sprintf("wide/%02d-%s", i, strings.Repeat("n", 1000)), "x\n"}) |
| 2605 | } |
| 2606 | h.commitMain("app: a wide file and a wide directory\n", files...) |
| 2607 | var tip, bundle string |
| 2608 | for i := range 8 { |
| 2609 | tip, bundle = h.commitMain(fmt.Sprintf("%d %s\n", i, strings.Repeat(`"`, maxLogText))) |
| 2610 | } |
| 2611 | h.publish(exporttest.SignedAt.Add(time.Minute), map[string]string{"app": bundle}, func(e *export.Export) { |
| 2612 | p := &e.Projects[0] |
| 2613 | p.SourceTip = tip |
| 2614 | p.Knots[0].Body = strings.Repeat("a", MaxResponse) |
| 2615 | for i := range 100 { |
| 2616 | p.Knots = append(p.Knots, export.Knot{ID: fmt.Sprintf("oc-e%06x", i), Type: "outcome", Status: "open", |
| 2617 | Active: true, State: "ready", Title: strings.Repeat(`"`, knot.MaxTitle), Created: "2026-10-01", CreatedBy: "operator"}) |
| 2618 | } |
| 2619 | }) |
| 2620 | |
| 2621 | h.tooLarge("/tools/app/knots/" + h.f.Export.Projects[0].Knots[0].ID) |
| 2622 | h.page("/tools/app/knots/oc-a000002") |
| 2623 | |
| 2624 | h.srv.maxResponse = 32 << 10 |
| 2625 | at := "/tools/app/source/blob/" + tip + "/" |
| 2626 | h.tooLarge(at + "wide.txt") |
| 2627 | h.page(at + "docs/guide.md") |
| 2628 | at = "/tools/app/source/tree/" + tip + "/" |
| 2629 | h.tooLarge(at + "wide/") |
| 2630 | h.page(at + "docs/") |
| 2631 | h.tooLarge("/tools/app/source/log/" + tip) |
| 2632 | h.page("/tools/app/source/log/" + git(t, h.f.Repos["app"], nil, "rev-parse", tip+"~8")) |
| 2633 | h.tooLarge("/") |
| 2634 | |
| 2635 | if len(logged) != 5 { |
| 2636 | t.Errorf("%d failures were logged for 5 pages too large: %q", len(logged), logged) |
| 2637 | } |
| 2638 | for _, l := range logged { |
| 2639 | if !strings.Contains(l, "larger than") { |
| 2640 | t.Errorf("the server logged %q", l) |
| 2641 | } |
| 2642 | } |
| 2643 | if len(tooLargePage) > 16<<10 { |
| 2644 | t.Errorf("the page that says a page is too large is %d bytes", len(tooLargePage)) |
| 2645 | } |
| 2646 | } |
| 2647 | |
| 2648 | // holding is how many pieces of the budget responses hold, and how many |
| 2649 | // of those the large budget counts. |
| 2650 | func (s *Server) holding() (held, large int) { |
| 2651 | s.pieces.Lock() |
| 2652 | defer s.pieces.Unlock() |
| 2653 | return s.held, s.large |
| 2654 | } |
| 2655 | |
| 2656 | // Rendered responses share a budget of MaxBuffered bytes, which each |
| 2657 | // holds from when it starts rendering until it is written. Responses |
| 2658 | // larger than SmallPage hold at most MaxLarge of it between them, their |
| 2659 | // first SmallPage bytes counted. Readers that never read large pages ask |
| 2660 | // for more than the whole budget, in pages of three sizes: one piece past |
| 2661 | // SmallPage, 1 MiB, and 4 MiB. Without the first SmallPage bytes counted, |
| 2662 | // 64 readers of the 1 MiB page would hold all of the budget. Once the |
| 2663 | // readers' pages hold what fits in MaxLarge, a large page answers 503 at |
| 2664 | // once, while small pages still render: the plan, a knot and a |
| 2665 | // directory. The server's heap grows by no more than the budget, and the |
| 2666 | // budget is whole again once the readers read. |
| 2667 | func TestSlowReadersShareTheBudget(t *testing.T) { |
| 2668 | for _, pieces := range []int{smallPieces + 1, 16, 64} { |
| 2669 | t.Run(fmt.Sprintf("%d pieces", pieces), func(t *testing.T) { slowReadersOfPages(t, pieces) }) |
| 2670 | } |
| 2671 | } |
| 2672 | |
| 2673 | // slowReadersOfPages runs TestSlowReadersShareTheBudget with large pages |
| 2674 | // of the number of pieces given. |
| 2675 | func slowReadersOfPages(t *testing.T, pieces int) { |
| 2676 | h := newHarness(t) |
| 2677 | target := "/tools/app/knots/" + h.f.Export.Projects[0].Knots[0].ID |
| 2678 | body := func(at time.Duration, text string) { |
| 2679 | h.publish(exporttest.SignedAt.Add(at), nil, func(e *export.Export) { e.Projects[0].Knots[0].Body = text }) |
| 2680 | } |
| 2681 | body(time.Minute, "x") |
| 2682 | rest := len(h.page(target)) - 1 |
| 2683 | body(2*time.Minute, strings.Repeat("a line of a long body\n", (pieces*pieceSize-rest-1024)/22)) |
| 2684 | size := len(h.page(target)) |
| 2685 | if got := (size + pieceSize - 1) / pieceSize; got != pieces { |
| 2686 | t.Fatalf("the large page takes %d pieces, not %d", got, pieces) |
| 2687 | } |
| 2688 | fit := largePieces / pieces |
| 2689 | n := MaxBuffered/size + 2 |
| 2690 | |
| 2691 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 2692 | if err != nil { |
| 2693 | t.Fatal(err) |
| 2694 | } |
| 2695 | sl := &stallingListener{Listener: ln, release: make(chan struct{}), stalled: make(chan struct{}, n)} |
| 2696 | sl.stall.Store(true) |
| 2697 | srv := &http.Server{Handler: h.srv} |
| 2698 | go srv.Serve(sl) |
| 2699 | var conns []net.Conn |
| 2700 | released := false |
| 2701 | defer func() { |
| 2702 | if !released { |
| 2703 | close(sl.release) |
| 2704 | } |
| 2705 | for _, c := range conns { |
| 2706 | c.Close() |
| 2707 | } |
| 2708 | srv.Close() |
| 2709 | }() |
| 2710 | |
| 2711 | var before runtime.MemStats |
| 2712 | runtime.GC() |
| 2713 | runtime.ReadMemStats(&before) |
| 2714 | // One reader at a time, each stalled before the next asks, so the |
| 2715 | // readers that fill the budget are the first fit of them. |
| 2716 | for i := range n { |
| 2717 | c, err := net.Dial("tcp", ln.Addr().String()) |
| 2718 | if err != nil { |
| 2719 | t.Fatal(err) |
| 2720 | } |
| 2721 | conns = append(conns, c) |
| 2722 | fmt.Fprintf(c, "GET %s HTTP/1.1\r\nHost: valley-host\r\n\r\n", target) |
| 2723 | select { |
| 2724 | case <-sl.stalled: |
| 2725 | case <-time.After(10 * time.Second): |
| 2726 | t.Fatalf("reader %d of %d was not answered", i+1, n) |
| 2727 | } |
| 2728 | } |
| 2729 | sl.stall.Store(false) |
| 2730 | var after runtime.MemStats |
| 2731 | runtime.GC() |
| 2732 | runtime.ReadMemStats(&after) |
| 2733 | if held, large := h.srv.holding(); held != fit*pieces || large != fit*pieces { |
| 2734 | t.Errorf("slow readers hold %d pieces, %d of them counted as large; %d pages of %d pieces fit", held, large, fit, pieces) |
| 2735 | } |
| 2736 | if grew := int64(after.HeapAlloc) - int64(before.HeapAlloc); grew > MaxBuffered+8<<20 { |
| 2737 | t.Errorf("%d slow readers of %d bytes each grew the heap by %d bytes, past MaxBuffered", n, size, grew) |
| 2738 | } |
| 2739 | |
| 2740 | client := &http.Client{Timeout: 10 * time.Second} |
| 2741 | get := func(target string) (int, string) { |
| 2742 | t.Helper() |
| 2743 | resp, err := client.Get("http://" + ln.Addr().String() + target) |
| 2744 | if err != nil { |
| 2745 | t.Fatal(err) |
| 2746 | } |
| 2747 | defer resp.Body.Close() |
| 2748 | io.Copy(io.Discard, resp.Body) |
| 2749 | return resp.StatusCode, resp.Header.Get("Retry-After") |
| 2750 | } |
| 2751 | if code, retry := get(target); code != http.StatusServiceUnavailable || retry == "" { |
| 2752 | t.Errorf("a page the budget has no room for answered %d, Retry-After %q", code, retry) |
| 2753 | } |
| 2754 | for _, small := range []string{"/", "/tools/app/knots/oc-a000002", "/tools/app/source/tree/" + h.tip() + "/"} { |
| 2755 | if code, _ := get(small); code != http.StatusOK { |
| 2756 | t.Errorf("the small page %s answered %d while slow readers hold MaxLarge", small, code) |
| 2757 | } |
| 2758 | } |
| 2759 | |
| 2760 | close(sl.release) |
| 2761 | released = true |
| 2762 | codes := map[int]int{} |
| 2763 | for _, c := range conns { |
| 2764 | c.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 2765 | resp, err := http.ReadResponse(bufio.NewReader(c), nil) |
| 2766 | if err != nil { |
| 2767 | t.Fatal(err) |
| 2768 | } |
| 2769 | read, err := io.Copy(io.Discard, resp.Body) |
| 2770 | resp.Body.Close() |
| 2771 | if err != nil || resp.StatusCode == http.StatusOK && read != int64(size) { |
| 2772 | t.Errorf("a slow reader read %d bytes of %d: %v", read, size, err) |
| 2773 | } |
| 2774 | codes[resp.StatusCode]++ |
| 2775 | } |
| 2776 | if codes[http.StatusOK] != fit || codes[http.StatusServiceUnavailable] != n-fit { |
| 2777 | t.Errorf("of %d slow readers, %d were served and %d answered 503; %d pages fit the budget", |
| 2778 | n, codes[http.StatusOK], codes[http.StatusServiceUnavailable], fit) |
| 2779 | } |
| 2780 | eventually(t, "the budget is whole again", func() bool { held, _ := h.srv.holding(); return held == 0 }) |
| 2781 | } |
| 2782 | |
| 2783 | // A load starts only once a request that waits for it takes a loader |
| 2784 | // slot. While MaxLoads loads run, a request for a newer generation waits |
| 2785 | // for a slot, holding no generation, until its time runs out, whatever |
| 2786 | // its route, or its reader goes away. Neither leaves a load behind. |
| 2787 | func TestExportLoadWaitsEnd(t *testing.T) { |
| 2788 | h := newHarness(t) |
| 2789 | var mu sync.Mutex |
| 2790 | var logged []string |
| 2791 | h.srv.log = func(err error) { |
| 2792 | mu.Lock() |
| 2793 | defer mu.Unlock() |
| 2794 | logged = append(logged, err.Error()) |
| 2795 | } |
| 2796 | loads := map[int64]int{} |
| 2797 | hold := make(chan struct{}) |
| 2798 | h.srv.loading = func(g export.Generation) { |
| 2799 | mu.Lock() |
| 2800 | loads[g.Sequence]++ |
| 2801 | mu.Unlock() |
| 2802 | <-hold |
| 2803 | } |
| 2804 | loaded := func(g export.Generation) int { |
| 2805 | mu.Lock() |
| 2806 | defer mu.Unlock() |
| 2807 | return loads[g.Sequence] |
| 2808 | } |
| 2809 | serve := func(r *http.Request) chan *httptest.ResponseRecorder { |
| 2810 | served := make(chan *httptest.ResponseRecorder, 1) |
| 2811 | go func() { |
| 2812 | w := httptest.NewRecorder() |
| 2813 | h.srv.ServeHTTP(w, r) |
| 2814 | served <- w |
| 2815 | }() |
| 2816 | return served |
| 2817 | } |
| 2818 | expect := func(served chan *httptest.ResponseRecorder, title string) { |
| 2819 | t.Helper() |
| 2820 | select { |
| 2821 | case w := <-served: |
| 2822 | if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 2823 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 2824 | } |
| 2825 | case <-time.After(10 * time.Second): |
| 2826 | t.Fatalf("a request was not answered with %q", title) |
| 2827 | } |
| 2828 | } |
| 2829 | |
| 2830 | first := h.active() |
| 2831 | firstServed := serve(httptest.NewRequest("GET", "/", nil)) |
| 2832 | eventually(t, "the first generation is read", func() bool { return loaded(first) == 1 }) |
| 2833 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 2834 | secondServed := serve(httptest.NewRequest("GET", "/", nil)) |
| 2835 | eventually(t, "both loader slots are taken", func() bool { return loaded(second) == 1 }) |
| 2836 | |
| 2837 | // A request that runs no git runs out of time waiting, and answers |
| 2838 | // 503. |
| 2839 | h.srv.timeout = 200 * time.Millisecond |
| 2840 | third := h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 2841 | select { |
| 2842 | case w := <-serve(httptest.NewRequest("GET", "/tools/app/knots/oc-a000001", nil)): |
| 2843 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 2844 | t.Errorf("a request that waited past its time for a read answered %d", w.Code) |
| 2845 | } |
| 2846 | case <-time.After(10 * time.Second): |
| 2847 | t.Fatal("a request waits for a read past its time of 200ms") |
| 2848 | } |
| 2849 | |
| 2850 | // A request whose reader goes away stops waiting, and answers |
| 2851 | // nothing. |
| 2852 | h.srv.timeout = time.Hour |
| 2853 | fourth := h.publish(exporttest.SignedAt.Add(3*time.Minute), nil, renamed("Readers browse the fourth plan")) |
| 2854 | ctx, cancel := context.WithCancel(context.Background()) |
| 2855 | defer cancel() |
| 2856 | gone := serve(httptest.NewRequest("GET", "/", nil).WithContext(ctx)) |
| 2857 | eventually(t, "a request waits for the fourth generation", func() bool { return len(h.srv.loadWaiting) == 3 }) |
| 2858 | cancel() |
| 2859 | select { |
| 2860 | case w := <-gone: |
| 2861 | if w.Body.Len() != 0 { |
| 2862 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 2863 | } |
| 2864 | case <-time.After(10 * time.Second): |
| 2865 | t.Fatal("a request whose reader went away still waits") |
| 2866 | } |
| 2867 | |
| 2868 | h.srv.mu.Lock() |
| 2869 | left := len(h.srv.loads) |
| 2870 | h.srv.mu.Unlock() |
| 2871 | if left != MaxLoads { |
| 2872 | t.Errorf("%d loads may be joined; only the %d that run are wanted", left, MaxLoads) |
| 2873 | } |
| 2874 | h.publish(exporttest.SignedAt.Add(4*time.Minute), nil, renamed("Readers browse the fifth plan")) |
| 2875 | for _, g := range []export.Generation{third, fourth} { |
| 2876 | if _, err := os.Stat(g.Dir); !os.IsNotExist(err) { |
| 2877 | t.Errorf("generation %d outlived an activation after its request gave up: %v", g.Sequence, err) |
| 2878 | } |
| 2879 | } |
| 2880 | |
| 2881 | // The first two reads end, and their requests are served the newest |
| 2882 | // generation. |
| 2883 | close(hold) |
| 2884 | expect(firstServed, "Readers browse the fifth plan") |
| 2885 | expect(secondServed, "Readers browse the fifth plan") |
| 2886 | for _, g := range []export.Generation{third, fourth} { |
| 2887 | if n := loaded(g); n != 0 { |
| 2888 | t.Errorf("generation %d's export was read %d times after every request for it gave up", g.Sequence, n) |
| 2889 | } |
| 2890 | } |
| 2891 | mu.Lock() |
| 2892 | defer mu.Unlock() |
| 2893 | if len(logged) != 1 || !strings.Contains(logged[0], "deadline exceeded") { |
| 2894 | t.Errorf("the server logged %q; it logs the one request that ran out of time", logged) |
| 2895 | } |
| 2896 | } |
| 2897 | |
| 2898 | // A load that reads slowly does not hold the request that waits for it: |
| 2899 | // the request answers 503 at its deadline. With no request left waiting, |
| 2900 | // the load stops reading part way through the export, caches nothing, and |
| 2901 | // gives back its generation, which the next activation deletes. A load |
| 2902 | // that ends is kept, and the requests after it are served without another |
| 2903 | // read. |
| 2904 | func TestSlowLoadEndsWithItsRequests(t *testing.T) { |
| 2905 | h := newHarness(t) |
| 2906 | h.srv.timeout = 200 * time.Millisecond |
| 2907 | var mu sync.Mutex |
| 2908 | var logged []string |
| 2909 | h.srv.log = func(err error) { |
| 2910 | mu.Lock() |
| 2911 | defer mu.Unlock() |
| 2912 | logged = append(logged, err.Error()) |
| 2913 | } |
| 2914 | var reads atomic.Int32 |
| 2915 | h.srv.loading = func(export.Generation) { reads.Add(1) } |
| 2916 | |
| 2917 | // The active generation's export.json becomes a pipe the test writes |
| 2918 | // a few bytes at a time, as a slow disk would give it: all of it |
| 2919 | // takes about 4 seconds, twenty times the request's time. |
| 2920 | old := h.active() |
| 2921 | data, err := os.ReadFile(old.ExportPath()) |
| 2922 | if err != nil { |
| 2923 | t.Fatal(err) |
| 2924 | } |
| 2925 | if err := os.Remove(old.ExportPath()); err != nil { |
| 2926 | t.Fatal(err) |
| 2927 | } |
| 2928 | if err := syscall.Mkfifo(old.ExportPath(), 0o600); err != nil { |
| 2929 | t.Fatal(err) |
| 2930 | } |
| 2931 | piece := max(1, len(data)/200) |
| 2932 | wrote := make(chan error, 1) |
| 2933 | go func() { |
| 2934 | f, err := os.OpenFile(old.ExportPath(), os.O_WRONLY, 0) |
| 2935 | if err != nil { |
| 2936 | wrote <- err |
| 2937 | return |
| 2938 | } |
| 2939 | defer f.Close() |
| 2940 | for p := data; len(p) > 0; p = p[min(len(p), piece):] { |
| 2941 | if _, err := f.Write(p[:min(len(p), piece)]); err != nil { |
| 2942 | wrote <- err |
| 2943 | return |
| 2944 | } |
| 2945 | time.Sleep(20 * time.Millisecond) |
| 2946 | } |
| 2947 | wrote <- nil |
| 2948 | }() |
| 2949 | |
| 2950 | start := time.Now() |
| 2951 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 2952 | t.Errorf("a request whose load ran past its time answered %d", w.Code) |
| 2953 | } |
| 2954 | if waited := time.Since(start); waited > 2*time.Second { |
| 2955 | t.Errorf("a request waited %v for a slow load, past its time of 200ms", waited) |
| 2956 | } |
| 2957 | select { |
| 2958 | case err := <-wrote: |
| 2959 | if !errors.Is(err, syscall.EPIPE) { |
| 2960 | t.Errorf("the load read the whole export after its request gave up: the writer ended with %v", err) |
| 2961 | } |
| 2962 | case <-time.After(10 * time.Second): |
| 2963 | t.Fatal("the load still reads the export") |
| 2964 | } |
| 2965 | eventually(t, "the load ends", func() bool { return len(h.srv.loaders) == 0 }) |
| 2966 | h.srv.mu.Lock() |
| 2967 | cached, loads := h.srv.cached, len(h.srv.loads) |
| 2968 | h.srv.mu.Unlock() |
| 2969 | if cached != nil || loads != 0 { |
| 2970 | t.Errorf("a load that stopped left a snapshot %v and %d loads", cached != nil, loads) |
| 2971 | } |
| 2972 | // The store reads the active export.json when it takes an upload. |
| 2973 | if err := os.Remove(old.ExportPath()); err != nil { |
| 2974 | t.Fatal(err) |
| 2975 | } |
| 2976 | if err := os.WriteFile(old.ExportPath(), data, 0o644); err != nil { |
| 2977 | t.Fatal(err) |
| 2978 | } |
| 2979 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 2980 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 2981 | t.Errorf("the generation a stopped load opened outlived an activation: %v", err) |
| 2982 | } |
| 2983 | |
| 2984 | h.srv.timeout = requestTimeout |
| 2985 | for range 3 { |
| 2986 | if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the second plan") { |
| 2987 | t.Error("a request after the stopped load is not served the new generation") |
| 2988 | } |
| 2989 | } |
| 2990 | if n := reads.Load(); n != 2 { |
| 2991 | t.Errorf("exports were read %d times: once in part, and once for the new generation", n) |
| 2992 | } |
| 2993 | mu.Lock() |
| 2994 | defer mu.Unlock() |
| 2995 | if len(logged) != 1 || !strings.Contains(logged[0], "export to be read: context deadline exceeded") { |
| 2996 | t.Errorf("the server logged %q; it logs the one request that ran out of time", logged) |
| 2997 | } |
| 2998 | } |
| 2999 | |
| 3000 | // openFiles is the number of files the process holds open, and false |
| 3001 | // where the system does not list them. |
| 3002 | func openFiles(t *testing.T) (int, bool) { |
| 3003 | t.Helper() |
| 3004 | entries, err := os.ReadDir("/proc/self/fd") |
| 3005 | if err != nil { |
| 3006 | return 0, false |
| 3007 | } |
| 3008 | return len(entries), true |
| 3009 | } |
| 3010 | |
| 3011 | // A flood of requests while a load runs: MaxLoadWaiting of them wait, and |
| 3012 | // the rest answer 503 at once, unlogged. A waiting request holds no |
| 3013 | // generation, so the goroutines and files the server holds stay within a |
| 3014 | // bound however large the flood. Once the load ends, every request that |
| 3015 | // waited is served from its one read. |
| 3016 | func TestLoadFlood(t *testing.T) { |
| 3017 | h := newHarness(t) |
| 3018 | var reads atomic.Int32 |
| 3019 | reading, hold := make(chan struct{}, 1), make(chan struct{}) |
| 3020 | h.srv.loading = func(export.Generation) { |
| 3021 | reads.Add(1) |
| 3022 | reading <- struct{}{} |
| 3023 | <-hold |
| 3024 | } |
| 3025 | get := func(n int) chan *httptest.ResponseRecorder { |
| 3026 | served := make(chan *httptest.ResponseRecorder, n) |
| 3027 | for range n { |
| 3028 | go func() { |
| 3029 | w := httptest.NewRecorder() |
| 3030 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/", nil)) |
| 3031 | served <- w |
| 3032 | }() |
| 3033 | } |
| 3034 | return served |
| 3035 | } |
| 3036 | |
| 3037 | first := get(1) |
| 3038 | select { |
| 3039 | case <-reading: |
| 3040 | case <-time.After(10 * time.Second): |
| 3041 | t.Fatal("no load started") |
| 3042 | } |
| 3043 | goroutines := runtime.NumGoroutine() |
| 3044 | files, listed := openFiles(t) |
| 3045 | |
| 3046 | flood := 4 * MaxLoadWaiting |
| 3047 | served := get(flood) |
| 3048 | refused := flood - (MaxLoadWaiting - 1) |
| 3049 | for range refused { |
| 3050 | if w := <-served; w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 3051 | t.Fatalf("a request past MaxLoadWaiting answered %d", w.Code) |
| 3052 | } |
| 3053 | } |
| 3054 | if n := len(h.srv.loadWaiting); n != MaxLoadWaiting { |
| 3055 | t.Errorf("%d requests wait for the load, not %d", n, MaxLoadWaiting) |
| 3056 | } |
| 3057 | const slack = 8 |
| 3058 | eventually(t, "the refused requests' goroutines end", func() bool { |
| 3059 | return runtime.NumGoroutine() <= goroutines+MaxLoadWaiting-1+slack |
| 3060 | }) |
| 3061 | if n, _ := openFiles(t); listed && n > files+slack { |
| 3062 | t.Errorf("the flood holds %d files open, %d more than before it", n, n-files) |
| 3063 | } |
| 3064 | |
| 3065 | close(hold) |
| 3066 | for range MaxLoadWaiting - 1 { |
| 3067 | if w := <-served; w.Code != http.StatusOK { |
| 3068 | t.Errorf("a request that waited for the load answered %d", w.Code) |
| 3069 | } |
| 3070 | } |
| 3071 | if w := <-first; w.Code != http.StatusOK { |
| 3072 | t.Errorf("the request that started the load answered %d", w.Code) |
| 3073 | } |
| 3074 | if n := reads.Load(); n != 1 { |
| 3075 | t.Errorf("the export was read %d times for one generation", n) |
| 3076 | } |
| 3077 | if n := len(h.srv.loadWaiting); n != 0 { |
| 3078 | t.Errorf("%d requests still hold a place among those that wait", n) |
| 3079 | } |
| 3080 | } |
| 3081 | |
| 3082 | // A request's time runs from its arrival through its rendering: a request |
| 3083 | // for a page that runs no git, held past its time before it renders, |
| 3084 | // answers 503, and the server logs it. |
| 3085 | func TestRenderingIsWithinTheDeadline(t *testing.T) { |
| 3086 | h := newHarness(t) |
| 3087 | h.page("/") |
| 3088 | h.srv.timeout = 50 * time.Millisecond |
| 3089 | var logged []string |
| 3090 | h.srv.log = func(err error) { logged = append(logged, err.Error()) } |
| 3091 | h.srv.opened = func(export.Generation) { time.Sleep(100 * time.Millisecond) } |
| 3092 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable || !bytes.Equal(w.Body.Bytes(), busyPage) { |
| 3093 | t.Errorf("a request that ran out of time before it rendered answered %d", w.Code) |
| 3094 | } |
| 3095 | if len(logged) != 1 || !strings.Contains(logged[0], "rendering plan: context deadline exceeded") { |
| 3096 | t.Errorf("the server logged %q", logged) |
| 3097 | } |
| 3098 | if n, _ := h.srv.holding(); n != 0 { |
| 3099 | t.Errorf("a page that stopped rendering kept %d pieces of the budget", n) |
| 3100 | } |
| 3101 | } |
| 3102 | |
| 3103 | // A FIFO with a writer that sends no bytes keeps Read blocked until the |
| 3104 | // request deadline. A FIFO without a writer must not block Open. |
| 3105 | func TestStalledLoadReleasesGeneration(t *testing.T) { |
| 3106 | for _, writer := range []bool{false, true} { |
| 3107 | t.Run(fmt.Sprint(writer), func(t *testing.T) { |
| 3108 | h := newHarness(t) |
| 3109 | h.srv.timeout = 100 * time.Millisecond |
| 3110 | h.srv.log = func(error) {} |
| 3111 | old := h.active() |
| 3112 | data, err := os.ReadFile(old.ExportPath()) |
| 3113 | if err != nil { |
| 3114 | t.Fatal(err) |
| 3115 | } |
| 3116 | if err := os.Remove(old.ExportPath()); err != nil { |
| 3117 | t.Fatal(err) |
| 3118 | } |
| 3119 | if err := syscall.Mkfifo(old.ExportPath(), 0600); err != nil { |
| 3120 | t.Fatal(err) |
| 3121 | } |
| 3122 | if writer { |
| 3123 | f, err := os.OpenFile(old.ExportPath(), os.O_RDWR|syscall.O_NONBLOCK, 0) |
| 3124 | if err != nil { |
| 3125 | t.Fatal(err) |
| 3126 | } |
| 3127 | defer f.Close() |
| 3128 | if _, err := f.Write([]byte("{")); err != nil { |
| 3129 | t.Fatal(err) |
| 3130 | } |
| 3131 | } |
| 3132 | if w := h.get("/"); w.Code != http.StatusServiceUnavailable { |
| 3133 | t.Fatalf("status = %d", w.Code) |
| 3134 | } |
| 3135 | eventually(t, "the stalled worker exits", func() bool { return len(h.srv.loaders) == 0 }) |
| 3136 | h.srv.mu.Lock() |
| 3137 | cached := h.srv.cached |
| 3138 | h.srv.mu.Unlock() |
| 3139 | if cached != nil { |
| 3140 | t.Fatal("stalled load cached a snapshot") |
| 3141 | } |
| 3142 | if err := os.Remove(old.ExportPath()); err != nil { |
| 3143 | t.Fatal(err) |
| 3144 | } |
| 3145 | if err := os.WriteFile(old.ExportPath(), data, 0644); err != nil { |
| 3146 | t.Fatal(err) |
| 3147 | } |
| 3148 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan")) |
| 3149 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 3150 | t.Fatalf("generation retained: %v", err) |
| 3151 | } |
| 3152 | h.srv.timeout = requestTimeout |
| 3153 | if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "The second plan") { |
| 3154 | t.Fatal("loader slot is not reusable") |
| 3155 | } |
| 3156 | }) |
| 3157 | } |
| 3158 | } |
| 3159 | |
| 3160 | // cancelInPhase cancels a real context on the cancellation check numbered |
| 3161 | // at, or the third when at is 0, inside a named processing function. It |
| 3162 | // makes cancellation during CPU work deterministic without replacing |
| 3163 | // decoding or graph traversal. With a nil cancel it counts alone. |
| 3164 | type cancelInPhase struct { |
| 3165 | context.Context |
| 3166 | cancel context.CancelFunc |
| 3167 | phase string |
| 3168 | at int |
| 3169 | checks int |
| 3170 | } |
| 3171 | |
| 3172 | func (c *cancelInPhase) Err() error { |
| 3173 | var pcs [32]uintptr |
| 3174 | n := runtime.Callers(2, pcs[:]) |
| 3175 | frames := runtime.CallersFrames(pcs[:n]) |
| 3176 | for { |
| 3177 | frame, more := frames.Next() |
| 3178 | if strings.HasSuffix(frame.Function, c.phase) { |
| 3179 | c.checks++ |
| 3180 | at := c.at |
| 3181 | if at == 0 { |
| 3182 | at = 3 |
| 3183 | } |
| 3184 | if c.checks == at && c.cancel != nil { |
| 3185 | c.cancel() |
| 3186 | } |
| 3187 | break |
| 3188 | } |
| 3189 | if !more { |
| 3190 | break |
| 3191 | } |
| 3192 | } |
| 3193 | return c.Context.Err() |
| 3194 | } |
| 3195 | |
| 3196 | func TestProcessingCancellationReleasesGeneration(t *testing.T) { |
| 3197 | for _, phase := range []string{".decodeValue", "exactjson.(*checker).check", ".(*Export).ValidateContext", ".CheckNames", ".(*Export).checkGroups", |
| 3198 | ".(*index).place", ".(*index).planPage", ".(*index).paths", ".(*index).milestones"} { |
| 3199 | t.Run(phase, func(t *testing.T) { |
| 3200 | h := newHarness(t) |
| 3201 | old := h.active() |
| 3202 | base, cancel := context.WithCancel(context.Background()) |
| 3203 | defer cancel() |
| 3204 | ctx := &cancelInPhase{Context: base, cancel: cancel, phase: phase} |
| 3205 | l := &load{done: make(chan struct{}), cancel: cancel} |
| 3206 | h.srv.loads[l] = struct{}{} |
| 3207 | h.srv.loaders <- struct{}{} |
| 3208 | finished := make(chan struct{}) |
| 3209 | go func() { h.srv.run(ctx, l); close(finished) }() |
| 3210 | select { |
| 3211 | case <-finished: |
| 3212 | case <-time.After(2 * time.Second): |
| 3213 | t.Fatal("processing did not stop") |
| 3214 | } |
| 3215 | if ctx.checks < 3 { |
| 3216 | t.Fatalf("phase was not reached: %d checks", ctx.checks) |
| 3217 | } |
| 3218 | if !errors.Is(l.err, context.Canceled) { |
| 3219 | t.Fatalf("load error = %v", l.err) |
| 3220 | } |
| 3221 | if h.srv.cached != nil || len(h.srv.loaders) != 0 || len(h.srv.loads) != 0 { |
| 3222 | t.Fatal("cancelled processing retained load state") |
| 3223 | } |
| 3224 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("The second plan")) |
| 3225 | if _, err := os.Stat(old.Dir); !os.IsNotExist(err) { |
| 3226 | t.Fatalf("generation retained: %v", err) |
| 3227 | } |
| 3228 | if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "The second plan") { |
| 3229 | t.Fatal("loader slot is not reusable") |
| 3230 | } |
| 3231 | }) |
| 3232 | } |
| 3233 | } |
| 3234 | |
| 3235 | // Indexing where each public project's pages are, and where each alias |
| 3236 | // and former name redirects to, stops when the load is cancelled, inside |
| 3237 | // each of its loops: over the groups and their aliases, and over the |
| 3238 | // projects and their former names and aliases. It checks before each name |
| 3239 | // it indexes, so a long list of names keeps no cancelled load at work. |
| 3240 | func TestPlacingStopsWhenCancelled(t *testing.T) { |
| 3241 | f := exporttest.New(t) |
| 3242 | e, err := export.Decode(f.ExportJSON) |
| 3243 | if err != nil { |
| 3244 | t.Fatal(err) |
| 3245 | } |
| 3246 | e.Groups[0].Aliases = []string{"t", "u", "v"} |
| 3247 | app := &e.Projects[0] |
| 3248 | app.FormerNames, app.Aliases = []string{"old-app", "older-app", "oldest-app"}, []string{"app", "a", "b"} |
| 3249 | if err := e.Validate(); err != nil { |
| 3250 | t.Fatal(err) |
| 3251 | } |
| 3252 | count := &cancelInPhase{Context: context.Background(), phase: ".(*index).place"} |
| 3253 | if _, err := newIndex(count, e, map[string]bool{"app": true}); err != nil { |
| 3254 | t.Fatal(err) |
| 3255 | } |
| 3256 | if names := 3 + 3 + 3; count.checks < names { |
| 3257 | t.Errorf("placing indexed %d names and checked the context %d times", names, count.checks) |
| 3258 | } |
| 3259 | for at := 1; at <= count.checks; at++ { |
| 3260 | base, cancel := context.WithCancel(context.Background()) |
| 3261 | ctx := &cancelInPhase{Context: base, cancel: cancel, phase: ".(*index).place", at: at} |
| 3262 | idx, err := newIndex(ctx, e, map[string]bool{"app": true}) |
| 3263 | cancel() |
| 3264 | if idx != nil || !errors.Is(err, context.Canceled) || ctx.checks != at { |
| 3265 | t.Errorf("cancelled at check %d of %d, newIndex returned %v after %d checks", at, count.checks, err, ctx.checks) |
| 3266 | } |
| 3267 | } |
| 3268 | } |
| 3269 | |
| 3270 | // The server reads the stored authorization on every request. One that |
| 3271 | // withdraws app takes it off every page at the next request, with no |
| 3272 | // restart; one that names it again serves it again; and with none stored, |
| 3273 | // nothing is served, though the export is indexed already. |
| 3274 | func TestAuthorizationIsReadOnEveryRequest(t *testing.T) { |
| 3275 | h := newHarness(t) |
| 3276 | h.srv.log = func(error) {} |
| 3277 | app := "/tools/app/knots/oc-a000002" |
| 3278 | if w := h.get(app); w.Code != http.StatusOK { |
| 3279 | t.Fatalf("GET %s answered %d", app, w.Code) |
| 3280 | } |
| 3281 | a, _, err := h.store.Authorization() |
| 3282 | if err != nil { |
| 3283 | t.Fatal(err) |
| 3284 | } |
| 3285 | withdrawn := exporttest.Authorization(a.Sequence + 1) |
| 3286 | h.authorize(withdrawn) |
| 3287 | for _, path := range []string{app, "/tools/app/", "/t/app/", "/app/", "/tools/old-app/"} { |
| 3288 | if w := h.get(path); w.Code != http.StatusNotFound { |
| 3289 | t.Errorf("after the withdrawal GET %s answered %d, want 404", path, w.Code) |
| 3290 | } |
| 3291 | } |
| 3292 | if page := h.page("/"); strings.Contains(page, "/tools/app") { |
| 3293 | t.Error("after the withdrawal the plan page links app") |
| 3294 | } |
| 3295 | h.authorize(exporttest.Authorization(a.Sequence+2, "app")) |
| 3296 | if w := h.get(app); w.Code != http.StatusOK { |
| 3297 | t.Errorf("named again, GET %s answered %d", app, w.Code) |
| 3298 | } |
| 3299 | if err := os.Remove(filepath.Join(h.store.Dir(), "authorization")); err != nil { |
| 3300 | t.Fatal(err) |
| 3301 | } |
| 3302 | for _, path := range []string{"/", app, "/tools/app/"} { |
| 3303 | w := h.get(path) |
| 3304 | if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Nothing published yet") || strings.Contains(w.Body.String(), "oc-a000002") { |
| 3305 | t.Errorf("with no authorization GET %s answered %d:\n%s", path, w.Code, w.Body) |
| 3306 | } |
| 3307 | } |
| 3308 | } |
| 3309 | |
| 3310 | // A response is written only under the authorization it was rendered |
| 3311 | // under. One the authorization withdraws while it renders, a page or a |
| 3312 | // redirect, is rendered again under the new one, and the reader gets the |
| 3313 | // 404 the new one gives. |
| 3314 | func TestAResponseIsHeldToTheAuthorizationWhenWritten(t *testing.T) { |
| 3315 | for _, path := range []string{"/tools/app/knots/oc-a000002", "/tools/app/", "/app/knots/oc-a000002"} { |
| 3316 | t.Run(path, func(t *testing.T) { |
| 3317 | h := newHarness(t) |
| 3318 | a, _, err := h.store.Authorization() |
| 3319 | if err != nil { |
| 3320 | t.Fatal(err) |
| 3321 | } |
| 3322 | renders := 0 |
| 3323 | h.srv.checked = func() { |
| 3324 | if renders++; renders == 1 { |
| 3325 | h.authorize(exporttest.Authorization(a.Sequence + 1)) |
| 3326 | } |
| 3327 | } |
| 3328 | if w := h.get(path); w.Code != http.StatusNotFound || w.Header().Get("Location") != "" { |
| 3329 | t.Errorf("GET %s withdrawn while it rendered answered %d, to %q", path, w.Code, w.Header().Get("Location")) |
| 3330 | } |
| 3331 | if renders != 2 { |
| 3332 | t.Errorf("GET %s rendered %d times, want twice", path, renders) |
| 3333 | } |
| 3334 | }) |
| 3335 | } |
| 3336 | } |
| 3337 | |
| 3338 | // headerClock is a response recorder that notes when the headers were |
| 3339 | // written. |
| 3340 | type headerClock struct { |
| 3341 | *httptest.ResponseRecorder |
| 3342 | at time.Time |
| 3343 | } |
| 3344 | |
| 3345 | func (h *headerClock) WriteHeader(status int) { |
| 3346 | h.at = time.Now() |
| 3347 | h.ResponseRecorder.WriteHeader(status) |
| 3348 | } |
| 3349 | |
| 3350 | // A withdrawal stored between a response's last read of the authorization |
| 3351 | // and its headers waits for the headers: Authorize renames the record |
| 3352 | // under the serving lock, which the response holds shared until its |
| 3353 | // headers are written. So the response the old authorization allowed is |
| 3354 | // one whose headers were written before the withdrawal returned, and the |
| 3355 | // next request is refused. |
| 3356 | func TestAWithdrawalWaitsForAResponseItsCheckAdmitted(t *testing.T) { |
| 3357 | h := newHarness(t) |
| 3358 | a, _, err := h.store.Authorization() |
| 3359 | if err != nil { |
| 3360 | t.Fatal(err) |
| 3361 | } |
| 3362 | withdrawal := exporttest.Authorization(a.Sequence + 1) |
| 3363 | signed := exporttest.SignAuthorization(t, withdrawal) |
| 3364 | stored := make(chan time.Time, 1) |
| 3365 | h.srv.starting = func() { |
| 3366 | h.srv.starting = nil |
| 3367 | go func() { |
| 3368 | if err := h.store.Authorize(context.Background(), withdrawal, signed); err != nil { |
| 3369 | t.Error(err) |
| 3370 | } |
| 3371 | stored <- time.Now() |
| 3372 | }() |
| 3373 | select { |
| 3374 | case at := <-stored: |
| 3375 | t.Error("the withdrawal was stored while a response held the serving lock") |
| 3376 | stored <- at |
| 3377 | case <-time.After(200 * time.Millisecond): |
| 3378 | } |
| 3379 | } |
| 3380 | w := &headerClock{ResponseRecorder: httptest.NewRecorder()} |
| 3381 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000002", nil)) |
| 3382 | if w.Code != http.StatusOK { |
| 3383 | t.Fatalf("the response admitted before the withdrawal answered %d", w.Code) |
| 3384 | } |
| 3385 | at := <-stored |
| 3386 | if !at.After(w.at) { |
| 3387 | t.Errorf("the withdrawal returned at %v, before the response's headers at %v", at, w.at) |
| 3388 | } |
| 3389 | if w := h.get("/tools/app/knots/oc-a000002"); w.Code != http.StatusNotFound { |
| 3390 | t.Errorf("after the withdrawal returned the next request answered %d, want 404", w.Code) |
| 3391 | } |
| 3392 | } |
| 3393 | |
| 3394 | // holdEnv names the serving lock TestHoldTheServingLock holds, when the |
| 3395 | // test binary runs as that helper. |
| 3396 | const holdEnv = "VALLEY_WEB_SERVER_TEST_HOLD" |
| 3397 | |
| 3398 | // TestHoldTheServingLock is a process of its own when holdEnv is set: it |
| 3399 | // holds the serving lock exclusively, as a receiver renaming an |
| 3400 | // authorization does, says so on stdout, and holds it until its stdin |
| 3401 | // closes. |
| 3402 | func TestHoldTheServingLock(t *testing.T) { |
| 3403 | path := os.Getenv(holdEnv) |
| 3404 | if path == "" { |
| 3405 | t.Skip("a helper process of TestAServingLockWaitEndsWithTheRequest") |
| 3406 | } |
| 3407 | f, err := os.OpenFile(path, os.O_RDWR, 0) |
| 3408 | if err != nil { |
| 3409 | t.Fatal(err) |
| 3410 | } |
| 3411 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil { |
| 3412 | t.Fatal(err) |
| 3413 | } |
| 3414 | fmt.Println("held") |
| 3415 | io.Copy(io.Discard, os.Stdin) |
| 3416 | } |
| 3417 | |
| 3418 | // lockProbe is a response writer that notes when the headers were |
| 3419 | // written, and whether the serving lock was free when the body was. |
| 3420 | type lockProbe struct { |
| 3421 | *httptest.ResponseRecorder |
| 3422 | lock string |
| 3423 | wrote bool |
| 3424 | freeAtBody bool |
| 3425 | bodyAttempted bool |
| 3426 | } |
| 3427 | |
| 3428 | func (p *lockProbe) WriteHeader(status int) { |
| 3429 | p.wrote = true |
| 3430 | p.ResponseRecorder.WriteHeader(status) |
| 3431 | } |
| 3432 | |
| 3433 | func (p *lockProbe) Write(b []byte) (int, error) { |
| 3434 | if !p.bodyAttempted { |
| 3435 | p.bodyAttempted = true |
| 3436 | if f, err := os.OpenFile(p.lock, os.O_RDWR, 0); err == nil { |
| 3437 | if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil { |
| 3438 | p.freeAtBody = true |
| 3439 | } |
| 3440 | f.Close() |
| 3441 | } |
| 3442 | } |
| 3443 | return p.ResponseRecorder.Write(b) |
| 3444 | } |
| 3445 | |
| 3446 | // A request waits for the serving lock only until its deadline, or until |
| 3447 | // its reader goes away. While another process holds the lock |
| 3448 | // exclusively, a request whose deadline passes answers 503 and writes |
| 3449 | // nothing it rendered, and one whose reader goes away writes nothing at |
| 3450 | // all. With the lock free, a page and a redirect write their bodies after |
| 3451 | // the lock is let go. |
| 3452 | func TestAServingLockWaitEndsWithTheRequest(t *testing.T) { |
| 3453 | h := newHarness(t) |
| 3454 | lock := filepath.Join(h.store.Dir(), "serving.lock") |
| 3455 | for _, path := range []string{"/tools/app/knots/oc-a000002", "/tools/app/"} { |
| 3456 | w := &lockProbe{ResponseRecorder: httptest.NewRecorder(), lock: lock} |
| 3457 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) |
| 3458 | if !w.bodyAttempted || !w.freeAtBody { |
| 3459 | t.Errorf("GET %s wrote its body with the serving lock held (body written: %v)", path, w.bodyAttempted) |
| 3460 | } |
| 3461 | } |
| 3462 | |
| 3463 | cmd := exec.Command(os.Args[0], "-test.run=^TestHoldTheServingLock$") |
| 3464 | cmd.Env = append(os.Environ(), holdEnv+"="+lock) |
| 3465 | stdin, err := cmd.StdinPipe() |
| 3466 | if err != nil { |
| 3467 | t.Fatal(err) |
| 3468 | } |
| 3469 | stdout, err := cmd.StdoutPipe() |
| 3470 | if err != nil { |
| 3471 | t.Fatal(err) |
| 3472 | } |
| 3473 | if err := cmd.Start(); err != nil { |
| 3474 | t.Fatal(err) |
| 3475 | } |
| 3476 | defer func() { |
| 3477 | stdin.Close() |
| 3478 | cmd.Wait() |
| 3479 | }() |
| 3480 | line, err := bufio.NewReader(stdout).ReadString('\n') |
| 3481 | if err != nil || line != "held\n" { |
| 3482 | t.Fatalf("the helper said %q, %v", line, err) |
| 3483 | } |
| 3484 | |
| 3485 | h.srv.timeout = 300 * time.Millisecond |
| 3486 | began := time.Now() |
| 3487 | w := &lockProbe{ResponseRecorder: httptest.NewRecorder(), lock: lock} |
| 3488 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/", nil)) |
| 3489 | if took := time.Since(began); took > 3*time.Second { |
| 3490 | t.Errorf("a request waited %v for a held serving lock, past its deadline", took) |
| 3491 | } |
| 3492 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Location") != "" || strings.Contains(w.Body.String(), "oc-a000002") { |
| 3493 | t.Errorf("a request past its deadline answered %d, to %q:\n%s", w.Code, w.Header().Get("Location"), w.Body) |
| 3494 | } |
| 3495 | |
| 3496 | h.srv.timeout = time.Minute |
| 3497 | ctx, cancel := context.WithCancel(context.Background()) |
| 3498 | time.AfterFunc(200*time.Millisecond, cancel) |
| 3499 | began = time.Now() |
| 3500 | w = &lockProbe{ResponseRecorder: httptest.NewRecorder(), lock: lock} |
| 3501 | h.srv.ServeHTTP(w, httptest.NewRequest("GET", "/tools/app/knots/oc-a000002", nil).WithContext(ctx)) |
| 3502 | if took := time.Since(began); took > 3*time.Second { |
| 3503 | t.Errorf("a request whose reader went away waited %v for a held serving lock", took) |
| 3504 | } |
| 3505 | if w.wrote || w.bodyAttempted { |
| 3506 | t.Errorf("a request whose reader went away wrote a response: %d\n%s", w.Code, w.Body) |
| 3507 | } |
| 3508 | } |