gunk-dev/the-valley

checkbuild_test.go

source69d7baef1f04main's published tip history
25.2 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strconv"
12 "strings"
13 "syscall"
14 "testing"
15 "time"
16
17 "the-valley/change"
18)
19
20const rigTree = "71ee"
21
22// buildRig is a worktree whose origin is a bare repository, and the
23// command's work in it, with the evidence reads and the worker stream the
24// test's: each read takes the next of reads, and the stream plays follows.
25type buildRig struct {
26 t *testing.T
27 origin, work, gitDir string
28 base, head string
29 a *asking
30 out, errs, states bytes.Buffer
31 reads []fakeRead
32 read int
33 stream *fakeStream
34}
35
36// fakeRead is one read of origin's evidence: the checks it covers, those
37// whose evidence does not count, or an error.
38type fakeRead struct {
39 covered, mismatched []string
40 err error
41}
42
43func newBuildRig(t *testing.T, nix ...string) *buildRig {
44 t.Helper()
45 dir := t.TempDir()
46 t.Setenv("HOME", dir)
47 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
48 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
49 r := &buildRig{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
50 r.git(dir, "init", "--quiet", "--bare", "--initial-branch=main", r.origin)
51 r.git(dir, "clone", "--quiet", r.origin, r.work)
52 r.git(r.work, "config", "user.name", "build-test")
53 r.git(r.work, "config", "user.email", "build-test@localhost")
54 r.git(r.work, "config", "valley.principal", "alice")
55 r.git(r.work, "commit", "--quiet", "--allow-empty", "-m", "base")
56 r.base = r.git(r.work, "rev-parse", "HEAD")
57 r.git(r.work, "push", "--quiet", "origin", "HEAD:refs/heads/main")
58 r.git(r.work, "commit", "--quiet", "--allow-empty", "-m", "draft")
59 r.head = r.git(r.work, "rev-parse", "HEAD")
60 r.gitDir = r.git(r.work, "rev-parse", "--absolute-git-dir")
61 r.stream = &fakeStream{t: t}
62
63 a := newAsking(git{env: gitEnvironment(os.Environ()), stderr: &r.errs, dir: r.work}, &r.out, &r.errs)
64 a.states, a.readEvery = &r.states, time.Hour
65 a.derive = func() error {
66 a.head, a.short, a.project = r.head, r.head[:7], "app"
67 a.required = len(nix)
68 for _, name := range nix {
69 a.nix = append(a.nix, nixCheck{name, name})
70 }
71 return nil
72 }
73 a.cover = func([]nixCheck) (evidence, error) {
74 f := r.reads[min(r.read, len(r.reads)-1)]
75 r.read++
76 e := evidence{digest: rigTree, covered: map[string]string{}, failed: map[string]string{}}
77 for _, name := range f.covered {
78 e.covered[name] = "ref worker"
79 }
80 for _, name := range f.mismatched {
81 e.failed[name] = "ref worker"
82 }
83 return e, f.err
84 }
85 a.stream = r.stream
86 r.a = a
87 return r
88}
89
90func (r *buildRig) git(dir string, args ...string) string {
91 r.t.Helper()
92 cmd := exec.Command("git", args...)
93 cmd.Dir = dir
94 out, err := cmd.CombinedOutput()
95 if err != nil {
96 r.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
97 }
98 return strings.TrimSpace(string(out))
99}
100
101// requests is every check request origin holds, as "<ref> <commit>".
102func (r *buildRig) requests() string {
103 return r.git(r.origin, "for-each-ref", "--format=%(refname) %(objectname)", change.CheckRequestPrefix)
104}
105
106// run runs the work and checks its exit status.
107func (r *buildRig) run(want int) {
108 r.t.Helper()
109 if got := r.a.run(); got != want {
110 r.t.Errorf("exit %d, want %d\nstdout:\n%s\nstderr:\n%s", got, want, r.out.String(), r.errs.String())
111 }
112}
113
114func (r *buildRig) says(out *bytes.Buffer, lines ...string) {
115 r.t.Helper()
116 for _, line := range lines {
117 if !strings.Contains(out.String(), line) {
118 r.t.Errorf("output lacks %q:\n%s", line, out.String())
119 }
120 }
121}
122
123func (r *buildRig) saysNot(out *bytes.Buffer, lines ...string) {
124 r.t.Helper()
125 for _, line := range lines {
126 if strings.Contains(out.String(), line) {
127 r.t.Errorf("output holds %q:\n%s", line, out.String())
128 }
129 }
130}
131
132// fakeStream plays each follow in turn: before, then its records, then
133// its cursor or err. Past the last follow it waits for the follow's end.
134type fakeStream struct {
135 t *testing.T
136 endErr error
137 follows []fakeFollow
138 ended int
139 tails map[[2]string]string
140}
141
142type fakeFollow struct {
143 before func()
144 records []workerRecord
145 err error
146}
147
148// end is the cursor before the filing, seq 1, and then the mark after
149// it, seq 10.
150func (s *fakeStream) end(context.Context) (string, error) {
151 s.ended++
152 if s.ended == 1 {
153 return "worker=0123456789abcdef:1", s.endErr
154 }
155 return "worker=0123456789abcdef:10", s.endErr
156}
157
158func (s *fakeStream) follow(ctx context.Context, cursor string, seconds int, records chan<- workerRecord) (string, error) {
159 if len(s.follows) == 0 {
160 <-ctx.Done()
161 return "", ctx.Err()
162 }
163 f := s.follows[0]
164 s.follows = s.follows[1:]
165 if f.before != nil {
166 f.before()
167 }
168 for _, r := range f.records {
169 select {
170 case records <- r:
171 case <-ctx.Done():
172 return "", ctx.Err()
173 }
174 }
175 return cursor, f.err
176}
177
178func (s *fakeStream) logs(context.Context) (map[[2]string]string, error) { return s.tails, nil }
179
180func record(typ, run, tree string, data map[string]any) workerRecord {
181 return workerRecord{Type: typ, Run: run, Project: "app", Tree: tree, Data: data}
182}
183
184func treeBatchEnd(result string) workerRecord {
185 return record("batch.end", "p1", rigTree, map[string]any{"attest_run": "attest-1", "result": result})
186}
187
188func published() workerRecord {
189 return record("publish.end", "p1", rigTree, map[string]any{"result": "passed"})
190}
191
192func TestCheckBuildWaitFlag(t *testing.T) {
193 for _, c := range []struct {
194 args []string
195 want time.Duration
196 bad bool
197 }{
198 {args: []string{"--build"}, want: 2 * time.Hour},
199 {args: []string{"--build", "--wait", "30m"}, want: 30 * time.Minute},
200 {args: []string{"--wait=45s", "--build"}, want: 45 * time.Second},
201 {args: []string{"--build", "--wait", "0s"}, bad: true},
202 {args: []string{"--build", "--names"}, bad: true},
203 } {
204 got, err := buildWait(c.args)
205 if (err != nil) != c.bad || !c.bad && got != c.want {
206 t.Errorf("%q: %v, %v", c.args, got, err)
207 }
208 }
209}
210
211// One complete first read passes without filing or reading the worker.
212func TestCheckBuildPassesWithoutFiling(t *testing.T) {
213 r := newBuildRig(t, "fast", "slow")
214 r.reads = []fakeRead{{covered: []string{"fast", "slow"}}}
215 r.run(0)
216 r.says(&r.out, "✓ "+r.head[:7]+" 2 checks passed")
217 if r.stream.ended != 0 || r.requests() != "" {
218 t.Errorf("the stream was read, or a request filed: %q", r.requests())
219 }
220}
221
222// Only the last read decides: reads that together covered every check do
223// not pass when the last read fails. The request is deleted.
224func TestCheckBuildLastReadDecides(t *testing.T) {
225 r := newBuildRig(t, "fast", "slow")
226 r.a.readEvery = time.Nanosecond
227 r.reads = []fakeRead{{covered: []string{"slow"}}, {covered: []string{"fast"}}, {err: errors.New("origin did not answer")}}
228 r.stream.follows = []fakeFollow{{}, {records: []workerRecord{published()}}}
229 r.run(1)
230 r.says(&r.out, "not established · the worker published for this tree · evidence unreadable")
231 r.saysNot(&r.out, "passed")
232 if r.read != 3 || r.requests() != "" {
233 t.Errorf("%d reads; origin holds %q", r.read, r.requests())
234 }
235}
236
237// Evidence that does not count for a check is no evidence for it, never
238// a failure: the request is filed, and the check has no evidence.
239func TestCheckBuildMismatchIsNoEvidence(t *testing.T) {
240 r := newBuildRig(t, "fast", "slow")
241 r.reads = []fakeRead{{covered: []string{"fast"}, mismatched: []string{"slow"}}}
242 r.stream.follows = []fakeFollow{{records: []workerRecord{published()}}}
243 r.run(1)
244 r.says(&r.out, "◇ slow no evidence on origin", "not established", "1 of 2 with evidence")
245 r.saysNot(&r.out, "fail", "✗")
246 r.says(&r.states, "filing ")
247}
248
249// A pass.end ends the wait only after its pass.start came after the
250// filing: a pass that started before may not have read the request. A
251// batch that passed is no wake-up either: its evidence is on origin only
252// once it publishes.
253func TestCheckBuildPassEndNeedsItsStart(t *testing.T) {
254 r := newBuildRig(t, "fast")
255 r.reads = []fakeRead{{}}
256 waited := false
257 r.stream.follows = []fakeFollow{
258 {records: []workerRecord{{Seq: 11, Type: "pass.end", Run: "p0"}, treeBatchEnd("passed"),
259 {Seq: 5, Type: "pass.start", Run: "p2"}, {Seq: 12, Type: "pass.end", Run: "p2"}}},
260 {before: func() { waited = r.read == 1 }, records: []workerRecord{{Seq: 21, Type: "pass.start", Run: "p1"}, {Seq: 22, Type: "pass.end", Run: "p1"}}},
261 }
262 r.run(1)
263 r.says(&r.out, "not established · a worker pass ended")
264 if !waited {
265 t.Error("the wait ended at a pass.end whose start it did not see")
266 }
267}
268
269// Each wake-up ends the wait in the last read; with every check covered
270// there, it passes.
271func TestCheckBuildWakes(t *testing.T) {
272 for _, c := range []struct {
273 name string
274 follow fakeFollow
275 endErr error
276 last []string
277 status int
278 says string
279 }{
280 {name: "a publish for the tree ends", follow: fakeFollow{records: []workerRecord{published()}},
281 last: []string{"fast"}, status: 0, says: "1 check passed"},
282 {name: "a quick worker's batch fails before the mark", follow: fakeFollow{records: []workerRecord{
283 func() workerRecord { r := treeBatchEnd("failed"); r.Seq = 5; return r }()}},
284 status: 1, says: "not established · the worker's batch for this tree ended with failures"},
285 {name: "a producer lost records", follow: fakeFollow{records: []workerRecord{{Type: "check.output", Data: map[string]any{"dropped_before": float64(2)}}}},
286 status: 1, says: "not established · telemetry lost records"},
287 {name: "the follow fails", follow: fakeFollow{err: errors.New("the host refused")}, status: 1, says: "not established · telemetry unreadable"},
288 {name: "the stream cannot be read", endErr: errors.New("no observe grant"), status: 1, says: "not established · telemetry unreadable"},
289 } {
290 t.Run(c.name, func(t *testing.T) {
291 r := newBuildRig(t, "fast")
292 r.reads = []fakeRead{{}, {covered: c.last}}
293 r.stream.endErr, r.stream.follows = c.endErr, []fakeFollow{c.follow}
294 r.run(c.status)
295 r.says(&r.out, c.says)
296 if r.requests() != "" || r.read != 2 {
297 t.Errorf("origin holds %q; %d reads, want the first and the last", r.requests(), r.read)
298 }
299 })
300 }
301}
302
303// What the worker wrote for the tree is printed as its records, not this
304// request's result: each check.result, a failed check's build output tied
305// to it by attest run, untrusted, escaped and cut to its last lines, and
306// for a failed check with no output the command that builds it here.
307func TestCheckBuildReportsTheTreesRecords(t *testing.T) {
308 r := newBuildRig(t, "fast", "slow", "lint")
309 r.reads = []fakeRead{{}}
310 result := func(check, res string, ms float64) workerRecord {
311 rec := record("check.result", "attest-1", rigTree, map[string]any{"result": res, "check_ms": ms})
312 rec.Check = check
313 return rec
314 }
315 other := result("fast", "failed", 1)
316 other.Tree = "0the4"
317 r.stream.follows = []fakeFollow{{records: []workerRecord{
318 record("batch.start", "p1", rigTree, map[string]any{"attest_run": "attest-1"}),
319 other, result("fast", "passed", 1000), result("slow", "failed", 2000), result("lint", "failed", 3000),
320 treeBatchEnd("failed"),
321 }}}
322 var tail strings.Builder
323 for i := 1; i <= 70; i++ {
324 fmt.Fprintf(&tail, "line %d\n", i)
325 }
326 tail.WriteString("said \x1b[31mred\n")
327 r.stream.tails = map[[2]string]string{{"attest-1", "slow"}: tail.String(), {"attest-0", "lint"}: "another run's output"}
328 r.run(1)
329 r.says(&r.out, "not established · the worker's batch for this tree ended with failures",
330 "the worker's recent records for this tree, not this request's result:",
331 " fast passed · 1s", " slow failed · 2s",
332 "slow · the worker's build output, untrusted, its last 60 lines:", " | line 70", `said \x1b[31mred`,
333 "run: nix build --no-link -L .#checks."+buildSystem()+".lint",
334 "see: valley telemetry read --source worker --logs")
335 r.saysNot(&r.out, "| line 11\n", "another run", "fast failed", "\x1b[31m")
336}
337
338// A push that dies in transport leaves the request's existence unknown:
339// the leased delete is tried, and printed when origin cannot confirm it.
340func TestCheckBuildPushDiesInTransport(t *testing.T) {
341 r := newBuildRig(t, "fast")
342 r.reads = []fakeRead{{}}
343 hook := "#!/bin/sh\nkill -9 $PPID\n"
344 if err := os.WriteFile(filepath.Join(r.origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
345 t.Fatal(err)
346 }
347 r.run(1)
348 r.says(&r.errs, "push did not finish", "is not established", "run: git push --force-with-lease="+r.a.ref+":"+r.head+" origin :"+r.a.ref)
349 r.says(&r.out, "not established · the request's push did not finish")
350 r.saysNot(&r.errs, "refused", "not filed")
351}
352
353// A push origin refuses files nothing, and leaves nothing to delete.
354func TestCheckBuildRefused(t *testing.T) {
355 r := newBuildRig(t, "fast")
356 r.reads = []fakeRead{{}}
357 hook := "#!/bin/sh\necho 'not this one' >&2\nexit 1\n"
358 if err := os.WriteFile(filepath.Join(r.origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
359 t.Fatal(err)
360 }
361 r.run(1)
362 r.says(&r.errs, "origin refused the check request: not this one")
363 r.saysNot(&r.errs, "is not established")
364}
365
366// The worktree's token is read or made, and its earlier requests deleted,
367// only under its lock: while another holds it, the command makes no token
368// and deletes nothing.
369func TestCheckBuildTokenAndRecoveryUnderTheLock(t *testing.T) {
370 r := newBuildRig(t, "fast")
371 r.reads = []fakeRead{{}}
372 lock, err := os.OpenFile(filepath.Join(r.gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
373 if err != nil {
374 t.Fatal(err)
375 }
376 defer lock.Close()
377 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
378 t.Fatal(err)
379 }
380 r.run(1)
381 r.says(&r.errs, "another valley checks --build is running in this worktree")
382 if _, err := os.Stat(filepath.Join(r.gitDir, worktreeTokenFile)); err == nil {
383 t.Error("a token was made without the lock")
384 }
385
386 r = newBuildRig(t, "fast")
387 r.reads = []fakeRead{{}}
388 token := "0123456789abcdef"
389 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
390 earlier, _ := change.CheckRequestRef("alice", token, "00000000000000aa")
391 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+earlier)
392 lock, err = os.OpenFile(filepath.Join(r.gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
393 if err != nil {
394 t.Fatal(err)
395 }
396 defer lock.Close()
397 syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
398 r.run(1)
399 if got := r.requests(); got != earlier+" "+r.head {
400 t.Errorf("origin holds %q, want the earlier request untouched", got)
401 }
402}
403
404// With the lock, the worktree's earlier requests go, each leased, and
405// another worktree's stays.
406func TestCheckBuildRecoversEarlierRequests(t *testing.T) {
407 r := newBuildRig(t, "fast")
408 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
409 token := "0123456789abcdef"
410 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
411 earlier, _ := change.CheckRequestRef("alice", token, "00000000000000aa")
412 other, _ := change.CheckRequestRef("alice", "fedcba9876543210", "00000000000000bb")
413 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+earlier, "HEAD:"+other)
414 r.stream.follows = []fakeFollow{{before: func() {
415 if got := r.requests(); got != other+" "+r.head+"\n"+r.a.ref+" "+r.head && got != r.a.ref+" "+r.head+"\n"+other+" "+r.head {
416 t.Errorf("while waiting, origin holds %q", got)
417 }
418 }, records: []workerRecord{published()}}}
419 r.run(0)
420 if got := r.requests(); got != other+" "+r.head {
421 t.Errorf("origin holds %q, want only the other worktree's", got)
422 }
423}
424
425// The deadline kills every program the command started, here the git
426// listing coverageOf runs to read origin's evidence, hung in its
427// transport, and the outcome is not established. The command is the
428// real one, run by the watchdog as a child: it derives the checks under a
429// floor, fetches main, and reads the evidence through coverageOf.
430func TestCheckBuildDeadline(t *testing.T) {
431 if _, err := exec.LookPath("cue"); err != nil {
432 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
433 t.Fatal("no cue on PATH, and VALLEY_TEST_TOOLS=required")
434 }
435 t.Skip("no cue to derive the checks with; the nix check provides one")
436 }
437 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
438 if err != nil {
439 t.Fatal(err)
440 }
441 self, err := filepath.Abs(os.Args[0])
442 if err != nil {
443 t.Fatal(err)
444 }
445 dir := t.TempDir()
446 t.Setenv("HOME", dir)
447 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
448 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
449 t.Setenv("VALLEY_VERIFICATION_SCHEMA", schema)
450 r := &buildRig{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
451 r.git(dir, "init", "--quiet", "--bare", "--initial-branch=main", r.origin)
452 r.git(dir, "clone", "--quiet", r.origin, r.work)
453 for _, kv := range [][2]string{{"user.name", "build-test"}, {"user.email", "build-test@localhost"}, {"valley.principal", "alice"}} {
454 r.git(r.work, "config", kv[0], kv[1])
455 }
456 write := func(path, body string) {
457 os.MkdirAll(filepath.Dir(path), 0o755)
458 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
459 t.Fatal(err)
460 }
461 }
462 write(filepath.Join(r.work, "policy", "instance", "floor.cue"), "package verification\nfloor: {\n"+
463 "\tchecks: \"c-docs\": {runner: \"nix\", attribute: \"c-docs\"}\n\tunclassified: \"c-docs\": true\n}\n")
464 write(filepath.Join(r.work, "docs", "a.md"), "base\n")
465 r.git(r.work, "add", "-A")
466 r.git(r.work, "commit", "--quiet", "-m", "base")
467 r.git(r.work, "push", "--quiet", "origin", "HEAD:refs/heads/main")
468 write(filepath.Join(r.work, "docs", "b.md"), "draft\n")
469 r.git(r.work, "add", "-A")
470 r.git(r.work, "commit", "--quiet", "-m", "draft")
471 r.git(r.work, "remote", "set-url", "origin", "ssh://valley-host"+r.origin)
472
473 // ssh and attest are this test binary (TestMain): ssh serves origin
474 // for the first upload-pack, main's fetch, and hangs at the next, the
475 // listing; attest digests any tree.
476 bin, fake := filepath.Join(dir, "bin"), filepath.Join(dir, "fake")
477 os.Mkdir(bin, 0o755)
478 os.Mkdir(fake, 0o755)
479 for _, name := range []string{"ssh", "attest"} {
480 if err := os.Symlink(self, filepath.Join(bin, name)); err != nil {
481 t.Fatal(err)
482 }
483 }
484 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
485 t.Setenv("FAKE_SSH_UPLOAD", fake)
486 t.Setenv("GIT_SSH_VARIANT", "ssh")
487 t.Chdir(r.work)
488
489 var out, errs bytes.Buffer
490 began := time.Now()
491 wait := 6 * time.Second
492 status := watch(git{env: gitEnvironment(os.Environ()), stderr: &errs}, self, wait, &out, &errs, make(chan os.Signal))
493 if status != 1 || !strings.Contains(out.String(), "not established · time limit") {
494 t.Errorf("exit %d\nstdout:\n%s\nstderr:\n%s", status, out.String(), errs.String())
495 }
496 if took := time.Since(began); took > wait+cleanupBound {
497 t.Errorf("the command took %s", took)
498 }
499 pid, err := os.ReadFile(filepath.Join(fake, "hung.pid"))
500 if err != nil {
501 t.Fatalf("the listing never reached origin: %v\nstderr:\n%s", err, errs.String())
502 }
503 if stat, err := os.ReadFile("/proc/" + strings.TrimSpace(string(pid)) + "/stat"); err == nil {
504 if f := strings.Fields(string(stat[bytes.LastIndexByte(stat, ')')+1:])); len(f) > 0 && f[0] != "Z" {
505 t.Errorf("the hung listing outlived the command: %s", stat)
506 }
507 }
508}
509
510// fakeUpload is ssh for TestCheckBuildDeadline: it serves the repository
511// an upload-pack names for the first one, and hangs at every later one.
512func fakeUpload(dir string, args []string) int {
513 path, ok := strings.CutPrefix(args[len(args)-1], "git-upload-pack ")
514 if !ok {
515 return 0
516 }
517 seen, _ := os.ReadFile(filepath.Join(dir, "uploads"))
518 os.WriteFile(filepath.Join(dir, "uploads"), append(seen, '.'), 0o600)
519 if len(seen) == 0 {
520 gitPath, err := exec.LookPath("git")
521 if err != nil {
522 return 255
523 }
524 syscall.Exec(gitPath, []string{"git", "upload-pack", strings.Trim(path, "'")}, os.Environ())
525 return 255
526 }
527 os.WriteFile(filepath.Join(dir, "hung.pid"), []byte(strconv.Itoa(os.Getpid())), 0o600)
528 time.Sleep(time.Hour)
529 return 255
530}
531
532// fakeAttest is attest for TestCheckBuildDeadline: every tree has one
533// digest.
534func fakeAttest() int {
535 fmt.Println("valley-tree-v1:" + strings.Repeat("ab", 32))
536 return 0
537}
538
539// No check required passes at once, with nothing filed.
540func TestCheckBuildNoRequiredChecks(t *testing.T) {
541 r := newBuildRig(t)
542 r.run(0)
543 r.says(&r.out, "no checks required")
544 if r.stream.ended != 0 || r.requests() != "" {
545 t.Errorf("the stream was read, or a request filed: %q", r.requests())
546 }
547}
548
549// A telemetry record cannot speak for the child: one whose fields are not
550// a required check, a known result and a run name is dropped, and no value
551// holding a newline or space reaches the state pipe, so a crafted result
552// cannot tell the parent the request is settled.
553func TestCheckBuildStateCannotBeInjected(t *testing.T) {
554 r := newBuildRig(t, "fast")
555 r.a.derive()
556 r.a.tree = rigTree
557 for _, c := range []struct{ check, result, run string }{
558 {"fast", "failed\nsettled\n", "attest-1"},
559 {"fast\nsettled", "failed", "attest-1"},
560 {"lint", "failed", "attest-1"},
561 {"fast", "failed", "attest-1\nsettled"},
562 } {
563 rec := record("check.result", c.run, rigTree, map[string]any{"result": c.result})
564 rec.Check = c.check
565 r.a.wake(rec, map[string]bool{}, map[string]bool{})
566 }
567 r.a.state("filing", "refs/x", "abc")
568 r.a.state("result", "x\nsettled")
569 raw := r.states.String()
570 var s childState
571 s.read(&r.states)
572 if len(r.a.results) != 0 || s.settled || raw != "filing refs/x abc\n" {
573 t.Errorf("results %v, state pipe %q", r.a.results, raw)
574 }
575}
576
577// Names and results print as one escaped line each.
578func TestCheckBuildReportEscapes(t *testing.T) {
579 var out bytes.Buffer
580 report(&out, []treeResult{{"attest-1", "fa\x1b[31mst\nsettled", "failed", 1000}}, nil, nil)
581 if !strings.Contains(out.String(), ` fa\x1b[31mst\nsettled failed · 1s`) {
582 t.Errorf("%q", out.String())
583 }
584}
585
586// Only a line rejecting the request's own ref is a rejection; a remote that
587// failed to report status, or another ref's rejection, leaves it unknown.
588func TestPushStatus(t *testing.T) {
589 ref := "refs/the-valley/check-requests/alice/0123456789abcdef/0123456789abcdef"
590 for _, c := range []struct{ out, want string }{
591 {"To origin\n!\tabc:" + ref + "\t[remote rejected] (pre-receive hook declined)\nDone\n", "rejected"},
592 {"!\tabc:" + ref + "\t[rejected] (stale info)\n", "rejected"},
593 {"!\tabc:" + ref + "\t[remote failure] (remote failed to report status)\n", "unknown"},
594 {"!\tabc:refs/heads/other\t[remote rejected] (no)\n", "unknown"},
595 {"", "unknown"},
596 } {
597 if got := pushStatus(c.out, ref); got != c.want {
598 t.Errorf("%q: %s, want %s", c.out, got, c.want)
599 }
600 }
601}
602
603// The parent exits 0 only when the child reported a pass: a child that
604// exits 0 without one is no pass.
605func TestCheckBuildFailsClosed(t *testing.T) {
606 self, err := exec.LookPath("true")
607 if err != nil {
608 t.Skip("no true on PATH")
609 }
610 var out, errs bytes.Buffer
611 if status := watch(git{env: os.Environ()}, self, time.Minute, &out, &errs, make(chan os.Signal)); status != 1 ||
612 !strings.Contains(errs.String(), "ended without an outcome") {
613 t.Errorf("exit %d\n%s%s", status, out.String(), errs.String())
614 }
615}
616
617// A token that does not read is reported, never replaced.
618func TestCheckBuildKeepsAMalformedToken(t *testing.T) {
619 r := newBuildRig(t, "fast")
620 r.reads = []fakeRead{{}}
621 path := filepath.Join(r.gitDir, worktreeTokenFile)
622 os.WriteFile(path, []byte("not a token\n"), 0o600)
623 r.run(1)
624 r.says(&r.errs, "holds no check request token")
625 if data, _ := os.ReadFile(path); string(data) != "not a token\n" || r.requests() != "" {
626 t.Errorf("the token is %q; origin holds %q", data, r.requests())
627 }
628}
629
630// An earlier request whose delete the child started and did not end is the
631// parent's to delete, leased; one the child cleared is not.
632func TestCheckBuildParentDeletesAStaleTarget(t *testing.T) {
633 r := newBuildRig(t, "fast")
634 cut, _ := change.CheckRequestRef("alice", "0123456789abcdef", "00000000000000aa")
635 done, _ := change.CheckRequestRef("alice", "0123456789abcdef", "00000000000000bb")
636 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+cut, "HEAD:"+done)
637 var s childState
638 s.read(strings.NewReader("stale " + cut + " " + r.head + "\nstale " + done + " " + r.head + "\ncleared " + done + "\n"))
639 s.settle(git{env: gitEnvironment(os.Environ()), dir: r.work}, &r.errs, make(chan os.Signal))
640 if got := r.requests(); got != done+" "+r.head {
641 t.Errorf("origin holds %q, want only the cleared one", got)
642 }
643}
644
645// A diagnostic from the host prints as one escaped line, so it cannot
646// forge a verdict line of its own.
647func TestCheckBuildDiagnosticsStayOnOneLine(t *testing.T) {
648 r := newBuildRig(t, "fast")
649 r.reads = []fakeRead{{}}
650 r.stream.endErr = errors.New("denied\n✓ HEAD 1 check passed")
651 r.run(1)
652 r.says(&r.errs, `denied\n✓ HEAD 1 check passed`)
653 if strings.Contains(r.errs.String()+r.out.String(), "\n✓ HEAD") {
654 t.Errorf("a diagnostic broke its line:\n%s%s", r.out.String(), r.errs.String())
655 }
656}
657
658// A listed ref under the worktree's prefix that is no check request is
659// skipped, and never reaches the state pipe, however long.
660func TestCheckBuildSkipsAMalformedStaleRef(t *testing.T) {
661 r := newBuildRig(t, "fast")
662 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
663 token := "0123456789abcdef"
664 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
665 long := change.CheckRequestPrefix + "alice/" + token + "/" + strings.Repeat("a", 60000)
666 if err := os.WriteFile(filepath.Join(r.origin, "packed-refs"), []byte(r.head+" "+long+"\n"), 0o644); err != nil {
667 t.Fatal(err)
668 }
669 r.stream.follows = []fakeFollow{{records: []workerRecord{published()}}}
670 r.run(0)
671 r.says(&r.errs, "is no check request, so it is skipped")
672 for _, line := range strings.Split(r.states.String(), "\n") {
673 if len(line) > 1000 {
674 t.Errorf("a %d-byte state line reached the pipe", len(line))
675 }
676 }
677}