gunk-dev/the-valley

read_test.go

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