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