gunk-dev/the-valley

publish_test.go

sourceda10cfe73ed0main's published tip history
33.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"), `package identity
269
270boundaries: {
271 registry: kind: "registry"
272 web: {kind: "edge-read", destination: "`+destination+`"}
273}
274genesis: "operator"
275principals: operator: {
276 kind: "human"
277 keys: [{class: "ssh-ed25519", bound: "hardware", public: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyForARejectedFixtureAAAAAAAAAAA"}]
278 grants: {
279 govern: boundary: "registry"
280 read: {boundary: "web", projects: "all"}
281 }
282}
283anyone: grants: read: {boundary: "web", projects: `+projects+`}
284`)
285 v.commit(instance, instance+": grant read")
286}
287
288func (v *testValley) commit(project, message string) {
289 v.t.Helper()
290 v.run(v.work[project], "git", "add", "--all")
291 v.run(v.work[project], "git", "commit", "--quiet", "-m", message)
292 v.run(v.work[project], "git", "push", "--quiet", "origin", "main")
293}
294
295// args are the publisher's arguments for this valley, with those given
296// after them.
297func (v *testValley) args(more ...string) []string {
298 return append([]string{
299 "--instance-repo", filepath.Join(v.srv, "valley.git"),
300 "--instance", instanceName, "--destination", destination,
301 "--state", v.state, "--principals", v.principals,
302 "--read-schema", filepath.Join(v.schemas, "read.cue"),
303 "--identity-schema", filepath.Join(v.schemas, "identity.cue"),
304 }, more...)
305}
306
307// publish runs one pass of the publisher, and fails the test unless it
308// succeeds.
309func (v *testValley) publish(more ...string) (stdout, stderr string) {
310 v.t.Helper()
311 stdout, stderr, err := v.tryPublish(nil, more...)
312 if err != nil {
313 v.t.Fatalf("the pass failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
314 }
315 return stdout, stderr
316}
317
318// tryPublish runs one pass, with a change to the publisher before it
319// runs.
320func (v *testValley) tryPublish(adjust func(*publisher), more ...string) (string, string, error) {
321 v.t.Helper()
322 var stdout, stderr bytes.Buffer
323 cfg, err := parseArgs(v.args(more...))
324 if err != nil {
325 v.t.Fatal(err)
326 }
327 p, err := newPublisher(cfg, &stdout, &stderr)
328 if err != nil {
329 v.t.Fatal(err)
330 }
331 if adjust != nil {
332 adjust(p)
333 }
334 err = p.pass(context.Background())
335 return stdout.String(), stderr.String(), err
336}
337
338// verifiers are the keys a receiver pins: the publisher's verifier line.
339func (v *testValley) verifiers() []note.VerifierKey {
340 v.t.Helper()
341 data, err := os.ReadFile(filepath.Join(v.state, verifierFile))
342 if err != nil {
343 v.t.Fatal(err)
344 }
345 keys, err := note.ParseVerifierKeys(data)
346 if err != nil {
347 v.t.Fatal(err)
348 }
349 return keys
350}
351
352// out runs a pass with --out into a fresh directory, and returns the
353// directory and its export, held to its manifest.
354func (v *testValley) out() (string, *export.Manifest, *export.Export) {
355 v.t.Helper()
356 dir := filepath.Join(v.t.TempDir(), "export")
357 v.publish("--out", dir)
358 signed, err := os.ReadFile(filepath.Join(dir, "manifest"))
359 if err != nil {
360 v.t.Fatal(err)
361 }
362 m, err := export.VerifyManifest(bytes.NewReader(signed), export.Admission{
363 Verifiers: v.verifiers(), Instance: instanceName, Destination: destination, Now: time.Now(),
364 })
365 if err != nil {
366 v.t.Fatalf("the manifest the publisher wrote is not admitted: %v", err)
367 }
368 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
369 if err != nil {
370 v.t.Fatal(err)
371 }
372 e, err := m.CheckExport(data)
373 if err != nil {
374 v.t.Fatalf("export.json does not agree with the manifest: %v", err)
375 }
376 return dir, m, e
377}
378
379func names(e *export.Export) []string {
380 list := []string{}
381 for _, p := range e.Projects {
382 list = append(list, p.Name)
383 }
384 return list
385}
386
387func knotOf(t *testing.T, p export.Project, id string) export.Knot {
388 t.Helper()
389 for _, k := range p.Knots {
390 if k.ID == id {
391 return k
392 }
393 }
394 t.Fatalf("%s holds no knot %s", p.Name, id)
395 return export.Knot{}
396}
397
398// --out writes an export that a receiver admits: its manifest opens under
399// the publisher's verifier, export.json agrees with it, and a store
400// activates the directory's bodies. It holds the public project alone, as
401// an anonymous reader may see it.
402func TestOutIsAnExportTheStoreActivates(t *testing.T) {
403 v := newValley(t)
404 dir, m, e := v.out()
405 if got := names(e); !reflect.DeepEqual(got, []string{"app"}) {
406 t.Fatalf("the export holds %v, want app alone", got)
407 }
408 app := e.Projects[0]
409 main := strings.TrimSpace(v.run("", "git", "-C", filepath.Join(v.srv, "app.git"), "rev-parse", "main"))
410 if app.SourceTip != main {
411 t.Errorf("app's source tip is %s, and its main is %s", app.SourceTip, main)
412 }
413
414 // The projection reached the export: the edge to site's knot keeps
415 // the reference alone, and principals pass through the mapping.
416 blocked := knotOf(t, app, v.knots["blocked"])
417 if len(blocked.Edges) != 1 || blocked.Edges[0].State != export.EdgeHidden || blocked.Edges[0].Title != nil {
418 t.Errorf("the edge to site's knot is %+v, want a hidden reference alone", blocked.Edges)
419 }
420 bug := knotOf(t, app, v.knots["bug"])
421 if bug.CreatedBy != "operator" || len(bug.Comments) != 1 || bug.Comments[0].Author != export.Unmapped {
422 t.Errorf("the bug's principals are %q and %+v, want operator and an unmapped commenter", bug.CreatedBy, bug.Comments)
423 }
424 if len(app.Changes) != 1 || app.Changes[0].ChangeID != changeID {
425 t.Errorf("app's changes are %+v, want the ready change", app.Changes)
426 }
427 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
428 if err != nil {
429 t.Fatal(err)
430 }
431 if bytes.Contains(data, []byte(v.siteTitle)) {
432 t.Errorf("export.json holds the title of a private project's knot")
433 }
434
435 // A store activates it, from the directory's bodies alone.
436 s, err := export.OpenStore(t.TempDir(), func(err error) { t.Errorf("the store reported: %v", err) })
437 if err != nil {
438 t.Fatal(err)
439 }
440 st, err := s.Stage(m)
441 if err != nil {
442 t.Fatal(err)
443 }
444 inv, err := s.Inventory(st)
445 if err != nil {
446 t.Fatal(err)
447 }
448 for _, need := range inv.Needs {
449 path := filepath.Join(dir, "bundles", need.Name+".bundle")
450 if need.Name == export.ExportFile {
451 path = filepath.Join(dir, export.ExportFile)
452 }
453 f, err := os.Open(path)
454 if err != nil {
455 t.Fatal(err)
456 }
457 req := httptest.NewRequest(http.MethodPut, export.BodyPath(m.Sequence, need.SHA256), f)
458 _, err = export.StageBody(st.Bodies(), export.Body{Name: need.Name, SHA256: need.SHA256, Size: need.Size}, 64<<20, req)
459 f.Close()
460 if err != nil {
461 t.Fatal(err)
462 }
463 }
464 g, err := s.Activate(context.Background(), st)
465 if err != nil {
466 t.Fatalf("the store did not activate the export: %v", err)
467 }
468 repo, _ := g.Repo("app")
469 if ok, err := export.Reachable(context.Background(), repo, main, main); err != nil || !ok {
470 t.Errorf("the activated repository does not serve app's main: %v %v", ok, err)
471 }
472}
473
474// A project is public only when anyone may read it: its own policy/read
475// names anyone, and the registry's read grant to anyone covers it by its
476// identity. A missing policy, an invalid one, one that does not name anyone,
477// and a grant that does not cover the project each keep it private, and
478// the old policy/web is never read. The operator's grant to every project
479// publishes nothing: the edge serves anyone alone.
480func TestVisibilityNeedsBothConsents(t *testing.T) {
481 v := newValley(t)
482 steps := []struct {
483 what string
484 change func()
485 public []string
486 private []string
487 warns string
488 }{
489 {"site has no policy/read", func() {}, []string{"app"}, []string{"site", "valley"}, ""},
490 {"site lets the operator alone read it", func() { v.declare("site", policy("site", "operator")) },
491 []string{"app"}, []string{"site", "valley"}, ""},
492 {"site lets no one read it", func() { v.declare("site", policy("site")) },
493 []string{"app"}, []string{"site", "valley"}, ""},
494 {"site lets anyone read it", func() { v.declare("site", policy("site", "anyone")) },
495 []string{"app", "site"}, []string{"valley"}, ""},
496 {"the instance's grant to anyone no longer covers site", func() {
497 v.grant(`{app: "` + identities["app"] + `"}`)
498 }, []string{"app"}, []string{"site", "valley"}, ""},
499 {"the instance's grant to anyone covers every project", func() { v.grant(`"all"`) },
500 []string{"app", "site"}, []string{"valley"}, ""},
501 {"the instance's grant to anyone covers no project", func() { v.grant(`{}`) },
502 []string{}, []string{"app", "site", "valley"}, ""},
503 {"the instance's grant to anyone covers app under another identity", func() {
504 v.grant(`{app: "` + identities["site"] + `", site: "` + identities["site"] + `"}`)
505 }, []string{"site"}, []string{"app", "valley"}, ""},
506 {"app's policy is invalid", func() {
507 v.grant(anyoneReadsAppAndSite)
508 v.declare("app", `project: "app"
509identity: "`+identities["app"]+`"
510reader: {anyone: true}`)
511 }, []string{"site"}, []string{"app", "valley"}, "app: its policy/read at"},
512 {"app's policy is site's", func() { v.declare("app", policy("site", "anyone")) },
513 []string{"site"}, []string{"app", "valley"}, `policy/read is for the project "site", and was read from "app"`},
514 {"app declares itself public in the old policy/web alone", func() {
515 v.declare("app", "")
516 v.write(filepath.Join(v.work["app"], "policy", "web", "web.cue"), "package web\n\nproject: visibility: \"public\"\n")
517 v.commit("app", "app: the old declaration")
518 }, []string{"site"}, []string{"app", "valley"}, ""},
519 {"app lets anyone read it again, and the instance drops its registry", func() {
520 v.declare("app", policy("app", "anyone"))
521 v.grant("")
522 }, []string{}, []string{"app", "site", "valley"}, ""},
523 }
524 for _, step := range steps {
525 step.change()
526 dir := filepath.Join(t.TempDir(), "export")
527 stdout, stderr := v.publish("--out", dir)
528 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
529 if err != nil {
530 t.Fatal(err)
531 }
532 e, err := export.Decode(data)
533 if err != nil {
534 t.Fatal(err)
535 }
536 if got := names(e); !reflect.DeepEqual(got, step.public) {
537 t.Errorf("%s: the export holds %v, want %v", step.what, got, step.public)
538 }
539 list := func(names []string) string {
540 if len(names) == 0 {
541 return "none"
542 }
543 return strings.Join(names, ", ")
544 }
545 if want := "public: " + list(step.public) + "; private: " + list(step.private); !strings.Contains(stdout, want) {
546 t.Errorf("%s: the pass did not say %q:\n%s", step.what, want, stdout)
547 }
548 if step.warns != "" && !strings.Contains(stderr, step.warns) {
549 t.Errorf("%s: the pass did not warn %q:\n%s", step.what, step.warns, stderr)
550 }
551 exported := false
552 for _, p := range e.Projects {
553 exported = exported || p.Name == "site"
554 }
555 if holds := bytes.Contains(data, []byte(v.siteTitle)); holds != exported {
556 t.Errorf("%s: export.json holds site's knot: %v; site is exported: %v", step.what, holds, exported)
557 }
558 }
559}
560
561// The key is made on the first start and kept: a second pass signs with
562// the same key, and says the verifier line only when it is new.
563func TestKeyIsMadeOnceAndKept(t *testing.T) {
564 v := newValley(t)
565 first, _ := v.publish("--out", filepath.Join(t.TempDir(), "one"))
566 key, err := os.ReadFile(filepath.Join(v.state, keyFile))
567 if err != nil {
568 t.Fatal(err)
569 }
570 info, err := os.Stat(filepath.Join(v.state, keyFile))
571 if err != nil || info.Mode().Perm() != 0o400 {
572 t.Errorf("the key's mode is %v, want 0400", info.Mode().Perm())
573 }
574 verifiers := v.verifiers()
575 if len(verifiers) != 1 || verifiers[0].Name != instanceName+"/web-export" {
576 t.Fatalf("the verifier file holds %+v, want one key named %s/web-export", verifiers, instanceName)
577 }
578 if !strings.Contains(first, "the export key's verifier line is "+verifiers[0].String()) {
579 t.Errorf("the first pass did not say the verifier line:\n%s", first)
580 }
581
582 dir := filepath.Join(t.TempDir(), "two")
583 second, _ := v.publish("--out", dir)
584 if strings.Contains(second, "verifier line") {
585 t.Errorf("a pass with the same key said the verifier line again:\n%s", second)
586 }
587 again, err := os.ReadFile(filepath.Join(v.state, keyFile))
588 if err != nil {
589 t.Fatal(err)
590 }
591 if !bytes.Equal(key, again) {
592 t.Errorf("the second pass replaced the key")
593 }
594 signed, err := os.ReadFile(filepath.Join(dir, "manifest"))
595 if err != nil {
596 t.Fatal(err)
597 }
598 if _, err := export.VerifyManifest(bytes.NewReader(signed), export.Admission{Verifiers: verifiers,
599 Instance: instanceName, Destination: destination, Now: time.Now()}); err != nil {
600 t.Errorf("the second pass's manifest does not open under the first pass's verifier: %v", err)
601 }
602}
603
604// testReceiver is a receiver over a real export.Store: the three steps
605// of the upload, each as package export defines it, with the publisher's
606// verifier pinned. It records the requests it takes, and refuse can
607// refuse one before it is handled.
608type testReceiver struct {
609 t *testing.T
610 v *testValley
611 server *httptest.Server
612
613 mu sync.Mutex
614 store *export.Store
615 staged map[int64]export.Staging
616 requests []string
617 // refuse is asked about each request, by its kind and sequence, and
618 // a refusal it returns is replied instead. A status alone, with no
619 // refusal, is replied as a plain error.
620 refuse func(kind string, sequence int64) (*export.Error, int)
621}
622
623func newReceiver(t *testing.T, v *testValley) *testReceiver {
624 rv := &testReceiver{t: t, v: v}
625 rv.replaceStore()
626 rv.server = httptest.NewServer(rv)
627 t.Cleanup(rv.server.Close)
628 return rv
629}
630
631// replaceStore gives the receiver an empty state directory, as a volume
632// replaced after a loss would.
633func (rv *testReceiver) replaceStore() {
634 s, err := export.OpenStore(rv.t.TempDir(), func(err error) { rv.t.Errorf("the store reported: %v", err) })
635 if err != nil {
636 rv.t.Fatal(err)
637 }
638 rv.mu.Lock()
639 rv.store, rv.staged = s, map[int64]export.Staging{}
640 rv.mu.Unlock()
641}
642
643// taken are the requests since the last call.
644func (rv *testReceiver) taken() []string {
645 rv.mu.Lock()
646 defer rv.mu.Unlock()
647 r := rv.requests
648 rv.requests = nil
649 if r == nil {
650 r = []string{}
651 }
652 return r
653}
654
655func (rv *testReceiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
656 rv.mu.Lock()
657 defer rv.mu.Unlock()
658 reply := func(status int, doc any) {
659 w.Header().Set("Content-Type", "application/json")
660 w.WriteHeader(status)
661 if doc != nil {
662 json.NewEncoder(w).Encode(doc)
663 }
664 }
665 fail := func(err error) {
666 var e *export.Error
667 if errors.As(err, &e) {
668 reply(e.Code.Status(), e.Reply())
669 return
670 }
671 reply(http.StatusInternalServerError, map[string]string{"error": err.Error()})
672 }
673 parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/web-export/v1/"), "/")
674 kind, seq := "", int64(0)
675 switch {
676 case r.Method == http.MethodPost && r.URL.Path == export.ManifestPath:
677 kind = "manifest"
678 case r.Method == http.MethodPut && len(parts) == 2:
679 kind = "body"
680 case r.Method == http.MethodPost && len(parts) == 2 && parts[1] == "commit":
681 kind = "commit"
682 default:
683 reply(http.StatusNotFound, nil)
684 return
685 }
686 if kind != "manifest" {
687 seq, _ = strconv.ParseInt(parts[0], 10, 64)
688 }
689 name := kind
690 if kind == "body" {
691 name = "body " + parts[1]
692 if st, ok := rv.staged[seq]; ok {
693 for _, b := range st.Manifest.Bodies() {
694 if b.SHA256 == parts[1] {
695 name = "body " + b.Name
696 }
697 }
698 }
699 }
700 rv.requests = append(rv.requests, name)
701 if rv.refuse != nil {
702 if e, status := rv.refuse(kind, seq); e != nil {
703 fail(e)
704 return
705 } else if status != 0 {
706 reply(status, nil)
707 return
708 }
709 }
710
711 switch kind {
712 case "manifest":
713 hw, err := rv.store.HighWater()
714 if err != nil {
715 fail(err)
716 return
717 }
718 m, err := export.VerifyManifest(r.Body, export.Admission{Verifiers: rv.v.verifiers(),
719 Instance: instanceName, Destination: destination, HighWater: hw, Now: time.Now()})
720 if err != nil {
721 fail(err)
722 return
723 }
724 st, err := rv.store.Stage(m)
725 if err != nil {
726 fail(err)
727 return
728 }
729 rv.staged[m.Sequence] = st
730 inv, err := rv.store.Inventory(st)
731 if err != nil {
732 fail(err)
733 return
734 }
735 reply(http.StatusOK, inv)
736 case "body":
737 st, ok := rv.staged[seq]
738 if !ok {
739 fail(&export.Error{Code: export.CodeNoManifest, Message: "nothing is staged"})
740 return
741 }
742 for _, b := range st.Manifest.Bodies() {
743 if b.SHA256 == parts[1] {
744 if _, err := export.StageBody(st.Bodies(), b, 64<<20, r); err != nil {
745 fail(err)
746 return
747 }
748 reply(http.StatusNoContent, nil)
749 return
750 }
751 }
752 fail(&export.Error{Code: export.CodeNotDeclared, Message: "not declared"})
753 case "commit":
754 st, ok := rv.staged[seq]
755 if !ok {
756 fail(&export.Error{Code: export.CodeNoManifest, Message: "nothing is staged"})
757 return
758 }
759 g, err := rv.store.Activate(r.Context(), st)
760 if err != nil {
761 fail(err)
762 return
763 }
764 reply(http.StatusOK, export.Committed{Schema: export.CommittedSchema, Sequence: g.Sequence})
765 }
766}
767
768// active is the export the receiver serves.
769func (rv *testReceiver) active() *export.Export {
770 rv.t.Helper()
771 rv.mu.Lock()
772 defer rv.mu.Unlock()
773 g, release, err := rv.store.Open()
774 defer release()
775 if err != nil {
776 rv.t.Fatal(err)
777 }
778 e, err := g.Export()
779 if err != nil {
780 rv.t.Fatal(err)
781 }
782 return e
783}
784
785func sameRequests(t *testing.T, what string, got []string, want ...string) {
786 t.Helper()
787 if want == nil {
788 want = []string{}
789 }
790 if !reflect.DeepEqual(got, want) {
791 t.Errorf("%s: the receiver took %q, want %q", what, got, want)
792 }
793}
794
795// An upload is made only when the content digest changed since the
796// receiver acknowledged it, or when the acknowledgement is older than
797// --recheck; then the inventory shows whether the receiver still serves
798// it, and a receiver that lost its state is sent everything again.
799func TestUploadSkipsAnUnchangedDigest(t *testing.T) {
800 v := newValley(t)
801 rv := newReceiver(t, v)
802 upload := func(more ...string) string {
803 stdout, _ := v.publish(append([]string{"--receiver", rv.server.URL}, more...)...)
804 return stdout
805 }
806
807 upload()
808 sameRequests(t, "the first pass", rv.taken(), "manifest", "body export.json", "body app", "commit")
809 if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app"}) {
810 t.Fatalf("the receiver serves %v, want app", got)
811 }
812
813 if out := upload(); !strings.Contains(out, "nothing has changed since; nothing is sent") {
814 t.Errorf("a pass with nothing changed did not say so:\n%s", out)
815 }
816 sameRequests(t, "a pass with nothing changed", rv.taken())
817
818 // A comment changes export.json and not app's main, so the receiver
819 // carries app's repository over and needs no bundle.
820 v.valley("app", "knot", "comment", v.knots["milestone"], "-m", "The first page is up.")
821 upload()
822 sameRequests(t, "a pass after a comment", rv.taken(), "manifest", "body export.json", "commit")
823 milestone := knotOf(t, rv.active().Projects[0], v.knots["milestone"])
824 if len(milestone.Comments) != 1 {
825 t.Errorf("the receiver serves the milestone with %d comments, want the new one", len(milestone.Comments))
826 }
827
828 // Past --recheck the publisher asks again, and stops at the inventory.
829 if out := upload("--recheck", "0s"); !strings.Contains(out, "the receiver serves this export already") {
830 t.Errorf("a recheck of a served export did not say so:\n%s", out)
831 }
832 sameRequests(t, "a recheck", rv.taken(), "manifest")
833
834 // A receiver that lost its state is sent everything at the recheck.
835 rv.replaceStore()
836 upload()
837 sameRequests(t, "a pass within --recheck after the receiver lost its state", rv.taken())
838 upload("--recheck", "0s")
839 sameRequests(t, "a recheck after the receiver lost its state", rv.taken(), "manifest", "body export.json", "body app", "commit")
840 if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app"}) {
841 t.Errorf("the receiver serves %v after it was synchronised again, want app", got)
842 }
843}
844
845// The upload retries what the receiver's reply says can succeed later, and
846// stops at what cannot.
847func TestUploadRetriesByTheReceiversReply(t *testing.T) {
848 v := newValley(t)
849 rv := newReceiver(t, v)
850 type refusal struct {
851 kind string
852 code export.Code
853 status int
854 }
855 cases := []struct {
856 name string
857 refuse refusal
858 fails string
859 takes []string
860 pausing bool
861 }{
862 {
863 name: "replayed: the clock is waited for",
864 refuse: refusal{kind: "manifest", code: export.CodeReplayed},
865 takes: []string{"manifest", "manifest", "body export.json", "body app", "commit"},
866 },
867 {
868 name: "superseded at the commit: a new manifest, and its bodies again",
869 refuse: refusal{kind: "commit", code: export.CodeSuperseded},
870 takes: []string{"manifest", "body export.json", "body app", "commit",
871 "manifest", "body export.json", "body app", "commit"},
872 pausing: true,
873 },
874 {
875 name: "a failure in transit: the same manifest, and what is still needed",
876 refuse: refusal{kind: "body", status: http.StatusBadGateway},
877 takes: []string{"manifest", "body export.json", "manifest", "body export.json", "body app", "commit"},
878 pausing: true,
879 },
880 {
881 name: "out-of-window: no retry",
882 refuse: refusal{kind: "manifest", code: export.CodeOutOfWindow},
883 fails: "check this host's clock",
884 takes: []string{"manifest"},
885 },
886 {
887 name: "bad-signature: no retry",
888 refuse: refusal{kind: "manifest", code: export.CodeBadSignature},
889 fails: "bad-signature",
890 takes: []string{"manifest"},
891 },
892 }
893 for i, c := range cases {
894 t.Run(c.name, func(t *testing.T) {
895 rv.replaceStore()
896 v.valley("app", "knot", "comment", v.knots["milestone"], "-m", "Comment "+strconv.Itoa(i)+".")
897 var highWater int64
898 refused := false
899 rv.mu.Lock()
900 rv.refuse = func(kind string, seq int64) (*export.Error, int) {
901 if refused || kind != c.refuse.kind {
902 return nil, 0
903 }
904 refused = true
905 if c.refuse.status != 0 {
906 return nil, c.refuse.status
907 }
908 e := &export.Error{Code: c.refuse.code, Message: "refused by the test"}
909 if c.refuse.code == export.CodeReplayed {
910 highWater = time.Now().Add(time.Second).UnixNano()
911 e.HighWater = highWater
912 }
913 return e, 0
914 }
915 rv.mu.Unlock()
916 rv.taken()
917 before, _ := os.ReadFile(filepath.Join(v.state, acknowledgedFile))
918
919 // The clock runs at real time, plus every pause the pass
920 // takes, so a wait for the receiver's mark is a short one
921 // and a backoff costs nothing.
922 var mu sync.Mutex
923 var skipped time.Duration
924 var pauses []time.Duration
925 stdout, stderr, err := v.tryPublish(func(p *publisher) {
926 p.now = func() time.Time {
927 mu.Lock()
928 defer mu.Unlock()
929 return time.Now().Add(skipped)
930 }
931 p.sleep = func(_ context.Context, d time.Duration) error {
932 mu.Lock()
933 defer mu.Unlock()
934 skipped += d
935 pauses = append(pauses, d)
936 return nil
937 }
938 }, "--receiver", rv.server.URL)
939 sameRequests(t, c.name, rv.taken(), c.takes...)
940 if c.fails != "" {
941 if err == nil || !strings.Contains(err.Error(), c.fails) {
942 t.Fatalf("the pass ended with %v, want an error saying %q", err, c.fails)
943 }
944 // An upload attempted and refused is not acknowledged.
945 after, _ := os.ReadFile(filepath.Join(v.state, acknowledgedFile))
946 if !bytes.Equal(before, after) {
947 t.Errorf("a refused upload changed the acknowledgement")
948 }
949 return
950 }
951 if err != nil {
952 t.Fatalf("the pass failed: %v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
953 }
954 if got := len(knotOf(t, rv.active().Projects[0], v.knots["milestone"]).Comments); got != i+1 {
955 t.Errorf("the receiver serves %d comments on the milestone, want %d", got, i+1)
956 }
957 if highWater != 0 {
958 ack, err := (&publisher{cfg: config{state: v.state}, stderr: &bytes.Buffer{}}).readAcknowledged()
959 if err != nil || ack.Sequence <= highWater {
960 t.Errorf("the upload after replayed has sequence %d, not past the mark %d", ack.Sequence, highWater)
961 }
962 }
963 if c.pausing && len(pauses) == 0 {
964 t.Errorf("the pass retried without a pause")
965 }
966 })
967 }
968}