gunk-dev/the-valley

publish_test.go

source00ee76e8c9e1main's published tip history
38.0 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "net/http"
10 "net/http/httptest"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "reflect"
15 "strconv"
16 "strings"
17 "sync"
18 "testing"
19 "time"
20
21 "the-valley/note"
22 "the-valley/webui/export"
23)
24
25// The tests run the publisher against a real valley: bare repositories
26// that run no hook, as any git remote would, an instance repository that
27// publishes its projects as valley-init writes the list, and a plan graph
28// written with the real valley knot verbs. The valley CLI is bin/valley
29// itself, run by bash, with valley-go on PATH; the instance's identity
30// registry and each project's policy/read are read by the real cue under
31// schema/identity.cue and schema/read.cue. Uploads go to a receiver over a
32// real export.Store.
33
34const (
35 instanceName = "valley-host"
36 destination = "example.org"
37 changeID = "pqrstuvwxyzkpqrstuvwxyzkpqrstuvw"
38)
39
40// The publication identities of the test valley's projects, which their
41// policy/read declares and the registry's grants name.
42var identities = map[string]string{
43 "app": "9da6809f038df92138c131cd16bed76d",
44 "site": "273d5668702918ea7ae079de374db96b",
45 "valley": "f83927d5a4ed068cdd02a8cdaa09f26d",
46 "fresh": "0d1f6c8e2b4a59736e8f1a2b3c4d5e6f",
47}
48
49// anyoneReadsAppAndSite is the scope of the registry's read grant to anyone
50// in every valley newValley makes: app and site, by their identities.
51var anyoneReadsAppAndSite = `{app: "` + identities["app"] + `", site: "` + identities["site"] + `"}`
52
53// The private sentinels: a line of site's source, the body of site's one
54// knot, and a comment on it. site is private in every valley newValley
55// makes until a test lets anyone read it, so no export or bundle of a pass
56// before that may hold any of them.
57const (
58 sentinelSource = "site-private-source-7f3a91"
59 sentinelBody = "site-private-body-91c2e4"
60 sentinelComment = "site-private-comment-4e8d07"
61)
62
63// testValley is a valley made for one test: an instance repository
64// (valley), two projects (app and site), a clone of each, and the
65// publisher's state, cache and display mapping.
66type testValley struct {
67 t *testing.T
68 root, srv string
69 work map[string]string
70 schemas string
71 state string
72 principals string
73 // siteTitle is the title of site's one knot, which no export of a
74 // private site may hold.
75 siteTitle string
76 knots map[string]string
77}
78
79func needTool(t *testing.T, name string) string {
80 t.Helper()
81 path, err := exec.LookPath(name)
82 if err != nil {
83 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
84 t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", name)
85 }
86 t.Skipf("no %s on PATH; the nix check provides one", name)
87 }
88 return path
89}
90
91// newValley makes the valley. The instance's registry grants anyone read
92// of app and site at the destination, and the operator read of every
93// project; app's policy/read lets anyone and the operator read it, and site
94// has none. site carries the private sentinels. The instance repository's
95// own policy/read lets the operator alone read it.
96func newValley(t *testing.T) *testValley {
97 t.Helper()
98 bash := needTool(t, "bash")
99 needTool(t, "git")
100 needTool(t, "cue")
101 needTool(t, "valley-go")
102 repoRoot, err := filepath.Abs(filepath.Join("..", "..", ".."))
103 if err != nil {
104 t.Fatal(err)
105 }
106 root := t.TempDir()
107 v := &testValley{t: t, root: root, srv: filepath.Join(root, "srv"), work: map[string]string{},
108 schemas: filepath.Join(repoRoot, "schema"), state: filepath.Join(root, "state"),
109 principals: filepath.Join(root, "principals.json"), knots: map[string]string{}}
110
111 bin := filepath.Join(root, "bin")
112 if err := os.MkdirAll(bin, 0o755); err != nil {
113 t.Fatal(err)
114 }
115 wrapper := "#!" + bash + "\nexec " + bash + " " + filepath.Join(repoRoot, "bin", "valley") + " \"$@\"\n"
116 v.write(filepath.Join(bin, "valley"), wrapper)
117 if err := os.Chmod(filepath.Join(bin, "valley"), 0o755); err != nil {
118 t.Fatal(err)
119 }
120 gitconfig := filepath.Join(root, "gitconfig")
121 v.write(gitconfig, "[user]\n\tname = valley-web-publish-test\n\temail = test@example.org\n[init]\n\tdefaultBranch = main\n")
122 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
123 t.Setenv("HOME", filepath.Join(root, "home"))
124 t.Setenv("XDG_CACHE_HOME", filepath.Join(root, "cache"))
125 t.Setenv("XDG_STATE_HOME", filepath.Join(root, "xdg-state"))
126 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
127 t.Setenv("GIT_CONFIG_GLOBAL", gitconfig)
128 t.Setenv("VALLEY_READ_SCHEMA", "")
129 t.Setenv("VALLEY_IDENTITY_SCHEMA", "")
130 v.write(v.principals, `{"operator": "operator"}`)
131
132 for _, name := range []string{"valley", "app", "site"} {
133 v.run("", "git", "init", "--quiet", "--bare", filepath.Join(v.srv, name+".git"))
134 work := filepath.Join(root, "work", name)
135 v.run("", "git", "init", "--quiet", work)
136 v.run(work, "git", "remote", "add", "origin", filepath.Join(v.srv, name+".git"))
137 v.run(work, "git", "config", "valley.principal", "operator")
138 v.work[name] = work
139 }
140 v.write(filepath.Join(v.work["valley"], "policy", "instance", "floor.cue"), "package verification\n")
141 v.grant(anyoneReadsAppAndSite)
142 v.declare("valley", policy("valley", "operator"))
143 projects := v.runInput(v.srv, "app\nsite\nvalley\n", "git", "-C", filepath.Join(v.srv, "valley.git"), "hash-object", "-w", "--stdin")
144 v.run("", "git", "-C", filepath.Join(v.srv, "valley.git"), "update-ref", "refs/the-valley/projects", strings.TrimSpace(projects))
145
146 for _, name := range []string{"app", "site"} {
147 v.write(filepath.Join(v.work[name], "policy", "valley"), filepath.Join(v.srv, "valley.git")+"\n")
148 readme := "# " + name + "\n"
149 if name == "site" {
150 readme += sentinelSource + "\n"
151 }
152 v.write(filepath.Join(v.work[name], "README.md"), readme)
153 v.commit(name, name+": the first commit")
154 }
155 v.declare("app", policy("app", "anyone", "operator"))
156
157 // The plan: a milestone in app with a child blocked by site's one knot,
158 // a bug with a body and a comment by a principal the display mapping
159 // does not name, and a change ready for approval.
160 v.siteTitle = "Private work in site"
161 v.knots["site"] = v.newKnot("app", "outcome", v.siteTitle, "--project", "site")
162 v.runInput(v.work["app"], sentinelBody+"\n", "valley", "knot", "edit", v.knots["site"], "--body", "-", "--project", "site")
163 v.valley("app", "knot", "comment", v.knots["site"], "-m", sentinelComment, "--project", "site")
164 v.knots["milestone"] = v.newKnot("app", "outcome", "Publish the plan")
165 v.knots["blocked"] = v.newKnot("app", "outcome", "Ship it", "--parent", v.knots["milestone"], "--blocked-by", "site:"+v.knots["site"])
166 v.knots["bug"] = v.newKnot("app", "bug", "The page is slow", "--parent", v.knots["milestone"])
167 v.run(v.work["app"], "git", "config", "valley.principal", "alice")
168 v.valley("app", "knot", "comment", v.knots["bug"], "-m", "It takes a second to load.")
169 v.run(v.work["app"], "git", "config", "valley.principal", "operator")
170 v.run(v.work["app"], "git", "checkout", "--quiet", "-b", "plan-page")
171 v.run(v.work["app"], "git", "commit", "--quiet", "--allow-empty", "-m", "app: the plan page")
172 v.run(v.work["app"], "git", "push", "--quiet", "origin", "plan-page")
173 v.valley("app", "ready", "--change", changeID, "plan-page")
174 v.run(v.work["app"], "git", "checkout", "--quiet", "main")
175 return v
176}
177
178func (v *testValley) write(path, body string) {
179 v.t.Helper()
180 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
181 v.t.Fatal(err)
182 }
183 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
184 v.t.Fatal(err)
185 }
186}
187
188func (v *testValley) run(dir string, name string, args ...string) string {
189 v.t.Helper()
190 return v.runInput(dir, "", name, args...)
191}
192
193// runInput runs a command of the test's own. Its valley commands read
194// through a cache of their own, so the publisher's starts empty.
195func (v *testValley) runInput(dir, stdin string, name string, args ...string) string {
196 v.t.Helper()
197 cmd := exec.Command(name, args...)
198 cmd.Dir = dir
199 cmd.Env = append(os.Environ(), "XDG_CACHE_HOME="+filepath.Join(v.root, "test-cache"))
200 cmd.Stdin = strings.NewReader(stdin)
201 var stderr bytes.Buffer
202 cmd.Stderr = &stderr
203 out, err := cmd.Output()
204 if err != nil {
205 v.t.Fatalf("%s %s: %v: %s", name, strings.Join(args, " "), err, stderr.String())
206 }
207 return string(out)
208}
209
210func (v *testValley) valley(project string, args ...string) string {
211 v.t.Helper()
212 return v.run(v.work[project], "valley", args...)
213}
214
215func (v *testValley) newKnot(from, kind, title string, args ...string) string {
216 v.t.Helper()
217 out := v.valley(from, append([]string{"knot", "new", kind, title, "--json"}, args...)...)
218 var doc struct {
219 Knot struct {
220 ID string `json:"id"`
221 } `json:"knot"`
222 }
223 if err := json.Unmarshal([]byte(out), &doc); err != nil || doc.Knot.ID == "" {
224 v.t.Fatalf("valley knot new printed %q", out)
225 }
226 return doc.Knot.ID
227}
228
229// declare writes a project's policy/read and pushes it to main. An empty
230// body removes it.
231func (v *testValley) declare(project, body string) {
232 v.t.Helper()
233 path := filepath.Join(v.work[project], "policy", "read", "read.cue")
234 if body == "" {
235 v.run(v.work[project], "git", "rm", "--quiet", "-r", "policy/read")
236 } else {
237 v.write(path, "package read\n\n"+body+"\n")
238 }
239 v.commit(project, project+": declare who may read it")
240}
241
242// policy is the body of a policy/read for the project, by its name and
243// identity, naming the readers given.
244func policy(project string, readers ...string) string {
245 set := make([]string, len(readers))
246 for i, r := range readers {
247 set[i] = r + ": true"
248 }
249 return fmt.Sprintf("project: %q\nidentity: %q\nreaders: {%s}", project, identities[project], strings.Join(set, ", "))
250}
251
252// grant writes the instance's identity registry, whose read grant to anyone
253// at the destination covers the projects given, and pushes it to main. An
254// empty scope removes the registry. The registry's genesis entry, the
255// operator, governs it and reads every project.
256func (v *testValley) grant(projects string) {
257 v.t.Helper()
258 v.grantIn("valley", projects)
259}
260
261func (v *testValley) grantIn(instance, projects string) {
262 v.t.Helper()
263 if projects == "" {
264 v.run(v.work[instance], "git", "rm", "--quiet", "-r", "identity")
265 v.commit(instance, instance+": no registry")
266 return
267 }
268 v.write(filepath.Join(v.work[instance], "identity", "registry.cue"), registryText(projects))
269 v.commit(instance, instance+": grant read")
270}
271
272// registryText is the instance's identity registry whose read grant to
273// anyone at the destination covers the projects given.
274func registryText(projects string) string {
275 return `package identity
276
277boundaries: {
278 registry: kind: "registry"
279 web: {kind: "edge-read", destination: "` + destination + `"}
280}
281genesis: "operator"
282principals: operator: {
283 kind: "human"
284 keys: [{class: "ssh-ed25519", bound: "hardware", public: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyForARejectedFixtureAAAAAAAAAAA"}]
285 grants: {
286 govern: boundary: "registry"
287 read: {boundary: "web", projects: "all"}
288 }
289}
290anyone: grants: read: {boundary: "web", projects: ` + projects + `}
291`
292}
293
294func (v *testValley) commit(project, message string) {
295 v.t.Helper()
296 v.run(v.work[project], "git", "add", "--all")
297 v.run(v.work[project], "git", "commit", "--quiet", "-m", message)
298 v.run(v.work[project], "git", "push", "--quiet", "origin", "main")
299}
300
301// args are the publisher's arguments for this valley, with those given
302// after them.
303func (v *testValley) args(more ...string) []string {
304 return append([]string{
305 "--instance-repo", filepath.Join(v.srv, "valley.git"),
306 "--instance", instanceName, "--destination", destination,
307 "--state", v.state, "--principals", v.principals,
308 "--read-schema", filepath.Join(v.schemas, "read.cue"),
309 "--identity-schema", filepath.Join(v.schemas, "identity.cue"),
310 }, more...)
311}
312
313// publish runs one pass of the publisher, and fails the test unless it
314// succeeds.
315func (v *testValley) publish(more ...string) (stdout, stderr string) {
316 v.t.Helper()
317 stdout, stderr, err := v.tryPublish(nil, more...)
318 if err != nil {
319 v.t.Fatalf("the pass failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
320 }
321 return stdout, stderr
322}
323
324// tryPublish runs one pass, with a change to the publisher before it
325// runs.
326func (v *testValley) tryPublish(adjust func(*publisher), more ...string) (string, string, error) {
327 v.t.Helper()
328 var stdout, stderr bytes.Buffer
329 cfg, err := parseArgs(v.args(more...))
330 if err != nil {
331 v.t.Fatal(err)
332 }
333 p, err := newPublisher(cfg, &stdout, &stderr)
334 if err != nil {
335 v.t.Fatal(err)
336 }
337 if adjust != nil {
338 adjust(p)
339 }
340 err = p.pass(context.Background())
341 return stdout.String(), stderr.String(), err
342}
343
344// verifiers are the keys a receiver pins: the publisher's verifier line.
345func (v *testValley) verifiers() []note.VerifierKey {
346 v.t.Helper()
347 data, err := os.ReadFile(filepath.Join(v.state, verifierFile))
348 if err != nil {
349 v.t.Fatal(err)
350 }
351 keys, err := note.ParseVerifierKeys(data)
352 if err != nil {
353 v.t.Fatal(err)
354 }
355 return keys
356}
357
358// out runs a pass with --out into a fresh directory, and returns the
359// directory and its export, held to its manifest.
360func (v *testValley) out() (string, *export.Manifest, *export.Export) {
361 v.t.Helper()
362 dir := filepath.Join(v.t.TempDir(), "export")
363 v.publish("--out", dir)
364 signed, err := os.ReadFile(filepath.Join(dir, "manifest"))
365 if err != nil {
366 v.t.Fatal(err)
367 }
368 m, err := export.VerifyManifest(bytes.NewReader(signed), export.Admission{
369 Verifiers: v.verifiers(), Instance: instanceName, Destination: destination, Now: time.Now(),
370 })
371 if err != nil {
372 v.t.Fatalf("the manifest the publisher wrote is not admitted: %v", err)
373 }
374 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
375 if err != nil {
376 v.t.Fatal(err)
377 }
378 e, err := m.CheckExport(data)
379 if err != nil {
380 v.t.Fatalf("export.json does not agree with the manifest: %v", err)
381 }
382 return dir, m, e
383}
384
385func names(e *export.Export) []string {
386 list := []string{}
387 for _, p := range e.Projects {
388 list = append(list, p.Name)
389 }
390 return list
391}
392
393func knotOf(t *testing.T, p export.Project, id string) export.Knot {
394 t.Helper()
395 for _, k := range p.Knots {
396 if k.ID == id {
397 return k
398 }
399 }
400 t.Fatalf("%s holds no knot %s", p.Name, id)
401 return export.Knot{}
402}
403
404// --out writes an export that a receiver admits: its manifest opens under
405// the publisher's verifier, export.json agrees with it, and a store
406// activates the directory's bodies. It holds the public project alone, as
407// an anonymous reader may see it.
408func TestOutIsAnExportTheStoreActivates(t *testing.T) {
409 v := newValley(t)
410 dir, m, e := v.out()
411 if got := names(e); !reflect.DeepEqual(got, []string{"app"}) {
412 t.Fatalf("the export holds %v, want app alone", got)
413 }
414 app := e.Projects[0]
415 main := strings.TrimSpace(v.run("", "git", "-C", filepath.Join(v.srv, "app.git"), "rev-parse", "main"))
416 if app.SourceTip != main {
417 t.Errorf("app's source tip is %s, and its main is %s", app.SourceTip, main)
418 }
419
420 // The projection reached the export: the edge to site's knot keeps
421 // the reference alone, and principals pass through the mapping.
422 blocked := knotOf(t, app, v.knots["blocked"])
423 if len(blocked.Edges) != 1 || blocked.Edges[0].State != export.EdgeHidden || blocked.Edges[0].Title != nil {
424 t.Errorf("the edge to site's knot is %+v, want a hidden reference alone", blocked.Edges)
425 }
426 bug := knotOf(t, app, v.knots["bug"])
427 if bug.CreatedBy != "operator" || len(bug.Comments) != 1 || bug.Comments[0].Author != export.Unmapped {
428 t.Errorf("the bug's principals are %q and %+v, want operator and an unmapped commenter", bug.CreatedBy, bug.Comments)
429 }
430 if len(app.Changes) != 1 || app.Changes[0].ChangeID != changeID {
431 t.Errorf("app's changes are %+v, want the ready change", app.Changes)
432 }
433 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
434 if err != nil {
435 t.Fatal(err)
436 }
437 if bytes.Contains(data, []byte(v.siteTitle)) {
438 t.Errorf("export.json holds the title of a private project's knot")
439 }
440
441 // A store activates it, from the directory's bodies alone.
442 s, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) })
443 if err != nil {
444 t.Fatal(err)
445 }
446 st, err := s.Stage(m)
447 if err != nil {
448 t.Fatal(err)
449 }
450 inv, err := s.Inventory(st)
451 if err != nil {
452 t.Fatal(err)
453 }
454 for _, need := range inv.Needs {
455 path := filepath.Join(dir, "bundles", need.Name+".bundle")
456 if need.Name == export.ExportFile {
457 path = filepath.Join(dir, export.ExportFile)
458 }
459 f, err := os.Open(path)
460 if err != nil {
461 t.Fatal(err)
462 }
463 req := httptest.NewRequest(http.MethodPut, export.BodyPath(m.Sequence, need.SHA256), f)
464 _, err = export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req)
465 f.Close()
466 if err != nil {
467 t.Fatal(err)
468 }
469 }
470 g, err := s.Activate(context.Background(), st)
471 if err != nil {
472 t.Fatalf("the store did not activate the export: %v", err)
473 }
474 repo, _ := g.Repo("app")
475 if ok, err := export.Reachable(context.Background(), repo, main, main); err != nil || !ok {
476 t.Errorf("the activated repository does not serve app's main: %v %v", ok, err)
477 }
478}
479
480// A project is public only when anyone may read it: its own policy/read
481// names anyone, and the registry's read grant to anyone covers it by its
482// identity. A missing policy, an invalid one, one that does not name anyone,
483// and a grant that does not cover the project each keep it private, and
484// the old policy/web is never read. The operator's grant to every project
485// publishes nothing: the edge serves anyone alone.
486func TestVisibilityNeedsBothConsents(t *testing.T) {
487 v := newValley(t)
488 steps := []struct {
489 what string
490 change func()
491 public []string
492 private []string
493 warns string
494 }{
495 {"site has no policy/read", func() {}, []string{"app"}, []string{"site", "valley"}, ""},
496 {"site lets the operator alone read it", func() { v.declare("site", policy("site", "operator")) },
497 []string{"app"}, []string{"site", "valley"}, ""},
498 {"site lets no one read it", func() { v.declare("site", policy("site")) },
499 []string{"app"}, []string{"site", "valley"}, ""},
500 {"site lets anyone read it", func() { v.declare("site", policy("site", "anyone")) },
501 []string{"app", "site"}, []string{"valley"}, ""},
502 {"the instance's grant to anyone no longer covers site", func() {
503 v.grant(`{app: "` + identities["app"] + `"}`)
504 }, []string{"app"}, []string{"site", "valley"}, ""},
505 {"the instance's grant to anyone covers every project", func() { v.grant(`"all"`) },
506 []string{"app", "site"}, []string{"valley"}, ""},
507 {"the instance's grant to anyone covers no project", func() { v.grant(`{}`) },
508 []string{}, []string{"app", "site", "valley"}, ""},
509 {"the instance's grant to anyone covers app under another identity", func() {
510 v.grant(`{app: "` + identities["site"] + `", site: "` + identities["site"] + `"}`)
511 }, []string{"site"}, []string{"app", "valley"}, ""},
512 {"app's policy is invalid", func() {
513 v.grant(anyoneReadsAppAndSite)
514 v.declare("app", `project: "app"
515identity: "`+identities["app"]+`"
516reader: {anyone: true}`)
517 }, []string{"site"}, []string{"app", "valley"}, "app: its policy/read at"},
518 {"app's policy is site's", func() { v.declare("app", policy("site", "anyone")) },
519 []string{"site"}, []string{"app", "valley"}, `policy/read is for the project "site", and was read from "app"`},
520 {"app declares itself public in the old policy/web alone", func() {
521 v.declare("app", "")
522 v.write(filepath.Join(v.work["app"], "policy", "web", "web.cue"), "package web\n\nproject: visibility: \"public\"\n")
523 v.commit("app", "app: the old declaration")
524 }, []string{"site"}, []string{"app", "valley"}, ""},
525 {"app lets anyone read it again, and the instance drops its registry", func() {
526 v.declare("app", policy("app", "anyone"))
527 v.grant("")
528 }, []string{}, []string{"app", "site", "valley"}, ""},
529 }
530 for _, step := range steps {
531 step.change()
532 dir := filepath.Join(t.TempDir(), "export")
533 stdout, stderr := v.publish("--out", dir)
534 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
535 if err != nil {
536 t.Fatal(err)
537 }
538 e, err := export.Decode(data)
539 if err != nil {
540 t.Fatal(err)
541 }
542 if got := names(e); !reflect.DeepEqual(got, step.public) {
543 t.Errorf("%s: the export holds %v, want %v", step.what, got, step.public)
544 }
545 list := func(names []string) string {
546 if len(names) == 0 {
547 return "none"
548 }
549 return strings.Join(names, ", ")
550 }
551 if want := "public: " + list(step.public) + "; private: " + list(step.private); !strings.Contains(stdout, want) {
552 t.Errorf("%s: the pass did not say %q:\n%s", step.what, want, stdout)
553 }
554 if step.warns != "" && !strings.Contains(stderr, step.warns) {
555 t.Errorf("%s: the pass did not warn %q:\n%s", step.what, step.warns, stderr)
556 }
557 exported := false
558 for _, p := range e.Projects {
559 exported = exported || p.Name == "site"
560 }
561 if holds := bytes.Contains(data, []byte(v.siteTitle)); holds != exported {
562 t.Errorf("%s: export.json holds site's knot: %v; site is exported: %v", step.what, holds, exported)
563 }
564 }
565}
566
567// A registry may reopen a definition of schema/identity.cue and add a
568// field to it, so cue exports Grants beside grants, or Projects beside
569// projects. encoding/json alone would read each into the field the schema
570// spells, and anyone would read site behind a grant that names app alone.
571// The publisher refuses the registry instead, so every project is private.
572func TestAGrantSpelledAnotherWayIsRefused(t *testing.T) {
573 v := newValley(t)
574 v.declare("site", policy("site", "anyone"))
575 appAlone := `{app: "` + identities["app"] + `"}`
576 steps := []struct {
577 what, more, says string
578 }{
579 {"anyone's grants spelled Grants", `#Anyone: Grants?: _
580anyone: Grants: more: {boundary: "web", projects: "all"}
581`, `anyone holds the key "Grants", which is its field "grants" spelled another way`},
582 {"a grant's projects spelled Projects", `#Grant: Projects?: _
583anyone: grants: read: Projects: "all"
584`, `anyone.grants["read"] holds the key "Projects", which is its field "projects" spelled another way`},
585 }
586 for _, step := range steps {
587 v.grant(appAlone)
588 dir := filepath.Join(t.TempDir(), "export")
589 v.publish("--out", dir)
590 if got := exportedNames(t, dir); !reflect.DeepEqual(got, []string{"app"}) {
591 t.Fatalf("%s: before the field is added, the export holds %v, want [app]", step.what, got)
592 }
593 v.write(filepath.Join(v.work["valley"], "identity", "registry.cue"), registryText(appAlone)+step.more)
594 v.commit("valley", "valley: "+step.what)
595 dir = filepath.Join(t.TempDir(), "export")
596 _, stderr := v.publish("--out", dir)
597 if got := exportedNames(t, dir); len(got) != 0 {
598 t.Errorf("%s: the export holds %v, want no project", step.what, got)
599 }
600 for _, says := range []string{"the instance's identity registry at", step.says} {
601 if !strings.Contains(stderr, says) {
602 t.Errorf("%s: the pass did not warn %q:\n%s", step.what, says, stderr)
603 }
604 }
605 }
606}
607
608// exportedNames is the names of the projects in the export written to dir.
609func exportedNames(t *testing.T, dir string) []string {
610 t.Helper()
611 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
612 if err != nil {
613 t.Fatal(err)
614 }
615 e, err := export.Decode(data)
616 if err != nil {
617 t.Fatal(err)
618 }
619 return names(e)
620}
621
622// The registry is read at --registry-ref, the ref the identity compiler
623// reads it at, which need not be main. A grant revoked on that ref alone
624// is revoked, whatever main still says. An instance repository with no
625// such ref has no registry, so every project is private, whatever another
626// ref git would take the name for grants.
627func TestTheRegistryIsReadAtItsRef(t *testing.T) {
628 v := newValley(t)
629 v.declare("site", policy("site", "anyone"))
630 work := v.work["valley"]
631 v.run(work, "git", "checkout", "--quiet", "-b", "registry")
632 v.write(filepath.Join(work, "identity", "registry.cue"), registryText(`{app: "`+identities["app"]+`"}`))
633 v.run(work, "git", "commit", "--quiet", "--all", "-m", "valley: site's grant to anyone is revoked")
634 v.run(work, "git", "push", "--quiet", "origin", "registry")
635 v.run(work, "git", "checkout", "--quiet", "main")
636
637 for _, c := range []struct {
638 what string
639 more []string
640 public string
641 warns string
642 }{
643 {"main", nil, "public: app, site; private: valley", ""},
644 {"refs/heads/registry, where site's grant is revoked", []string{"--registry-ref", "refs/heads/registry"},
645 "public: app; private: site, valley", ""},
646 {"a ref the instance repository does not hold", []string{"--registry-ref", "refs/heads/none"},
647 "public: none; private: app, site, valley", "the instance repository holds no refs/heads/none"},
648 } {
649 stdout, stderr := v.publish(append([]string{"--out", filepath.Join(t.TempDir(), "export")}, c.more...)...)
650 mustSay(t, c.what, stdout, c.public)
651 if c.warns != "" {
652 mustSay(t, c.what, stderr, c.warns)
653 }
654 }
655
656 // With refs/heads/registry gone, git rev-parse would resolve the name
657 // to refs/heads/refs/heads/registry, a branch any pusher can make, here
658 // granting anyone read of app and site. The registry is read at the
659 // ref named exactly, so there is none, and every project is private.
660 v.run(work, "git", "push", "--quiet", "origin", ":refs/heads/registry")
661 v.run(work, "git", "push", "--quiet", "origin", "main:refs/heads/refs/heads/registry")
662 stdout, stderr := v.publish("--out", filepath.Join(t.TempDir(), "export"), "--registry-ref", "refs/heads/registry")
663 mustSay(t, "refs/heads/registry gone", stdout, "public: none; private: app, site, valley")
664 mustSay(t, "refs/heads/registry gone", stderr, "the instance repository holds no refs/heads/registry")
665
666 for _, ref := range []string{"main", "refs/heads/main~1", "refs/heads/../main", "refs/heads/registry.lock", "refs/heads/a b", "refs//main"} {
667 var stdout, stderr bytes.Buffer
668 if code := run(context.Background(), v.args("--out", t.TempDir(), "--registry-ref", ref), &stdout, &stderr); code != 2 {
669 t.Errorf("--registry-ref %q: the pass exited %d, want 2", ref, code)
670 }
671 }
672}
673
674// The key is made on the first start and kept: a second pass signs with
675// the same key, and says the verifier line only when it is new.
676func TestKeyIsMadeOnceAndKept(t *testing.T) {
677 v := newValley(t)
678 first, _ := v.publish("--out", filepath.Join(t.TempDir(), "one"))
679 key, err := os.ReadFile(filepath.Join(v.state, keyFile))
680 if err != nil {
681 t.Fatal(err)
682 }
683 info, err := os.Stat(filepath.Join(v.state, keyFile))
684 if err != nil || info.Mode().Perm() != 0o400 {
685 t.Errorf("the key's mode is %v, want 0400", info.Mode().Perm())
686 }
687 verifiers := v.verifiers()
688 if len(verifiers) != 1 || verifiers[0].Name != instanceName+"/web-export" {
689 t.Fatalf("the verifier file holds %+v, want one key named %s/web-export", verifiers, instanceName)
690 }
691 if !strings.Contains(first, "the export key's verifier line is "+verifiers[0].String()) {
692 t.Errorf("the first pass did not say the verifier line:\n%s", first)
693 }
694
695 dir := filepath.Join(t.TempDir(), "two")
696 second, _ := v.publish("--out", dir)
697 if strings.Contains(second, "verifier line") {
698 t.Errorf("a pass with the same key said the verifier line again:\n%s", second)
699 }
700 again, err := os.ReadFile(filepath.Join(v.state, keyFile))
701 if err != nil {
702 t.Fatal(err)
703 }
704 if !bytes.Equal(key, again) {
705 t.Errorf("the second pass replaced the key")
706 }
707 signed, err := os.ReadFile(filepath.Join(dir, "manifest"))
708 if err != nil {
709 t.Fatal(err)
710 }
711 if _, err := export.VerifyManifest(bytes.NewReader(signed), export.Admission{Verifiers: verifiers,
712 Instance: instanceName, Destination: destination, Now: time.Now()}); err != nil {
713 t.Errorf("the second pass's manifest does not open under the first pass's verifier: %v", err)
714 }
715}
716
717// testReceiver is a receiver over a real export.Store: the three steps
718// of the upload, each as package export defines it, with the publisher's
719// verifier pinned. It records the requests it takes, and refuse can
720// refuse one before it is handled.
721type testReceiver struct {
722 t *testing.T
723 v *testValley
724 server *httptest.Server
725
726 mu sync.Mutex
727 store *export.Store
728 staged map[int64]export.Staging
729 requests []string
730 // refuse is asked about each request, by its kind and sequence, and
731 // a refusal it returns is replied instead. A status alone, with no
732 // refusal, is replied as a plain error.
733 refuse func(kind string, sequence int64) (*export.Error, int)
734}
735
736func newReceiver(t *testing.T, v *testValley) *testReceiver {
737 rv := &testReceiver{t: t, v: v}
738 rv.replaceStore()
739 rv.server = httptest.NewServer(rv)
740 t.Cleanup(rv.server.Close)
741 return rv
742}
743
744// replaceStore gives the receiver an empty state directory, as a volume
745// replaced after a loss would.
746func (rv *testReceiver) replaceStore() {
747 s, err := export.OpenStore(rv.t.TempDir(), func(err error) { rv.t.Errorf("the store reported: %v", err) })
748 if err != nil {
749 rv.t.Fatal(err)
750 }
751 rv.mu.Lock()
752 rv.store, rv.staged = s, map[int64]export.Staging{}
753 rv.mu.Unlock()
754}
755
756// taken are the requests since the last call.
757func (rv *testReceiver) taken() []string {
758 rv.mu.Lock()
759 defer rv.mu.Unlock()
760 r := rv.requests
761 rv.requests = nil
762 if r == nil {
763 r = []string{}
764 }
765 return r
766}
767
768func (rv *testReceiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
769 rv.mu.Lock()
770 defer rv.mu.Unlock()
771 reply := func(status int, doc any) {
772 w.Header().Set("Content-Type", "application/json")
773 w.WriteHeader(status)
774 if doc != nil {
775 json.NewEncoder(w).Encode(doc)
776 }
777 }
778 fail := func(err error) {
779 var e *export.Error
780 if errors.As(err, &e) {
781 reply(e.Code.Status(), e.Reply())
782 return
783 }
784 reply(http.StatusInternalServerError, map[string]string{"error": err.Error()})
785 }
786 parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/web-export/v1/"), "/")
787 kind, seq := "", int64(0)
788 switch {
789 case r.Method == http.MethodPost && r.URL.Path == export.ManifestPath:
790 kind = "manifest"
791 case r.Method == http.MethodPut && len(parts) == 2:
792 kind = "body"
793 case r.Method == http.MethodPost && len(parts) == 2 && parts[1] == "commit":
794 kind = "commit"
795 default:
796 reply(http.StatusNotFound, nil)
797 return
798 }
799 if kind != "manifest" {
800 seq, _ = strconv.ParseInt(parts[0], 10, 64)
801 }
802 name := kind
803 if kind == "body" {
804 name = "body " + parts[1]
805 if st, ok := rv.staged[seq]; ok {
806 for _, b := range st.Manifest.Bodies() {
807 if b.SHA256 == parts[1] {
808 name = "body " + b.Name
809 }
810 }
811 }
812 }
813 rv.requests = append(rv.requests, name)
814 if rv.refuse != nil {
815 if e, status := rv.refuse(kind, seq); e != nil {
816 fail(e)
817 return
818 } else if status != 0 {
819 reply(status, nil)
820 return
821 }
822 }
823
824 switch kind {
825 case "manifest":
826 hw, err := rv.store.HighWater()
827 if err != nil {
828 fail(err)
829 return
830 }
831 m, err := export.VerifyManifest(r.Body, export.Admission{Verifiers: rv.v.verifiers(),
832 Instance: instanceName, Destination: destination, HighWater: hw, Now: time.Now()})
833 if err != nil {
834 fail(err)
835 return
836 }
837 st, err := rv.store.Stage(m)
838 if err != nil {
839 fail(err)
840 return
841 }
842 rv.staged[m.Sequence] = st
843 inv, err := rv.store.Inventory(st)
844 if err != nil {
845 fail(err)
846 return
847 }
848 reply(http.StatusOK, inv)
849 case "body":
850 st, ok := rv.staged[seq]
851 if !ok {
852 fail(&export.Error{Code: export.CodeNoManifest, Message: "nothing is staged"})
853 return
854 }
855 for _, b := range st.Manifest.Bodies() {
856 if b.SHA256 == parts[1] {
857 if _, err := export.StageBody(st.Bodies(), b, 64<<20, r); err != nil {
858 fail(err)
859 return
860 }
861 reply(http.StatusNoContent, nil)
862 return
863 }
864 }
865 fail(&export.Error{Code: export.CodeNotDeclared, Message: "not declared"})
866 case "commit":
867 st, ok := rv.staged[seq]
868 if !ok {
869 fail(&export.Error{Code: export.CodeNoManifest, Message: "nothing is staged"})
870 return
871 }
872 g, err := rv.store.Activate(r.Context(), st)
873 if err != nil {
874 fail(err)
875 return
876 }
877 reply(http.StatusOK, export.Committed{Schema: export.CommittedSchema, Sequence: g.Sequence})
878 }
879}
880
881// active is the export the receiver serves.
882func (rv *testReceiver) active() *export.Export {
883 rv.t.Helper()
884 rv.mu.Lock()
885 defer rv.mu.Unlock()
886 g, release, err := rv.store.Open()
887 defer release()
888 if err != nil {
889 rv.t.Fatal(err)
890 }
891 e, err := g.Export()
892 if err != nil {
893 rv.t.Fatal(err)
894 }
895 return e
896}
897
898func sameRequests(t *testing.T, what string, got []string, want ...string) {
899 t.Helper()
900 if want == nil {
901 want = []string{}
902 }
903 if !reflect.DeepEqual(got, want) {
904 t.Errorf("%s: the receiver took %q, want %q", what, got, want)
905 }
906}
907
908// An upload is made only when the content digest changed since the
909// receiver acknowledged it, or when the acknowledgement is older than
910// --recheck; then the inventory shows whether the receiver still serves
911// it, and a receiver that lost its state is sent everything again.
912func TestUploadSkipsAnUnchangedDigest(t *testing.T) {
913 v := newValley(t)
914 rv := newReceiver(t, v)
915 upload := func(more ...string) string {
916 stdout, _ := v.publish(append([]string{"--receiver", rv.server.URL}, more...)...)
917 return stdout
918 }
919
920 upload()
921 sameRequests(t, "the first pass", rv.taken(), "manifest", "body export.json", "body app", "commit")
922 if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app"}) {
923 t.Fatalf("the receiver serves %v, want app", got)
924 }
925
926 if out := upload(); !strings.Contains(out, "nothing has changed since; nothing is sent") {
927 t.Errorf("a pass with nothing changed did not say so:\n%s", out)
928 }
929 sameRequests(t, "a pass with nothing changed", rv.taken())
930
931 // A comment changes export.json and not app's main, so the receiver
932 // carries app's repository over and needs no bundle.
933 v.valley("app", "knot", "comment", v.knots["milestone"], "-m", "The first page is up.")
934 upload()
935 sameRequests(t, "a pass after a comment", rv.taken(), "manifest", "body export.json", "commit")
936 milestone := knotOf(t, rv.active().Projects[0], v.knots["milestone"])
937 if len(milestone.Comments) != 1 {
938 t.Errorf("the receiver serves the milestone with %d comments, want the new one", len(milestone.Comments))
939 }
940
941 // Past --recheck the publisher asks again, and stops at the inventory.
942 if out := upload("--recheck", "0s"); !strings.Contains(out, "the receiver serves this export already") {
943 t.Errorf("a recheck of a served export did not say so:\n%s", out)
944 }
945 sameRequests(t, "a recheck", rv.taken(), "manifest")
946
947 // A receiver that lost its state is sent everything at the recheck.
948 rv.replaceStore()
949 upload()
950 sameRequests(t, "a pass within --recheck after the receiver lost its state", rv.taken())
951 upload("--recheck", "0s")
952 sameRequests(t, "a recheck after the receiver lost its state", rv.taken(), "manifest", "body export.json", "body app", "commit")
953 if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app"}) {
954 t.Errorf("the receiver serves %v after it was synchronised again, want app", got)
955 }
956}
957
958// The upload retries what the receiver's reply says can succeed later, and
959// stops at what cannot.
960func TestUploadRetriesByTheReceiversReply(t *testing.T) {
961 v := newValley(t)
962 rv := newReceiver(t, v)
963 type refusal struct {
964 kind string
965 code export.Code
966 status int
967 }
968 cases := []struct {
969 name string
970 refuse refusal
971 fails string
972 takes []string
973 pausing bool
974 }{
975 {
976 name: "replayed: the clock is waited for",
977 refuse: refusal{kind: "manifest", code: export.CodeReplayed},
978 takes: []string{"manifest", "manifest", "body export.json", "body app", "commit"},
979 },
980 {
981 name: "superseded at the commit: a new manifest, and its bodies again",
982 refuse: refusal{kind: "commit", code: export.CodeSuperseded},
983 takes: []string{"manifest", "body export.json", "body app", "commit",
984 "manifest", "body export.json", "body app", "commit"},
985 pausing: true,
986 },
987 {
988 name: "a failure in transit: the same manifest, and what is still needed",
989 refuse: refusal{kind: "body", status: http.StatusBadGateway},
990 takes: []string{"manifest", "body export.json", "manifest", "body export.json", "body app", "commit"},
991 pausing: true,
992 },
993 {
994 name: "out-of-window: no retry",
995 refuse: refusal{kind: "manifest", code: export.CodeOutOfWindow},
996 fails: "check this host's clock",
997 takes: []string{"manifest"},
998 },
999 {
1000 name: "bad-signature: no retry",
1001 refuse: refusal{kind: "manifest", code: export.CodeBadSignature},
1002 fails: "bad-signature",
1003 takes: []string{"manifest"},
1004 },
1005 }
1006 for i, c := range cases {
1007 t.Run(c.name, func(t *testing.T) {
1008 rv.replaceStore()
1009 v.valley("app", "knot", "comment", v.knots["milestone"], "-m", "Comment "+strconv.Itoa(i)+".")
1010 var highWater int64
1011 refused := false
1012 rv.mu.Lock()
1013 rv.refuse = func(kind string, seq int64) (*export.Error, int) {
1014 if refused || kind != c.refuse.kind {
1015 return nil, 0
1016 }
1017 refused = true
1018 if c.refuse.status != 0 {
1019 return nil, c.refuse.status
1020 }
1021 e := &export.Error{Code: c.refuse.code, Message: "refused by the test"}
1022 if c.refuse.code == export.CodeReplayed {
1023 highWater = time.Now().Add(time.Second).UnixNano()
1024 e.HighWater = highWater
1025 }
1026 return e, 0
1027 }
1028 rv.mu.Unlock()
1029 rv.taken()
1030 before, _ := os.ReadFile(filepath.Join(v.state, acknowledgedFile))
1031
1032 // The clock runs at real time, plus every pause the pass
1033 // takes, so a wait for the receiver's mark is a short one
1034 // and a backoff costs nothing.
1035 var mu sync.Mutex
1036 var skipped time.Duration
1037 var pauses []time.Duration
1038 stdout, stderr, err := v.tryPublish(func(p *publisher) {
1039 p.now = func() time.Time {
1040 mu.Lock()
1041 defer mu.Unlock()
1042 return time.Now().Add(skipped)
1043 }
1044 p.sleep = func(_ context.Context, d time.Duration) error {
1045 mu.Lock()
1046 defer mu.Unlock()
1047 skipped += d
1048 pauses = append(pauses, d)
1049 return nil
1050 }
1051 }, "--receiver", rv.server.URL)
1052 sameRequests(t, c.name, rv.taken(), c.takes...)
1053 if c.fails != "" {
1054 if err == nil || !strings.Contains(err.Error(), c.fails) {
1055 t.Fatalf("the pass ended with %v, want an error saying %q", err, c.fails)
1056 }
1057 // An upload attempted and refused is not acknowledged.
1058 after, _ := os.ReadFile(filepath.Join(v.state, acknowledgedFile))
1059 if !bytes.Equal(before, after) {
1060 t.Errorf("a refused upload changed the acknowledgement")
1061 }
1062 return
1063 }
1064 if err != nil {
1065 t.Fatalf("the pass failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
1066 }
1067 if got := len(knotOf(t, rv.active().Projects[0], v.knots["milestone"]).Comments); got != i+1 {
1068 t.Errorf("the receiver serves %d comments on the milestone, want %d", got, i+1)
1069 }
1070 if highWater != 0 {
1071 ack, err := (&publisher{cfg: config{state: v.state}, stderr: &bytes.Buffer{}}).readAcknowledged()
1072 if err != nil || ack.Sequence <= highWater {
1073 t.Errorf("the upload after replayed has sequence %d, not past the mark %d", ack.Sequence, highWater)
1074 }
1075 }
1076 if c.pausing && len(pauses) == 0 {
1077 t.Errorf("the pass retried without a pause")
1078 }
1079 })
1080 }
1081}