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