gunk-dev/the-valley

read_test.go

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