| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "maps" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "regexp" |
| 14 | "slices" |
| 15 | "sort" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | "sync/atomic" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "the-valley/web/export" |
| 23 | "the-valley/web/export/exporttest" |
| 24 | ) |
| 25 | |
| 26 | // readerKey is the request context's key under which a test names the |
| 27 | // reader a request is read as. |
| 28 | type readerKey struct{} |
| 29 | |
| 30 | // as answers a request for target read as reader, with header's fields. |
| 31 | func (h *harness) as(reader, method, target string, header http.Header) *httptest.ResponseRecorder { |
| 32 | h.t.Helper() |
| 33 | r := httptest.NewRequest(method, target, nil) |
| 34 | for k, vs := range header { |
| 35 | r.Header[k] = vs |
| 36 | } |
| 37 | r = r.WithContext(context.WithValue(r.Context(), readerKey{}, reader)) |
| 38 | w := httptest.NewRecorder() |
| 39 | h.srv.ServeHTTP(w, r) |
| 40 | return w |
| 41 | } |
| 42 | |
| 43 | // pageAs is the body of a GET read as reader that must answer 200. |
| 44 | func (h *harness) pageAs(reader, target string) string { |
| 45 | h.t.Helper() |
| 46 | w := h.as(reader, "GET", target, nil) |
| 47 | if w.Code != http.StatusOK { |
| 48 | h.t.Fatalf("GET %s as %s answered %d:\n%s", target, reader, w.Code, w.Body) |
| 49 | } |
| 50 | return w.Body.String() |
| 51 | } |
| 52 | |
| 53 | // The publication identities these tests give site, which the fixture |
| 54 | // does not export, and docs, which the tests make of site. |
| 55 | const ( |
| 56 | siteIdentity = "273d5668702918ea7ae079de374db96b" |
| 57 | docsIdentity = "5b1e0c7a9f3d2e4c6a8b0d1f3e5c7a92" |
| 58 | ) |
| 59 | |
| 60 | // buildExport is the fixture's valley exported by export.Build, as a |
| 61 | // publisher builds it, with its plan changed by change first, when change |
| 62 | // is not nil: change is given the plan's knot of a project by ID. With |
| 63 | // site set, site is exported too, as for an edge where site has a named |
| 64 | // reader, and bundles holds its bundle. |
| 65 | func (h *harness) buildExport(site bool, change func(knot func(project, id string) map[string]any)) (e *export.Export, bundles map[string]string) { |
| 66 | t := h.t |
| 67 | t.Helper() |
| 68 | var plan map[string]any |
| 69 | if err := json.Unmarshal(h.f.Inputs.Plan, &plan); err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | project := func(name string) map[string]any { |
| 73 | for _, p := range plan["projects"].([]any) { |
| 74 | if p := p.(map[string]any); p["project"] == name { |
| 75 | return p |
| 76 | } |
| 77 | } |
| 78 | t.Fatalf("the fixture's plan has no project %s", name) |
| 79 | return nil |
| 80 | } |
| 81 | knot := func(name, id string) map[string]any { |
| 82 | for _, k := range project(name)["knots"].([]any) { |
| 83 | if k := k.(map[string]any); k["id"] == id { |
| 84 | return k |
| 85 | } |
| 86 | } |
| 87 | t.Fatalf("the fixture's plan has no knot %s:%s", name, id) |
| 88 | return nil |
| 89 | } |
| 90 | if change != nil { |
| 91 | change(knot) |
| 92 | } |
| 93 | data, err := json.Marshal(plan) |
| 94 | if err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | in := h.f.Inputs |
| 98 | in.Plan = data |
| 99 | in.Identities = map[string]string{"app": exporttest.Identities["app"]} |
| 100 | in.SourceTips = map[string]string{"app": h.f.Inputs.SourceTips["app"]} |
| 101 | in.Details = slices.Clone(h.f.Inputs.Details) |
| 102 | bundles = map[string]string{} |
| 103 | if site { |
| 104 | in.Identities["site"] = siteIdentity |
| 105 | in.SourceTips["site"] = git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef) |
| 106 | for _, k := range project("site")["knots"].([]any) { |
| 107 | id := k.(map[string]any)["id"].(string) |
| 108 | detail, err := json.Marshal(map[string]any{"schema": "valley-knot/v1", "project": "site", "tip": project("site")["tip"], |
| 109 | "knot": map[string]any{"id": id, "body": "What site says of " + id + ".\n", "comments": []any{}}}) |
| 110 | if err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | in.Details = append(in.Details, detail) |
| 114 | } |
| 115 | bundles["site"] = filepath.Join(t.TempDir(), "site.bundle") |
| 116 | git(t, h.f.Repos["site"], nil, "bundle", "create", "--quiet", bundles["site"], "main") |
| 117 | } |
| 118 | if e, err = export.Build(in); err != nil { |
| 119 | t.Fatal(err) |
| 120 | } |
| 121 | return e, bundles |
| 122 | } |
| 123 | |
| 124 | // withDocs adds to e a project docs, a copy of site with an identity of |
| 125 | // its own, in a group of its own, pages, whose alias is p. docs was |
| 126 | // renamed from old-docs, and has the short alias d. Its bundle is site's. |
| 127 | func withDocs(e *export.Export, bundles map[string]string) { |
| 128 | var site export.Project |
| 129 | for _, p := range e.Projects { |
| 130 | if p.Name == "site" { |
| 131 | site = p |
| 132 | } |
| 133 | } |
| 134 | docs := site |
| 135 | docs.Name, docs.Identity, docs.Group, docs.WebName = "docs", docsIdentity, "web", "docs" |
| 136 | docs.FormerNames, docs.Aliases = []string{"old-docs"}, []string{"d"} |
| 137 | e.Projects = append(e.Projects, docs) |
| 138 | sort.Slice(e.Projects, func(i, j int) bool { return e.Projects[i].Name < e.Projects[j].Name }) |
| 139 | e.Groups = append(e.Groups, export.Group{ID: "web", Name: "pages", Aliases: []string{"p"}}) |
| 140 | bundles["docs"] = bundles["site"] |
| 141 | } |
| 142 | |
| 143 | // authorizeReaders stores an authorization one sequence past the stored |
| 144 | // one's that lets the readers given for each project of e read it, under |
| 145 | // e's identity. A project given no reader is not named. The policy check's |
| 146 | // time is kept, so the pages' freshness does not change. |
| 147 | func (h *harness) authorizeReaders(e *export.Export, readers map[string][]string) { |
| 148 | h.t.Helper() |
| 149 | a, _, err := h.store.Authorization() |
| 150 | if err != nil { |
| 151 | h.t.Fatal(err) |
| 152 | } |
| 153 | next := &export.Authorization{Instance: exporttest.Instance, Destination: exporttest.Destination, |
| 154 | Sequence: a.Sequence + 1, Checked: a.Checked} |
| 155 | for _, p := range e.Projects { |
| 156 | if rs := readers[p.Name]; len(rs) > 0 { |
| 157 | next.Projects = append(next.Projects, export.AuthorizedProject{Name: p.Name, Identity: p.Identity, Readers: rs}) |
| 158 | } |
| 159 | } |
| 160 | h.authorize(next) |
| 161 | } |
| 162 | |
| 163 | // edge activates, signed at, an export that holds app, site and docs, as |
| 164 | // an edge holds them for site's and docs' named readers, and stores an |
| 165 | // authorization that lets the readers given for each read it. It returns |
| 166 | // the export. |
| 167 | func (h *harness) edge(at time.Time, readers map[string][]string) *export.Export { |
| 168 | h.t.Helper() |
| 169 | e, bundles := h.buildExport(true, nil) |
| 170 | withDocs(e, bundles) |
| 171 | h.authorizeReaders(e, readers) |
| 172 | h.publishExport(at, e, bundles) |
| 173 | return e |
| 174 | } |
| 175 | |
| 176 | // anonymousIndex is the index of the newest generation's view of what |
| 177 | // anyone may see, under the last authorization read. |
| 178 | func (s *Server) anonymousIndex() *index { |
| 179 | s.mu.Lock() |
| 180 | defer s.mu.Unlock() |
| 181 | var newest *view |
| 182 | for _, v := range s.views { |
| 183 | if v.idx != nil && maps.Equal(v.shown, visible(v.e, s.auth.a, export.Anyone)) && (newest == nil || v.key.seq > newest.key.seq) { |
| 184 | newest = v |
| 185 | } |
| 186 | } |
| 187 | if newest == nil { |
| 188 | return nil |
| 189 | } |
| 190 | return newest.idx |
| 191 | } |
| 192 | |
| 193 | // heldSlots is how many source requests hold a git slot, and |
| 194 | // waitingForSlots how many wait for one. |
| 195 | func (s *Server) heldSlots() int { |
| 196 | s.gitMu.Lock() |
| 197 | defer s.gitMu.Unlock() |
| 198 | return s.running |
| 199 | } |
| 200 | |
| 201 | func (s *Server) waitingForSlots() int { |
| 202 | s.gitMu.Lock() |
| 203 | defer s.gitMu.Unlock() |
| 204 | return len(s.queue) |
| 205 | } |
| 206 | |
| 207 | // runningLoads is how many loader slots loads hold. |
| 208 | func (s *Server) runningLoads() int { return len(s.anonLoader) + len(s.loaders) } |
| 209 | |
| 210 | // loadWaiters counts the requests that wait for the loads a request may |
| 211 | // still join, anonymous and named apart. |
| 212 | func (s *Server) loadWaiters() (anonymous, named int) { |
| 213 | s.mu.Lock() |
| 214 | defer s.mu.Unlock() |
| 215 | for l := range s.loads { |
| 216 | anonymous += l.anon |
| 217 | named += l.wants - l.anon |
| 218 | } |
| 219 | return anonymous, named |
| 220 | } |
| 221 | |
| 222 | // stoppingViews counts the views whose builds were stopped and whose |
| 223 | // workers have not ended. |
| 224 | func (s *Server) stoppingViews() int { |
| 225 | s.mu.Lock() |
| 226 | defer s.mu.Unlock() |
| 227 | return len(s.stopping) |
| 228 | } |
| 229 | |
| 230 | // heldViews counts the places of each pool that the views the server |
| 231 | // holds take, and the pins on all of them. A stopped build's place is not |
| 232 | // counted. |
| 233 | func (s *Server) heldViews() (anonymous, named, pins int) { |
| 234 | s.mu.Lock() |
| 235 | defer s.mu.Unlock() |
| 236 | for _, v := range s.views { |
| 237 | if v.holds[anonymousPool] { |
| 238 | anonymous++ |
| 239 | } |
| 240 | if v.holds[namedPool] { |
| 241 | named++ |
| 242 | } |
| 243 | pins += v.pins[anonymousPool] + v.pins[namedPool] |
| 244 | } |
| 245 | return anonymous, named, pins |
| 246 | } |
| 247 | |
| 248 | // Each reader is served from the projects they may see: what anyone may |
| 249 | // read, app, and what their principal may read, site for alice and docs |
| 250 | // for bob. For each reader, every route, the navigation, the landing, the |
| 251 | // projects page, each group's page, each project's knots page, the |
| 252 | // aliases, the former names, the references between projects, the |
| 253 | // rendered Markdown and the archives are built from those projects alone. |
| 254 | // A project the reader may not see answers every route exactly as one that |
| 255 | // does not exist, takes no git slot, and its group, when none of the |
| 256 | // group's projects is the reader's, has no page and no alias. |
| 257 | func TestNamedReadersSeeTheirOwnProjects(t *testing.T) { |
| 258 | h := newHarness(t) |
| 259 | h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{ |
| 260 | "app": {export.Anyone}, "site": {"alice"}, "docs": {"bob"}}) |
| 261 | appTip, siteTip := h.tip(), git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef) |
| 262 | var admitted atomic.Int32 |
| 263 | h.srv.admitted = func() { admitted.Add(1) } |
| 264 | |
| 265 | type project struct{ base, tip, readme string } |
| 266 | projects := map[string]project{ |
| 267 | "app": {"/tools/app", appTip, `<h1 id="app">`}, |
| 268 | "site": {"/tools/site", siteTip, `<h1 id="site">`}, |
| 269 | "docs": {"/pages/docs", siteTip, `<h1 id="site">`}, |
| 270 | } |
| 271 | readers := map[string][]string{export.Anyone: {"app"}, "alice": {"app", "site"}, "bob": {"app", "docs"}} |
| 272 | for reader, sees := range readers { |
| 273 | t.Run(reader, func(t *testing.T) { |
| 274 | // The navigation, the knots page and the landing: a reader who |
| 275 | // may see app alone lands on its tree, and one who may see more |
| 276 | // on the projects page. |
| 277 | plan := h.pageAs(reader, "/-/knots") |
| 278 | if nav := section(t, plan, `<nav class="site"`, `<span class="fresh">`); nav != `<nav class="site" aria-label="Pages"><a href="/-/projects">projects</a>` { |
| 279 | t.Errorf("the navigation is\n%s", nav) |
| 280 | } |
| 281 | if !strings.Contains(plan, "Policy last checked") { |
| 282 | t.Error("the knots page does not say when the policy was checked") |
| 283 | } |
| 284 | landing := "/-/projects" |
| 285 | if len(sees) == 1 { |
| 286 | landing = "/tools/app/source/tree/" + appTip + "/" |
| 287 | } |
| 288 | if w := h.as(reader, "GET", "/", nil); w.Code != http.StatusFound || w.Header().Get("Location") != landing { |
| 289 | t.Errorf("/ answered %d to %q, not to %s", w.Code, w.Header().Get("Location"), landing) |
| 290 | } |
| 291 | |
| 292 | // The projects page lists each project the reader may see, by |
| 293 | // group, and each group's page those of the group alone. A group |
| 294 | // none of whose projects the reader may see answers as a path |
| 295 | // that does not exist. |
| 296 | row := func(name string) string { |
| 297 | p := projects[name] |
| 298 | return `<li class="listed"><a class="mono" href="` + p.base + `/source/tree/` + p.tip + `/">` + |
| 299 | strings.TrimPrefix(p.base, "/") + `</a><a href="` + p.base + `/knots">knots</a></li>` |
| 300 | } |
| 301 | listed := h.pageAs(reader, "/-/projects") |
| 302 | groups := map[string][]string{"/tools/": nil, "/pages/": nil} |
| 303 | for _, name := range sees { |
| 304 | group := "/" + strings.Split(projects[name].base, "/")[1] + "/" |
| 305 | groups[group] = append(groups[group], row(name)) |
| 306 | } |
| 307 | if n := strings.Count(listed, `<li class="listed">`); n != len(sees) || !strings.Contains(listed, `<a href="/-/knots">all knots</a>`) { |
| 308 | t.Errorf("the projects page lists %d projects, not %d, or does not link all knots", n, len(sees)) |
| 309 | } |
| 310 | missing := h.as(reader, "GET", "/tools/nosuch/", nil) |
| 311 | for group, rows := range groups { |
| 312 | for _, r := range rows { |
| 313 | if !strings.Contains(listed, r) { |
| 314 | t.Errorf("the projects page does not list %s", r) |
| 315 | } |
| 316 | } |
| 317 | for _, target := range []string{group, strings.TrimSuffix(group, "/")} { |
| 318 | w := h.as(reader, "GET", target, nil) |
| 319 | if rows == nil { |
| 320 | if w.Code != http.StatusNotFound || fmt.Sprint(w.Header()) != fmt.Sprint(missing.Header()) || |
| 321 | !bytes.Equal(w.Body.Bytes(), missing.Body.Bytes()) { |
| 322 | t.Errorf("GET %s answered %d, not as a path that does not exist", target, w.Code) |
| 323 | } |
| 324 | continue |
| 325 | } |
| 326 | page := w.Body.String() |
| 327 | if w.Code != http.StatusOK || strings.Count(page, `<li class="listed">`) != len(rows) { |
| 328 | t.Errorf("GET %s answered %d without its group's projects alone", target, w.Code) |
| 329 | } |
| 330 | for _, r := range rows { |
| 331 | if !strings.Contains(page, r) { |
| 332 | t.Errorf("GET %s does not list %s", target, r) |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // Each project's knots page shows its own knots alone, under |
| 339 | // its project header, whose knots tab is current. |
| 340 | for _, name := range sees { |
| 341 | p := projects[name] |
| 342 | page := h.pageAs(reader, p.base+"/knots") |
| 343 | head := `<header class="project-head"> |
| 344 | <span class="mono">` + strings.TrimPrefix(p.base, "/") + `</span> |
| 345 | <nav class="tabs" aria-label="Project"><a href="` + p.base + `/source/tree/` + p.tip + `/">source</a><a href="` + p.base + `/knots" aria-current="page">knots</a></nav> |
| 346 | </header>` |
| 347 | if !strings.Contains(page, head) { |
| 348 | t.Errorf("%s's knots page has no project header with its knots tab current", name) |
| 349 | } |
| 350 | links := regexp.MustCompile(`href="([^"]*/knots/[^"]*)"`).FindAllStringSubmatch(page, -1) |
| 351 | if len(links) == 0 { |
| 352 | t.Errorf("%s's knots page links no knot", name) |
| 353 | } |
| 354 | for _, l := range links { |
| 355 | if !strings.HasPrefix(l[1], p.base+"/knots/") { |
| 356 | t.Errorf("%s's knots page links %s", name, l[1]) |
| 357 | } |
| 358 | } |
| 359 | if !strings.Contains(page, "<script>") { |
| 360 | t.Errorf("%s's knots page carries no script", name) |
| 361 | } |
| 362 | } |
| 363 | seesSite := slices.Contains(sees, "site") |
| 364 | if strings.Contains(plan, "/tools/site/knots/") != seesSite { |
| 365 | t.Errorf("the knots page shows site's knots %v, though the reader sees site %v", !seesSite, seesSite) |
| 366 | } |
| 367 | if strings.Contains(plan, "/pages/docs/") != slices.Contains(sees, "docs") { |
| 368 | t.Error("the knots page links docs's knots to a reader who may not see it, or not to one who may") |
| 369 | } |
| 370 | |
| 371 | // The references from app's knots into site. |
| 372 | blocked := h.pageAs(reader, "/tools/app/knots/oc-a000003") + h.pageAs(reader, "/tools/app/knots/bd-a000004") |
| 373 | for text, shown := range map[string]bool{ |
| 374 | `<a href="/tools/site/knots/oc-b000001">The site deploys the app</a>`: seesSite, |
| 375 | `<dt>Lands in</dt><dd><a href="/tools/site/source/tree/` + siteTip + `/">site</a></dd>`: seesSite, |
| 376 | `<dt>Lands in</dt><dd><a href="/tools/site/knots/oc-b000002">site:oc-b000002</a></dd>`: seesSite, |
| 377 | `<span class="t"><span class="muted">a knot in an unpublished project</span></span>`: !seesSite, |
| 378 | "<dt>Lands in</dt><dd>an unpublished project</dd>": !seesSite, |
| 379 | "<dt>Lands in</dt><dd>a knot in an unpublished project</dd>": !seesSite, |
| 380 | "site:oc-b000001": seesSite, |
| 381 | "The site serves the docs": false, |
| 382 | } { |
| 383 | if strings.Contains(blocked, text) != shown { |
| 384 | t.Errorf("app's blocked knots show %q %v, not %v", text, !shown, shown) |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | // Each project the reader may see, on every route. |
| 389 | for _, name := range sees { |
| 390 | p := projects[name] |
| 391 | admitted.Store(0) |
| 392 | if page := h.pageAs(reader, p.base+"/source/tree/"+p.tip+"/"); !strings.Contains(page, p.readme) { |
| 393 | t.Errorf("%s's tree does not render its README", name) |
| 394 | } |
| 395 | h.pageAs(reader, p.base+"/source/blob/"+p.tip+"/README.md") |
| 396 | h.pageAs(reader, p.base+"/source/log/"+p.tip) |
| 397 | archive := h.as(reader, "GET", p.base+"/source/archive/"+p.tip+".tar.gz", nil) |
| 398 | if archive.Code != http.StatusOK || !strings.Contains(archive.Header().Get("Content-Disposition"), name+"-"+p.tip[:12]+".tar.gz") { |
| 399 | t.Errorf("%s's archive answered %d, %q", name, archive.Code, archive.Header().Get("Content-Disposition")) |
| 400 | } else if _, ok := archiveEntries(t, archive.Body.Bytes())[name+"-"+p.tip[:12]+"/README.md"]; !ok { |
| 401 | t.Errorf("%s's archive does not hold its README", name) |
| 402 | } |
| 403 | if n := admitted.Load(); n != 4 { |
| 404 | t.Errorf("%s's four source routes took %d git slots", name, n) |
| 405 | } |
| 406 | for target, to := range map[string]string{ |
| 407 | p.base + "/": p.base + "/source/tree/" + p.tip + "/", |
| 408 | p.base + "/source/": p.base + "/source/tree/" + p.tip + "/", |
| 409 | p.base + "/source/archive/main.tar.gz": p.base + "/source/archive/" + p.tip + ".tar.gz", |
| 410 | } { |
| 411 | if w := h.as(reader, "GET", target, nil); w.Code != http.StatusFound || w.Header().Get("Location") != to { |
| 412 | t.Errorf("GET %s answered %d to %q, not to %s", target, w.Code, w.Header().Get("Location"), to) |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | aliases := map[string]string{ |
| 417 | "/t/app/": "/tools/app/", "/tools/old-app/": "/tools/app/", "/app/knots/oc-a000002": "/tools/app/knots/oc-a000002", |
| 418 | "/t/site/": "/tools/site/", "/t/nosuch/": "/tools/nosuch/", |
| 419 | } |
| 420 | if seesSite { |
| 421 | aliases["/site/"], aliases["/tools/old-site/"] = "/tools/site/", "/tools/site/" |
| 422 | } |
| 423 | if slices.Contains(sees, "docs") { |
| 424 | aliases["/p/docs/"], aliases["/d/"], aliases["/pages/old-docs/x"] = "/pages/docs/", "/pages/docs/", "/pages/docs/x" |
| 425 | } |
| 426 | for from, to := range aliases { |
| 427 | if w := h.as(reader, "GET", from, nil); w.Code != http.StatusPermanentRedirect || w.Header().Get("Location") != to { |
| 428 | t.Errorf("GET %s answered %d to %q, not to %s", from, w.Code, w.Header().Get("Location"), to) |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | // Each project the reader may not see answers as one that does |
| 433 | // not exist, on every route, and takes no git slot. |
| 434 | for _, name := range []string{"site", "docs"} { |
| 435 | if slices.Contains(sees, name) { |
| 436 | continue |
| 437 | } |
| 438 | p := projects[name] |
| 439 | admitted.Store(0) |
| 440 | var hidden []string |
| 441 | for _, route := range []string{"", "/", "/knots/oc-b000001", "/source", "/source/", "/source/tree/" + p.tip + "/", |
| 442 | "/source/blob/" + p.tip + "/README.md", "/source/log/" + p.tip, "/source/archive/" + p.tip + ".tar.gz", |
| 443 | "/source/archive/main.tar.gz"} { |
| 444 | hidden = append(hidden, p.base+route) |
| 445 | } |
| 446 | if name == "site" { |
| 447 | hidden = append(hidden, "/site/", "/site/knots/oc-b000001", "/tools/old-site/source/") |
| 448 | } else { |
| 449 | hidden = append(hidden, "/p/docs/", "/p/", "/d/", "/pages/old-docs/", "/pages/") |
| 450 | } |
| 451 | for _, target := range hidden { |
| 452 | w := h.as(reader, "GET", target, nil) |
| 453 | if w.Code != http.StatusNotFound || fmt.Sprint(w.Header()) != fmt.Sprint(missing.Header()) || |
| 454 | !bytes.Equal(w.Body.Bytes(), missing.Body.Bytes()) { |
| 455 | t.Errorf("GET %s answered %d, not as a project that does not exist", target, w.Code) |
| 456 | } |
| 457 | } |
| 458 | // A knots page's path carries the knots pages' policy, whether |
| 459 | // or not its project is one the reader may see. |
| 460 | w, none := h.as(reader, "GET", p.base+"/knots", nil), h.as(reader, "GET", "/tools/nosuch/knots", nil) |
| 461 | if w.Code != http.StatusNotFound || fmt.Sprint(w.Header()) != fmt.Sprint(none.Header()) || |
| 462 | !bytes.Equal(w.Body.Bytes(), none.Body.Bytes()) || w.Header().Get("Content-Security-Policy") != knotsPolicy { |
| 463 | t.Errorf("GET %s/knots answered %d, not as a project that does not exist", p.base, w.Code) |
| 464 | } |
| 465 | if n := admitted.Load(); n != 0 { |
| 466 | t.Errorf("the routes of %s, which the reader may not see, took %d git slots", name, n) |
| 467 | } |
| 468 | } |
| 469 | }) |
| 470 | } |
| 471 | |
| 472 | // With app withdrawn from anyone, / lands on the one project each |
| 473 | // named reader may see, and on the projects page for a reader who may |
| 474 | // see none, which says so. |
| 475 | e, _ := h.buildExport(true, nil) |
| 476 | withDocs(e, map[string]string{"site": ""}) |
| 477 | h.authorizeReaders(e, map[string][]string{"app": {"carol"}, "site": {"alice"}, "docs": {"bob"}}) |
| 478 | for reader, to := range map[string]string{export.Anyone: projectsURL, "alice": "/tools/site/source/tree/" + siteTip + "/", |
| 479 | "bob": "/pages/docs/source/tree/" + siteTip + "/", "carol": "/tools/app/source/tree/" + appTip + "/"} { |
| 480 | if w := h.as(reader, "GET", "/", nil); w.Code != http.StatusFound || w.Header().Get("Location") != to { |
| 481 | t.Errorf("/ as %s answered %d to %q, not to %s", reader, w.Code, w.Header().Get("Location"), to) |
| 482 | } |
| 483 | } |
| 484 | empty := h.pageAs(export.Anyone, "/-/projects") |
| 485 | if !strings.Contains(empty, `<p class="muted">No project is readable here.</p>`) || strings.Contains(empty, "all knots") || |
| 486 | strings.Contains(empty, `<li class="listed">`) || strings.Contains(empty, "tools") { |
| 487 | t.Errorf("with no project to see, the projects page is not its empty state:\n%s", empty) |
| 488 | } |
| 489 | if w := h.as(export.Anyone, "GET", "/tools/", nil); w.Code != http.StatusNotFound { |
| 490 | t.Errorf("a group none of whose projects anyone may see answered %d", w.Code) |
| 491 | } |
| 492 | if w := h.as(export.Anyone, "GET", "/t/app/", nil); w.Code != http.StatusNotFound { |
| 493 | t.Errorf("a group none of whose projects anyone may see kept its alias: %d", w.Code) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | // A reader may see a project when the authorization names it, under the |
| 498 | // identity the export gives it, for anyone or for the reader's principal: |
| 499 | // the union of the two. A grant under another identity grants nothing. |
| 500 | func TestVisibilityIsTheUnionUnderThePublicationIdentity(t *testing.T) { |
| 501 | e := &export.Export{Groups: []export.Group{{ID: "core", Name: "tools"}}, Projects: []export.Project{ |
| 502 | {Name: "app", Identity: exporttest.Identities["app"], Group: "core"}, |
| 503 | {Name: "loose", Identity: docsIdentity}, |
| 504 | {Name: "site", Identity: siteIdentity, Group: "core"}, |
| 505 | }} |
| 506 | a := &export.Authorization{Projects: []export.AuthorizedProject{ |
| 507 | {Name: "app", Identity: exporttest.Identities["app"], Readers: []string{"alice"}}, |
| 508 | {Name: "loose", Identity: docsIdentity, Readers: []string{export.Anyone, "alice"}}, |
| 509 | {Name: "site", Identity: siteIdentity, Readers: []string{export.Anyone, "bob"}}, |
| 510 | }} |
| 511 | for reader, want := range map[string][]string{ |
| 512 | export.Anyone: {"site"}, "alice": {"app", "site"}, "bob": {"site"}, "carol": {"site"}, |
| 513 | } { |
| 514 | var got []string |
| 515 | for name := range visible(e, a, reader) { |
| 516 | got = append(got, name) |
| 517 | } |
| 518 | sort.Strings(got) |
| 519 | if !slices.Equal(got, want) { |
| 520 | t.Errorf("%s may see %v, not %v", reader, got, want) |
| 521 | } |
| 522 | } |
| 523 | a.Projects[0].Identity = siteIdentity |
| 524 | if shown := visible(e, a, "alice"); shown["app"] { |
| 525 | t.Error("a grant under another identity lets alice see app") |
| 526 | } |
| 527 | if shown := visible(e, nil, "alice"); len(shown) != 0 { |
| 528 | t.Errorf("no authorization lets alice see %v", shown) |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | // Readers who may see the same projects share one index, and a named |
| 533 | // reader who may see no more than anyone shares anyone's. The index names |
| 534 | // no reader, and neither does any page built from it. |
| 535 | func TestIdenticalViewsShareAnIndex(t *testing.T) { |
| 536 | h := newHarness(t) |
| 537 | h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{ |
| 538 | "app": {export.Anyone}, "site": {"alice", "carol"}, "docs": {"bob"}}) |
| 539 | var built []string |
| 540 | var mu sync.Mutex |
| 541 | h.srv.indexing = func(_ context.Context, key viewKey) { |
| 542 | mu.Lock() |
| 543 | defer mu.Unlock() |
| 544 | built = append(built, key.projects) |
| 545 | } |
| 546 | pages := map[string]string{} |
| 547 | for _, reader := range []string{export.Anyone, "alice", "carol", "dave", "alice", export.Anyone} { |
| 548 | pages[reader] = h.pageAs(reader, "/-/knots") + h.pageAs(reader, "/tools/app/knots/oc-a000003") |
| 549 | } |
| 550 | if len(built) != 2 { |
| 551 | t.Errorf("the server built %d indexes for two views:\n%s", len(built), strings.Join(built, "--\n")) |
| 552 | } |
| 553 | if anonymous, named, pins := h.srv.heldViews(); anonymous != 1 || named != 1 || pins != 0 { |
| 554 | t.Errorf("the server holds %d views of what anyone may see and %d others, pinned %d times", anonymous, named, pins) |
| 555 | } |
| 556 | if pages["alice"] != pages["carol"] || pages["dave"] != pages[export.Anyone] || pages["alice"] == pages[export.Anyone] { |
| 557 | t.Error("readers who may see the same projects were served other pages") |
| 558 | } |
| 559 | for reader, page := range pages { |
| 560 | for _, name := range []string{"alice", "carol", "dave", "bob"} { |
| 561 | if strings.Contains(page, name) { |
| 562 | t.Errorf("the page served to %s names %s", reader, name) |
| 563 | } |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | // A knot whose one blocker is in a project the reader may not see reads |
| 569 | // the same whether the export leaves that project out or holds it for |
| 570 | // another reader: its projected fields, the knots page and its own page |
| 571 | // are the same, byte for byte. Its blocker done, neither says it waits; |
| 572 | // its blocker open, both say once that it waits on something the reader |
| 573 | // may not see. |
| 574 | func TestAHiddenBlockerReadsAlikeInEitherExport(t *testing.T) { |
| 575 | for _, status := range []string{"done", "open"} { |
| 576 | t.Run(status, func(t *testing.T) { |
| 577 | h := newHarness(t) |
| 578 | change := func(knot func(project, id string) map[string]any) { |
| 579 | k := knot("app", "oc-a000003") |
| 580 | k["blocked_by"] = []any{"site:oc-b000001"} |
| 581 | k["waiting_on"], k["state"], k["ready"] = []any{"site:oc-b000001"}, "blocked", false |
| 582 | k["edges"].([]any)[0].(map[string]any)["status"] = status |
| 583 | knot("app", "oc-a000002")["blocks"] = []any{} |
| 584 | if status == "done" { |
| 585 | k["waiting_on"], k["state"], k["ready"] = []any{}, "ready", true |
| 586 | b := knot("site", "oc-b000001") |
| 587 | b["status"], b["active"], b["state"], b["ready"] = "done", false, "done", false |
| 588 | } |
| 589 | } |
| 590 | targets := []string{"/-/knots", "/tools/app/knots/oc-a000003", "/tools/app/knots/bd-a000004", "/tools/app/knots/oc-a000001"} |
| 591 | served := func(at time.Time, site bool) (map[string]string, *export.Project) { |
| 592 | t.Helper() |
| 593 | e, bundles := h.buildExport(site, change) |
| 594 | h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}, "site": {"alice"}}) |
| 595 | h.publishExport(at, e, bundles) |
| 596 | pages := map[string]string{} |
| 597 | for _, target := range targets { |
| 598 | pages[target] = h.page(target) |
| 599 | } |
| 600 | return pages, h.srv.anonymousIndex().projects["app"] |
| 601 | } |
| 602 | without, projectedWithout := served(exporttest.SignedAt.Add(time.Minute), false) |
| 603 | with, projectedWith := served(exporttest.SignedAt.Add(2*time.Minute), true) |
| 604 | if !reflect.DeepEqual(projectedWithout, projectedWith) { |
| 605 | t.Errorf("app is projected one way from the export without site and another from the one with it:\n%+v\n%+v", |
| 606 | projectedWithout.Knots[2], projectedWith.Knots[2]) |
| 607 | } |
| 608 | for _, target := range targets { |
| 609 | if without[target] != with[target] { |
| 610 | t.Errorf("GET %s answered one page from the export without site and another from the one with it", target) |
| 611 | } |
| 612 | } |
| 613 | plan := with["/-/knots"] |
| 614 | switch status { |
| 615 | case "done": |
| 616 | if strings.Contains(plan, `class="chip blocked"`) { |
| 617 | t.Error("a knot whose hidden blocker is done is shown waiting") |
| 618 | } |
| 619 | case "open": |
| 620 | if strings.Count(plan, `<span class="chip blocked">`) != 1 || |
| 621 | !strings.Contains(plan, `<span class="chip blocked">waits on a knot in an unpublished project</span>`) { |
| 622 | t.Errorf("a knot whose hidden blocker is open does not say once that it waits:\n%s", section(t, plan, `id="ms-h"`, "</body>")) |
| 623 | } |
| 624 | } |
| 625 | for _, page := range with { |
| 626 | for _, unwanted := range append([]string{"/tools/site/"}, unpublishedText...) { |
| 627 | if strings.Contains(page, unwanted) { |
| 628 | t.Errorf("a page holds %q", unwanted) |
| 629 | } |
| 630 | } |
| 631 | } |
| 632 | if page := h.pageAs("alice", "/tools/app/knots/oc-a000003"); !strings.Contains(page, `<a href="/tools/site/knots/oc-b000001">The site deploys the app</a>`) { |
| 633 | t.Error("alice, who may see site, is not shown the blocker") |
| 634 | } |
| 635 | }) |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | // The projection copies the projects a reader may see, and of each knot |
| 640 | // keeps what it says of those projects and the export's opaque summary |
| 641 | // alone: the references into other projects leave its four derived lists, |
| 642 | // its WaitingOnHidden is set when one leaves WaitingOn, and its edges into |
| 643 | // them are hidden, with nothing of their targets kept. The export it reads |
| 644 | // does not change. |
| 645 | func TestProjectionHidesOtherProjects(t *testing.T) { |
| 646 | h := newHarness(t) |
| 647 | e, _ := h.buildExport(true, nil) |
| 648 | app := &e.Projects[0] |
| 649 | at := slices.IndexFunc(app.Knots, func(k export.Knot) bool { return k.ID == "oc-a000003" }) |
| 650 | k := &app.Knots[at] |
| 651 | why, status, title := "a reason", "open", "A title of site's" |
| 652 | // "site" alone is neither a knot's ID nor <project>:<id>, so it names |
| 653 | // no knot the reader may see, and is taken out. |
| 654 | k.WaitingOn = []string{"oc-a000002", "site:oc-b000001", "app:oc-a000006", "gone:oc-c000001", "site"} |
| 655 | k.ClearedByEnding = []string{"site:oc-b000002", "oc-a000006"} |
| 656 | k.Dangling = []string{"site:oc-bfffff1", "app:oc-afffff1"} |
| 657 | k.Unresolved = []string{"site:oc-b000003", "oc-a000001", "site"} |
| 658 | k.Edges = []export.Edge{ |
| 659 | {Field: "blocked_by", Ref: "site:oc-b000001", Project: "site", ID: "oc-b000001", State: export.EdgeResolved, Why: &why, Status: &status, Title: &title}, |
| 660 | {Field: "blocked_by", Ref: "site:oc-bfffff1", Project: "site", ID: "oc-bfffff1", State: export.EdgeDangling, Why: &why}, |
| 661 | {Field: "blocked_by", Ref: "app:oc-afffff1", Project: "app", ID: "oc-afffff1", State: export.EdgeDangling}, |
| 662 | {Field: "target", Ref: "gone:oc-c000001", Project: "gone", ID: "oc-c000001", State: export.EdgeHidden}, |
| 663 | } |
| 664 | before, err := e.Encode() |
| 665 | if err != nil { |
| 666 | t.Fatal(err) |
| 667 | } |
| 668 | projected, err := projectForReader(context.Background(), e, map[string]bool{"app": true}) |
| 669 | if err != nil { |
| 670 | t.Fatal(err) |
| 671 | } |
| 672 | if len(projected.Projects) != 1 || projected.Projects[0].Name != "app" || len(projected.Groups) != 1 { |
| 673 | t.Fatalf("the projection holds %d projects and %d groups", len(projected.Projects), len(projected.Groups)) |
| 674 | } |
| 675 | got := projected.Projects[0].Knots[at] |
| 676 | hide := func(edge export.Edge) export.Edge { |
| 677 | return export.Edge{Field: edge.Field, Ref: edge.Ref, Project: edge.Project, ID: edge.ID, State: export.EdgeHidden} |
| 678 | } |
| 679 | for field, c := range map[string][2]any{ |
| 680 | "WaitingOn": {got.WaitingOn, []string{"oc-a000002", "app:oc-a000006"}}, |
| 681 | "WaitingOnHidden": {got.WaitingOnHidden, true}, |
| 682 | "ClearedByEnding": {got.ClearedByEnding, []string{"oc-a000006"}}, |
| 683 | "Dangling": {got.Dangling, []string{"app:oc-afffff1"}}, |
| 684 | "Unresolved": {got.Unresolved, []string{"oc-a000001"}}, |
| 685 | "Edges": {got.Edges, []export.Edge{hide(k.Edges[0]), hide(k.Edges[1]), k.Edges[2], k.Edges[3]}}, |
| 686 | "State": {got.State, k.State}, |
| 687 | "Ready": {got.Ready, k.Ready}, |
| 688 | "BlockedBy": {got.BlockedBy, k.BlockedBy}, |
| 689 | } { |
| 690 | if !reflect.DeepEqual(c[0], c[1]) { |
| 691 | t.Errorf("the projected %s is %v, not %v", field, c[0], c[1]) |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | // Everything kept for a reader who may see site, and the export read |
| 696 | // is the same bytes, though the copies change. |
| 697 | all, err := projectForReader(context.Background(), e, map[string]bool{"app": true, "site": true}) |
| 698 | if err != nil { |
| 699 | t.Fatal(err) |
| 700 | } |
| 701 | if kept := all.Projects[0].Knots[at]; !reflect.DeepEqual(kept.WaitingOn, k.WaitingOn[:3]) || !kept.WaitingOnHidden || |
| 702 | !reflect.DeepEqual(kept.Edges, k.Edges) || !reflect.DeepEqual(kept.Dangling, k.Dangling) || len(all.Projects) != 2 { |
| 703 | t.Errorf("a reader who may see site is not told what the export says of it: %+v", kept) |
| 704 | } |
| 705 | projected.Projects[0].Knots[at].Title = "changed" |
| 706 | projected.Projects[0].Knots[at].WaitingOn[0] = "changed" |
| 707 | projected.Projects[0].Knots[at].Edges[2].ID = "changed" |
| 708 | all.Projects[0].Knots[at].Dangling[0] = "changed" |
| 709 | if after, err := e.Encode(); err != nil || !bytes.Equal(before, after) { |
| 710 | t.Errorf("projecting the export, or changing a projection, changed the export: %v", err) |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | // privateViews activates an export that holds app, which anyone may |
| 715 | // read, and four private projects, p1 to p4, copies of site. It stores an |
| 716 | // authorization that lets each of the principals r1 to r15 read another |
| 717 | // set of the four, so each of them has a view of their own. It returns the |
| 718 | // export and its bundles. |
| 719 | func (h *harness) privateViews() (*export.Export, map[string]string) { |
| 720 | h.t.Helper() |
| 721 | e, bundles := h.buildExport(true, nil) |
| 722 | var site export.Project |
| 723 | for _, p := range e.Projects { |
| 724 | if p.Name == "site" { |
| 725 | site = p |
| 726 | } |
| 727 | } |
| 728 | readers := map[string][]string{"app": {export.Anyone}} |
| 729 | for i := 1; i <= 4; i++ { |
| 730 | p := site |
| 731 | p.Name, p.WebName, p.Identity, p.FormerNames, p.Aliases = fmt.Sprintf("p%d", i), fmt.Sprintf("p%d", i), fmt.Sprintf("%032x", i), nil, nil |
| 732 | e.Projects = append(e.Projects, p) |
| 733 | bundles[p.Name] = bundles["site"] |
| 734 | for set := 1; set < 16; set++ { |
| 735 | if set&(1<<(i-1)) != 0 { |
| 736 | readers[p.Name] = append(readers[p.Name], fmt.Sprintf("r%d", set)) |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | sort.Slice(e.Projects, func(i, j int) bool { return e.Projects[i].Name < e.Projects[j].Name }) |
| 741 | h.authorizeReaders(e, readers) |
| 742 | h.publishExport(exporttest.SignedAt.Add(time.Minute), e, bundles) |
| 743 | return e, bundles |
| 744 | } |
| 745 | |
| 746 | // serving answers a GET of target read as reader, under ctx, in a |
| 747 | // goroutine of its own, and sends its response on the channel it returns. |
| 748 | func (h *harness) serving(reader, target string, ctx context.Context) chan *httptest.ResponseRecorder { |
| 749 | served := make(chan *httptest.ResponseRecorder, 1) |
| 750 | go func() { |
| 751 | w := httptest.NewRecorder() |
| 752 | r := httptest.NewRequest("GET", target, nil) |
| 753 | h.srv.ServeHTTP(w, r.WithContext(context.WithValue(ctx, readerKey{}, reader))) |
| 754 | served <- w |
| 755 | }() |
| 756 | return served |
| 757 | } |
| 758 | |
| 759 | // A target names a project, or a knot of one, and never a knot of its |
| 760 | // own graph, so a project may be named as a knot's ID and still be a |
| 761 | // project. Here oc-c000001, a copy of site that alice alone may read, is |
| 762 | // the target of app's oc-a000003. A reader who may not see it is told the |
| 763 | // knot lands in an unpublished project, on its page and on the knots |
| 764 | // page, and no page of theirs names it. alice is shown it and linked to |
| 765 | // its source. The other references a knot's page names are held to their |
| 766 | // own fields: graduated_into names a knot of the knot's own graph, and a |
| 767 | // blocked_by entry, a waiting_on entry or a changes link that names a |
| 768 | // hidden project in neither of the shapes its field allows names nothing |
| 769 | // of it. |
| 770 | func TestATargetNamesNoProjectTheReaderMayNotSee(t *testing.T) { |
| 771 | h := newHarness(t) |
| 772 | e, bundles := h.buildExport(true, nil) |
| 773 | const hidden = "oc-c000001" |
| 774 | for _, p := range e.Projects { |
| 775 | if p.Name == "site" { |
| 776 | p.Name, p.WebName, p.Identity, p.FormerNames, p.Aliases = hidden, hidden, fmt.Sprintf("%032x", 0xc1), nil, nil |
| 777 | e.Projects = append(e.Projects, p) |
| 778 | bundles[hidden] = bundles["site"] |
| 779 | break |
| 780 | } |
| 781 | } |
| 782 | sort.Slice(e.Projects, func(i, j int) bool { return e.Projects[i].Name < e.Projects[j].Name }) |
| 783 | app := &e.Projects[0] |
| 784 | for i := range app.Knots { |
| 785 | switch k := &app.Knots[i]; k.ID { |
| 786 | case "oc-a000003": |
| 787 | k.Target = hidden |
| 788 | k.BlockedBy = append(k.BlockedBy, "site") |
| 789 | k.WaitingOn = append(k.WaitingOn, "site") |
| 790 | k.Changes = append(k.Changes, "valley:site") |
| 791 | case "bd-a000004": |
| 792 | k.GraduatedInto = "oc-a000002" |
| 793 | case "oc-a000006": |
| 794 | k.GraduatedInto = "site" |
| 795 | } |
| 796 | } |
| 797 | h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}, hidden: {"alice"}}) |
| 798 | h.publishExport(exporttest.SignedAt.Add(time.Minute), e, bundles) |
| 799 | tip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef) |
| 800 | |
| 801 | for reader, sees := range map[string]bool{export.Anyone: false, "bob": false, "alice": true} { |
| 802 | t.Run(reader, func(t *testing.T) { |
| 803 | knot := h.pageAs(reader, "/tools/app/knots/oc-a000003") |
| 804 | plan := h.pageAs(reader, "/-/knots") |
| 805 | lands := "<dt>Lands in</dt><dd>an unpublished project</dd>" |
| 806 | chip := `<span class="chip quiet">lands in an unpublished project</span>` |
| 807 | if sees { |
| 808 | lands = `<dt>Lands in</dt><dd><a href="/tools/` + hidden + `/source/tree/` + tip + `/">` + hidden + `</a></dd>` |
| 809 | chip = `<span class="chip quiet">lands in ` + hidden + `</span>` |
| 810 | } |
| 811 | if !strings.Contains(knot, lands) { |
| 812 | t.Errorf("oc-a000003's page does not show %q", lands) |
| 813 | } |
| 814 | if !strings.Contains(plan, chip) { |
| 815 | t.Errorf("the knots page does not show %q", chip) |
| 816 | } |
| 817 | |
| 818 | // Every page the reader may see of app, and the landing. |
| 819 | pages := []string{knot, plan} |
| 820 | for _, k := range app.Knots { |
| 821 | pages = append(pages, h.pageAs(reader, "/tools/app/knots/"+k.ID)) |
| 822 | } |
| 823 | pages = append(pages, h.pageAs(reader, "/tools/app/source/tree/"+h.tip()+"/")) |
| 824 | if w := h.as(reader, "GET", "/", nil); w.Code != http.StatusFound { |
| 825 | t.Errorf("/ answered %d", w.Code) |
| 826 | } else { |
| 827 | pages = append(pages, w.Header().Get("Location")+w.Body.String()) |
| 828 | } |
| 829 | all := strings.Join(pages, "\n") |
| 830 | if strings.Contains(all, hidden) != sees { |
| 831 | t.Errorf("the reader's pages name %s %v, though the reader sees it %v", hidden, !sees, sees) |
| 832 | } |
| 833 | for _, unwanted := range []string{">site<", "site,", ", site", "valley:site", "/tools/site/"} { |
| 834 | if strings.Contains(all, unwanted) { |
| 835 | t.Errorf("the reader's pages hold %q", unwanted) |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | // The fields beside the target, each by its own shape. |
| 840 | for _, want := range []string{ |
| 841 | `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`, |
| 842 | } { |
| 843 | if !strings.Contains(plan, want) { |
| 844 | t.Errorf("the knots page does not show %q", want) |
| 845 | } |
| 846 | } |
| 847 | for target, want := range map[string]string{ |
| 848 | "/tools/app/knots/oc-a000003": `<li class="mono">a change in an unpublished project</li>`, |
| 849 | "/tools/app/knots/bd-a000004": `<dt>Graduated into</dt><dd><a href="/tools/app/knots/oc-a000002">oc-a000002</a></dd>`, |
| 850 | "/tools/app/knots/oc-a000006": "<dt>Graduated into</dt><dd>a knot in an unpublished project</dd>", |
| 851 | } { |
| 852 | if page := h.pageAs(reader, target); !strings.Contains(page, want) { |
| 853 | t.Errorf("%s does not show %q", target, want) |
| 854 | } |
| 855 | } |
| 856 | if n := strings.Count(knot, `<span class="muted">a knot in an unpublished project</span>`); n != 2 { |
| 857 | t.Errorf("oc-a000003's page names %d blockers as unpublished, not its two", n) |
| 858 | } |
| 859 | }) |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | // A reference is read by the whole of a shape its field allows before |
| 864 | // anything of it is resolved or shown (knot/validate.go): a project's |
| 865 | // name, <project>:<id>, a knot's ID, or valley:<project>/<change ID>. Here |
| 866 | // app is anyone's, site is alice's alone, and each value opens with app, |
| 867 | // which every reader sees, but has none of its field's shapes. Every page |
| 868 | // that names the field shows it as unpublished, with none of its text, |
| 869 | // whatever the reader sees, and the projection takes it out of the four |
| 870 | // derived lists. |
| 871 | func TestMalformedReferencesNameNothing(t *testing.T) { |
| 872 | malformed := []string{"app:site:oc-b000001", "app:oc-b000001:site", "app:site", "app/site", "app:site/oc-b000001"} |
| 873 | for _, c := range []struct { |
| 874 | field string |
| 875 | knot string |
| 876 | values []string |
| 877 | set func(k *export.Knot, value string) |
| 878 | shown map[string]string // a route that names the field, and what it shows there |
| 879 | }{ |
| 880 | {"blocked_by", "oc-a000003", malformed, |
| 881 | func(k *export.Knot, v string) { k.BlockedBy = []string{"oc-a000002", v} }, |
| 882 | map[string]string{"/tools/app/knots/oc-a000003": `<span class="t"><span class="muted">a knot in an unpublished project</span></span>`}}, |
| 883 | {"target", "oc-a000003", malformed, |
| 884 | func(k *export.Knot, v string) { k.Target = v }, |
| 885 | map[string]string{ |
| 886 | "/tools/app/knots/oc-a000003": "<dt>Lands in</dt><dd>an unpublished project</dd>", |
| 887 | "/-/knots": `<span class="chip quiet">lands in an unpublished project</span>`, |
| 888 | }}, |
| 889 | {"waiting_on", "oc-a000003", malformed, |
| 890 | func(k *export.Knot, v string) { k.WaitingOn = []string{"oc-a000002", v} }, |
| 891 | map[string]string{"/-/knots": `<span class="chip blocked">waits on oc-a000002, a knot in an unpublished project</span>`}}, |
| 892 | {"graduated_into", "oc-a000006", append([]string{"site", "app:oc-a000002", "bd-a000004", "ida-a000007"}, malformed...), |
| 893 | func(k *export.Knot, v string) { k.GraduatedInto = v }, |
| 894 | map[string]string{"/tools/app/knots/oc-a000006": "<dt>Graduated into</dt><dd>a knot in an unpublished project</dd>"}}, |
| 895 | {"changes", "oc-a000003", []string{"valley:app/site/secret", "valley:app/site", "valley:app:site", |
| 896 | "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm/site", "valley:app/kmnopqrstuvwxyzkmnopqrstuvwxyzkm site"}, |
| 897 | func(k *export.Knot, v string) { k.Changes = []string{v} }, |
| 898 | map[string]string{"/tools/app/knots/oc-a000003": `<li class="mono">a change in an unpublished project</li>`}}, |
| 899 | } { |
| 900 | t.Run(c.field, func(t *testing.T) { |
| 901 | h := newHarness(t) |
| 902 | e, bundles := h.buildExport(true, nil) |
| 903 | h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}, "site": {"alice"}}) |
| 904 | for i, value := range c.values { |
| 905 | next := *e |
| 906 | next.Projects = slices.Clone(e.Projects) |
| 907 | app := &next.Projects[0] |
| 908 | app.Knots = slices.Clone(app.Knots) |
| 909 | at := slices.IndexFunc(app.Knots, func(k export.Knot) bool { return k.ID == c.knot }) |
| 910 | c.set(&app.Knots[at], value) |
| 911 | h.publishExport(exporttest.SignedAt.Add(time.Duration(i+1)*time.Minute), &next, bundles) |
| 912 | // A bare word is looked for as an element's text, since |
| 913 | // the pages' own markup holds words such as site. |
| 914 | named := value |
| 915 | if !strings.ContainsAny(value, ":/") { |
| 916 | named = ">" + value + "<" |
| 917 | } |
| 918 | for _, reader := range []string{export.Anyone, "bob", "alice"} { |
| 919 | for route, want := range c.shown { |
| 920 | page := h.pageAs(reader, route) |
| 921 | if !strings.Contains(page, want) { |
| 922 | t.Errorf("%s = %q: %s as %s does not show %q", c.field, value, route, reader, want) |
| 923 | } |
| 924 | if strings.Contains(page, named) { |
| 925 | t.Errorf("%s = %q: %s as %s names it", c.field, value, route, reader) |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | } |
| 930 | }) |
| 931 | } |
| 932 | |
| 933 | t.Run("derived lists", func(t *testing.T) { |
| 934 | h := newHarness(t) |
| 935 | e, _ := h.buildExport(true, nil) |
| 936 | app := &e.Projects[0] |
| 937 | at := slices.IndexFunc(app.Knots, func(k export.Knot) bool { return k.ID == "oc-a000003" }) |
| 938 | k := &app.Knots[at] |
| 939 | k.WaitingOn = append([]string{"oc-a000002"}, malformed...) |
| 940 | k.ClearedByEnding, k.Dangling, k.Unresolved = malformed, malformed, malformed |
| 941 | for _, shown := range []map[string]bool{{"app": true}, {"app": true, "site": true}} { |
| 942 | projected, err := projectForReader(context.Background(), e, shown) |
| 943 | if err != nil { |
| 944 | t.Fatal(err) |
| 945 | } |
| 946 | got := projected.Projects[0].Knots[at] |
| 947 | if !slices.Equal(got.WaitingOn, []string{"oc-a000002"}) || !got.WaitingOnHidden || |
| 948 | len(got.ClearedByEnding) != 0 || len(got.Dangling) != 0 || len(got.Unresolved) != 0 { |
| 949 | t.Errorf("projected for %v, the lists keep %v, %v, %v and %v, and waiting_on_hidden is %v", |
| 950 | shown, got.WaitingOn, got.ClearedByEnding, got.Dangling, got.Unresolved, got.WaitingOnHidden) |
| 951 | } |
| 952 | } |
| 953 | }) |
| 954 | } |
| 955 | |
| 956 | // The views of what anyone may see have places no named reader's view |
| 957 | // takes. While every named place holds a view being built, a named |
| 958 | // reader's request whose view needs another waits, holding no loader |
| 959 | // slot, no git slot and no generation, and answers 503 at its deadline, |
| 960 | // or nothing once its reader goes away, leaving no view behind. So does a |
| 961 | // named reader who may see no more than anyone, though it would share |
| 962 | // anyone's index. Meanwhile anyone is served, a load of a new generation |
| 963 | // runs, and the new generation's view of what anyone may see is built and |
| 964 | // served. Once the builds end, every request that waited for one is |
| 965 | // served. |
| 966 | func TestAnonymousViewsSurviveNamedSaturation(t *testing.T) { |
| 967 | h := newHarness(t) |
| 968 | e, bundles := h.privateViews() |
| 969 | h.page("/-/knots") |
| 970 | |
| 971 | hold := make(chan struct{}) |
| 972 | var holding atomic.Int32 |
| 973 | h.srv.indexing = func(ctx context.Context, key viewKey) { |
| 974 | if strings.Contains(key.projects, "\np") { |
| 975 | holding.Add(1) |
| 976 | select { |
| 977 | case <-hold: |
| 978 | case <-ctx.Done(): |
| 979 | } |
| 980 | } |
| 981 | } |
| 982 | var gitSlots atomic.Int32 |
| 983 | h.srv.admitted = func() { gitSlots.Add(1) } |
| 984 | serve := h.serving |
| 985 | var waiting []chan *httptest.ResponseRecorder |
| 986 | for i := 1; i <= MaxViews; i++ { |
| 987 | waiting = append(waiting, serve(fmt.Sprintf("r%d", i), "/-/knots", context.Background())) |
| 988 | } |
| 989 | eventually(t, "every named place holds a view being built", func() bool { return holding.Load() == MaxViews }) |
| 990 | |
| 991 | // A ninth named view finds no room. It waits holding nothing, and |
| 992 | // answers 503 at its deadline; another whose reader goes away answers |
| 993 | // nothing. Neither leaves a view or a pin behind. |
| 994 | h.srv.timeout = 300 * time.Millisecond |
| 995 | h.srv.log = func(error) {} |
| 996 | late := serve("r9", "/tools/p1/source/tree/"+h.tip()+"/", context.Background()) |
| 997 | // The eight wait for their builds, each in a waiting place, and the |
| 998 | // ninth waits for room in one more. |
| 999 | eventually(t, "the ninth named view waits for room", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 }) |
| 1000 | if h.srv.runningLoads() != 0 || h.srv.heldSlots() != 0 || gitSlots.Load() != 0 { |
| 1001 | t.Errorf("a request waiting for room holds %d loader slots and %d git slots", h.srv.runningLoads(), h.srv.heldSlots()) |
| 1002 | } |
| 1003 | select { |
| 1004 | case w := <-late: |
| 1005 | if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" { |
| 1006 | t.Errorf("a named view that found no room answered %d", w.Code) |
| 1007 | } |
| 1008 | case <-time.After(10 * time.Second): |
| 1009 | t.Fatal("a named view that found no room waited past its deadline") |
| 1010 | } |
| 1011 | h.srv.timeout = time.Hour |
| 1012 | ctx, cancel := context.WithCancel(context.Background()) |
| 1013 | gone := serve("r10", "/-/knots", ctx) |
| 1014 | eventually(t, "the tenth named view waits for room", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 }) |
| 1015 | cancel() |
| 1016 | if w := <-gone; w.Body.Len() != 0 { |
| 1017 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 1018 | } |
| 1019 | if anonymous, named, _ := h.srv.heldViews(); anonymous != 1 || named != MaxViews { |
| 1020 | t.Errorf("the server holds %d views of what anyone may see and %d others", anonymous, named) |
| 1021 | } |
| 1022 | |
| 1023 | // Anyone is served still, from the generation's view, and from the |
| 1024 | // next generation's, whose export is read and indexed meanwhile. r0, |
| 1025 | // who may see no more than anyone, shares anyone's index, but takes a |
| 1026 | // named place for it, so it waits for room. |
| 1027 | h.page("/-/knots") |
| 1028 | r0 := serve("r0", "/tools/app/knots/oc-a000002", context.Background()) |
| 1029 | eventually(t, "r0 waits for a named place", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 }) |
| 1030 | app := e.Projects[0] |
| 1031 | app.Knots = slices.Clone(app.Knots) |
| 1032 | app.Knots[0].Title = "Readers browse the next plan" |
| 1033 | next := *e |
| 1034 | next.Projects = slices.Clone(e.Projects) |
| 1035 | next.Projects[0] = app |
| 1036 | h.publishExport(exporttest.SignedAt.Add(2*time.Minute), &next, bundles) |
| 1037 | if !strings.Contains(h.page("/tools/app/knots/oc-a000001"), "Readers browse the next plan") { |
| 1038 | t.Error("anyone is not served the next generation while named views fill their places") |
| 1039 | } |
| 1040 | |
| 1041 | select { |
| 1042 | case w := <-r0: |
| 1043 | t.Errorf("r0 answered %d while every named place was taken", w.Code) |
| 1044 | default: |
| 1045 | } |
| 1046 | |
| 1047 | close(hold) |
| 1048 | for _, served := range waiting { |
| 1049 | if w := <-served; w.Code != http.StatusOK { |
| 1050 | t.Errorf("a named view that was built answered %d", w.Code) |
| 1051 | } |
| 1052 | } |
| 1053 | if w := <-r0; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "/tools/app/knots/oc-a000001") { |
| 1054 | t.Errorf("r0 answered %d once there was room", w.Code) |
| 1055 | } |
| 1056 | if page := h.pageAs("r15", "/-/knots"); !strings.Contains(page, "/tools/p4/knots/") || !strings.Contains(page, "next plan") { |
| 1057 | t.Error("a named reader is not served the next generation once there is room") |
| 1058 | } |
| 1059 | if _, named, pins := h.srv.heldViews(); named > MaxViews || pins != 0 { |
| 1060 | t.Errorf("the server holds %d named views, pinned %d times", named, pins) |
| 1061 | } |
| 1062 | if n := len(h.srv.loadWaiting); n != 0 { |
| 1063 | t.Errorf("%d requests still hold a place among those that wait", n) |
| 1064 | } |
| 1065 | } |
| 1066 | |
| 1067 | // A named reader who may see no more than anyone shares anyone's index, |
| 1068 | // but takes a named place for it, and never an anonymous one. Here r0's |
| 1069 | // source requests hold the indexes of what anyone may see of generations |
| 1070 | // A and B while they wait in their git slots, and generation C is |
| 1071 | // activated. An anonymous request for the knots page is served from C at |
| 1072 | // once, while they still hold them. With every other named place held by |
| 1073 | // a view being built, it is served at once too, while r0's request for |
| 1074 | // the knots page of C waits for a named place. Once the named requests |
| 1075 | // let their places go, every request is served. |
| 1076 | func TestNamedRequestsTakeNoAnonymousPlace(t *testing.T) { |
| 1077 | for _, full := range []bool{false, true} { |
| 1078 | t.Run(map[bool]string{false: "named places free", true: "named places full"}[full], func(t *testing.T) { |
| 1079 | h := newHarness(t) |
| 1080 | e, bundles := h.privateViews() |
| 1081 | activate := func(at time.Duration, title string) { |
| 1082 | app := e.Projects[0] |
| 1083 | app.Knots = slices.Clone(app.Knots) |
| 1084 | app.Knots[0].Title = title |
| 1085 | next := *e |
| 1086 | next.Projects = slices.Clone(e.Projects) |
| 1087 | next.Projects[0] = app |
| 1088 | h.publishExport(exporttest.SignedAt.Add(at), &next, bundles) |
| 1089 | } |
| 1090 | held := make(chan struct{}) |
| 1091 | var admitted atomic.Int32 |
| 1092 | h.srv.admitted = func() { |
| 1093 | admitted.Add(1) |
| 1094 | <-held |
| 1095 | } |
| 1096 | hold := make(chan struct{}) |
| 1097 | var holding atomic.Int32 |
| 1098 | h.srv.indexing = func(ctx context.Context, key viewKey) { |
| 1099 | if strings.Contains(key.projects, "\np") { |
| 1100 | holding.Add(1) |
| 1101 | select { |
| 1102 | case <-hold: |
| 1103 | case <-ctx.Done(): |
| 1104 | } |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | // r0 holds generation A's index of what anyone may see, and |
| 1109 | // then generation B's, each in a request that waits in its |
| 1110 | // git slot. |
| 1111 | source := "/tools/app/source/tree/" + h.tip() + "/" |
| 1112 | named := []chan *httptest.ResponseRecorder{h.serving("r0", source, context.Background())} |
| 1113 | eventually(t, "r0 holds generation A's index", func() bool { return admitted.Load() == 1 }) |
| 1114 | activate(2*time.Minute, "Readers browse plan B") |
| 1115 | named = append(named, h.serving("r0", source, context.Background())) |
| 1116 | eventually(t, "r0 holds generation B's index", func() bool { return admitted.Load() == 2 }) |
| 1117 | if anonymous, places, pins := h.srv.heldViews(); anonymous != 0 || places != 2 || pins != 2 { |
| 1118 | t.Fatalf("named requests hold %d anonymous places and %d named ones, pinned %d times", anonymous, places, pins) |
| 1119 | } |
| 1120 | if full { |
| 1121 | for i := 1; i <= MaxViews-2; i++ { |
| 1122 | named = append(named, h.serving(fmt.Sprintf("r%d", i), "/-/knots", context.Background())) |
| 1123 | } |
| 1124 | eventually(t, "every named place is taken", func() bool { return holding.Load() == MaxViews-2 }) |
| 1125 | } |
| 1126 | |
| 1127 | activate(3*time.Minute, "Readers browse plan C") |
| 1128 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 1129 | defer cancel() |
| 1130 | if w := <-h.serving(export.Anyone, "/-/knots", ctx); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "plan C") { |
| 1131 | t.Errorf("an anonymous request for generation C answered %d, %d bytes, while named requests held their places", w.Code, w.Body.Len()) |
| 1132 | } |
| 1133 | late := h.serving("r0", "/-/knots", context.Background()) |
| 1134 | if full { |
| 1135 | eventually(t, "r0 waits for a named place", func() bool { return len(h.srv.namedWaiting) == MaxViews-1 }) |
| 1136 | time.Sleep(20 * time.Millisecond) |
| 1137 | select { |
| 1138 | case w := <-late: |
| 1139 | t.Errorf("r0 answered %d while every named place was taken", w.Code) |
| 1140 | default: |
| 1141 | } |
| 1142 | } |
| 1143 | if admitted.Load() != 2 { |
| 1144 | t.Errorf("%d source requests took git slots, not r0's two", admitted.Load()) |
| 1145 | } |
| 1146 | |
| 1147 | close(hold) |
| 1148 | close(held) |
| 1149 | for _, served := range append(named, late) { |
| 1150 | if w := <-served; w.Code != http.StatusOK { |
| 1151 | t.Errorf("a named reader's request answered %d", w.Code) |
| 1152 | } |
| 1153 | } |
| 1154 | if page := h.pageAs("r0", source); !strings.Contains(page, "/tools/app/") { |
| 1155 | t.Error("r0 is not served once the places are free") |
| 1156 | } |
| 1157 | if anonymous, places, pins := h.srv.heldViews(); anonymous > anonymousViews || places > MaxViews || pins != 0 { |
| 1158 | t.Errorf("the server holds %d anonymous places and %d named ones, pinned %d times", anonymous, places, pins) |
| 1159 | } |
| 1160 | if len(h.srv.loadWaiting) != 0 || len(h.srv.namedWaiting) != 0 { |
| 1161 | t.Errorf("%d requests, %d of them named, still hold a place among those that wait", len(h.srv.loadWaiting), len(h.srv.namedWaiting)) |
| 1162 | } |
| 1163 | }) |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | // Named readers take MaxNamedWaiting of the MaxLoadWaiting places at |
| 1168 | // most, and the rest are anonymous requests' alone. While every named |
| 1169 | // place holds a view being built, and named readers' requests wait in |
| 1170 | // every place they may take, a named reader's request past them answers |
| 1171 | // 503 at once. A new generation is then activated, and as many anonymous |
| 1172 | // requests as the places left wait for its load together, and each is |
| 1173 | // served from it. Once the builds end, every named request that waited is |
| 1174 | // served. |
| 1175 | func TestAnonymousRequestsKeepTheirWaitingPlaces(t *testing.T) { |
| 1176 | h := newHarness(t) |
| 1177 | e, bundles := h.privateViews() |
| 1178 | h.page("/-/knots") |
| 1179 | |
| 1180 | hold := make(chan struct{}) |
| 1181 | var holding atomic.Int32 |
| 1182 | h.srv.indexing = func(ctx context.Context, key viewKey) { |
| 1183 | if strings.Contains(key.projects, "\np") { |
| 1184 | holding.Add(1) |
| 1185 | select { |
| 1186 | case <-hold: |
| 1187 | case <-ctx.Done(): |
| 1188 | } |
| 1189 | } |
| 1190 | } |
| 1191 | var named []chan *httptest.ResponseRecorder |
| 1192 | for i := 1; i <= MaxViews; i++ { |
| 1193 | named = append(named, h.serving(fmt.Sprintf("r%d", i), "/-/knots", context.Background())) |
| 1194 | } |
| 1195 | eventually(t, "every named place holds a view being built", func() bool { return holding.Load() == MaxViews }) |
| 1196 | |
| 1197 | // Named readers with no room for their views try to take every place |
| 1198 | // left. MaxNamedWaiting of them wait, counting the eight, and the rest |
| 1199 | // answer 503 at once, well before their deadline. |
| 1200 | var refused atomic.Int32 |
| 1201 | var waited []chan *httptest.ResponseRecorder |
| 1202 | for i := range MaxLoadWaiting - MaxViews { |
| 1203 | served := h.serving(fmt.Sprintf("r%d", 9+i%7), "/-/knots", context.Background()) |
| 1204 | answered := make(chan *httptest.ResponseRecorder, 1) |
| 1205 | go func() { |
| 1206 | w := <-served |
| 1207 | if w.Code == http.StatusServiceUnavailable && w.Header().Get("Retry-After") != "" { |
| 1208 | refused.Add(1) |
| 1209 | } |
| 1210 | answered <- w |
| 1211 | }() |
| 1212 | waited = append(waited, answered) |
| 1213 | } |
| 1214 | eventually(t, "named readers fill the places they may take", func() bool { |
| 1215 | return len(h.srv.namedWaiting) == MaxNamedWaiting && refused.Load() == MaxLoadWaiting-MaxNamedWaiting |
| 1216 | }) |
| 1217 | if n := len(h.srv.loadWaiting); n != MaxNamedWaiting { |
| 1218 | t.Fatalf("%d requests wait, not the %d named readers may take", n, MaxNamedWaiting) |
| 1219 | } |
| 1220 | |
| 1221 | // A new generation, whose load is held until every anonymous request |
| 1222 | // waits for it in a place of its own. |
| 1223 | loadHold := make(chan struct{}) |
| 1224 | h.srv.loading = func(export.Generation) { <-loadHold } |
| 1225 | app := e.Projects[0] |
| 1226 | app.Knots = slices.Clone(app.Knots) |
| 1227 | app.Knots[0].Title = "Readers browse the next plan" |
| 1228 | next := *e |
| 1229 | next.Projects = slices.Clone(e.Projects) |
| 1230 | next.Projects[0] = app |
| 1231 | h.publishExport(exporttest.SignedAt.Add(2*time.Minute), &next, bundles) |
| 1232 | var anonymous []chan *httptest.ResponseRecorder |
| 1233 | for range MaxLoadWaiting - MaxNamedWaiting { |
| 1234 | anonymous = append(anonymous, h.serving(export.Anyone, "/tools/app/knots/oc-a000001", context.Background())) |
| 1235 | } |
| 1236 | eventually(t, "every anonymous request waits for the load", func() bool { return len(h.srv.loadWaiting) == MaxLoadWaiting }) |
| 1237 | close(loadHold) |
| 1238 | for _, served := range anonymous { |
| 1239 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "Readers browse the next plan") { |
| 1240 | t.Errorf("an anonymous request answered %d, not from the next generation", w.Code) |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | close(hold) |
| 1245 | answered := 0 |
| 1246 | for _, served := range append(named, waited...) { |
| 1247 | switch w := <-served; w.Code { |
| 1248 | case http.StatusOK: |
| 1249 | answered++ |
| 1250 | case http.StatusServiceUnavailable: |
| 1251 | default: |
| 1252 | t.Errorf("a named reader's request answered %d", w.Code) |
| 1253 | } |
| 1254 | } |
| 1255 | if want := MaxNamedWaiting; answered != want { |
| 1256 | t.Errorf("%d named readers' requests were served, not the %d that waited", answered, want) |
| 1257 | } |
| 1258 | if _, views, pins := h.srv.heldViews(); views > MaxViews || pins != 0 { |
| 1259 | t.Errorf("the server holds %d named views, pinned %d times", views, pins) |
| 1260 | } |
| 1261 | if len(h.srv.loadWaiting) != 0 || len(h.srv.namedWaiting) != 0 { |
| 1262 | t.Errorf("%d requests, %d of them named, still hold a place among those that wait", len(h.srv.loadWaiting), len(h.srv.namedWaiting)) |
| 1263 | } |
| 1264 | } |
| 1265 | |
| 1266 | // A view whose build is stopped, because the last request that waited for |
| 1267 | // it went away, keeps its place until its worker ends, and no request |
| 1268 | // takes it again. Here the stopped worker does not notice it was stopped |
| 1269 | // until it is let go. Meanwhile a request for another view, and one for |
| 1270 | // the same view, wait for room, and no worker starts beyond the MaxViews |
| 1271 | // places. Once the stopped worker ends, both are served, and at no time |
| 1272 | // do more than MaxViews workers build named views. |
| 1273 | func TestAStoppedBuildKeepsItsPlace(t *testing.T) { |
| 1274 | h := newHarness(t) |
| 1275 | e, _ := h.privateViews() |
| 1276 | h.page("/-/knots") |
| 1277 | // r1 alone may read p1 and nothing else. |
| 1278 | r1 := projectsKey(e, map[string]bool{"app": true, "p1": true}) |
| 1279 | |
| 1280 | release, rest := make(chan struct{}), make(chan struct{}) |
| 1281 | var live, peak, r1Builds atomic.Int32 |
| 1282 | h.srv.indexing = func(_ context.Context, key viewKey) { |
| 1283 | if !strings.Contains(key.projects, "\np") { |
| 1284 | return |
| 1285 | } |
| 1286 | n := live.Add(1) |
| 1287 | defer live.Add(-1) |
| 1288 | for p := peak.Load(); n > p && !peak.CompareAndSwap(p, n); p = peak.Load() { |
| 1289 | } |
| 1290 | if key.projects == r1 && r1Builds.Add(1) == 1 { |
| 1291 | <-release |
| 1292 | return |
| 1293 | } |
| 1294 | <-rest |
| 1295 | } |
| 1296 | ctx, cancel := context.WithCancel(context.Background()) |
| 1297 | first := h.serving("r1", "/-/knots", ctx) |
| 1298 | var others []chan *httptest.ResponseRecorder |
| 1299 | for i := 2; i <= MaxViews; i++ { |
| 1300 | others = append(others, h.serving(fmt.Sprintf("r%d", i), "/-/knots", context.Background())) |
| 1301 | } |
| 1302 | eventually(t, "every named place holds a view being built", func() bool { return live.Load() == MaxViews }) |
| 1303 | |
| 1304 | // r1 goes away. Its view's build is stopped, though its worker runs on. |
| 1305 | cancel() |
| 1306 | if w := <-first; w.Body.Len() != 0 { |
| 1307 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 1308 | } |
| 1309 | if n := h.srv.stoppingViews(); n != 1 { |
| 1310 | t.Fatalf("%d stopped views keep their places, not 1", n) |
| 1311 | } |
| 1312 | |
| 1313 | // Another reader's view and r1's view again find no room. |
| 1314 | another := h.serving("r9", "/-/knots", context.Background()) |
| 1315 | again := h.serving("r1", "/-/knots", context.Background()) |
| 1316 | eventually(t, "both requests wait for room", func() bool { return len(h.srv.loadWaiting) == MaxViews+1 }) |
| 1317 | time.Sleep(20 * time.Millisecond) |
| 1318 | if n := live.Load(); n != MaxViews { |
| 1319 | t.Errorf("%d workers build named views while a stopped one runs", n) |
| 1320 | } |
| 1321 | |
| 1322 | // The stopped worker ends, and gives back its place. |
| 1323 | close(release) |
| 1324 | eventually(t, "the stopped view gives back its place", func() bool { return h.srv.stoppingViews() == 0 }) |
| 1325 | close(rest) |
| 1326 | for _, served := range append(others, another, again) { |
| 1327 | if w := <-served; w.Code != http.StatusOK { |
| 1328 | t.Errorf("a named reader's request answered %d", w.Code) |
| 1329 | } |
| 1330 | } |
| 1331 | if p := peak.Load(); p > MaxViews { |
| 1332 | t.Errorf("%d workers built named views at once, more than the %d places", p, MaxViews) |
| 1333 | } |
| 1334 | if _, views, pins := h.srv.heldViews(); views > MaxViews || pins != 0 || h.srv.stoppingViews() != 0 { |
| 1335 | t.Errorf("the server holds %d named views, pinned %d times", views, pins) |
| 1336 | } |
| 1337 | } |
| 1338 | |
| 1339 | // Loads that only named readers wait for take one of the MaxLoads |
| 1340 | // workers at most, so a load that an anonymous request waits for always |
| 1341 | // has one: while one named reader's load runs and another's waits for a |
| 1342 | // worker, an anonymous request joins the waiting load and starts it. |
| 1343 | func TestAnonymousRequestsKeepALoader(t *testing.T) { |
| 1344 | h := newHarness(t) |
| 1345 | var mu sync.Mutex |
| 1346 | holds := map[int64]chan struct{}{} |
| 1347 | hold := func(seq int64) chan struct{} { |
| 1348 | mu.Lock() |
| 1349 | defer mu.Unlock() |
| 1350 | if holds[seq] == nil { |
| 1351 | holds[seq] = make(chan struct{}) |
| 1352 | } |
| 1353 | return holds[seq] |
| 1354 | } |
| 1355 | var loaded sync.Map |
| 1356 | h.srv.loading = func(g export.Generation) { |
| 1357 | loaded.Store(g.Sequence, true) |
| 1358 | <-hold(g.Sequence) |
| 1359 | } |
| 1360 | serve := func(reader string) chan *httptest.ResponseRecorder { |
| 1361 | served := make(chan *httptest.ResponseRecorder, 1) |
| 1362 | go func() { served <- h.as(reader, "GET", "/tools/app/knots/oc-a000001", nil) }() |
| 1363 | return served |
| 1364 | } |
| 1365 | first := h.active() |
| 1366 | alice := serve("alice") |
| 1367 | eventually(t, "alice's load runs", func() bool { _, ok := loaded.Load(first.Sequence); return ok }) |
| 1368 | second := h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1369 | bob := serve("bob") |
| 1370 | eventually(t, "bob waits for a load", func() bool { return len(h.srv.loadWaiting) == 2 }) |
| 1371 | time.Sleep(20 * time.Millisecond) |
| 1372 | if _, ok := loaded.Load(second.Sequence); ok || h.srv.runningLoads() != 1 { |
| 1373 | t.Fatalf("a second load that only named readers wait for started, with %d workers", h.srv.runningLoads()) |
| 1374 | } |
| 1375 | anyone := serve(export.Anyone) |
| 1376 | eventually(t, "the anonymous request starts the waiting load", func() bool { _, ok := loaded.Load(second.Sequence); return ok }) |
| 1377 | if len(h.srv.anonLoader) != 1 || len(h.srv.loaders) != 1 { |
| 1378 | t.Errorf("the loads hold %d anonymous and %d shared workers", len(h.srv.anonLoader), len(h.srv.loaders)) |
| 1379 | } |
| 1380 | close(hold(second.Sequence)) |
| 1381 | close(hold(first.Sequence)) |
| 1382 | for _, served := range []chan *httptest.ResponseRecorder{alice, bob, anyone} { |
| 1383 | if w := <-served; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "second plan") { |
| 1384 | t.Errorf("a request answered %d, not from the second generation", w.Code) |
| 1385 | } |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | // holdFirstReads makes the first read of each generation held with hold |
| 1390 | // wait until the function hold returns is called. reads counts each |
| 1391 | // generation's reads. |
| 1392 | func holdFirstReads(h *harness) (hold func(export.Generation) func(), reads func(export.Generation) int) { |
| 1393 | var mu sync.Mutex |
| 1394 | holds := map[int64]chan struct{}{} |
| 1395 | counts := map[int64]int{} |
| 1396 | h.srv.loading = func(g export.Generation) { |
| 1397 | mu.Lock() |
| 1398 | counts[g.Sequence]++ |
| 1399 | held, first := holds[g.Sequence], counts[g.Sequence] == 1 |
| 1400 | mu.Unlock() |
| 1401 | if first && held != nil { |
| 1402 | <-held |
| 1403 | } |
| 1404 | } |
| 1405 | hold = func(g export.Generation) func() { |
| 1406 | mu.Lock() |
| 1407 | defer mu.Unlock() |
| 1408 | held := make(chan struct{}) |
| 1409 | holds[g.Sequence] = held |
| 1410 | return func() { close(held) } |
| 1411 | } |
| 1412 | reads = func(g export.Generation) int { |
| 1413 | mu.Lock() |
| 1414 | defer mu.Unlock() |
| 1415 | return counts[g.Sequence] |
| 1416 | } |
| 1417 | return hold, reads |
| 1418 | } |
| 1419 | |
| 1420 | // When the last anonymous request leaves a load on the kept loader while |
| 1421 | // a named reader still waits for it, and the other loader is free, the |
| 1422 | // load moves to the other loader and runs on: the kept loader is free for |
| 1423 | // the next anonymous request at once, and the export is read only once. |
| 1424 | func TestALoadAnonymousRequestsLeaveMovesToTheOtherLoader(t *testing.T) { |
| 1425 | h := newHarness(t) |
| 1426 | hold, reads := holdFirstReads(h) |
| 1427 | const target = "/tools/app/knots/oc-a000001" |
| 1428 | first := h.active() |
| 1429 | letFirstGo := hold(first) |
| 1430 | ctx, cancel := context.WithCancel(context.Background()) |
| 1431 | anyone := h.serving(export.Anyone, target, ctx) |
| 1432 | eventually(t, "the anonymous request's load runs", func() bool { return reads(first) == 1 }) |
| 1433 | if len(h.srv.anonLoader) != 1 { |
| 1434 | t.Fatal("the anonymous request's load does not run on the kept loader") |
| 1435 | } |
| 1436 | bob := h.serving("bob", target, context.Background()) |
| 1437 | eventually(t, "bob joins the load", func() bool { a, n := h.srv.loadWaiters(); return a == 1 && n == 1 }) |
| 1438 | |
| 1439 | cancel() |
| 1440 | if w := <-anyone; w.Body.Len() != 0 { |
| 1441 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 1442 | } |
| 1443 | if len(h.srv.anonLoader) != 0 || len(h.srv.loaders) != 1 { |
| 1444 | t.Errorf("the load holds %d kept and %d other loaders, not the other alone", len(h.srv.anonLoader), len(h.srv.loaders)) |
| 1445 | } |
| 1446 | if a, n := h.srv.loadWaiters(); a != 0 || n != 1 { |
| 1447 | t.Errorf("%d anonymous and %d named requests wait for loads, not bob alone", a, n) |
| 1448 | } |
| 1449 | |
| 1450 | // While bob's load runs on, an anonymous request for a newer |
| 1451 | // generation is read on the kept loader and served. |
| 1452 | h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1453 | if w := h.as(export.Anyone, "GET", target, nil); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "second plan") { |
| 1454 | t.Errorf("an anonymous request answered %d, not from the second generation", w.Code) |
| 1455 | } |
| 1456 | letFirstGo() |
| 1457 | if w := <-bob; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "second plan") { |
| 1458 | t.Errorf("bob's request answered %d, not from the second generation", w.Code) |
| 1459 | } |
| 1460 | if n := reads(first); n != 1 { |
| 1461 | t.Errorf("the first generation was read %d times, not once", n) |
| 1462 | } |
| 1463 | eventually(t, "every loader is given back", func() bool { return h.srv.runningLoads() == 0 }) |
| 1464 | } |
| 1465 | |
| 1466 | // When the last anonymous request leaves a load on the kept loader while |
| 1467 | // a named reader still waits for it, and the other loader runs a named |
| 1468 | // reader's load, the load is stopped and the kept loader is free at once, |
| 1469 | // though the stopped worker has not ended. Here alice's load of the first |
| 1470 | // generation holds the other loader. An anonymous request starts the |
| 1471 | // second generation's load on the kept loader, bob joins it, and the |
| 1472 | // anonymous request goes away. bob waits for a load again. Then either a |
| 1473 | // third generation is activated, and an anonymous request for it is |
| 1474 | // served while alice's load and the stopped worker still run, or alice's |
| 1475 | // load ends, and bob's load takes the other loader. Every request is |
| 1476 | // served, and once every worker has ended the loads hold no loader. |
| 1477 | func TestALoadAnonymousRequestsLeaveGivesBackTheKeptLoader(t *testing.T) { |
| 1478 | const target = "/tools/app/knots/oc-a000001" |
| 1479 | stopped := func(t *testing.T) (h *harness, letFirstGo, letSecondGo func(), alice, bob chan *httptest.ResponseRecorder, reads func(export.Generation) int, second export.Generation) { |
| 1480 | h = newHarness(t) |
| 1481 | var hold func(export.Generation) func() |
| 1482 | hold, reads = holdFirstReads(h) |
| 1483 | first := h.active() |
| 1484 | letFirstGo = hold(first) |
| 1485 | alice = h.serving("alice", target, context.Background()) |
| 1486 | eventually(t, "alice's load runs", func() bool { return reads(first) == 1 }) |
| 1487 | if len(h.srv.loaders) != 1 { |
| 1488 | t.Fatal("alice's load does not run on the other loader") |
| 1489 | } |
| 1490 | |
| 1491 | second = h.publish(exporttest.SignedAt.Add(time.Minute), nil, renamed("Readers browse the second plan")) |
| 1492 | letSecondGo = hold(second) |
| 1493 | ctx, cancel := context.WithCancel(context.Background()) |
| 1494 | anyone := h.serving(export.Anyone, target, ctx) |
| 1495 | eventually(t, "the anonymous request's load runs", func() bool { return reads(second) == 1 }) |
| 1496 | bob = h.serving("bob", target, context.Background()) |
| 1497 | eventually(t, "bob joins the load", func() bool { a, n := h.srv.loadWaiters(); return a == 1 && n == 2 }) |
| 1498 | |
| 1499 | cancel() |
| 1500 | if w := <-anyone; w.Body.Len() != 0 { |
| 1501 | t.Errorf("a request whose reader went away answered %d", w.Code) |
| 1502 | } |
| 1503 | if len(h.srv.anonLoader) != 0 || len(h.srv.loaders) != 1 { |
| 1504 | t.Errorf("the loads hold %d kept and %d other loaders, not the other alone", len(h.srv.anonLoader), len(h.srv.loaders)) |
| 1505 | } |
| 1506 | eventually(t, "bob waits for a load again", func() bool { a, n := h.srv.loadWaiters(); return a == 0 && n == 2 }) |
| 1507 | return |
| 1508 | } |
| 1509 | expect := func(t *testing.T, title string, served ...chan *httptest.ResponseRecorder) { |
| 1510 | t.Helper() |
| 1511 | for _, w := range served { |
| 1512 | if w := <-w; w.Code != http.StatusOK || !strings.Contains(w.Body.String(), title) { |
| 1513 | t.Errorf("a request answered %d, not with %q", w.Code, title) |
| 1514 | } |
| 1515 | } |
| 1516 | } |
| 1517 | |
| 1518 | t.Run("an anonymous request for a newer generation", func(t *testing.T) { |
| 1519 | h, letFirstGo, letSecondGo, alice, bob, _, _ := stopped(t) |
| 1520 | h.publish(exporttest.SignedAt.Add(2*time.Minute), nil, renamed("Readers browse the third plan")) |
| 1521 | if w := h.as(export.Anyone, "GET", target, nil); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "third plan") { |
| 1522 | t.Errorf("the anonymous request answered %d, not from the third generation", w.Code) |
| 1523 | } |
| 1524 | letFirstGo() |
| 1525 | letSecondGo() |
| 1526 | expect(t, "Readers browse the third plan", alice, bob) |
| 1527 | eventually(t, "every loader is given back", func() bool { return h.srv.runningLoads() == 0 }) |
| 1528 | }) |
| 1529 | |
| 1530 | t.Run("the other loader comes free", func(t *testing.T) { |
| 1531 | h, letFirstGo, letSecondGo, alice, bob, reads, second := stopped(t) |
| 1532 | letFirstGo() |
| 1533 | expect(t, "Readers browse the second plan", alice, bob) |
| 1534 | if n := reads(second); n != 2 { |
| 1535 | t.Errorf("the second generation was read %d times, not by the stopped load and bob's", n) |
| 1536 | } |
| 1537 | letSecondGo() |
| 1538 | eventually(t, "every loader is given back", func() bool { return h.srv.runningLoads() == 0 }) |
| 1539 | }) |
| 1540 | } |
| 1541 | |
| 1542 | // A response a named reader was rendered is written only under the |
| 1543 | // authorization it was rendered under. One whose grant is withdrawn while |
| 1544 | // it renders, a Markdown page, an archive, a knot or a redirect, is |
| 1545 | // rendered again under the new authorization, and answers the one 404. |
| 1546 | func TestANamedReadersResponseIsHeldToTheAuthorization(t *testing.T) { |
| 1547 | for _, path := range []string{"/tools/site/source/blob/%s/README.md", "/tools/site/source/archive/%s.tar.gz", |
| 1548 | "/tools/site/knots/oc-b000001", "/site/", "/tools/site/source/tree/%s/"} { |
| 1549 | t.Run(path, func(t *testing.T) { |
| 1550 | h := newHarness(t) |
| 1551 | e := h.edge(exporttest.SignedAt.Add(time.Minute), map[string][]string{"app": {export.Anyone}, "site": {"alice"}}) |
| 1552 | siteTip := git(t, h.f.Repos["site"], nil, "rev-parse", export.MainRef) |
| 1553 | target := strings.ReplaceAll(path, "%s", siteTip) |
| 1554 | if w := h.as("alice", "GET", target, nil); w.Code != http.StatusOK && w.Code != http.StatusPermanentRedirect { |
| 1555 | t.Fatalf("GET %s as alice answered %d", target, w.Code) |
| 1556 | } |
| 1557 | missing := h.as("alice", "GET", "/tools/nosuch/", nil) |
| 1558 | renders := 0 |
| 1559 | h.srv.checked = func() { |
| 1560 | if renders++; renders == 1 { |
| 1561 | h.authorizeReaders(e, map[string][]string{"app": {export.Anyone}}) |
| 1562 | } |
| 1563 | } |
| 1564 | w := h.as("alice", "GET", target, nil) |
| 1565 | if w.Code != http.StatusNotFound || !bytes.Equal(w.Body.Bytes(), missing.Body.Bytes()) || w.Header().Get("Location") != "" { |
| 1566 | t.Errorf("GET %s withdrawn while it rendered answered %d, to %q", target, w.Code, w.Header().Get("Location")) |
| 1567 | } |
| 1568 | if renders != 2 { |
| 1569 | t.Errorf("GET %s rendered %d times, want twice", target, renders) |
| 1570 | } |
| 1571 | }) |
| 1572 | } |
| 1573 | } |