gunk-dev/the-valley

pending_test.go

sourced9c8073fd613main's published tip history
34.4 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "regexp"
13 "slices"
14 "strings"
15 "syscall"
16 "testing"
17 "time"
18
19 "the-valley/note"
20 "the-valley/telemetry"
21)
22
23// pending fits its text to 80 columns when stdout is no terminal: a long
24// title is cut short with …, and a branch or a handle is printed whole,
25// even where the line it is on cannot fit. A stack of branches four deep
26// is listed at one indentation, so its deepest entry has the room its
27// second has. Nothing it prints is an escape code.
28func TestPendingFitsEightyColumnsAndKeepsNamesWhole(t *testing.T) {
29 dir := t.TempDir()
30 t.Setenv("HOME", dir)
31 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
32 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
33 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
34 origin, work := filepath.Join(dir, "origin.git"), filepath.Join(dir, "work")
35 sh := func(args ...string) {
36 t.Helper()
37 cmd := exec.Command("git", args...)
38 cmd.Dir = work
39 if out, err := cmd.CombinedOutput(); err != nil {
40 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
41 }
42 }
43 if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil {
44 t.Fatalf("git init: %v\n%s", err, out)
45 }
46 if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil {
47 t.Fatalf("git clone: %v\n%s", err, out)
48 }
49 sh("config", "user.name", "a committer whose name is so long that the line it is on has to cut it short")
50 sh("config", "user.email", "committer@localhost")
51 sh("config", "valley.principal", "alice")
52 sh("checkout", "--quiet", "-b", "main")
53 sh("commit", "--quiet", "--allow-empty", "-m", "base")
54 sh("push", "--quiet", "origin", "main")
55
56 long := "a-branch-whose-name-runs-on-well-past-the-eightieth-column-of-any-terminal-it-is-shown-in"
57 title := "a subject that says far more than one line has room for, " + strings.Repeat("and then some more ", 4)
58 sh("checkout", "--quiet", "-b", long, "main")
59 sh("commit", "--quiet", "--allow-empty", "-m", title+"on the long branch")
60 sh("push", "--quiet", "origin", long)
61 sh("checkout", "--quiet", "-b", "short", "main")
62 sh("commit", "--quiet", "--allow-empty", "-m", title)
63 sh("push", "--quiet", "origin", "short")
64 from := "main"
65 for _, layer := range []string{"1", "2", "3", "4"} {
66 sh("checkout", "--quiet", "-b", "layer-"+layer, from)
67 sh("commit", "--quiet", "--allow-empty", "-m", "layer "+layer+": "+title)
68 sh("push", "--quiet", "origin", "layer-"+layer)
69 from = "layer-" + layer
70 }
71
72 t.Chdir(work)
73 var stdout, stderr bytes.Buffer
74 if code := run([]string{"ready", "--change", strings.Repeat("q", 32), "short"}, &stdout, &stderr, os.Exit); code != 0 {
75 t.Fatalf("ready: %s", stderr.String())
76 }
77 stdout.Reset()
78 if code := run([]string{"pending", "--branches"}, &stdout, &stderr, os.Exit); code != 0 {
79 t.Fatalf("pending: %s", stderr.String())
80 }
81 out := stdout.String()
82 if strings.Contains(out, "\x1b") {
83 t.Errorf("pending printed an escape code to no terminal:\n%s", out)
84 }
85 if !strings.Contains(out, "\n"+long+"\n") {
86 t.Errorf("the long branch is not whole, on a line of its own:\n%s", out)
87 }
88 if !strings.Contains(out, "\n 1 qqqq v1") {
89 t.Errorf("the change is not named by its whole handle and version:\n%s", out)
90 }
91 cut := 0
92 for _, line := range strings.Split(strings.TrimSuffix(out, "\n"), "\n") {
93 if strings.Contains(line, long) {
94 continue
95 }
96 if columns(line) > 80 {
97 t.Errorf("a line is %d columns wide: %q", columns(line), line)
98 }
99 if strings.HasPrefix(strings.TrimLeft(line, " "), "a subject that says") {
100 if columns(line) != 80 || !strings.HasSuffix(line, "…") {
101 t.Errorf("a long title is not cut to 80 columns with …: %q", line)
102 }
103 cut++
104 }
105 if strings.HasPrefix(line, "layer-4 ") && !strings.HasSuffix(line, "…") {
106 t.Errorf("the author is not cut short to keep the line within 80 columns: %q", line)
107 }
108 }
109 lines := strings.Split(out, "\n")
110 for layer, lead := range map[string]string{"4": " ", "3": " │ ", "2": " │ ", "1": " "} {
111 listed := false
112 for _, line := range lines {
113 if strings.HasPrefix(line, lead+"layer "+layer+": ") {
114 listed = true
115 if columns(line) != 80 || !strings.HasSuffix(line, "…") {
116 t.Errorf("layer %s's title is not cut to 80 columns with …: %q", layer, line)
117 }
118 }
119 }
120 if !listed {
121 t.Errorf("layer %s's title is not at %q:\n%s", layer, lead, out)
122 }
123 }
124 if !strings.Contains(out, "\n approving it lands the 3 below too\n") || strings.Contains(out, "on layer-") {
125 t.Errorf("the stack four deep is not one list, each layer on the next:\n%s", out)
126 }
127 if cut != 2 {
128 t.Errorf("%d titles were cut short, where the change's and the branch's should be:\n%s", cut, out)
129 }
130}
131
132// fit cuts by columns, not bytes: a wide character takes two, and a
133// combining mark none.
134func TestFitCountsColumns(t *testing.T) {
135 for _, c := range []struct {
136 s string
137 n int
138 want string
139 }{
140 {"short", 10, "short"},
141 {"exactly ten", 11, "exactly ten"},
142 {"one word too many", 12, "one word to…"},
143 {"漢字漢字漢字", 7, "漢字漢…"},
144 {"café au lait", 5, "café au lait"[:6] + "…"},
145 } {
146 if got := fit(c.s, c.n); got != c.want || columns(got) > c.n {
147 t.Errorf("fit(%q, %d) = %q, %d columns; want %q", c.s, c.n, got, columns(got), c.want)
148 }
149 }
150}
151
152// toolsOnPath puts on PATH, for the test, a shim for each tool named that
153// logs each start to the file it returns and runs the real tool. It
154// skips the test when a tool is missing, unless VALLEY_TEST_TOOLS is
155// required.
156func toolsOnPath(t *testing.T, dir string, tools ...string) (starts string) {
157 t.Helper()
158 bin, starts := filepath.Join(dir, "bin"), filepath.Join(dir, "starts")
159 if err := os.MkdirAll(bin, 0o755); err != nil {
160 t.Fatal(err)
161 }
162 for _, tool := range tools {
163 real, err := exec.LookPath(tool)
164 if err != nil {
165 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
166 t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", tool)
167 }
168 t.Skipf("no %s to run; the nix check provides one", tool)
169 }
170 shim := fmt.Sprintf("#!/bin/sh\necho %s >> '%s'\nexec '%s' \"$@\"\n", tool, starts, real)
171 if err := os.WriteFile(filepath.Join(bin, tool), []byte(shim), 0o755); err != nil {
172 t.Fatal(err)
173 }
174 }
175 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
176 return starts
177}
178
179// testSchema is the verification schema, read from the package's
180// directory before a test changes to another.
181var testSchema, _ = filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
182
183// policyProject is a repository at root with its own origin, whose floor
184// has one class requiring checks c-1 to c-<checks> of every path under
185// src/, made the current directory. head pushes a branch off main that
186// adds src/<branch> and readies it as the change id.
187func policyProject(t *testing.T, root string, checks int) (sh func(...string), head func(branch, id string)) {
188 t.Helper()
189 t.Setenv("HOME", root)
190 t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))
191 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
192 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
193 t.Setenv("VALLEY_VERIFICATION_SCHEMA", testSchema)
194 origin, work := filepath.Join(root, "origin.git"), filepath.Join(root, "work")
195 sh = func(args ...string) {
196 t.Helper()
197 cmd := exec.Command("git", args...)
198 cmd.Dir = work
199 if out, err := cmd.CombinedOutput(); err != nil {
200 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
201 }
202 }
203 if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil {
204 t.Fatalf("git init: %v\n%s", err, out)
205 }
206 if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil {
207 t.Fatalf("git clone: %v\n%s", err, out)
208 }
209 sh("config", "user.name", "operator")
210 sh("config", "user.email", "operator@example.org")
211 sh("config", "valley.principal", "operator")
212 sh("checkout", "--quiet", "-b", "main")
213 var floor strings.Builder
214 floor.WriteString("package verification\nfloor: {\n")
215 for i := 1; i <= checks; i++ {
216 fmt.Fprintf(&floor, "\tchecks: \"c-%d\": {runner: \"nix\", attribute: \"c-%d\"}\n", i, i)
217 fmt.Fprintf(&floor, "\tclasses: src: {paths: \"src/**\": true, requires: \"c-%d\": true}\n", i)
218 }
219 floor.WriteString("\tunclassified: \"c-1\": true\n}\n")
220 if err := os.MkdirAll(filepath.Join(work, "policy", "instance"), 0o755); err != nil {
221 t.Fatal(err)
222 }
223 if err := os.WriteFile(filepath.Join(work, "policy", "instance", "floor.cue"), []byte(floor.String()), 0o644); err != nil {
224 t.Fatal(err)
225 }
226 sh("add", ".")
227 sh("commit", "--quiet", "-m", "base")
228 sh("push", "--quiet", "origin", "main")
229 t.Chdir(work)
230 head = func(branch, id string) {
231 t.Helper()
232 sh("checkout", "--quiet", "-b", branch, "main")
233 if err := os.MkdirAll(filepath.Join(work, "src"), 0o755); err != nil {
234 t.Fatal(err)
235 }
236 if err := os.WriteFile(filepath.Join(work, "src", branch), []byte(branch+"\n"), 0o644); err != nil {
237 t.Fatal(err)
238 }
239 sh("add", ".")
240 sh("commit", "--quiet", "-m", branch)
241 sh("push", "--quiet", "origin", branch)
242 var stdout, stderr bytes.Buffer
243 if code := run([]string{"ready", "--change", id, branch}, &stdout, &stderr, os.Exit); code != 0 {
244 t.Fatalf("ready: %s", stderr.String())
245 }
246 }
247 return sh, head
248}
249
250// runCounted runs valley with args, and returns what it printed and how
251// many processes the shims on PATH logged, by tool, and in all under "".
252func runCounted(t *testing.T, starts string, args ...string) (string, map[string]int) {
253 t.Helper()
254 os.Remove(starts)
255 var stdout, stderr bytes.Buffer
256 if code := run(args, &stdout, &stderr, os.Exit); code != 0 {
257 t.Fatalf("%s: %s", strings.Join(args, " "), stderr.String())
258 }
259 log, _ := os.ReadFile(starts)
260 started := map[string]int{}
261 for _, tool := range strings.Fields(string(log)) {
262 started[tool]++
263 started[""]++
264 }
265 return stdout.String(), started
266}
267
268// pending reads the policy at main's tip once for a project, and asks cue
269// no requirement's pin: the cue processes it starts, with --checks or
270// without, are as many for a class requiring nine checks and four ready
271// heads as for one requiring three and one head.
272func TestPendingStartsCueOncePerProject(t *testing.T) {
273 dir := t.TempDir()
274 starts := toolsOnPath(t, dir, "cue")
275
276 // project lists a project whose class requires checks c-1 to
277 // c-<checks>, with heads ready changes touching it. It returns what
278 // each listing printed and how many cue processes it started.
279 project := func(checks, heads int) (printed map[string]string, started map[string]int) {
280 t.Helper()
281 _, head := policyProject(t, filepath.Join(dir, fmt.Sprintf("%d-%d", checks, heads)), checks)
282 for i := 1; i <= heads; i++ {
283 head(fmt.Sprintf("head-%d", i), strings.Repeat(string(rune('p'+i)), 32))
284 }
285 printed, started = map[string]string{}, map[string]int{}
286 for _, args := range [][]string{{"pending"}, {"pending", "--checks"}} {
287 listing := strings.Join(args, " ")
288 out, n := runCounted(t, starts, args...)
289 printed[listing], started[listing] = out, n["cue"]
290 }
291 return printed, started
292 }
293
294 _, small := project(3, 1)
295 out, large := project(9, 4)
296 if want := "requires 9 quick checks, 0 slow"; strings.Count(out["pending --checks"], want) != 4 {
297 t.Fatalf("pending --checks does not say %q of each of four heads:\n%s", want, out["pending --checks"])
298 }
299 for listing, n := range small {
300 if n == 0 || large[listing] != n {
301 t.Errorf("%s started %d cue processes for three checks and one head, and %d for nine and four heads", listing, n, large[listing])
302 }
303 }
304}
305
306// pending starts as many git processes for a project with five landed
307// changes, five withdrawn ones and five branches no change is on as for
308// one with one of each, beside a draft: what the landed heads reach, what
309// the branches reach, and what the heads a draft may include reach, is
310// read in one batch each, however many there are.
311func TestPendingStartsGitAsOftenWhateverItLists(t *testing.T) {
312 dir := t.TempDir()
313 starts := toolsOnPath(t, dir, "git", "cue")
314 project := func(n int) (string, int) {
315 t.Helper()
316 sh, head := policyProject(t, filepath.Join(dir, fmt.Sprint(n)), 1)
317 for i := 0; i < n; i++ {
318 branch := fmt.Sprintf("landed-%d", i)
319 head(branch, strings.Repeat(string(rune('p'+i)), 32))
320 sh("checkout", "--quiet", "main")
321 sh("merge", "--quiet", "--ff-only", branch)
322 sh("push", "--quiet", "origin", "main")
323 }
324 for i := 0; i < n; i++ {
325 sh("checkout", "--quiet", "-b", fmt.Sprintf("stray-%d", i), "main")
326 sh("commit", "--quiet", "--allow-empty", "-m", fmt.Sprintf("stray %d", i))
327 sh("push", "--quiet", "origin", "HEAD")
328 }
329 valley := func(args ...string) {
330 t.Helper()
331 var stdout, stderr bytes.Buffer
332 if code := run(args, &stdout, &stderr, os.Exit); code != 0 {
333 t.Fatalf("%s: %s", strings.Join(args, " "), stderr.String())
334 }
335 }
336 for i := 0; i < n; i++ {
337 id := strings.Repeat(string(rune('u'+i)), 32)
338 head(fmt.Sprintf("withdrawn-%d", i), id)
339 valley("withdraw", id)
340 }
341 draft := strings.Repeat("z", 32)
342 head("draft", draft)
343 valley("unready", draft)
344 out, started := runCounted(t, starts, "pending")
345 return out, started["git"]
346 }
347 few, small := project(1)
348 many, large := project(5)
349 if !strings.Contains(few, "1 branch no change is on") || !strings.Contains(many, "5 branches no change is on") {
350 t.Fatalf("pending does not count the stray branches:\n%s\n%s", few, many)
351 }
352 if small == 0 || large != small {
353 t.Errorf("pending started git %d times for one landed change, withdrawn change and stray branch, and %d times for five of each", small, large)
354 }
355}
356
357// A host that refuses the read of the worker's telemetry and sources, as
358// it does when the principal already has every bounded request it may
359// have open, leaves main's line without the worker's runs and prints no
360// host entry: pending asks each operation once, says why once on stderr
361// (no extra warning for sources), and prints main's line from the walk
362// alone.
363func TestPendingAsksARefusingHostOnce(t *testing.T) {
364 dir := t.TempDir()
365 starts := toolsOnPath(t, dir, "git", "cue")
366 refusal := fmt.Sprintf(`{"kind":"error","error":%q}`, telemetry.SlotRefusal("operator", telemetry.BoundedSlots, "bounded"))
367 ssh := fmt.Sprintf("#!/bin/sh\necho \"$*\" >> '%s'\necho '%s'\n", starts, refusal)
368 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil {
369 t.Fatal(err)
370 }
371 followProject(t, filepath.Join(dir, "origin"))
372
373 os.Remove(starts)
374 var stdout, stderr bytes.Buffer
375 if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 {
376 t.Fatalf("pending: %s", stderr.String())
377 }
378 log, _ := os.ReadFile(starts)
379 if n := strings.Count(string(log), "valley-telemetry read"); n != 1 {
380 t.Errorf("pending asked the refusing host for worker reads %d times:\n%s", n, log)
381 }
382 if n := strings.Count(string(log), "valley-telemetry sources"); n != 1 {
383 t.Errorf("pending asked the refusing host for sources %d times:\n%s", n, log)
384 }
385 if n := strings.Count(stderr.String(), "refused"); n != 1 || strings.Count(stderr.String(), "\n") != 1 {
386 t.Errorf("pending said, of the refusal:\n%s", stderr.String())
387 }
388 if !strings.HasPrefix(stdout.String(), "main ◐ clearing · f-1 due · covers ") || strings.Contains(stdout.String(), "host ") {
389 t.Errorf("pending's main line, with the host refusing:\n%s", stdout.String())
390 }
391}
392
393// followProject is policyProject with a class that check f-1 follows, a
394// landing on main that sets it due, and its telemetry read from an ssh
395// host, so valley pending waits on the worker's telemetry for main's line.
396func followProject(t *testing.T, root string) {
397 t.Helper()
398 sh, head := policyProject(t, root, 1)
399 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
400 floor := "package verification\nfloor: {\n" +
401 "\tchecks: \"c-1\": {runner: \"nix\", attribute: \"c-1\"}\n" +
402 "\tchecks: \"f-1\": {runner: \"nix\", attribute: \"f-1\"}\n" +
403 "\tclasses: src: {paths: \"src/**\": true, requires: \"c-1\": true, follows: \"f-1\": true}\n" +
404 "\tunclassified: \"c-1\": true\n}\n"
405 if err := os.WriteFile(filepath.Join("policy", "instance", "floor.cue"), []byte(floor), 0o644); err != nil {
406 t.Fatal(err)
407 }
408 sh("commit", "--quiet", "-a", "-m", "follow f-1")
409 sh("push", "--quiet", "origin", "main")
410 head("landed", strings.Repeat("p", 32))
411 sh("checkout", "--quiet", "main")
412 sh("merge", "--quiet", "--ff-only", "landed")
413 sh("push", "--quiet", "origin", "main")
414}
415
416// A host that accepts the read of the worker's telemetry and then stalls
417// does not hold valley pending, nor outlive it: with no follow check and
418// nothing ready, nothing waits on the read, so pending cancels it as it
419// returns, and no ssh it started is left running.
420func TestPendingEndsAReadNobodyWaitsFor(t *testing.T) {
421 if _, err := os.Stat("/proc/self/stat"); err != nil {
422 t.Skip("no /proc to find a child left running in")
423 }
424 dir := t.TempDir()
425 toolsOnPath(t, dir, "git", "cue")
426 // ssh is the host: it answers sources with nothing unhealthy, and on
427 // the worker read says the answer's first line and stalls as a sleep
428 // of a length nothing else in this process sleeps.
429 header := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}`
430 stall := fmt.Sprintf("#!/bin/sh\necho '%s'\ncase \"$*\" in *\"valley-telemetry sources\"*) echo '{\"kind\":\"end\"}'; exit 0 ;; esac\nexec sleep 86399\n", header)
431 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(stall), 0o755); err != nil {
432 t.Fatal(err)
433 }
434 sh, _ := policyProject(t, filepath.Join(dir, "origin"), 1)
435 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
436
437 began := time.Now()
438 var stdout, stderr bytes.Buffer
439 if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 {
440 t.Fatalf("pending: %s", stderr.String())
441 }
442 // The read's own time limit is 30 s: a pending that waited for it
443 // would take that long.
444 if took := time.Since(began); took > 20*time.Second {
445 t.Errorf("pending took %s beside a stalled host", took)
446 }
447 if !strings.Contains(stdout.String(), "nothing needs you") || stderr.Len() != 0 {
448 t.Errorf("pending beside a stalled host printed:\n%s\nand said:\n%s", stdout.String(), stderr.String())
449 }
450 stats, _ := filepath.Glob("/proc/[0-9]*/stat")
451 for _, stat := range stats {
452 data, err := os.ReadFile(stat)
453 if err != nil {
454 continue
455 }
456 f := strings.Fields(string(data[bytes.LastIndexByte(data, ')')+1:]))
457 cmdline, _ := os.ReadFile(filepath.Join(filepath.Dir(stat), "cmdline"))
458 if len(f) > 1 && f[1] == fmt.Sprint(os.Getpid()) && strings.Contains(string(cmdline), "86399") {
459 t.Errorf("pending left its ssh running: %s", filepath.Dir(stat))
460 }
461 }
462}
463
464// pending --checks reads a draft's checks only when --drafts lists the
465// drafts. With no evidence on origin it starts no attest: a head's tree
466// digest is worked out in-process. Without --drafts, two drafts add
467// nothing to what --checks starts and change no row; with it, each
468// draft's checks are read and its block shows them.
469func TestPendingReadsDraftChecksOnlyWhenListed(t *testing.T) {
470 dir := t.TempDir()
471 starts := toolsOnPath(t, dir, "git", "cue")
472 // attest logs its start as the shims do. Origin holds no evidence, and
473 // a head's tree digest is worked out in-process, so nothing starts it.
474 stand := fmt.Sprintf("#!/bin/sh\necho attest >> '%s'\n", starts)
475 if err := os.WriteFile(filepath.Join(dir, "bin", "attest"), []byte(stand), 0o755); err != nil {
476 t.Fatal(err)
477 }
478 _, head := policyProject(t, filepath.Join(dir, "project"), 2)
479 head("ready-1", strings.Repeat("p", 32))
480 // listing is pending with args and --checks: what it printed, its ages
481 // left out, since a row's age ticks, the attest processes it started,
482 // and how many processes --checks added.
483 ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$`)
484 listing := func(args ...string) (out string, attest, added int) {
485 t.Helper()
486 _, without := runCounted(t, starts, append([]string{"pending"}, args...)...)
487 out, with := runCounted(t, starts, append([]string{"pending", "--checks"}, args...)...)
488 return ages.ReplaceAllString(out, ""), with["attest"], with[""] - without[""]
489 }
490 listing() // so every count is of a listing whose caches are warm
491 before, attest, added := listing()
492 if attest != 0 {
493 t.Fatalf("pending --checks started attest %d times for one ready head and no evidence", attest)
494 }
495 for _, id := range []string{"q", "r"} {
496 head("draft-"+id, strings.Repeat(id, 32))
497 var stdout, stderr bytes.Buffer
498 if code := run([]string{"unready", strings.Repeat(id, 32)}, &stdout, &stderr, os.Exit); code != 0 {
499 t.Fatalf("unready: %s", stderr.String())
500 }
501 }
502 after, drafted, addedNow := listing()
503 if drafted != attest || addedNow != added {
504 t.Errorf("with two drafts not listed, pending --checks started attest %d times, not %d, and --checks added %d processes, not %d",
505 drafted, attest, addedNow, added)
506 }
507 if want := before + "\n2 drafts · valley pending --drafts\n"; after != want {
508 t.Errorf("pending --checks printed, with two drafts:\n%s\nand with none:\n%s", after, before)
509 }
510 out, listed, addedListed := listing("--drafts")
511 if listed != 0 || addedListed <= added {
512 t.Errorf("pending --drafts --checks started attest %d times, and --checks added %d processes, not more than %d, for one ready head and two drafts",
513 listed, addedListed, added)
514 }
515 for _, d := range []string{"qqqq v1 on draft-q 2 checks pending", "rrrr v1 on draft-r 2 checks pending"} {
516 if !strings.Contains(out, "\n"+d) {
517 t.Errorf("pending --drafts --checks does not open a block with %q:\n%s", d, out)
518 }
519 }
520 if n := strings.Count(out, "\n checks: 2 pending\n"); n != 2 {
521 t.Errorf("pending --drafts --checks gives %d drafts their checks line, not 2:\n%s", n, out)
522 }
523}
524
525// pending --checks says when the worker's newest build of a pending
526// check failed, for a ready change and for a draft alike, apart from a
527// check whose failed build a later one passed and a check never built, and
528// says where the worker's report is read. With --json, the check's state
529// stays pending and the worker's report is beside it. A batch that failed
530// before any check ran is said the same way. A host whose telemetry does
531// not read leaves the listing as it is with no worker records.
532func TestPendingSaysWhenTheWorkersBuildFailed(t *testing.T) {
533 dir := t.TempDir()
534 toolsOnPath(t, dir, "git", "cue")
535 // ssh answers the worker's read from a file, as the host would.
536 answer := filepath.Join(dir, "answer")
537 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(fmt.Sprintf("#!/bin/sh\ncat '%s'\n", answer)), 0o755); err != nil {
538 t.Fatal(err)
539 }
540 sh, head := policyProject(t, filepath.Join(dir, "origin"), 3)
541 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
542 ready, draft := strings.Repeat("p", 32), strings.Repeat("q", 32)
543 head("ready-1", ready)
544 head("draft-1", draft)
545 var stdout, stderr bytes.Buffer
546 if code := run([]string{"unready", draft}, &stdout, &stderr, os.Exit); code != 0 {
547 t.Fatalf("unready: %s", stderr.String())
548 }
549 // The worker's records about a tree are about the ready change's and
550 // the draft's alike: each is written once for each head's tree.
551 var trees []string
552 for _, branch := range []string{"ready-1", "draft-1"} {
553 tree, err := rememberedDigest(git{env: gitEnvironment(os.Environ())}, branch)
554 if err != nil {
555 t.Fatal(err)
556 }
557 trees = append(trees, tree)
558 }
559
560 // records makes the host's answer: one page of the worker's records,
561 // each about each head's tree where it names the tree "0123".
562 records := func(given ...string) {
563 t.Helper()
564 var lines []string
565 for _, l := range given {
566 for _, tree := range trees {
567 lines = append(lines, strings.ReplaceAll(l, `"tree":"0123"`, `"tree":"`+tree+`"`))
568 }
569 }
570 page := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}` + "\n"
571 for i, l := range lines {
572 page += fmt.Sprintf(`{"kind":"record","stream":"worker","seq":%d,%s}`+"\n", i+1, l)
573 }
574 page += fmt.Sprintf(`{"kind":"end","cursor":"worker=0123456789abcdef:%d","truncated":false}`+"\n", len(lines))
575 if err := os.WriteFile(answer, []byte(page), 0o644); err != nil {
576 t.Fatal(err)
577 }
578 }
579 at := func(ago time.Duration) string { return telemetry.Stamp(time.Now().Add(-ago)) }
580 // build is a check.result of the draft's version, as attest records
581 // one.
582 build := func(when, run, tree, check, result string) string {
583 return fmt.Sprintf(`"type":"check.result","time":%q,"run":%q,"project":"origin","change":%q,"version":1,"tree":%q,"check":%q,`+
584 `"data":{"result":%q,"build_ms":1000,"eval_ms":4000,"log_bytes":10,"cached":false}`, when, run, draft, tree, check, result)
585 }
586 ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$| +[0-9]+ [a-z]+ ago · operator$`)
587 pending := func(args ...string) (string, string) {
588 t.Helper()
589 var stdout, stderr bytes.Buffer
590 if code := run(append([]string{"pending", "--checks", "--drafts"}, args...), &stdout, &stderr, os.Exit); code != 0 {
591 t.Fatalf("pending: %s", stderr.String())
592 }
593 return ages.ReplaceAllString(stdout.String(), ""), stderr.String()
594 }
595 checksOf := func() map[string]*jsonVersionChecks {
596 t.Helper()
597 out, _ := pending("--json")
598 var doc jsonChanges
599 if err := json.Unmarshal([]byte(out), &doc); err != nil || len(doc.Repos) != 1 || doc.Repos[0].Drafts == nil {
600 t.Fatalf("pending --json printed no listing of one project (%v):\n%s", err, out)
601 }
602 checks := map[string]*jsonVersionChecks{}
603 for _, c := range append(doc.Repos[0].Changes, *doc.Repos[0].Drafts...) {
604 checks[c.ChangeID] = c.Versions[c.Active-1].Checks
605 }
606 if len(checks) != 2 {
607 t.Fatalf("pending --json lists %d changes, not the ready change and the draft:\n%s", len(checks), out)
608 }
609 return checks
610 }
611 see := " see: valley telemetry read --source worker --logs"
612
613 records()
614 plain, _ := pending()
615
616 // c-1's newest build failed; c-2 failed, then passed; c-3 was built
617 // only for another tree.
618 failed := at(5*time.Minute + 10*time.Second)
619 records(build(at(20*time.Minute), "r1", "0123", "c-1", "failed"), build(at(20*time.Minute), "r1", "0123", "c-2", "failed"),
620 build(failed, "r2", "0123", "c-1", "failed"), build(at(5*time.Minute), "r2", "0123", "c-2", "passed"),
621 build(at(time.Minute), "r3", "4567", "c-3", "failed"))
622 out, _ := pending()
623 says := "c-1 failed in the worker's build, 5m ago"
624 for _, want := range []string{
625 "\n 1 pppp v1 ✗ " + says + "\n ready-1\n requires 3 quick checks, 0 slow\n" +
626 " checks: 3 pending (" + says + ")\n " + see + "\n",
627 "\nqqqq v1 on draft-1 ✗ " + says + "\n",
628 "\n requires 3 quick checks, 0 slow\n checks: 3 pending (" + says + ") in 2s (eval 4s)\n " + see + "\n",
629 } {
630 if !strings.Contains(out, want) {
631 t.Errorf("pending --checks --drafts does not say\n%s\nin:\n%s", want, out)
632 }
633 }
634 for id, c := range checksOf() {
635 if c == nil || c.State != checkPending || c.Worker != nil || len(c.Required) != 3 {
636 t.Fatalf("%s's checks are not three, pending, with no batch reported: %+v", id, c)
637 }
638 if q := c.Required[0]; q.State != checkPending || q.Worker == nil || *q.Worker != (jsonWorkerReport{Result: checkFailed, Time: failed, Run: "r2"}) {
639 t.Errorf("%s's c-1 is not pending with the worker's report of r2's failure: %+v", id, q)
640 }
641 for _, q := range c.Required[1:] {
642 if q.State != checkPending || q.Worker != nil {
643 t.Errorf("%s's %s is not pending with no worker's report: %+v", id, q.Name, q)
644 }
645 }
646 }
647
648 // A batch that failed before any check ran recorded no check's result.
649 ended := at(time.Minute + 10*time.Second)
650 records(build(at(20*time.Minute), "r1", "0123", "c-1", "passed"),
651 fmt.Sprintf(`"type":"batch.end","time":%q,"run":"p1","project":"origin","change":%q,"version":1,"tree":"0123",`+
652 `"data":{"result":"failed","attest_run":"r4","reason":"attest run r4: exit status 1"}`, ended, ready))
653 out, _ = pending()
654 says = "the worker's batch failed, 1m ago"
655 if want := "\n 1 pppp v1 ✗ " + says + "\n ready-1\n requires 3 quick checks, 0 slow\n" +
656 " checks: 3 pending (" + says + ")\n " + see + "\n"; !strings.Contains(out, want) {
657 t.Errorf("pending --checks does not say\n%s\nin:\n%s", want, out)
658 }
659 for id, c := range checksOf() {
660 if c.Worker == nil || *c.Worker != (jsonWorkerReport{Result: checkFailed, Time: ended, Run: "r4"}) || c.State != checkPending {
661 t.Errorf("%s's checks do not carry the worker's report of the failed batch: %+v", id, c)
662 }
663 }
664
665 // A host that refuses: the listing is as it is with no worker records.
666 if err := os.WriteFile(answer, []byte(`{"kind":"error","error":"operator holds no observe grant"}`+"\n"), 0o644); err != nil {
667 t.Fatal(err)
668 }
669 out, errs := pending()
670 if out != plain {
671 t.Errorf("with the worker's telemetry refused, pending printed:\n%s\nand with no worker records:\n%s", out, plain)
672 }
673 if n := strings.Count(errs, "no check lists its build times"); n != 1 {
674 t.Errorf("a refusing host was said %d times on stderr, not once:\n%s", n, errs)
675 }
676 for id, c := range checksOf() {
677 reported := c.Worker != nil
678 for _, q := range c.Required {
679 reported = reported || q.Worker != nil
680 }
681 if reported {
682 t.Errorf("with the worker's telemetry refused, %s carries a worker's report: %+v", id, c)
683 }
684 }
685}
686
687// unheard opens a FIFO to write and closes it, so a reader still waiting
688// on it reads nothing and ends.
689func unheard(fifo string) {
690 if f, err := os.OpenFile(fifo, os.O_WRONLY|syscall.O_NONBLOCK, 0); err == nil {
691 f.Close()
692 }
693}
694
695// bareGit is git run in the bare repository origin, with stdin, giving
696// what it printed.
697func bareGit(t *testing.T, origin string) func(stdin string, args ...string) string {
698 return func(stdin string, args ...string) string {
699 t.Helper()
700 cmd := exec.Command("git", append([]string{"--git-dir", origin}, args...)...)
701 cmd.Stdin = strings.NewReader(stdin)
702 out, err := cmd.Output()
703 if err != nil {
704 t.Fatalf("git %s: %v", strings.Join(args, " "), err)
705 }
706 return strings.TrimSpace(string(out))
707 }
708}
709
710// publishSigners publishes the host's signers in origin, a bare
711// repository whose main carries its own instance: a key for each name,
712// and the integrator's name, integrator.
713func publishSigners(t *testing.T, origin string, names ...string) {
714 t.Helper()
715 in := bareGit(t, origin)
716 var keys strings.Builder
717 for _, name := range names {
718 pub, _, err := ed25519.GenerateKey(nil)
719 if err != nil {
720 t.Fatal(err)
721 }
722 keys.WriteString(note.NewVerifierKey(name, pub).String() + "\n")
723 }
724 blob := func(text string) string { return in(text, "hash-object", "-w", "--stdin") }
725 in("", "update-ref", signersRef, in(fmt.Sprintf("100644 blob %s\tintegrator-name\n100644 blob %s\tknown-signers\n",
726 blob("integrator\n"), blob(keys.String())), "mktree"))
727}
728
729// Each reader of evidence reads the host's signers as its use says. An
730// assessment, as approve, review's approve step and checks --build make
731// one, reads the publication afresh each time, so a worker key removed or
732// published again between two assessments in one command is honoured by
733// the second. A listing, which displays and authorises nothing, reads it
734// once in the command, with transfer verification and main's walk.
735func TestEvidenceReadsTheSignersAsItsUseSays(t *testing.T) {
736 dir := t.TempDir()
737 real, err := exec.LookPath("git")
738 if err != nil {
739 t.Skip("no git to run")
740 }
741 self, err := os.Executable()
742 if err != nil {
743 t.Fatal(err)
744 }
745 starts, bin := filepath.Join(dir, "starts"), filepath.Join(dir, "bin")
746 origin := filepath.Join(dir, "origin", "origin.git")
747 policyProject(t, filepath.Join(dir, "origin"), 1)
748 publish := func(names ...string) { publishSigners(t, origin, names...) }
749 publish("integrator", "worker")
750 // The worker's note about c-1, stored for the digest the attest
751 // stand-in gives every tree (fakeAttest), which verifies a note's
752 // signer when the known-signers file holds its key (fakeVerify).
753 in := bareGit(t, origin)
754 stored := in("predicateType "+predicatePure+"\npredicate.check.name c-1\npredicate.check.runner nix\n"+
755 "predicate.check.attribute c-1\npredicate.result passed\nsigner worker+00000001\n\n— worker signature\n",
756 "hash-object", "-w", "--stdin")
757 check := in(fmt.Sprintf("100644 blob %s\tstatement.note\n", stored), "mktree")
758 in("", "update-ref", attestationRefs+strings.Repeat("ab", 32)+"/00000001",
759 in(fmt.Sprintf("040000 tree %s\tc-1\n", check), "mktree"))
760 if err := os.MkdirAll(bin, 0o755); err != nil {
761 t.Fatal(err)
762 }
763 shim := fmt.Sprintf("#!/bin/sh\necho \"$*\" >> '%s'\nexec '%s' \"$@\"\n", starts, real)
764 if err := os.WriteFile(filepath.Join(bin, "git"), []byte(shim), 0o755); err != nil {
765 t.Fatal(err)
766 }
767 if err := os.Symlink(self, filepath.Join(bin, "attest")); err != nil {
768 t.Fatal(err)
769 }
770 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
771 t.Setenv("VALLEY_TEST_ATTEST_VERIFY", "batch")
772 reads := func() int {
773 log, _ := os.ReadFile(starts)
774 n := 0
775 for _, line := range strings.Split(string(log), "\n") {
776 if f := strings.Fields(line); slices.Contains(f, "ls-remote") && slices.Contains(f, signersRef) {
777 n++
778 }
779 }
780 return n
781 }
782
783 g := git{env: gitEnvironment(os.Environ()), stderr: io.Discard}
784 before := verification
785 verification = &signerSource{g: g, stderr: io.Discard}
786 defer func() { verification = before }()
787 tip, err := g.output(true, "rev-parse", "HEAD")
788 if err != nil {
789 t.Fatal(err)
790 }
791 checks := []nixCheck{{"c-1", "c-1"}}
792 covered := func(e evidence, err error) bool {
793 t.Helper()
794 if err != nil {
795 t.Fatal(err)
796 }
797 return e.covered["c-1"] != ""
798 }
799
800 approving := &approval{}
801 first := covered(approving.coverage(g, tip, checks, io.Discard))
802 publish("integrator")
803 revoked := covered(approving.coverage(g, tip, checks, io.Discard))
804 publish("integrator", "worker")
805 restored := covered(approving.coverage(g, tip, checks, io.Discard))
806 if !first || revoked || !restored || reads() != 3 {
807 t.Errorf("approve's assessments covered c-1: %v, with the worker's key removed %v, restored %v, in %d reads of the signers, not 3",
808 first, revoked, restored, reads())
809 }
810
811 building := newAsking(g, io.Discard, io.Discard)
812 building.head = tip
813 first = covered(building.cover(checks))
814 publish("integrator")
815 revoked = covered(building.cover(checks))
816 if !first || revoked || reads() != 5 {
817 t.Errorf("checks --build's assessments covered c-1: %v, with the worker's key removed %v, in %d reads of the signers, not 5",
818 first, revoked, reads())
819 }
820
821 publish("integrator", "worker")
822 _, name, _ := verification.resolve() // transfer verification
823 walk := hostKeys{use: listEvidence} // main's walk
824 defer walk.done()
825 _, walked, why := walk.read(g)
826 publish("integrator")
827 keys, listedP, unsigned := hostSignersFrom(g, listEvidence.signers()) // a listing's evidence
828 if unsigned == "" {
829 defer os.Remove(keys)
830 }
831 if why != "" || unsigned != "" || walked == nil || walked != listedP || name != "integrator" || reads() != 6 {
832 t.Errorf("a listing read the signers %d times, not once more: transfers %q, the walk %p (%s), the evidence %p (%s)",
833 reads()-5, name, walked, why, listedP, unsigned)
834 }
835}