| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "crypto/sha256" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io/fs" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "reflect" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "the-valley/web/export" |
| 21 | ) |
| 22 | |
| 23 | // fails runs one pass through run, the program's entry point, and fails the |
| 24 | // test unless the pass exits 1 having sent and written nothing: to rv when |
| 25 | // it is given, and otherwise to a fresh --out directory. It returns what |
| 26 | // the pass said on stderr. |
| 27 | func (v *testValley) fails(rv *testReceiver, more ...string) string { |
| 28 | v.t.Helper() |
| 29 | out := filepath.Join(v.t.TempDir(), "export") |
| 30 | to := []string{"--out", out} |
| 31 | if rv != nil { |
| 32 | rv.taken() |
| 33 | to = rv.flags() |
| 34 | } |
| 35 | var stdout, stderr bytes.Buffer |
| 36 | if code := run(context.Background(), v.args(append(to, more...)...), &stdout, &stderr); code != 1 { |
| 37 | v.t.Fatalf("the pass exited %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout.String(), stderr.String()) |
| 38 | } |
| 39 | if rv != nil { |
| 40 | sameRequests(v.t, "a failed pass", rv.taken()) |
| 41 | } else if _, err := os.Stat(out); !errors.Is(err, os.ErrNotExist) { |
| 42 | v.t.Errorf("a failed pass wrote %s", out) |
| 43 | } |
| 44 | return stderr.String() |
| 45 | } |
| 46 | |
| 47 | func mustSay(t *testing.T, what, said, want string) { |
| 48 | t.Helper() |
| 49 | if !strings.Contains(said, want) { |
| 50 | t.Errorf("%s: the pass did not say %q:\n%s", what, want, said) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // elsewhere makes a second instance beside the first, with projects of the |
| 55 | // same names: valley, whose registry grants anyone read of app and site; |
| 56 | // app, which lets anyone read it and carries a sentinel of its own; and |
| 57 | // site, with no main. |
| 58 | // It returns the instance repository. |
| 59 | func (v *testValley) elsewhere(sentinel string) string { |
| 60 | v.t.Helper() |
| 61 | srv := filepath.Join(v.root, "elsewhere") |
| 62 | for _, name := range []string{"valley", "app", "site"} { |
| 63 | v.run("", "git", "init", "--quiet", "--bare", filepath.Join(srv, name+".git")) |
| 64 | } |
| 65 | for _, name := range []string{"valley", "app"} { |
| 66 | work := filepath.Join(v.root, "elsewhere-work", name) |
| 67 | v.run("", "git", "init", "--quiet", work) |
| 68 | v.run(work, "git", "remote", "add", "origin", filepath.Join(srv, name+".git")) |
| 69 | v.work["elsewhere/"+name] = work |
| 70 | } |
| 71 | v.write(filepath.Join(v.work["elsewhere/valley"], "policy", "instance", "floor.cue"), "package verification\n") |
| 72 | v.grantIn("elsewhere/valley", anyoneReadsAppAndSite) |
| 73 | v.write(filepath.Join(v.work["elsewhere/app"], "policy", "valley"), filepath.Join(srv, "valley.git")+"\n") |
| 74 | v.write(filepath.Join(v.work["elsewhere/app"], "source.txt"), sentinel+"\n") |
| 75 | v.declare("elsewhere/app", policy("app", "anyone")) |
| 76 | list := v.runInput("", "app\nsite\nvalley\n", "git", "-C", filepath.Join(srv, "valley.git"), "hash-object", "-w", "--stdin") |
| 77 | v.run("", "git", "-C", filepath.Join(srv, "valley.git"), "update-ref", projectsRef, strings.TrimSpace(list)) |
| 78 | return filepath.Join(srv, "valley.git") |
| 79 | } |
| 80 | |
| 81 | // Two instances publish a project called app. When the instance repository |
| 82 | // the publisher is given points at the other with policy/valley, the CLI |
| 83 | // would read the other's app, and the pass refuses before it reads any |
| 84 | // project. |
| 85 | func TestAnotherInstanceIsNeverRead(t *testing.T) { |
| 86 | v := newValley(t) |
| 87 | other := v.elsewhere("elsewhere-app-source-c3d1") |
| 88 | v.write(filepath.Join(v.work["valley"], "policy", "valley"), other+"\n") |
| 89 | v.commit("valley", "valley: point at another instance") |
| 90 | |
| 91 | mustSay(t, "--out", v.fails(nil), "holds policy/valley on main") |
| 92 | rv := newReceiver(t, v) |
| 93 | mustSay(t, "--receiver", v.fails(rv), "holds policy/valley on main") |
| 94 | if _, err := os.Stat(filepath.Join(v.root, "cache", "valley-web-publish", "repos", "app.git")); !errors.Is(err, os.ErrNotExist) { |
| 95 | t.Errorf("the pass fetched a project before it refused the instance repository") |
| 96 | } |
| 97 | |
| 98 | // The CLI reads policy/valley up to a # and without the spaces around |
| 99 | // it, so an instance repository whose URL holds them is refused before |
| 100 | // the pass runs: policy/valley would name another. |
| 101 | instance := filepath.Join(v.srv, "valley.git") |
| 102 | for _, url := range []string{"relative.git", "https://example.org/valley.git", instance + "#other", " " + instance, instance + "\n" + other} { |
| 103 | var stdout, stderr bytes.Buffer |
| 104 | if code := run(context.Background(), v.args("--out", t.TempDir(), "--instance-repo", url), &stdout, &stderr); code != 2 { |
| 105 | t.Errorf("--instance-repo %q: the pass exited %d, want 2", url, code) |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // The pass reads the instance repository at the main it began with, and |
| 111 | // the CLI never reads that main again. So a policy/valley that lands on |
| 112 | // main while the CLI reads changes nothing in the read: not when main is |
| 113 | // put back before the read ends, which no comparison of main before and |
| 114 | // after the read could see, and not when it stays, which the next pass |
| 115 | // refuses. Read through the pointer, the export would hold the other |
| 116 | // instance's app. |
| 117 | func TestAPointerLandingDuringAReadIsNeverRead(t *testing.T) { |
| 118 | const otherSource = "elsewhere-app-source-c3d1" |
| 119 | for _, restored := range []bool{true, false} { |
| 120 | t.Run(fmt.Sprintf("restored %v", restored), func(t *testing.T) { |
| 121 | v := newValley(t) |
| 122 | other := v.elsewhere(otherSource) |
| 123 | instance := filepath.Join(v.srv, "valley.git") |
| 124 | began := strings.TrimSpace(v.run("", "git", "-C", instance, "rev-parse", "main")) |
| 125 | work := v.work["valley"] |
| 126 | v.run(work, "git", "checkout", "--quiet", "-b", "pointer") |
| 127 | v.write(filepath.Join(work, "policy", "valley"), other+"\n") |
| 128 | v.run(work, "git", "add", "--all") |
| 129 | v.run(work, "git", "commit", "--quiet", "-m", "valley: point at another instance") |
| 130 | pointer := strings.TrimSpace(v.run(work, "git", "rev-parse", "HEAD")) |
| 131 | v.run(work, "git", "push", "--quiet", "origin", "pointer") |
| 132 | |
| 133 | // The CLI's first command moves main to the pointer before it |
| 134 | // runs. When restored, main is put back once the second, the |
| 135 | // pending listing, is done: the CLI has then read the pointer |
| 136 | // twice, if it reads main at all, and main is where the pass |
| 137 | // began. |
| 138 | wrapper := filepath.Join(v.root, "bin", "valley") |
| 139 | data, err := os.ReadFile(wrapper) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | shebang, rest, _ := strings.Cut(string(data), "\n") |
| 144 | rest = strings.Replace(rest, "exec ", "", 1) |
| 145 | count := filepath.Join(v.root, "count") |
| 146 | restore := ":" |
| 147 | if restored { |
| 148 | restore = fmt.Sprintf("git -C %s update-ref refs/heads/main %s", instance, began) |
| 149 | } |
| 150 | v.write(wrapper, fmt.Sprintf(`%s |
| 151 | n=$(( $(cat %[2]s 2>/dev/null || echo 0) + 1 )); echo "$n" > %[2]s |
| 152 | if [ "$n" = 1 ]; then git -C %[3]s update-ref refs/heads/main %[4]s; fi |
| 153 | rc=0 |
| 154 | %[5]s || rc=$? |
| 155 | if [ "$n" = 2 ]; then %[6]s; fi |
| 156 | exit "$rc" |
| 157 | `, shebang, count, instance, pointer, strings.TrimSpace(rest), restore)) |
| 158 | |
| 159 | dir, _, e := v.out() |
| 160 | if calls, _ := strconv.Atoi(strings.TrimSpace(v.run("", "cat", count))); calls < 2 { |
| 161 | t.Fatalf("the CLI ran %d commands, so the pointer was never in place while it read", calls) |
| 162 | } |
| 163 | if got := names(e); !reflect.DeepEqual(got, []string{"app"}) { |
| 164 | t.Fatalf("the export holds %v, want app alone", got) |
| 165 | } |
| 166 | app := strings.TrimSpace(v.run("", "git", "-C", filepath.Join(v.srv, "app.git"), "rev-parse", "main")) |
| 167 | if e.Projects[0].SourceTip != app { |
| 168 | t.Errorf("the export's app is at %s, and this instance's app is at %s", e.Projects[0].SourceTip, app) |
| 169 | } |
| 170 | if strings.Contains(v.unbundled(filepath.Join(dir, "bundles", "app.bundle")), otherSource) { |
| 171 | t.Errorf("the bundle of app holds the other instance's source") |
| 172 | } |
| 173 | if len(knotOf(t, e.Projects[0], v.knots["bug"]).Comments) != 1 { |
| 174 | t.Errorf("the export's app does not hold this instance's plan") |
| 175 | } |
| 176 | |
| 177 | if restored { |
| 178 | return |
| 179 | } |
| 180 | v.write(wrapper, shebang+"\n"+rest) |
| 181 | mustSay(t, "the next pass", v.fails(nil), "holds policy/valley on main") |
| 182 | }) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | // A project a read grant to anyone names that cannot be read fails the |
| 187 | // pass, which sends and writes nothing: published without it, the export |
| 188 | // would take it off the web. A project with no main yet is private, and the pass |
| 189 | // goes on. |
| 190 | func TestAProjectThatCannotBeReadFailsThePass(t *testing.T) { |
| 191 | cases := []struct { |
| 192 | name string |
| 193 | upload bool |
| 194 | breaks func(v *testValley) []string |
| 195 | says string |
| 196 | }{ |
| 197 | { |
| 198 | // The policy path reads site's policy before any content |
| 199 | // work, finds it cannot, and fails the pass once it has sent |
| 200 | // what it could check. |
| 201 | name: "site cannot be read", |
| 202 | upload: true, |
| 203 | breaks: func(v *testValley) []string { |
| 204 | if err := os.Rename(filepath.Join(v.srv, "site.git"), filepath.Join(v.srv, "site.moved")); err != nil { |
| 205 | v.t.Fatal(err) |
| 206 | } |
| 207 | return nil |
| 208 | }, |
| 209 | says: "the policy check is incomplete: site: could not read main", |
| 210 | }, |
| 211 | { |
| 212 | name: "a project mirror cannot be staged", |
| 213 | breaks: func(v *testValley) []string { |
| 214 | // A file where the parent directory belongs prevents staging. |
| 215 | v.write(filepath.Join(v.root, "cache", "valley-web-publish", "repos"), "blocked") |
| 216 | return nil |
| 217 | }, |
| 218 | says: "app: could not read main", |
| 219 | }, |
| 220 | { |
| 221 | name: "discovery fails, and the CLI lists its own repository alone", |
| 222 | breaks: func(v *testValley) []string { |
| 223 | list := v.runInput("", "app\nsite\nvalley\nnot a name\n", "git", "-C", filepath.Join(v.srv, "valley.git"), "hash-object", "-w", "--stdin") |
| 224 | v.run("", "git", "-C", filepath.Join(v.srv, "valley.git"), "update-ref", projectsRef, strings.TrimSpace(list)) |
| 225 | return nil |
| 226 | }, |
| 227 | says: "valley plan --all lists _pointer, and the instance repository publishes app, not a name, site, valley", |
| 228 | }, |
| 229 | { |
| 230 | // With no project list, git rev-parse would read a tag named |
| 231 | // refs/tags/refs/the-valley/projects as the list. The tag |
| 232 | // holds the list the instance published, which reads as a |
| 233 | // project list, so only the exact read refuses it. |
| 234 | name: "the instance publishes no project list", |
| 235 | breaks: func(v *testValley) []string { |
| 236 | instance := filepath.Join(v.srv, "valley.git") |
| 237 | list := strings.TrimSpace(v.run("", "git", "-C", instance, "show-ref", "--verify", "--hash", projectsRef)) |
| 238 | v.run("", "git", "-C", instance, "update-ref", "-d", projectsRef) |
| 239 | v.run("", "git", "-C", instance, "update-ref", "refs/tags/"+projectsRef, list) |
| 240 | return nil |
| 241 | }, |
| 242 | says: "the instance repository publishes no refs/the-valley/projects", |
| 243 | }, |
| 244 | { |
| 245 | // With no main, git rev-parse would read a branch named |
| 246 | // refs/heads/refs/heads/main, here the instance's own main, |
| 247 | // as main. |
| 248 | name: "the instance has no main", |
| 249 | breaks: func(v *testValley) []string { |
| 250 | instance := filepath.Join(v.srv, "valley.git") |
| 251 | v.run("", "git", "-C", instance, "update-ref", "refs/heads/refs/heads/main", "refs/heads/main") |
| 252 | v.run("", "git", "-C", instance, "update-ref", "-d", "refs/heads/main") |
| 253 | return nil |
| 254 | }, |
| 255 | says: filepath.Join("SRV", "valley.git") + " holds no main, so it is not an instance repository", |
| 256 | }, |
| 257 | { |
| 258 | name: "the read schema cannot be read", |
| 259 | breaks: func(v *testValley) []string { return []string{"--read-schema", filepath.Join(v.root, "no-such.cue")} }, |
| 260 | says: "does not load", |
| 261 | }, |
| 262 | { |
| 263 | name: "the identity schema cannot be read", |
| 264 | breaks: func(v *testValley) []string { |
| 265 | return []string{"--identity-schema", filepath.Join(v.root, "no-such.cue")} |
| 266 | }, |
| 267 | says: "does not load", |
| 268 | }, |
| 269 | } |
| 270 | for _, c := range cases { |
| 271 | t.Run(c.name, func(t *testing.T) { |
| 272 | v := newValley(t) |
| 273 | more := c.breaks(v) |
| 274 | var rv *testReceiver |
| 275 | if c.upload { |
| 276 | rv = newReceiver(t, v) |
| 277 | } |
| 278 | mustSay(t, c.name, v.fails(rv, more...), strings.ReplaceAll(c.says, "SRV", v.srv)) |
| 279 | }) |
| 280 | } |
| 281 | |
| 282 | // The grants are read before any project is: the CLI's clones are |
| 283 | // made for the projects a grant names, and the CLI can make no other. |
| 284 | // So a project no grant names is never read, and one that cannot be |
| 285 | // read fails no pass. |
| 286 | t.Run("a project no grant names that cannot be read is private", func(t *testing.T) { |
| 287 | v := newValley(t) |
| 288 | appAlone := `{app: "` + identities["app"] + `"}` |
| 289 | v.write(filepath.Join(v.work["valley"], "identity", "registry.cue"), registryFor(appAlone, appAlone)) |
| 290 | v.commit("valley", "valley: grant app alone") |
| 291 | if err := os.Rename(filepath.Join(v.srv, "site.git"), filepath.Join(v.srv, "site.moved")); err != nil { |
| 292 | t.Fatal(err) |
| 293 | } |
| 294 | stdout, _ := v.publish("--out", filepath.Join(t.TempDir(), "export")) |
| 295 | mustSay(t, "site cannot be read, and no grant names it", stdout, "exported: app; not exported: site, valley") |
| 296 | clones, err := filepath.Glob(filepath.Join(v.root, "cache", "valley", "repos", "*-site")) |
| 297 | if err != nil || len(clones) != 0 { |
| 298 | t.Errorf("the CLI has a clone of site, which no grant names: %v %v", clones, err) |
| 299 | } |
| 300 | }) |
| 301 | |
| 302 | t.Run("a project with no main is private", func(t *testing.T) { |
| 303 | v := newValley(t) |
| 304 | v.run("", "git", "init", "--quiet", "--bare", filepath.Join(v.srv, "fresh.git")) |
| 305 | list := v.runInput("", "app\nfresh\nsite\nvalley\n", "git", "-C", filepath.Join(v.srv, "valley.git"), "hash-object", "-w", "--stdin") |
| 306 | v.run("", "git", "-C", filepath.Join(v.srv, "valley.git"), "update-ref", projectsRef, strings.TrimSpace(list)) |
| 307 | v.grant(`"all"`) |
| 308 | stdout, _ := v.publish("--out", filepath.Join(t.TempDir(), "export")) |
| 309 | mustSay(t, "a project with no main", stdout, "exported: app; not exported: fresh, site, valley") |
| 310 | }) |
| 311 | } |
| 312 | |
| 313 | // Only a cue run that ends by refusing a document makes it invalid, and so |
| 314 | // private. A cue that is killed, that crashes or that runs past its timeout |
| 315 | // has read nothing, and the pass fails, sending and writing nothing: taken |
| 316 | // as invalid, the instance's registry would make every project private and |
| 317 | // take them all off the web. |
| 318 | func TestACueThatDoesNotFinishFailsThePass(t *testing.T) { |
| 319 | cases := []struct { |
| 320 | name, does, says string |
| 321 | timeout time.Duration |
| 322 | }{ |
| 323 | {name: "killed", does: "kill -KILL $$", says: "cue did not finish reading the document: signal: killed"}, |
| 324 | {name: "crashed", does: "echo 'panic: runtime error' >&2; exit 2", |
| 325 | says: "cue did not finish reading the document: exit status 2: panic: runtime error"}, |
| 326 | {name: "past its timeout", does: "exec sleep 60", says: "cue took longer than 3s", timeout: 3 * time.Second}, |
| 327 | } |
| 328 | for _, c := range cases { |
| 329 | t.Run(c.name, func(t *testing.T) { |
| 330 | v := newValley(t) |
| 331 | bash, cue := needTool(t, "bash"), needTool(t, "cue") |
| 332 | // Each schema is checked with cue over it alone; a document is |
| 333 | // read with cue over its schema and its files. |
| 334 | wrapper := filepath.Join(v.root, "bin", "cue") |
| 335 | v.write(wrapper, fmt.Sprintf("#!%s\nif [ \"$#\" -gt 4 ]; then %s; fi\nexec %s \"$@\"\n", bash, c.does, cue)) |
| 336 | if err := os.Chmod(wrapper, 0o755); err != nil { |
| 337 | t.Fatal(err) |
| 338 | } |
| 339 | if c.timeout != 0 { |
| 340 | was := cueTimeout |
| 341 | cueTimeout = c.timeout |
| 342 | t.Cleanup(func() { cueTimeout = was }) |
| 343 | } |
| 344 | said := v.fails(nil) |
| 345 | mustSay(t, c.name, said, "could not read the instance's identity registry") |
| 346 | mustSay(t, c.name, said, c.says) |
| 347 | }) |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | // The bundles of an export are held to --max-bundles together, and the |
| 352 | // state and the cache to --max-storage, before anything is sent. What a |
| 353 | // program prints is held to a bound: git's output past it fails the call, |
| 354 | // and a policy whose export is past cue's bound is invalid. |
| 355 | func TestBoundsStopThePass(t *testing.T) { |
| 356 | v := newValley(t) |
| 357 | rv := newReceiver(t, v) |
| 358 | mustSay(t, "--max-bundles", v.fails(rv, "--max-bundles", "100"), "app: its bundle is larger than the 100 bytes --max-bundles 100 leaves for it") |
| 359 | mustSay(t, "--max-storage", v.fails(nil, "--max-storage", "1K"), "more than --max-storage 1024") |
| 360 | for _, size := range []string{"0", "-1", "1X", "K", "9000000000T"} { |
| 361 | var stdout, stderr bytes.Buffer |
| 362 | if code := run(context.Background(), v.args("--out", t.TempDir(), "--max-bundles", size), &stdout, &stderr); code != 2 { |
| 363 | t.Errorf("--max-bundles %s: the pass exited %d, want 2", size, code) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | big := v.runInput("", strings.Repeat("x", maxGitOutput+1), "git", "-C", filepath.Join(v.srv, "app.git"), "hash-object", "-w", "--stdin") |
| 368 | if _, err := git(context.Background(), filepath.Join(v.srv, "app.git"), "cat-file", "blob", strings.TrimSpace(big)); !errors.Is(err, errTooLong) { |
| 369 | t.Errorf("git printing more than %d bytes returned %v, want errTooLong", maxGitOutput, err) |
| 370 | } |
| 371 | |
| 372 | v.declare("app", `import "list" |
| 373 | |
| 374 | project: "app" |
| 375 | identity: "`+identities["app"]+`" |
| 376 | readers: {for i in list.Range(0, 20000, 1) {"reader-with-a-long-name-for-the-bound-on-cue-output-\(i)": true}}`) |
| 377 | stdout, stderr := v.publish("--out", filepath.Join(t.TempDir(), "export")) |
| 378 | mustSay(t, "a policy past cue's bound", stdout, "exported: none") |
| 379 | mustSay(t, "a policy past cue's bound", stderr, "cue exported more than") |
| 380 | } |
| 381 | |
| 382 | // du is what the regular files under dirs hold together. A file that goes |
| 383 | // while it is counted is not counted. |
| 384 | func du(dirs ...string) int64 { |
| 385 | var total int64 |
| 386 | for _, dir := range dirs { |
| 387 | filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error { |
| 388 | if err == nil && d.Type().IsRegular() { |
| 389 | if info, err := d.Info(); err == nil { |
| 390 | total += info.Size() |
| 391 | } |
| 392 | } |
| 393 | return nil |
| 394 | }) |
| 395 | } |
| 396 | return total |
| 397 | } |
| 398 | |
| 399 | // peakSize runs f, and returns the most the files under dirs held together |
| 400 | // at any moment it looked while f ran. It looks again as soon as it has |
| 401 | // looked. |
| 402 | func peakSize(dirs []string, f func()) int64 { |
| 403 | done, peak := make(chan struct{}), make(chan int64) |
| 404 | go func() { |
| 405 | var most int64 |
| 406 | for { |
| 407 | most = max(most, du(dirs...)) |
| 408 | select { |
| 409 | case <-done: |
| 410 | peak <- most |
| 411 | return |
| 412 | default: |
| 413 | } |
| 414 | } |
| 415 | }() |
| 416 | f() |
| 417 | close(done) |
| 418 | return <-peak |
| 419 | } |
| 420 | |
| 421 | // A pass over its budget writes no more than the budget, and leaves no |
| 422 | // bundle behind. A bundle is written only into what --max-bundles and |
| 423 | // --max-storage leave, and its writing stops there. A pass whose state and |
| 424 | // cache are past --max-storage stops before it fetches anything, and that |
| 425 | // holds for a pass that would send nothing because the receiver |
| 426 | // acknowledged its digest. |
| 427 | func TestABundlePastTheBudgetIsNeverWritten(t *testing.T) { |
| 428 | v := newValley(t) |
| 429 | cache := filepath.Join(v.root, "cache") |
| 430 | bundles := filepath.Join(cache, "valley-web-publish", "bundles") |
| 431 | // What --max-storage bounds: the state directory, the publisher's |
| 432 | // cache, and the CLI's. |
| 433 | storage := []string{v.state, filepath.Join(cache, "valley-web-publish"), filepath.Join(cache, "valley")} |
| 434 | mustSay(t, "--max-storage 1", v.fails(nil, "--max-storage", "1"), "more than --max-storage 1,") |
| 435 | if _, err := os.Stat(filepath.Join(cache, "valley-web-publish")); !errors.Is(err, os.ErrNotExist) { |
| 436 | t.Errorf("a pass whose state was past --max-storage fetched before it stopped") |
| 437 | } |
| 438 | |
| 439 | // app's history grows by 4 MiB that do not compress, so its bundle is |
| 440 | // past every budget below. |
| 441 | noise := make([]byte, 4<<20) |
| 442 | if _, err := rand.Read(noise); err != nil { |
| 443 | t.Fatal(err) |
| 444 | } |
| 445 | v.write(filepath.Join(v.work["app"], "noise"), string(noise)) |
| 446 | v.commit("app", "app: a large history") |
| 447 | |
| 448 | // A cold cache with room for less than one shared repository refuses |
| 449 | // before writing it. The source history is much larger than the budget. |
| 450 | coldBudget := du(storage...) + 128 |
| 451 | var coldSaid string |
| 452 | coldPeak := peakSize(storage, func() { |
| 453 | coldSaid = v.fails(nil, "--max-storage", strconv.FormatInt(coldBudget, 10)) |
| 454 | }) |
| 455 | mustSay(t, "cold cache", coldSaid, "more than --max-storage") |
| 456 | if coldPeak > coldBudget { |
| 457 | t.Fatalf("cold cache reached %d bytes with budget %d", coldPeak, coldBudget) |
| 458 | } |
| 459 | if entries, _ := os.ReadDir(filepath.Join(cache, "valley-web-publish")); len(entries) != 0 { |
| 460 | t.Fatalf("cold refusal left partial data: %v", entries) |
| 461 | } |
| 462 | |
| 463 | var said string |
| 464 | peak := peakSize(storage, func() { said = v.fails(nil, "--max-bundles", "64K", "--max-storage", "256K") }) |
| 465 | mustSay(t, "--max-bundles", said, "app: its bundle is larger than the 65536 bytes --max-bundles 65536 leaves for it") |
| 466 | if peak > 256<<10 { |
| 467 | t.Errorf("the cold pass held %d bytes, more than --max-storage 262144", peak) |
| 468 | } |
| 469 | if left, _ := os.ReadDir(bundles); len(left) != 0 { |
| 470 | t.Errorf("the refused pass left %v behind in the bundles", left) |
| 471 | } |
| 472 | |
| 473 | publisherCache := filepath.Join(cache, "valley-web-publish") |
| 474 | if size := du(storage...); size > int64(len(noise))/16 { |
| 475 | t.Fatalf("shared cache grew to %d bytes for a %d-byte history", size, len(noise)) |
| 476 | } |
| 477 | for _, repo := range []string{"origin.git", "repos/app.git"} { |
| 478 | objects := filepath.Join(publisherCache, repo, "objects") |
| 479 | if _, err := os.Stat(filepath.Join(objects, "info", "alternates")); err != nil { |
| 480 | t.Fatal(err) |
| 481 | } |
| 482 | entries, err := os.ReadDir(objects) |
| 483 | if err != nil || len(entries) != 1 || entries[0].Name() != "info" { |
| 484 | t.Fatalf("cache copied objects: %v, %v", entries, err) |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | // The CLI has a clone of each project a grant to anyone names: app |
| 489 | // and site. |
| 490 | cliRepos := filepath.Join(cache, "valley", "repos") |
| 491 | entries, err := os.ReadDir(cliRepos) |
| 492 | if err != nil || len(entries) != 2 { |
| 493 | t.Fatalf("CLI caches: %v, %v", entries, err) |
| 494 | } |
| 495 | for _, entry := range entries { |
| 496 | objects := filepath.Join(cliRepos, entry.Name(), ".git", "objects") |
| 497 | files, err := os.ReadDir(objects) |
| 498 | if err != nil || len(files) != 1 || files[0].Name() != "info" { |
| 499 | t.Fatalf("CLI copied objects: %v, %v", files, err) |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | // The cache now holds what a read fetches, and the budget leaves |
| 504 | // 256 KiB beside it. |
| 505 | budget := du(storage...) + 256<<10 |
| 506 | peak = peakSize(storage, func() { said = v.fails(nil, "--max-storage", strconv.FormatInt(budget, 10)) }) |
| 507 | mustSay(t, "--max-storage", said, fmt.Sprintf("--max-storage %d leaves for it", budget)) |
| 508 | if peak > budget { |
| 509 | t.Errorf("the state and the cache held %d bytes while the pass ran, more than --max-storage %d", peak, budget) |
| 510 | } |
| 511 | if left, _ := os.ReadDir(bundles); len(left) != 0 { |
| 512 | t.Errorf("the refused pass left %v behind in the bundles", left) |
| 513 | } |
| 514 | |
| 515 | rv := newReceiver(t, v) |
| 516 | v.publish(rv.flags()...) |
| 517 | mustSay(t, "an acknowledged digest past --max-storage", v.fails(rv, "--max-storage", strconv.FormatInt(budget, 10)), |
| 518 | fmt.Sprintf("more than --max-storage %d", budget)) |
| 519 | } |
| 520 | |
| 521 | // objects is every object a repository holds, decompressed, as git |
| 522 | // cat-file --batch-all-objects prints them. |
| 523 | func (v *testValley) objects(repo string) string { |
| 524 | v.t.Helper() |
| 525 | return v.run("", "git", "-C", repo, "cat-file", "--batch-all-objects", "--batch") |
| 526 | } |
| 527 | |
| 528 | // unbundled is every object a bundle carries, decompressed. |
| 529 | func (v *testValley) unbundled(bundle string) string { |
| 530 | v.t.Helper() |
| 531 | repo := filepath.Join(v.t.TempDir(), "unbundled.git") |
| 532 | v.run("", "git", "init", "--quiet", "--bare", repo) |
| 533 | v.run("", "git", "-C", repo, "bundle", "unbundle", bundle) |
| 534 | return v.objects(repo) |
| 535 | } |
| 536 | |
| 537 | // noSentinels fails the test if any private sentinel appears in what. |
| 538 | func noSentinels(t *testing.T, where, what string) { |
| 539 | t.Helper() |
| 540 | for _, s := range []string{sentinelSource, sentinelBody, sentinelComment} { |
| 541 | if strings.Contains(what, s) { |
| 542 | t.Errorf("%s holds the private sentinel %s", where, s) |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | // inActive runs f over the generation the receiver serves. |
| 548 | func (rv *testReceiver) inActive(f func(export.Generation)) { |
| 549 | rv.t.Helper() |
| 550 | rv.mu.Lock() |
| 551 | defer rv.mu.Unlock() |
| 552 | g, release, err := rv.store.Open() |
| 553 | defer release() |
| 554 | if err != nil { |
| 555 | rv.t.Fatal(err) |
| 556 | } |
| 557 | f(g) |
| 558 | } |
| 559 | |
| 560 | // No private sentinel leaves the host: not in export.json, and not in any |
| 561 | // object of any bundle, whether the export is written to --out or |
| 562 | // uploaded and activated by a receiver. |
| 563 | func TestPrivateSentinelsNeverLeave(t *testing.T) { |
| 564 | v := newValley(t) |
| 565 | held := v.objects(filepath.Join(v.srv, "site.git")) |
| 566 | for _, s := range []string{sentinelSource, sentinelBody, sentinelComment} { |
| 567 | if !strings.Contains(held, s) { |
| 568 | t.Fatalf("site's repository does not hold the sentinel %s, so the test proves nothing", s) |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | dir, _, _ := v.out() |
| 573 | data, err := os.ReadFile(filepath.Join(dir, export.ExportFile)) |
| 574 | if err != nil { |
| 575 | t.Fatal(err) |
| 576 | } |
| 577 | noSentinels(t, "--out's export.json", string(data)) |
| 578 | bundles, _ := filepath.Glob(filepath.Join(dir, "bundles", "*")) |
| 579 | if len(bundles) != 1 { |
| 580 | t.Fatalf("--out holds the bundles %v, want app's alone", bundles) |
| 581 | } |
| 582 | noSentinels(t, "--out's bundle of app", v.unbundled(bundles[0])) |
| 583 | |
| 584 | rv := newReceiver(t, v) |
| 585 | v.publish(rv.flags()...) |
| 586 | rv.inActive(func(g export.Generation) { |
| 587 | data, err := os.ReadFile(g.ExportPath()) |
| 588 | if err != nil { |
| 589 | t.Fatal(err) |
| 590 | } |
| 591 | noSentinels(t, "the receiver's export.json", string(data)) |
| 592 | repos, _ := filepath.Glob(filepath.Join(g.Dir, "repos", "*")) |
| 593 | if len(repos) != 1 { |
| 594 | t.Fatalf("the receiver serves the repositories %v, want app's alone", repos) |
| 595 | } |
| 596 | noSentinels(t, "the receiver's repository of app", v.objects(repos[0])) |
| 597 | }) |
| 598 | } |
| 599 | |
| 600 | // A project that loses one of two readers stays on the edge for the other. |
| 601 | // One that loses its last reader is gone from the next export the |
| 602 | // receiver activates: from export.json and from its repositories. |
| 603 | func TestAProjectMadePrivateLeavesTheReceiver(t *testing.T) { |
| 604 | v := newValley(t) |
| 605 | rv := newReceiver(t, v) |
| 606 | v.declare("site", policy("site", "anyone", "operator")) |
| 607 | v.publish(rv.flags()...) |
| 608 | if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app", "site"}) { |
| 609 | t.Fatalf("the receiver serves %v, want app and site", got) |
| 610 | } |
| 611 | |
| 612 | v.declare("site", policy("site", "operator")) |
| 613 | stdout, _ := v.publish(rv.flags()...) |
| 614 | mustSay(t, "site read by the operator alone", stdout, "site to operator") |
| 615 | if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app", "site"}) { |
| 616 | t.Errorf("the receiver serves %v once anyone may not read site, want app and site", got) |
| 617 | } |
| 618 | |
| 619 | v.declare("site", policy("site")) |
| 620 | stdout, _ = v.publish(rv.flags()...) |
| 621 | mustSay(t, "site made private", stdout, "exported: app; not exported: site, valley") |
| 622 | if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app"}) { |
| 623 | t.Errorf("the receiver serves %v once no one may read site, want app alone", got) |
| 624 | } |
| 625 | rv.inActive(func(g export.Generation) { |
| 626 | repo, _ := g.Repo("site") |
| 627 | if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) { |
| 628 | t.Errorf("the receiver's active generation still holds site's repository") |
| 629 | } |
| 630 | data, err := os.ReadFile(g.ExportPath()) |
| 631 | if err != nil { |
| 632 | t.Fatal(err) |
| 633 | } |
| 634 | noSentinels(t, "the receiver's export.json once site is private", string(data)) |
| 635 | }) |
| 636 | } |
| 637 | |
| 638 | // landedChangeID is a change of app's that the integrator lands as a new |
| 639 | // commit, so only its transfer statement shows it landed. |
| 640 | const landedChangeID = "kpqrstuvwxyzkpqrstuvwxyzkpqrstuv" |
| 641 | |
| 642 | // publishSigners publishes, in the instance repository, the signers a |
| 643 | // client verifies the integrator's landings with, as the host's signers |
| 644 | // publisher writes them: a tree at refs/the-valley/signers holding the |
| 645 | // known-signers file and the integrator's name. The integrator's key is |
| 646 | // made here; its verifier line is the file's one line. |
| 647 | func (v *testValley) publishSigners(name string) (key string) { |
| 648 | v.t.Helper() |
| 649 | key = filepath.Join(v.root, "integrator.key") |
| 650 | v.run("", "ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "integrator", "-f", key) |
| 651 | instance := filepath.Join(v.srv, "valley.git") |
| 652 | keys := v.runInput("", v.run("", "attest", "key", "--key", key, "--name", name), "git", "-C", instance, "hash-object", "-w", "--stdin") |
| 653 | named := v.runInput("", name, "git", "-C", instance, "hash-object", "-w", "--stdin") |
| 654 | tree := v.runInput("", fmt.Sprintf("100644 blob %s\tintegrator-name\n100644 blob %s\tknown-signers\n", |
| 655 | strings.TrimSpace(named), strings.TrimSpace(keys)), "git", "-C", instance, "mktree") |
| 656 | v.run("", "git", "-C", instance, "update-ref", "refs/the-valley/signers", strings.TrimSpace(tree)) |
| 657 | return key |
| 658 | } |
| 659 | |
| 660 | // landByIntegration readies a change on app and lands it as the |
| 661 | // integrator does: a new commit on main, the outcome record, and the |
| 662 | // transfer statement, signed with key under name. |
| 663 | func (v *testValley) landByIntegration(key, name string) { |
| 664 | v.t.Helper() |
| 665 | work, bare := v.work["app"], filepath.Join(v.srv, "app.git") |
| 666 | v.run(work, "git", "checkout", "--quiet", "-b", "landed", "main") |
| 667 | v.write(filepath.Join(work, "landed.txt"), "landed\n") |
| 668 | v.run(work, "git", "add", "landed.txt") |
| 669 | v.run(work, "git", "commit", "--quiet", "-m", "app: a change the integrator lands") |
| 670 | head := strings.TrimSpace(v.run(work, "git", "rev-parse", "HEAD")) |
| 671 | v.run(work, "git", "push", "--quiet", "origin", "landed") |
| 672 | v.valley("app", "ready", "--change", landedChangeID, "landed") |
| 673 | // main moves on first, so the landing is a new commit and never the |
| 674 | // change's head. |
| 675 | v.run(work, "git", "checkout", "--quiet", "main") |
| 676 | v.write(filepath.Join(work, "moved.txt"), "moved\n") |
| 677 | v.commit("app", "app: main moves on") |
| 678 | tip := strings.TrimSpace(v.run(work, "git", "rev-parse", "main")) |
| 679 | v.run(work, "git", "checkout", "--quiet", "-b", "landing", "main") |
| 680 | v.run(work, "git", "cherry-pick", head) |
| 681 | landed := strings.TrimSpace(v.run(work, "git", "rev-parse", "HEAD")) |
| 682 | v.run(work, "git", "push", "--quiet", "origin", "landing:main") |
| 683 | v.run(work, "git", "checkout", "--quiet", "main") |
| 684 | v.run(work, "git", "pull", "--quiet", "--ff-only", "origin", "main") |
| 685 | |
| 686 | request := "c-" + landedChangeID |
| 687 | memo := v.runInput("", fmt.Sprintf("%s %s 0123456789abcdef land\n", head, tip), "git", "-C", bare, "hash-object", "-w", "--stdin") |
| 688 | v.run("", "git", "-C", bare, "update-ref", "refs/the-valley/integration-outcomes/main/"+request, strings.TrimSpace(memo)) |
| 689 | digest := func(rev string) string { |
| 690 | out := strings.TrimSpace(v.run("", "attest", "digest", "--repo", work, "--rev", rev)) |
| 691 | _, d, _ := strings.Cut(out, ":") |
| 692 | return d |
| 693 | } |
| 694 | statement, err := json.Marshal(map[string]any{ |
| 695 | "statementType": "the-valley/attestation/v1", |
| 696 | "subject": map[string]any{"primary": "valley-tree-v1", |
| 697 | "digest": map[string]string{"valley-tree-v1": digest(landed), "git-sha1": landed}}, |
| 698 | "predicateType": "the-valley/integration/transfer/v1", |
| 699 | "predicate": map[string]any{"change": request, "target": "refs/heads/main", |
| 700 | "base": map[string]string{"valley-tree-v1": digest(head)}, |
| 701 | "policy": map[string]string{"sha256": strings.Repeat("ab", 32), "git-sha1": tip}, "required": "none"}, |
| 702 | }) |
| 703 | if err != nil { |
| 704 | v.t.Fatal(err) |
| 705 | } |
| 706 | path := filepath.Join(v.root, "statement.json") |
| 707 | v.write(path, string(statement)) |
| 708 | note := v.runInput("", v.run("", "attest", "render", path), "attest", "sign", "--key", key, "--name", name) |
| 709 | blob := v.runInput("", note, "git", "-C", bare, "hash-object", "-w", "--stdin") |
| 710 | tree := v.runInput("", "100644 blob "+strings.TrimSpace(blob)+"\ttransfer.note\n", "git", "-C", bare, "mktree") |
| 711 | // The ref is named for the signer's key hash, as the integrator names |
| 712 | // its own. |
| 713 | hash := strings.Split(strings.TrimSpace(v.run("", "attest", "key", "--key", key, "--name", name)), "+")[1] |
| 714 | v.run("", "git", "-C", bare, "update-ref", |
| 715 | fmt.Sprintf("refs/the-valley/attestations/%s/%s", digest(landed), hash), strings.TrimSpace(tree)) |
| 716 | } |
| 717 | |
| 718 | // The CLI the publisher runs verifies a landing with the signers the |
| 719 | // instance repository publishes, and with nothing the caller's environment |
| 720 | // names: a landed change is not exported as ready for approval. Without |
| 721 | // the publication the landing is not believed, and the change is. |
| 722 | func TestLandingsAreVerifiedWithThePublishedSigners(t *testing.T) { |
| 723 | v := newValley(t) |
| 724 | needTool(t, "attest") |
| 725 | needTool(t, "ssh-keygen") |
| 726 | const signer = "valley-host/integration" |
| 727 | key := v.publishSigners(signer) |
| 728 | v.landByIntegration(key, signer) |
| 729 | |
| 730 | // The caller's own material names the signer with another key, under |
| 731 | // which the statement would not verify. |
| 732 | other := filepath.Join(v.root, "other.key") |
| 733 | v.run("", "ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "other", "-f", other) |
| 734 | otherSigners := filepath.Join(v.root, "other-signers") |
| 735 | v.write(otherSigners, v.run("", "attest", "key", "--key", other, "--name", signer)) |
| 736 | t.Setenv("VALLEY_KNOWN_SIGNERS", otherSigners) |
| 737 | t.Setenv("VALLEY_INTEGRATOR_SIGNER", signer) |
| 738 | |
| 739 | changes := func() []string { |
| 740 | _, _, e := v.out() |
| 741 | ids := []string{} |
| 742 | for _, c := range e.Projects[0].Changes { |
| 743 | ids = append(ids, c.ChangeID) |
| 744 | } |
| 745 | return ids |
| 746 | } |
| 747 | if got := changes(); !reflect.DeepEqual(got, []string{changeID}) { |
| 748 | t.Errorf("with the published signers, app's changes ready for approval are %v, want %s alone", got, changeID) |
| 749 | } |
| 750 | v.run("", "git", "-C", filepath.Join(v.srv, "valley.git"), "update-ref", "-d", "refs/the-valley/signers") |
| 751 | got := changes() |
| 752 | if len(got) != 2 || !strings.Contains(strings.Join(got, " "), landedChangeID) { |
| 753 | t.Errorf("with no published signers, app's changes ready for approval are %v, want the landed change among them", got) |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | // A refresh reserves the entire replacement while the old cache remains. |
| 758 | // Refusal leaves the old readable snapshot intact and no staged files. |
| 759 | func TestSharedCacheRefreshBudget(t *testing.T) { |
| 760 | v := newValley(t) |
| 761 | cache := filepath.Join(v.root, "shared-cache") |
| 762 | p := &publisher{cache: cache, cfg: config{state: v.state, maxStorage: 1 << 20}} |
| 763 | dir := filepath.Join(cache, "app.git") |
| 764 | source := filepath.Join(v.srv, "app.git") |
| 765 | refs := map[string]string{"refs/heads/main": "refs/heads/main"} |
| 766 | ctx := context.Background() |
| 767 | if _, err := p.shareRepository(ctx, dir, source, refs); err != nil { |
| 768 | t.Fatal(err) |
| 769 | } |
| 770 | old, err := revParse(ctx, dir, "refs/heads/main") |
| 771 | if err != nil { |
| 772 | t.Fatal(err) |
| 773 | } |
| 774 | v.write(filepath.Join(v.work["app"], "next"), "next") |
| 775 | v.commit("app", "app: next") |
| 776 | used, err := p.storageUsed() |
| 777 | if err != nil { |
| 778 | t.Fatal(err) |
| 779 | } |
| 780 | p.cfg.maxStorage = byteSize(used) |
| 781 | if _, err := p.shareRepository(ctx, dir, source, refs); err == nil { |
| 782 | t.Fatal("refresh exceeded its budget") |
| 783 | } |
| 784 | if tip, err := revParse(ctx, dir, "refs/heads/main"); err != nil || tip != old { |
| 785 | t.Fatalf("refused refresh changed the cache: %s, %v", tip, err) |
| 786 | } |
| 787 | if entries, err := os.ReadDir(cache); err != nil || len(entries) != 1 { |
| 788 | t.Fatalf("refused refresh left partial data: %v, %v", entries, err) |
| 789 | } |
| 790 | p.cfg.maxStorage = 1 << 20 |
| 791 | if _, err := p.shareRepository(ctx, dir, source, refs); err != nil { |
| 792 | t.Fatal(err) |
| 793 | } |
| 794 | if tip, err := revParse(ctx, dir, "refs/heads/main"); err != nil || tip == old { |
| 795 | t.Fatalf("refresh did not advance main: %s, %v", tip, err) |
| 796 | } |
| 797 | } |
| 798 | |
| 799 | // A cache's refs are read from the source by their exact names. With main |
| 800 | // gone from app and refs/heads/refs/heads/main made in its place, git |
| 801 | // rev-parse would read that branch as main; sharedFiles finds no main. The |
| 802 | // publisher lists a project's main before it reads it, so only a push |
| 803 | // between the two reaches this. |
| 804 | func TestSharedFilesReadEachRefByItsExactName(t *testing.T) { |
| 805 | v := newValley(t) |
| 806 | source := filepath.Join(v.srv, "app.git") |
| 807 | v.run("", "git", "-C", source, "update-ref", "refs/heads/refs/heads/main", "refs/heads/main") |
| 808 | v.run("", "git", "-C", source, "update-ref", "-d", "refs/heads/main") |
| 809 | files, err := sharedFiles(context.Background(), source, map[string]string{"refs/heads/main": "refs/heads/main"}) |
| 810 | if err == nil || err.Error() != source+" holds no refs/heads/main" { |
| 811 | t.Fatalf("with app's main gone, the cache's files are %v (%v)", files, err) |
| 812 | } |
| 813 | } |
| 814 | |
| 815 | // Refusing a pointer replacement leaves the previous pointer readable. |
| 816 | func TestPointerBudget(t *testing.T) { |
| 817 | v := newValley(t) |
| 818 | cache := filepath.Join(v.root, "cache", "valley-web-publish") |
| 819 | p := &publisher{cache: cache, pointer: filepath.Join(cache, "_pointer.git"), cfg: config{instanceRepo: filepath.Join(v.srv, "valley.git"), state: v.state, maxStorage: 1}} |
| 820 | ctx := context.Background() |
| 821 | if err := p.preparePointer(ctx); err == nil { |
| 822 | t.Fatal("cold pointer exceeded budget") |
| 823 | } |
| 824 | if entries, _ := os.ReadDir(cache); len(entries) != 0 { |
| 825 | t.Fatalf("partial pointer: %v", entries) |
| 826 | } |
| 827 | p.cfg.maxStorage = 1 << 20 |
| 828 | if err := p.preparePointer(ctx); err != nil { |
| 829 | t.Fatal(err) |
| 830 | } |
| 831 | tip, err := revParse(ctx, p.pointer, "refs/heads/main") |
| 832 | if err != nil { |
| 833 | t.Fatal(err) |
| 834 | } |
| 835 | used, err := p.storageUsed() |
| 836 | if err != nil { |
| 837 | t.Fatal(err) |
| 838 | } |
| 839 | p.cfg.maxStorage = byteSize(used) |
| 840 | if err := p.preparePointer(ctx); err == nil { |
| 841 | t.Fatal("warm pointer exceeded budget") |
| 842 | } |
| 843 | if got, err := revParse(ctx, p.pointer, "refs/heads/main"); err != nil || got != tip { |
| 844 | t.Fatalf("pointer changed: %s, %v", got, err) |
| 845 | } |
| 846 | if entries, _ := os.ReadDir(cache); len(entries) != 1 { |
| 847 | t.Fatalf("partial pointer: %v", entries) |
| 848 | } |
| 849 | } |
| 850 | |
| 851 | // The CLI's cache must be complete enough for cacheComplete to reuse it, |
| 852 | // and a refusal must leave no repository for the CLI to mistake as complete. |
| 853 | func TestCLICacheBudget(t *testing.T) { |
| 854 | v := newValley(t) |
| 855 | cache := filepath.Join(v.root, "cache", "valley-web-publish") |
| 856 | p := &publisher{cache: cache, cfg: config{instanceRepo: filepath.Join(v.srv, "valley.git"), state: v.state, maxStorage: 1}} |
| 857 | ctx := context.Background() |
| 858 | if err := p.prepareCLICaches(ctx, []string{"app"}); err == nil { |
| 859 | t.Fatal("cold CLI cache exceeded budget") |
| 860 | } |
| 861 | root := filepath.Join(v.root, "cache", "valley", "repos") |
| 862 | if entries, _ := os.ReadDir(root); len(entries) != 0 { |
| 863 | t.Fatalf("partial CLI cache: %v", entries) |
| 864 | } |
| 865 | p.cfg.maxStorage = 1 << 20 |
| 866 | if err := p.prepareCLICaches(ctx, []string{"app"}); err != nil { |
| 867 | t.Fatal(err) |
| 868 | } |
| 869 | entries, err := os.ReadDir(root) |
| 870 | if err != nil || len(entries) != 1 { |
| 871 | t.Fatalf("CLI cache: %v, %v", entries, err) |
| 872 | } |
| 873 | dir := filepath.Join(root, entries[0].Name()) |
| 874 | got := strings.TrimSpace(v.run(dir, "git", "config", "--file", ".git/config", "--get", "remote.origin.url")) |
| 875 | if got != filepath.Join(v.srv, "app.git") { |
| 876 | t.Fatalf("CLI cache origin: %q", got) |
| 877 | } |
| 878 | used, err := p.storageUsed() |
| 879 | if err != nil { |
| 880 | t.Fatal(err) |
| 881 | } |
| 882 | p.cfg.maxStorage = byteSize(used) |
| 883 | if err := p.prepareCLICaches(ctx, []string{"app"}); err == nil { |
| 884 | t.Fatal("warm CLI cache exceeded budget") |
| 885 | } |
| 886 | if after, _ := p.storageUsed(); after != used { |
| 887 | t.Fatalf("refusal changed storage: %d -> %d", used, after) |
| 888 | } |
| 889 | if entries, _ := os.ReadDir(root); len(entries) != 1 { |
| 890 | t.Fatalf("partial CLI replacement: %v", entries) |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | // Neither live discovery nor a foreign knot edge may make an unshared |
| 895 | // cache after the publisher has staged its snapshot's project list. |
| 896 | func TestUnstagedCLICachesCannotGrowStorage(t *testing.T) { |
| 897 | if os.Geteuid() == 0 { |
| 898 | t.Skip("directory permissions require an unprivileged user") |
| 899 | } |
| 900 | for _, added := range []bool{false, true} { |
| 901 | t.Run(fmt.Sprintf("added during collection %v", added), func(t *testing.T) { |
| 902 | v := newValley(t) |
| 903 | foreign := filepath.Join(v.srv, "unlisted.git") |
| 904 | v.run("", "git", "init", "--quiet", "--bare", foreign) |
| 905 | noise := make([]byte, 4<<20) |
| 906 | if _, err := rand.Read(noise); err != nil { |
| 907 | t.Fatal(err) |
| 908 | } |
| 909 | blob := strings.TrimSpace(v.runInput("", string(noise), "git", "-C", foreign, "hash-object", "-w", "--stdin")) |
| 910 | tree := strings.TrimSpace(v.runInput("", "100644 blob "+blob+"\tnoise\n", "git", "-C", foreign, "mktree")) |
| 911 | commit := strings.TrimSpace(v.runInput("", "large history\n", "git", "-C", foreign, "commit-tree", tree)) |
| 912 | for _, ref := range []string{"refs/heads/main", "refs/the-valley/knots"} { |
| 913 | v.run("", "git", "-C", foreign, "update-ref", ref, commit) |
| 914 | } |
| 915 | if !added { |
| 916 | v.newKnot("app", "outcome", "Wait for external work", "--blocked-by", "unlisted:oc-a000001") |
| 917 | } else { |
| 918 | instance := filepath.Join(v.srv, "valley.git") |
| 919 | list := strings.TrimSpace(v.runInput("", "app\nsite\nunlisted\nvalley\n", "git", "-C", instance, "hash-object", "-w", "--stdin")) |
| 920 | wrapper := filepath.Join(v.root, "bin", "valley") |
| 921 | data, err := os.ReadFile(wrapper) |
| 922 | if err != nil { |
| 923 | t.Fatal(err) |
| 924 | } |
| 925 | shebang, rest, _ := strings.Cut(string(data), "\n") |
| 926 | v.write(wrapper, fmt.Sprintf("%s\ngit -C %s update-ref %s %s\n%s", shebang, instance, projectsRef, list, rest)) |
| 927 | } |
| 928 | cache := filepath.Join(v.root, "cache") |
| 929 | if err := os.RemoveAll(cache); err != nil { |
| 930 | t.Fatal(err) |
| 931 | } |
| 932 | repos := filepath.Join(cache, "valley", "repos") |
| 933 | // Remove an obsolete complete cache and recover a parent sealed |
| 934 | // by an interrupted earlier pass before staging the new set. |
| 935 | sum := sha256.Sum256([]byte(foreign)) |
| 936 | stale := filepath.Join(repos, fmt.Sprintf("%x-unlisted", sum[:8])) |
| 937 | v.run("", "git", "init", "--quiet", stale) |
| 938 | v.run(stale, "git", "remote", "add", "origin", foreign) |
| 939 | |
| 940 | if err := os.Chmod(repos, 0o500); err != nil { |
| 941 | t.Fatal(err) |
| 942 | } |
| 943 | const budget = 256 << 10 |
| 944 | storage := []string{v.state, filepath.Join(cache, "valley"), filepath.Join(cache, "valley-web-publish")} |
| 945 | peak := peakSize(storage, func() { |
| 946 | if added { |
| 947 | mustSay(t, "new project", v.fails(nil, "--max-storage", "256K"), "valley plan --all lists") |
| 948 | } else { |
| 949 | v.publish("--out", filepath.Join(v.root, "export"), "--max-storage", "256K") |
| 950 | } |
| 951 | }) |
| 952 | if peak > budget { |
| 953 | t.Fatalf("storage reached %d bytes, budget %d", peak, budget) |
| 954 | } |
| 955 | // app and site, the projects a grant to anyone names. |
| 956 | entries, err := os.ReadDir(repos) |
| 957 | if err != nil || len(entries) != 2 { |
| 958 | t.Fatalf("unstaged caches: %v, %v", entries, err) |
| 959 | } |
| 960 | for _, entry := range entries { |
| 961 | if strings.HasSuffix(entry.Name(), "-unlisted") || entry.Name() == "obsolete" { |
| 962 | t.Fatalf("unstaged cache %s", entry.Name()) |
| 963 | } |
| 964 | objects, err := os.ReadDir(filepath.Join(repos, entry.Name(), ".git", "objects")) |
| 965 | if err != nil || len(objects) != 1 || objects[0].Name() != "info" { |
| 966 | t.Fatalf("copied objects: %v, %v", objects, err) |
| 967 | } |
| 968 | } |
| 969 | info, err := os.Stat(repos) |
| 970 | if err != nil { |
| 971 | t.Fatal(err) |
| 972 | } |
| 973 | if info.Mode().Perm() != 0o700 { |
| 974 | t.Fatalf("cache parent remains sealed: %v", info.Mode()) |
| 975 | } |
| 976 | }) |
| 977 | } |
| 978 | } |