gunk-dev/the-valley

publish_test.go

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