gunk-dev/the-valley

publish_test.go

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