gunk-dev/the-valley

publish_test.go

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