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