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