gunk-dev/the-valley

read_test.go

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