gunk-dev/the-valley

published_test.go

sourcef961a59e125emain's published tip history
15.1 KiB
1package server
2
3import (
4 "bytes"
5 "context"
6 "net/http"
7 "net/http/httptest"
8 "os"
9 "path/filepath"
10 "reflect"
11 "slices"
12 "sort"
13 "strings"
14 "testing"
15 "time"
16
17 "the-valley/note"
18 "the-valley/web/export"
19 "the-valley/web/export/exporttest"
20)
21
22// publishedReader is the request context's key under which
23// TestThePublishersOutputServesEachReader names the reader a request is
24// read as.
25type publishedReader struct{}
26
27// The real publisher's output (web-published in nix/packages.nix), in the
28// directory VALLEY_WEB_PUBLISHED names. Anyone may read app. alice alone
29// may read site, and the operator alone docs. notes has no effective
30// reader. The store admits the authorization and the manifest under the
31// export key's verifier line, and takes the bodies, as a receiver does.
32//
33// The export holds app, docs and site, and nothing notes' knots say.
34// Three of app's knots are each blocked by an open, an abandoned and a
35// missing knot of site, docs or notes. A blocker in an exported project
36// keeps every derived field and its edges in the export; one in notes
37// leaves only waiting_on_hidden and hidden edges. projectForReader then
38// takes out, for each reader, what those fields and edges say of an
39// exported project the reader may not see.
40//
41// The server serves each reader the union of what anyone and they may
42// read. For anyone, bob, alice and the operator, no page it renders, a
43// knot, the knots page, a source page, a redirect or an error, holds the
44// name, alias, former name, README, knot titles, comment or ready change
45// of a private project the reader may not see.
46func TestThePublishersOutputServesEachReader(t *testing.T) {
47 dir := os.Getenv("VALLEY_WEB_PUBLISHED")
48 if dir == "" {
49 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
50 t.Fatal("VALLEY_WEB_PUBLISHED names no publisher output")
51 }
52 t.Skip("VALLEY_WEB_PUBLISHED names no publisher output")
53 }
54 ctx := context.Background()
55 read := func(path string) []byte {
56 t.Helper()
57 data, err := os.ReadFile(filepath.Join(dir, path))
58 if err != nil {
59 t.Fatal(err)
60 }
61 return data
62 }
63 verifiers, err := note.ParseVerifierKeys(read("verifier"))
64 if err != nil {
65 t.Fatal(err)
66 }
67 store, err := export.OpenStore(exporttest.StorePath(t), func(err error) { t.Errorf("the store reported: %v", err) })
68 if err != nil {
69 t.Fatal(err)
70 }
71
72 signed := read("published/authorization")
73 a, err := export.VerifyAuthorization(bytes.NewReader(signed), export.AuthorizationAdmission{
74 Verifiers: verifiers, Instance: exporttest.Instance, Destination: exporttest.Destination})
75 if err != nil {
76 t.Fatal(err)
77 }
78 if err := store.Authorize(ctx, a, signed); err != nil {
79 t.Fatal(err)
80 }
81 for _, c := range []struct {
82 reader, project string
83 allowed bool
84 }{
85 {export.Anyone, "app", true}, {export.Anyone, "site", false}, {export.Anyone, "docs", false},
86 {"alice", "site", true}, {"alice", "docs", false}, {"operator", "docs", true}, {"operator", "site", false},
87 {"bob", "site", false}, {"bob", "docs", false},
88 } {
89 p, _ := a.Project(c.project)
90 if got := a.Allows(c.reader, c.project, p.Identity); got != c.allowed {
91 t.Errorf("the authorization lets %s read %s: %v, want %v", c.reader, c.project, got, c.allowed)
92 }
93 }
94 if _, named := a.Project("notes"); named {
95 t.Errorf("the authorization names notes, which has no effective reader")
96 }
97
98 // The manifest was signed when the publisher ran; it is admitted a
99 // second after its signing time, as a receiver admits it then.
100 signedManifest := read("published/manifest")
101 text, _, err := note.Open(signedManifest, verifiers)
102 if err != nil {
103 t.Fatal(err)
104 }
105 unverified, err := export.ParseManifest(text)
106 if err != nil {
107 t.Fatal(err)
108 }
109 m, err := export.VerifyManifest(bytes.NewReader(signedManifest), export.Admission{
110 Verifiers: verifiers, Instance: exporttest.Instance, Destination: exporttest.Destination,
111 Now: time.Unix(0, unverified.Sequence).Add(time.Second)})
112 if err != nil {
113 t.Fatal(err)
114 }
115 st, err := store.Stage(ctx, m)
116 if err != nil {
117 t.Fatal(err)
118 }
119 inv, err := store.Inventory(st)
120 if err != nil {
121 t.Fatal(err)
122 }
123 for _, need := range inv.Needs {
124 path := filepath.Join("published", "bundles", need.Name+".bundle")
125 if need.Name == export.ExportFile {
126 path = filepath.Join("published", export.ExportFile)
127 }
128 req := httptest.NewRequest("PUT", export.BodyPath(m.Sequence, need.SHA256), bytes.NewReader(read(path)))
129 if _, err := export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req); err != nil {
130 t.Fatal(err)
131 }
132 }
133 if _, err := store.Activate(ctx, st); err != nil {
134 t.Fatal(err)
135 }
136
137 data := read(filepath.Join("published", export.ExportFile))
138 e, err := export.Decode(data)
139 if err != nil {
140 t.Fatal(err)
141 }
142 var names []string
143 projects := map[string]export.Project{}
144 for _, p := range e.Projects {
145 names = append(names, p.Name)
146 projects[p.Name] = p
147 }
148 sort.Strings(names)
149 if !reflect.DeepEqual(names, []string{"app", "docs", "site"}) {
150 t.Fatalf("the export holds %v, want app, docs and site", names)
151 }
152 for _, text := range []string{"notes-readme-text", "notes-knot-text", "notes-abandoned-text", "notes-comment-text"} {
153 if bytes.Contains(data, []byte(text)) {
154 t.Errorf("export.json holds %s, which only notes says", text)
155 }
156 }
157 knotOf := func(e *export.Export, project, title string) *export.Knot {
158 t.Helper()
159 for i := range e.Projects {
160 if e.Projects[i].Name != project {
161 continue
162 }
163 for j := range e.Projects[i].Knots {
164 if k := &e.Projects[i].Knots[j]; k.Title == title {
165 return k
166 }
167 }
168 }
169 t.Fatalf("%s has no knot %q", project, title)
170 return nil
171 }
172 waits := map[string]string{"site": "Waits on the first private project", "docs": "Waits on the second private project",
173 "notes": "Waits on the third private project"}
174
175 // What the export says of each blocker app's knots name: everything
176 // the plan derived of one in site or docs, and of one in notes, which
177 // is not exported, that the knot waits on something hidden.
178 for _, project := range []string{"site", "docs"} {
179 k := knotOf(e, "app", waits[project])
180 open := project + ":" + knotOf(e, project, project+"-knot-text").ID
181 ended := project + ":" + knotOf(e, project, project+"-abandoned-text").ID
182 missing := project + ":oc-0000000"
183 for _, c := range []struct {
184 field string
185 got, want []string
186 }{
187 {"waiting_on", k.WaitingOn, []string{missing, open}}, {"cleared_by_ending", k.ClearedByEnding, []string{ended}},
188 {"dangling", k.Dangling, []string{missing}}, {"unresolved", k.Unresolved, []string{}},
189 } {
190 if !sameSet(c.got, c.want) {
191 t.Errorf("the export's %s of app's knot blocked by %s is %q, want %q", c.field, project, c.got, c.want)
192 }
193 }
194 if k.WaitingOnHidden {
195 t.Errorf("the export says app's knot blocked by %s waits on a hidden knot", project)
196 }
197 edges := map[string]export.Edge{}
198 for _, edge := range k.Edges {
199 edges[edge.Ref] = edge
200 }
201 for ref, want := range map[string][3]string{
202 open: {export.EdgeResolved, "open", project + "-knot-text"}, ended: {export.EdgeResolved, "abandoned", project + "-abandoned-text"},
203 missing: {export.EdgeDangling, "", ""},
204 } {
205 edge, ok := edges[ref]
206 if !ok || edge.State != want[0] || deref(edge.Status) != want[1] || deref(edge.Title) != want[2] {
207 t.Errorf("the export's edge to %s is %+v, want %s with status %q and title %q", ref, edge, want[0], want[1], want[2])
208 }
209 }
210 if len(edges) != 3 {
211 t.Errorf("app's knot blocked by %s has %d edges, want 3", project, len(edges))
212 }
213 }
214 unexported := knotOf(e, "app", waits["notes"])
215 if !unexported.WaitingOnHidden || len(unexported.WaitingOn)+len(unexported.ClearedByEnding)+len(unexported.Dangling)+len(unexported.Unresolved) > 0 {
216 t.Errorf("the export says of app's knot blocked by notes more than that it waits on a hidden knot: %+v", unexported)
217 }
218 if len(unexported.Edges) != 3 {
219 t.Errorf("app's knot blocked by notes has %d edges, want 3", len(unexported.Edges))
220 }
221 for _, edge := range unexported.Edges {
222 if want := (export.Edge{Field: "blocked_by", Ref: edge.Ref, Project: "notes", ID: edge.ID, State: export.EdgeHidden}); !reflect.DeepEqual(edge, want) {
223 t.Errorf("the export's edge into notes is %+v, want %+v", edge, want)
224 }
225 }
226
227 // Each reader's projection keeps what app's knots say of the
228 // projects that reader may see, and takes out the rest: a blocker in
229 // another private project leaves waiting_on_hidden and hidden edges
230 // alone, as one in notes does in the export. The real publisher
231 // writes no unresolved reference into a project it exports, so a
232 // second copy of the export is given one into site and one into docs.
233 shownTo := map[string][]string{
234 export.Anyone: {"app"}, "bob": {"app"}, "alice": {"app", "site"}, "operator": {"app", "docs"},
235 }
236 readers := []string{export.Anyone, "bob", "alice", "operator"}
237 for _, reader := range readers {
238 shown := map[string]bool{}
239 for _, p := range shownTo[reader] {
240 shown[p] = true
241 }
242 out, err := projectForReader(ctx, e, shown)
243 if err != nil {
244 t.Fatal(err)
245 }
246 var got []string
247 for _, p := range out.Projects {
248 got = append(got, p.Name)
249 }
250 sort.Strings(got)
251 if !reflect.DeepEqual(got, shownTo[reader]) {
252 t.Errorf("%s's projection holds %v, want %v", reader, got, shownTo[reader])
253 }
254 for _, project := range []string{"site", "docs", "notes"} {
255 k, orig := knotOf(out, "app", waits[project]), knotOf(e, "app", waits[project])
256 if shown[project] || project == "notes" {
257 if !reflect.DeepEqual(k, orig) {
258 t.Errorf("%s's projection changed app's knot blocked by %s:\n%+v\nwant\n%+v", reader, project, k, orig)
259 }
260 continue
261 }
262 if !k.WaitingOnHidden || len(k.WaitingOn)+len(k.ClearedByEnding)+len(k.Dangling)+len(k.Unresolved) > 0 {
263 t.Errorf("%s's projection says of app's knot blocked by %s more than that it waits on a hidden knot: %+v", reader, project, k)
264 }
265 if len(k.Edges) != len(orig.Edges) {
266 t.Fatalf("%s's projection has %d edges of app's knot blocked by %s, want %d", reader, len(k.Edges), project, len(orig.Edges))
267 }
268 for i, edge := range k.Edges {
269 o := orig.Edges[i]
270 if want := (export.Edge{Field: o.Field, Ref: o.Ref, Project: o.Project, ID: o.ID, State: export.EdgeHidden}); !reflect.DeepEqual(edge, want) {
271 t.Errorf("%s's projection keeps the edge %+v, want %+v", reader, edge, want)
272 }
273 }
274 }
275 }
276 withUnresolved, err := export.Decode(data)
277 if err != nil {
278 t.Fatal(err)
279 }
280 unresolved := []string{"site:oc-1111111", "docs:oc-1111111"}
281 knotOf(withUnresolved, "app", waits["site"]).Unresolved = unresolved
282 for _, reader := range readers {
283 shown := map[string]bool{}
284 var want []string
285 for _, p := range shownTo[reader] {
286 shown[p] = true
287 if p != "app" {
288 want = append(want, p+":oc-1111111")
289 }
290 }
291 out, err := projectForReader(ctx, withUnresolved, shown)
292 if err != nil {
293 t.Fatal(err)
294 }
295 if got := knotOf(out, "app", waits["site"]).Unresolved; !sameSet(got, want) {
296 t.Errorf("%s's projection keeps the unresolved references %q, want %q", reader, got, want)
297 }
298 }
299
300 srv := New(Config{Store: store, Now: time.Now, Log: func(err error) { t.Errorf("the server logged: %v", err) }})
301 srv.reader = func(r *http.Request) string {
302 if name, ok := r.Context().Value(publishedReader{}).(string); ok {
303 return name
304 }
305 return export.Anyone
306 }
307 get := func(reader, target string) *httptest.ResponseRecorder {
308 r := httptest.NewRequest("GET", target, nil)
309 r = r.WithContext(context.WithValue(r.Context(), publishedReader{}, reader))
310 w := httptest.NewRecorder()
311 srv.ServeHTTP(w, r)
312 return w
313 }
314
315 // Every page of a project: its home, source pages and knots. The
316 // archive is checked for its status alone, as it is compressed.
317 pages := func(project string) []string {
318 p := projects[project]
319 base := "/tools/" + project
320 out := []string{base + "/", base + "/source/tree/" + p.SourceTip + "/", base + "/source/blob/" + p.SourceTip + "/README.md",
321 base + "/source/log/" + p.SourceTip}
322 for _, k := range p.Knots {
323 out = append(out, base+"/knots/"+k.ID)
324 }
325 return out
326 }
327 archive := func(project string) string {
328 return "/tools/" + project + "/source/archive/" + projects[project].SourceTip + ".tar.gz"
329 }
330 private := map[string]struct{ alias, former string }{"site": {"portal", "homepage"}, "docs": {"handbook", "manual"}}
331 // What only a private project says: its name, alias, former name,
332 // README, knot titles, comment and ready change.
333 secrets := func(project string) []string {
334 out := []string{project, project + "-readme-text", project + "-comment-text", project + "-change-subject"}
335 if p, ok := private[project]; ok {
336 out = append(out, p.alias, p.former)
337 for _, k := range projects[project].Knots {
338 out = append(out, k.Title)
339 }
340 for _, c := range projects[project].Changes {
341 out = append(out, c.ChangeID)
342 }
343 } else {
344 out = append(out, project+"-knot-text", project+"-abandoned-text")
345 }
346 return out
347 }
348 for _, reader := range readers {
349 shown := map[string]bool{}
350 for _, p := range shownTo[reader] {
351 shown[p] = true
352 }
353 var hidden []string
354 answers := map[string]int{"/": http.StatusFound, knotsURL: http.StatusOK, "/nowhere/": http.StatusNotFound,
355 "/tools/nowhere/": http.StatusNotFound, archive("app"): http.StatusOK}
356 for _, project := range []string{"app", "site", "docs"} {
357 want := http.StatusNotFound
358 if shown[project] {
359 want = http.StatusOK
360 } else {
361 hidden = append(hidden, secrets(project)...)
362 }
363 for _, target := range pages(project) {
364 answers[target] = want
365 }
366 if shown[project] {
367 answers["/tools/"+project+"/"] = http.StatusFound
368 }
369 if p, ok := private[project]; ok {
370 moved := http.StatusPermanentRedirect
371 if !shown[project] {
372 moved = http.StatusNotFound
373 }
374 answers["/"+p.alias+"/"] = moved
375 answers["/tools/"+p.former+"/source/tree/"+projects[project].SourceTip+"/"] = moved
376 }
377 }
378 hidden = append(hidden, secrets("notes")...)
379 answers["/tools/notes/"] = http.StatusNotFound
380 for target, want := range answers {
381 w := get(reader, target)
382 if w.Code != want {
383 t.Errorf("GET %s as %s answered %d, want %d", target, reader, w.Code, want)
384 }
385 if strings.HasSuffix(target, ".tar.gz") {
386 continue
387 }
388 // The layout's navigation is of class site, in its markup and
389 // its stylesheet, which names no project.
390 page := w.Header().Get("Location") + "\n" + layoutSite.Replace(w.Body.String())
391 for _, secret := range hidden {
392 if strings.Contains(page, secret) {
393 t.Errorf("GET %s as %s answered with %q, which only a project %s may not read says", target, reader, secret, reader)
394 }
395 }
396 }
397 for project, title := range waits {
398 page := get(reader, "/tools/app/knots/"+knotOf(e, "app", title).ID).Body.String()
399 if names := strings.Contains(page, project+"-knot-text"); names != shown[project] {
400 t.Errorf("app's knot blocked by %s names its blocker to %s: %v, want %v", project, reader, names, shown[project])
401 }
402 }
403 }
404}
405
406// layoutSite takes out of a page the layout's class site.
407var layoutSite = strings.NewReplacer(`<nav class="site"`, "", "nav.site", "")
408
409// sameSet reports whether a and b hold the same strings, in any order.
410func sameSet(a, b []string) bool {
411 a, b = slices.Clone(a), slices.Clone(b)
412 sort.Strings(a)
413 sort.Strings(b)
414 return slices.Equal(a, b)
415}
416
417func deref(s *string) string {
418 if s == nil {
419 return ""
420 }
421 return *s
422}