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