gunk-dev/the-valley

read_test.go

source122dfe2eac3dmain's published tip history
29.6 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: the pending listing could not read it",
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: "valley plan --all lists _pointer, and the instance repository publishes app, not a name, site, valley",
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([]string{bundles}, func() { said = v.fails(nil, "--max-bundles", "64K") })
418 mustSay(t, "--max-bundles", said, "app: its bundle is larger than the 65536 bytes --max-bundles 65536 leaves for it")
419 if peak > 64<<10 {
420 t.Errorf("the bundles held %d bytes while the pass ran, more than --max-bundles 65536", 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(publisherCache); 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 // The cache now holds what a read fetches, and the budget leaves
442 // 256 KiB beside it.
443 budget := du(storage...) + 256<<10
444 peak = peakSize(storage, func() { said = v.fails(nil, "--max-storage", strconv.FormatInt(budget, 10)) })
445 mustSay(t, "--max-storage", said, fmt.Sprintf("--max-storage %d leaves for it", budget))
446 if peak > budget {
447 t.Errorf("the state and the cache held %d bytes while the pass ran, more than --max-storage %d", peak, budget)
448 }
449 if left, _ := os.ReadDir(bundles); len(left) != 0 {
450 t.Errorf("the refused pass left %v behind in the bundles", left)
451 }
452
453 rv := newReceiver(t, v)
454 v.publish("--receiver", rv.server.URL)
455 mustSay(t, "an acknowledged digest past --max-storage", v.fails(rv, "--max-storage", strconv.FormatInt(budget, 10)),
456 fmt.Sprintf("more than --max-storage %d", budget))
457}
458
459// objects is every object a repository holds, decompressed, as git
460// cat-file --batch-all-objects prints them.
461func (v *testValley) objects(repo string) string {
462 v.t.Helper()
463 return v.run("", "git", "-C", repo, "cat-file", "--batch-all-objects", "--batch")
464}
465
466// unbundled is every object a bundle carries, decompressed.
467func (v *testValley) unbundled(bundle string) string {
468 v.t.Helper()
469 repo := filepath.Join(v.t.TempDir(), "unbundled.git")
470 v.run("", "git", "init", "--quiet", "--bare", repo)
471 v.run("", "git", "-C", repo, "bundle", "unbundle", bundle)
472 return v.objects(repo)
473}
474
475// noSentinels fails the test if any private sentinel appears in what.
476func noSentinels(t *testing.T, where, what string) {
477 t.Helper()
478 for _, s := range []string{sentinelSource, sentinelBody, sentinelComment} {
479 if strings.Contains(what, s) {
480 t.Errorf("%s holds the private sentinel %s", where, s)
481 }
482 }
483}
484
485// inActive runs f over the generation the receiver serves.
486func (rv *testReceiver) inActive(f func(export.Generation)) {
487 rv.t.Helper()
488 rv.mu.Lock()
489 defer rv.mu.Unlock()
490 g, release, err := rv.store.Open()
491 defer release()
492 if err != nil {
493 rv.t.Fatal(err)
494 }
495 f(g)
496}
497
498// No private sentinel leaves the host: not in export.json, and not in any
499// object of any bundle, whether the export is written to --out or
500// uploaded and activated by a receiver.
501func TestPrivateSentinelsNeverLeave(t *testing.T) {
502 v := newValley(t)
503 held := v.objects(filepath.Join(v.srv, "site.git"))
504 for _, s := range []string{sentinelSource, sentinelBody, sentinelComment} {
505 if !strings.Contains(held, s) {
506 t.Fatalf("site's repository does not hold the sentinel %s, so the test proves nothing", s)
507 }
508 }
509
510 dir, _, _ := v.out()
511 data, err := os.ReadFile(filepath.Join(dir, export.ExportFile))
512 if err != nil {
513 t.Fatal(err)
514 }
515 noSentinels(t, "--out's export.json", string(data))
516 bundles, _ := filepath.Glob(filepath.Join(dir, "bundles", "*"))
517 if len(bundles) != 1 {
518 t.Fatalf("--out holds the bundles %v, want app's alone", bundles)
519 }
520 noSentinels(t, "--out's bundle of app", v.unbundled(bundles[0]))
521
522 rv := newReceiver(t, v)
523 v.publish("--receiver", rv.server.URL)
524 rv.inActive(func(g export.Generation) {
525 data, err := os.ReadFile(g.ExportPath())
526 if err != nil {
527 t.Fatal(err)
528 }
529 noSentinels(t, "the receiver's export.json", string(data))
530 repos, _ := filepath.Glob(filepath.Join(g.Dir, "repos", "*"))
531 if len(repos) != 1 {
532 t.Fatalf("the receiver serves the repositories %v, want app's alone", repos)
533 }
534 noSentinels(t, "the receiver's repository of app", v.objects(repos[0]))
535 })
536}
537
538// A project that declares itself private again is gone from the next
539// export the receiver activates: from export.json and from its
540// repositories.
541func TestAProjectMadePrivateLeavesTheReceiver(t *testing.T) {
542 v := newValley(t)
543 rv := newReceiver(t, v)
544 v.declare("site", `project: visibility: "public"`)
545 v.publish("--receiver", rv.server.URL)
546 if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app", "site"}) {
547 t.Fatalf("the receiver serves %v, want app and site", got)
548 }
549
550 v.declare("site", `project: visibility: "private"`)
551 stdout, _ := v.publish("--receiver", rv.server.URL)
552 mustSay(t, "site made private", stdout, "public: app; private: site, valley")
553 if got := names(rv.active()); !reflect.DeepEqual(got, []string{"app"}) {
554 t.Errorf("the receiver serves %v once site is private, want app alone", got)
555 }
556 rv.inActive(func(g export.Generation) {
557 repo, _ := g.Repo("site")
558 if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) {
559 t.Errorf("the receiver's active generation still holds site's repository")
560 }
561 data, err := os.ReadFile(g.ExportPath())
562 if err != nil {
563 t.Fatal(err)
564 }
565 noSentinels(t, "the receiver's export.json once site is private", string(data))
566 })
567}
568
569// landedChangeID is a change of app's that the integrator lands as a new
570// commit, so only its transfer statement shows it landed.
571const landedChangeID = "kpqrstuvwxyzkpqrstuvwxyzkpqrstuv"
572
573// publishSigners publishes, in the instance repository, the signers a
574// client verifies the integrator's landings with, as the host's signers
575// publisher writes them: a tree at refs/the-valley/signers holding the
576// known-signers file and the integrator's name. The integrator's key is
577// made here; its verifier line is the file's one line.
578func (v *testValley) publishSigners(name string) (key string) {
579 v.t.Helper()
580 key = filepath.Join(v.root, "integrator.key")
581 v.run("", "ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "integrator", "-f", key)
582 instance := filepath.Join(v.srv, "valley.git")
583 keys := v.runInput("", v.run("", "attest", "key", "--key", key, "--name", name), "git", "-C", instance, "hash-object", "-w", "--stdin")
584 named := v.runInput("", name, "git", "-C", instance, "hash-object", "-w", "--stdin")
585 tree := v.runInput("", fmt.Sprintf("100644 blob %s\tintegrator-name\n100644 blob %s\tknown-signers\n",
586 strings.TrimSpace(named), strings.TrimSpace(keys)), "git", "-C", instance, "mktree")
587 v.run("", "git", "-C", instance, "update-ref", "refs/the-valley/signers", strings.TrimSpace(tree))
588 return key
589}
590
591// landByIntegration readies a change on app and lands it as the
592// integrator does: a new commit on main, the outcome record, and the
593// transfer statement, signed with key under name.
594func (v *testValley) landByIntegration(key, name string) {
595 v.t.Helper()
596 work, bare := v.work["app"], filepath.Join(v.srv, "app.git")
597 v.run(work, "git", "checkout", "--quiet", "-b", "landed", "main")
598 v.write(filepath.Join(work, "landed.txt"), "landed\n")
599 v.run(work, "git", "add", "landed.txt")
600 v.run(work, "git", "commit", "--quiet", "-m", "app: a change the integrator lands")
601 head := strings.TrimSpace(v.run(work, "git", "rev-parse", "HEAD"))
602 v.run(work, "git", "push", "--quiet", "origin", "landed")
603 v.valley("app", "ready", "--change", landedChangeID, "landed")
604 // main moves on first, so the landing is a new commit and never the
605 // change's head.
606 v.run(work, "git", "checkout", "--quiet", "main")
607 v.write(filepath.Join(work, "moved.txt"), "moved\n")
608 v.commit("app", "app: main moves on")
609 tip := strings.TrimSpace(v.run(work, "git", "rev-parse", "main"))
610 v.run(work, "git", "checkout", "--quiet", "-b", "landing", "main")
611 v.run(work, "git", "cherry-pick", head)
612 landed := strings.TrimSpace(v.run(work, "git", "rev-parse", "HEAD"))
613 v.run(work, "git", "push", "--quiet", "origin", "landing:main")
614 v.run(work, "git", "checkout", "--quiet", "main")
615 v.run(work, "git", "pull", "--quiet", "--ff-only", "origin", "main")
616
617 request := "c-" + landedChangeID
618 memo := v.runInput("", fmt.Sprintf("%s %s 0123456789abcdef land\n", head, tip), "git", "-C", bare, "hash-object", "-w", "--stdin")
619 v.run("", "git", "-C", bare, "update-ref", "refs/the-valley/integration-outcomes/main/"+request, strings.TrimSpace(memo))
620 digest := func(rev string) string {
621 out := strings.TrimSpace(v.run("", "attest", "digest", "--repo", work, "--rev", rev))
622 _, d, _ := strings.Cut(out, ":")
623 return d
624 }
625 statement, err := json.Marshal(map[string]any{
626 "statementType": "the-valley/attestation/v1",
627 "subject": map[string]any{"primary": "valley-tree-v1",
628 "digest": map[string]string{"valley-tree-v1": digest(landed), "git-sha1": landed}},
629 "predicateType": "the-valley/integration/transfer/v1",
630 "predicate": map[string]any{"change": request, "target": "refs/heads/main",
631 "base": map[string]string{"valley-tree-v1": digest(head)},
632 "policy": map[string]string{"sha256": strings.Repeat("ab", 32), "git-sha1": tip}, "required": "none"},
633 })
634 if err != nil {
635 v.t.Fatal(err)
636 }
637 path := filepath.Join(v.root, "statement.json")
638 v.write(path, string(statement))
639 note := v.runInput("", v.run("", "attest", "render", path), "attest", "sign", "--key", key, "--name", name)
640 blob := v.runInput("", note, "git", "-C", bare, "hash-object", "-w", "--stdin")
641 tree := v.runInput("", "100644 blob "+strings.TrimSpace(blob)+"\ttransfer.note\n", "git", "-C", bare, "mktree")
642 v.run("", "git", "-C", bare, "update-ref",
643 fmt.Sprintf("refs/the-valley/attestations/%s/%08x", digest(landed), len(name)), strings.TrimSpace(tree))
644}
645
646// The CLI the publisher runs verifies a landing with the signers the
647// instance repository publishes, and with nothing the caller's environment
648// names: a landed change is not exported as ready for approval. Without
649// the publication the landing is not believed, and the change is.
650func TestLandingsAreVerifiedWithThePublishedSigners(t *testing.T) {
651 v := newValley(t)
652 needTool(t, "attest")
653 needTool(t, "ssh-keygen")
654 const signer = "valley-host/integration"
655 key := v.publishSigners(signer)
656 v.landByIntegration(key, signer)
657
658 // The caller's own material names the signer with another key, under
659 // which the statement would not verify.
660 other := filepath.Join(v.root, "other.key")
661 v.run("", "ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "other", "-f", other)
662 otherSigners := filepath.Join(v.root, "other-signers")
663 v.write(otherSigners, v.run("", "attest", "key", "--key", other, "--name", signer))
664 t.Setenv("VALLEY_KNOWN_SIGNERS", otherSigners)
665 t.Setenv("VALLEY_INTEGRATOR_SIGNER", signer)
666
667 changes := func() []string {
668 _, _, e := v.out()
669 ids := []string{}
670 for _, c := range e.Projects[0].Changes {
671 ids = append(ids, c.ChangeID)
672 }
673 return ids
674 }
675 if got := changes(); !reflect.DeepEqual(got, []string{changeID}) {
676 t.Errorf("with the published signers, app's changes ready for approval are %v, want %s alone", got, changeID)
677 }
678 v.run("", "git", "-C", filepath.Join(v.srv, "valley.git"), "update-ref", "-d", "refs/the-valley/signers")
679 got := changes()
680 if len(got) != 2 || !strings.Contains(strings.Join(got, " "), landedChangeID) {
681 t.Errorf("with no published signers, app's changes ready for approval are %v, want the landed change among them", got)
682 }
683}
684
685// A refresh reserves the entire replacement while the old cache remains.
686// Refusal leaves the old readable snapshot intact and no staged files.
687func TestSharedCacheRefreshBudget(t *testing.T) {
688 v := newValley(t)
689 cache := filepath.Join(v.root, "shared-cache")
690 p := &publisher{cache: cache, cfg: config{state: v.state, maxStorage: 1 << 20}}
691 dir := filepath.Join(cache, "app.git")
692 source := filepath.Join(v.srv, "app.git")
693 refs := map[string]string{"refs/heads/main": "refs/heads/main"}
694 ctx := context.Background()
695 if err := p.shareRepository(ctx, dir, source, refs); err != nil {
696 t.Fatal(err)
697 }
698 old, err := revParse(ctx, dir, "refs/heads/main")
699 if err != nil {
700 t.Fatal(err)
701 }
702 v.write(filepath.Join(v.work["app"], "next"), "next")
703 v.commit("app", "app: next")
704 used, err := p.storageUsed()
705 if err != nil {
706 t.Fatal(err)
707 }
708 p.cfg.maxStorage = byteSize(used)
709 if err := p.shareRepository(ctx, dir, source, refs); err == nil {
710 t.Fatal("refresh exceeded its budget")
711 }
712 if tip, err := revParse(ctx, dir, "refs/heads/main"); err != nil || tip != old {
713 t.Fatalf("refused refresh changed the cache: %s, %v", tip, err)
714 }
715 if entries, err := os.ReadDir(cache); err != nil || len(entries) != 1 {
716 t.Fatalf("refused refresh left partial data: %v, %v", entries, err)
717 }
718 p.cfg.maxStorage = 1 << 20
719 if err := p.shareRepository(ctx, dir, source, refs); err != nil {
720 t.Fatal(err)
721 }
722 if tip, err := revParse(ctx, dir, "refs/heads/main"); err != nil || tip == old {
723 t.Fatalf("refresh did not advance main: %s, %v", tip, err)
724 }
725}