gunk-dev/the-valley

publish_test.go

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