gunk-dev/the-valley

publish_test.go

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