gunk-dev/the-valley

pending_test.go

source64f5539ce840main's published tip history
33.9 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, as it does when
358// the principal already has every bounded request it may have open,
359// leaves main's line without the worker's runs: pending says why once,
360// asks the host once, and prints main's line from the walk alone.
361func TestPendingAsksARefusingHostOnce(t *testing.T) {
362 dir := t.TempDir()
363 starts := toolsOnPath(t, dir, "git", "cue")
364 refusal := `{"kind":"error","error":"operator already has 4 bounded requests open; try again when one ends"}`
365 ssh := fmt.Sprintf("#!/bin/sh\necho ssh >> '%s'\necho '%s'\n", starts, refusal)
366 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil {
367 t.Fatal(err)
368 }
369 followProject(t, filepath.Join(dir, "origin"))
370
371 os.Remove(starts)
372 var stdout, stderr bytes.Buffer
373 if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 {
374 t.Fatalf("pending: %s", stderr.String())
375 }
376 log, _ := os.ReadFile(starts)
377 if n := strings.Count(string(log), "ssh"); n != 1 {
378 t.Errorf("pending asked the refusing host %d times", n)
379 }
380 if n := strings.Count(stderr.String(), "refused"); n != 1 || strings.Count(stderr.String(), "\n") != 1 {
381 t.Errorf("pending said, of the refusal:\n%s", stderr.String())
382 }
383 if !strings.HasPrefix(stdout.String(), "main ◐ clearing · f-1 due · covers ") {
384 t.Errorf("pending's main line, with the host refusing:\n%s", stdout.String())
385 }
386}
387
388// followProject is policyProject with a class that check f-1 follows, a
389// landing on main that sets it due, and its telemetry read from an ssh
390// host, so valley pending waits on the worker's telemetry for main's line.
391func followProject(t *testing.T, root string) {
392 t.Helper()
393 sh, head := policyProject(t, root, 1)
394 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
395 floor := "package verification\nfloor: {\n" +
396 "\tchecks: \"c-1\": {runner: \"nix\", attribute: \"c-1\"}\n" +
397 "\tchecks: \"f-1\": {runner: \"nix\", attribute: \"f-1\"}\n" +
398 "\tclasses: src: {paths: \"src/**\": true, requires: \"c-1\": true, follows: \"f-1\": true}\n" +
399 "\tunclassified: \"c-1\": true\n}\n"
400 if err := os.WriteFile(filepath.Join("policy", "instance", "floor.cue"), []byte(floor), 0o644); err != nil {
401 t.Fatal(err)
402 }
403 sh("commit", "--quiet", "-a", "-m", "follow f-1")
404 sh("push", "--quiet", "origin", "main")
405 head("landed", strings.Repeat("p", 32))
406 sh("checkout", "--quiet", "main")
407 sh("merge", "--quiet", "--ff-only", "landed")
408 sh("push", "--quiet", "origin", "main")
409}
410
411// A host that accepts the read of the worker's telemetry and then stalls
412// does not hold valley pending, nor outlive it: with no follow check and
413// nothing ready, nothing waits on the read, so pending cancels it as it
414// returns, and no ssh it started is left running.
415func TestPendingEndsAReadNobodyWaitsFor(t *testing.T) {
416 if _, err := os.Stat("/proc/self/stat"); err != nil {
417 t.Skip("no /proc to find a child left running in")
418 }
419 dir := t.TempDir()
420 toolsOnPath(t, dir, "git", "cue")
421 // ssh is the host: it says the answer's first line, and stalls as a
422 // sleep of a length nothing else in this process sleeps.
423 header := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}`
424 stall := fmt.Sprintf("#!/bin/sh\necho '%s'\nexec sleep 86399\n", header)
425 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(stall), 0o755); err != nil {
426 t.Fatal(err)
427 }
428 sh, _ := policyProject(t, filepath.Join(dir, "origin"), 1)
429 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
430
431 began := time.Now()
432 var stdout, stderr bytes.Buffer
433 if code := run([]string{"pending"}, &stdout, &stderr, os.Exit); code != 0 {
434 t.Fatalf("pending: %s", stderr.String())
435 }
436 // The read's own time limit is 30 s: a pending that waited for it
437 // would take that long.
438 if took := time.Since(began); took > 20*time.Second {
439 t.Errorf("pending took %s beside a stalled host", took)
440 }
441 if !strings.Contains(stdout.String(), "nothing needs you") || stderr.Len() != 0 {
442 t.Errorf("pending beside a stalled host printed:\n%s\nand said:\n%s", stdout.String(), stderr.String())
443 }
444 stats, _ := filepath.Glob("/proc/[0-9]*/stat")
445 for _, stat := range stats {
446 data, err := os.ReadFile(stat)
447 if err != nil {
448 continue
449 }
450 f := strings.Fields(string(data[bytes.LastIndexByte(data, ')')+1:]))
451 cmdline, _ := os.ReadFile(filepath.Join(filepath.Dir(stat), "cmdline"))
452 if len(f) > 1 && f[1] == fmt.Sprint(os.Getpid()) && strings.Contains(string(cmdline), "86399") {
453 t.Errorf("pending left its ssh running: %s", filepath.Dir(stat))
454 }
455 }
456}
457
458// pending --checks reads a draft's checks only when --drafts lists the
459// drafts. With no evidence on origin it starts no attest: a head's tree
460// digest is worked out in-process. Without --drafts, two drafts add
461// nothing to what --checks starts and change no row; with it, each
462// draft's checks are read and its block shows them.
463func TestPendingReadsDraftChecksOnlyWhenListed(t *testing.T) {
464 dir := t.TempDir()
465 starts := toolsOnPath(t, dir, "git", "cue")
466 // attest logs its start as the shims do. Origin holds no evidence, and
467 // a head's tree digest is worked out in-process, so nothing starts it.
468 stand := fmt.Sprintf("#!/bin/sh\necho attest >> '%s'\n", starts)
469 if err := os.WriteFile(filepath.Join(dir, "bin", "attest"), []byte(stand), 0o755); err != nil {
470 t.Fatal(err)
471 }
472 _, head := policyProject(t, filepath.Join(dir, "project"), 2)
473 head("ready-1", strings.Repeat("p", 32))
474 // listing is pending with args and --checks: what it printed, its ages
475 // left out, since a row's age ticks, the attest processes it started,
476 // and how many processes --checks added.
477 ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$`)
478 listing := func(args ...string) (out string, attest, added int) {
479 t.Helper()
480 _, without := runCounted(t, starts, append([]string{"pending"}, args...)...)
481 out, with := runCounted(t, starts, append([]string{"pending", "--checks"}, args...)...)
482 return ages.ReplaceAllString(out, ""), with["attest"], with[""] - without[""]
483 }
484 listing() // so every count is of a listing whose caches are warm
485 before, attest, added := listing()
486 if attest != 0 {
487 t.Fatalf("pending --checks started attest %d times for one ready head and no evidence", attest)
488 }
489 for _, id := range []string{"q", "r"} {
490 head("draft-"+id, strings.Repeat(id, 32))
491 var stdout, stderr bytes.Buffer
492 if code := run([]string{"unready", strings.Repeat(id, 32)}, &stdout, &stderr, os.Exit); code != 0 {
493 t.Fatalf("unready: %s", stderr.String())
494 }
495 }
496 after, drafted, addedNow := listing()
497 if drafted != attest || addedNow != added {
498 t.Errorf("with two drafts not listed, pending --checks started attest %d times, not %d, and --checks added %d processes, not %d",
499 drafted, attest, addedNow, added)
500 }
501 if want := before + "\n2 drafts · valley pending --drafts\n"; after != want {
502 t.Errorf("pending --checks printed, with two drafts:\n%s\nand with none:\n%s", after, before)
503 }
504 out, listed, addedListed := listing("--drafts")
505 if listed != 0 || addedListed <= added {
506 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",
507 listed, addedListed, added)
508 }
509 for _, d := range []string{"qqqq v1 on draft-q 2 checks pending", "rrrr v1 on draft-r 2 checks pending"} {
510 if !strings.Contains(out, "\n"+d) {
511 t.Errorf("pending --drafts --checks does not open a block with %q:\n%s", d, out)
512 }
513 }
514 if n := strings.Count(out, "\n checks: 2 pending\n"); n != 2 {
515 t.Errorf("pending --drafts --checks gives %d drafts their checks line, not 2:\n%s", n, out)
516 }
517}
518
519// pending --checks says when the worker's newest build of a pending
520// check failed, for a ready change and for a draft alike, apart from a
521// check whose failed build a later one passed and a check never built, and
522// says where the worker's report is read. With --json, the check's state
523// stays pending and the worker's report is beside it. A batch that failed
524// before any check ran is said the same way. A host whose telemetry does
525// not read leaves the listing as it is with no worker records.
526func TestPendingSaysWhenTheWorkersBuildFailed(t *testing.T) {
527 dir := t.TempDir()
528 toolsOnPath(t, dir, "git", "cue")
529 // ssh answers the worker's read from a file, as the host would.
530 answer := filepath.Join(dir, "answer")
531 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(fmt.Sprintf("#!/bin/sh\ncat '%s'\n", answer)), 0o755); err != nil {
532 t.Fatal(err)
533 }
534 sh, head := policyProject(t, filepath.Join(dir, "origin"), 3)
535 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
536 ready, draft := strings.Repeat("p", 32), strings.Repeat("q", 32)
537 head("ready-1", ready)
538 head("draft-1", draft)
539 var stdout, stderr bytes.Buffer
540 if code := run([]string{"unready", draft}, &stdout, &stderr, os.Exit); code != 0 {
541 t.Fatalf("unready: %s", stderr.String())
542 }
543 // The worker's records about a tree are about the ready change's and
544 // the draft's alike: each is written once for each head's tree.
545 var trees []string
546 for _, branch := range []string{"ready-1", "draft-1"} {
547 tree, err := rememberedDigest(git{env: gitEnvironment(os.Environ())}, branch)
548 if err != nil {
549 t.Fatal(err)
550 }
551 trees = append(trees, tree)
552 }
553
554 // records makes the host's answer: one page of the worker's records,
555 // each about each head's tree where it names the tree "0123".
556 records := func(given ...string) {
557 t.Helper()
558 var lines []string
559 for _, l := range given {
560 for _, tree := range trees {
561 lines = append(lines, strings.ReplaceAll(l, `"tree":"0123"`, `"tree":"`+tree+`"`))
562 }
563 }
564 page := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}` + "\n"
565 for i, l := range lines {
566 page += fmt.Sprintf(`{"kind":"record","stream":"worker","seq":%d,%s}`+"\n", i+1, l)
567 }
568 page += fmt.Sprintf(`{"kind":"end","cursor":"worker=0123456789abcdef:%d","truncated":false}`+"\n", len(lines))
569 if err := os.WriteFile(answer, []byte(page), 0o644); err != nil {
570 t.Fatal(err)
571 }
572 }
573 at := func(ago time.Duration) string { return telemetry.Stamp(time.Now().Add(-ago)) }
574 // build is a check.result of the draft's version, as attest records
575 // one.
576 build := func(when, run, tree, check, result string) string {
577 return fmt.Sprintf(`"type":"check.result","time":%q,"run":%q,"project":"origin","change":%q,"version":1,"tree":%q,"check":%q,`+
578 `"data":{"result":%q,"build_ms":1000,"eval_ms":4000,"log_bytes":10,"cached":false}`, when, run, draft, tree, check, result)
579 }
580 ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$| +[0-9]+ [a-z]+ ago · operator$`)
581 pending := func(args ...string) (string, string) {
582 t.Helper()
583 var stdout, stderr bytes.Buffer
584 if code := run(append([]string{"pending", "--checks", "--drafts"}, args...), &stdout, &stderr, os.Exit); code != 0 {
585 t.Fatalf("pending: %s", stderr.String())
586 }
587 return ages.ReplaceAllString(stdout.String(), ""), stderr.String()
588 }
589 checksOf := func() map[string]*jsonVersionChecks {
590 t.Helper()
591 out, _ := pending("--json")
592 var doc jsonChanges
593 if err := json.Unmarshal([]byte(out), &doc); err != nil || len(doc.Repos) != 1 || doc.Repos[0].Drafts == nil {
594 t.Fatalf("pending --json printed no listing of one project (%v):\n%s", err, out)
595 }
596 checks := map[string]*jsonVersionChecks{}
597 for _, c := range append(doc.Repos[0].Changes, *doc.Repos[0].Drafts...) {
598 checks[c.ChangeID] = c.Versions[c.Active-1].Checks
599 }
600 if len(checks) != 2 {
601 t.Fatalf("pending --json lists %d changes, not the ready change and the draft:\n%s", len(checks), out)
602 }
603 return checks
604 }
605 see := " see: valley telemetry read --source worker --logs"
606
607 records()
608 plain, _ := pending()
609
610 // c-1's newest build failed; c-2 failed, then passed; c-3 was built
611 // only for another tree.
612 failed := at(5*time.Minute + 10*time.Second)
613 records(build(at(20*time.Minute), "r1", "0123", "c-1", "failed"), build(at(20*time.Minute), "r1", "0123", "c-2", "failed"),
614 build(failed, "r2", "0123", "c-1", "failed"), build(at(5*time.Minute), "r2", "0123", "c-2", "passed"),
615 build(at(time.Minute), "r3", "4567", "c-3", "failed"))
616 out, _ := pending()
617 says := "c-1 failed in the worker's build, 5m ago"
618 for _, want := range []string{
619 "\n 1 pppp v1 ✗ " + says + "\n ready-1\n requires 3 quick checks, 0 slow\n" +
620 " checks: 3 pending (" + says + ")\n " + see + "\n",
621 "\nqqqq v1 on draft-1 ✗ " + says + "\n",
622 "\n requires 3 quick checks, 0 slow\n checks: 3 pending (" + says + ") in 2s (eval 4s)\n " + see + "\n",
623 } {
624 if !strings.Contains(out, want) {
625 t.Errorf("pending --checks --drafts does not say\n%s\nin:\n%s", want, out)
626 }
627 }
628 for id, c := range checksOf() {
629 if c == nil || c.State != checkPending || c.Worker != nil || len(c.Required) != 3 {
630 t.Fatalf("%s's checks are not three, pending, with no batch reported: %+v", id, c)
631 }
632 if q := c.Required[0]; q.State != checkPending || q.Worker == nil || *q.Worker != (jsonWorkerReport{Result: checkFailed, Time: failed, Run: "r2"}) {
633 t.Errorf("%s's c-1 is not pending with the worker's report of r2's failure: %+v", id, q)
634 }
635 for _, q := range c.Required[1:] {
636 if q.State != checkPending || q.Worker != nil {
637 t.Errorf("%s's %s is not pending with no worker's report: %+v", id, q.Name, q)
638 }
639 }
640 }
641
642 // A batch that failed before any check ran recorded no check's result.
643 ended := at(time.Minute + 10*time.Second)
644 records(build(at(20*time.Minute), "r1", "0123", "c-1", "passed"),
645 fmt.Sprintf(`"type":"batch.end","time":%q,"run":"p1","project":"origin","change":%q,"version":1,"tree":"0123",`+
646 `"data":{"result":"failed","attest_run":"r4","reason":"attest run r4: exit status 1"}`, ended, ready))
647 out, _ = pending()
648 says = "the worker's batch failed, 1m ago"
649 if want := "\n 1 pppp v1 ✗ " + says + "\n ready-1\n requires 3 quick checks, 0 slow\n" +
650 " checks: 3 pending (" + says + ")\n " + see + "\n"; !strings.Contains(out, want) {
651 t.Errorf("pending --checks does not say\n%s\nin:\n%s", want, out)
652 }
653 for id, c := range checksOf() {
654 if c.Worker == nil || *c.Worker != (jsonWorkerReport{Result: checkFailed, Time: ended, Run: "r4"}) || c.State != checkPending {
655 t.Errorf("%s's checks do not carry the worker's report of the failed batch: %+v", id, c)
656 }
657 }
658
659 // A host that refuses: the listing is as it is with no worker records.
660 if err := os.WriteFile(answer, []byte(`{"kind":"error","error":"operator holds no observe grant"}`+"\n"), 0o644); err != nil {
661 t.Fatal(err)
662 }
663 out, errs := pending()
664 if out != plain {
665 t.Errorf("with the worker's telemetry refused, pending printed:\n%s\nand with no worker records:\n%s", out, plain)
666 }
667 if n := strings.Count(errs, "no check lists its build times"); n != 1 {
668 t.Errorf("a refusing host was said %d times on stderr, not once:\n%s", n, errs)
669 }
670 for id, c := range checksOf() {
671 reported := c.Worker != nil
672 for _, q := range c.Required {
673 reported = reported || q.Worker != nil
674 }
675 if reported {
676 t.Errorf("with the worker's telemetry refused, %s carries a worker's report: %+v", id, c)
677 }
678 }
679}
680
681// unheard opens a FIFO to write and closes it, so a reader still waiting
682// on it reads nothing and ends.
683func unheard(fifo string) {
684 if f, err := os.OpenFile(fifo, os.O_WRONLY|syscall.O_NONBLOCK, 0); err == nil {
685 f.Close()
686 }
687}
688
689// bareGit is git run in the bare repository origin, with stdin, giving
690// what it printed.
691func bareGit(t *testing.T, origin string) func(stdin string, args ...string) string {
692 return func(stdin string, args ...string) string {
693 t.Helper()
694 cmd := exec.Command("git", append([]string{"--git-dir", origin}, args...)...)
695 cmd.Stdin = strings.NewReader(stdin)
696 out, err := cmd.Output()
697 if err != nil {
698 t.Fatalf("git %s: %v", strings.Join(args, " "), err)
699 }
700 return strings.TrimSpace(string(out))
701 }
702}
703
704// publishSigners publishes the host's signers in origin, a bare
705// repository whose main carries its own instance: a key for each name,
706// and the integrator's name, integrator.
707func publishSigners(t *testing.T, origin string, names ...string) {
708 t.Helper()
709 in := bareGit(t, origin)
710 var keys strings.Builder
711 for _, name := range names {
712 pub, _, err := ed25519.GenerateKey(nil)
713 if err != nil {
714 t.Fatal(err)
715 }
716 keys.WriteString(note.NewVerifierKey(name, pub).String() + "\n")
717 }
718 blob := func(text string) string { return in(text, "hash-object", "-w", "--stdin") }
719 in("", "update-ref", signersRef, in(fmt.Sprintf("100644 blob %s\tintegrator-name\n100644 blob %s\tknown-signers\n",
720 blob("integrator\n"), blob(keys.String())), "mktree"))
721}
722
723// Each reader of evidence reads the host's signers as its use says. An
724// assessment, as approve, review's approve step and checks --build make
725// one, reads the publication afresh each time, so a worker key removed or
726// published again between two assessments in one command is honoured by
727// the second. A listing, which displays and authorises nothing, reads it
728// once in the command, with transfer verification and main's walk.
729func TestEvidenceReadsTheSignersAsItsUseSays(t *testing.T) {
730 dir := t.TempDir()
731 real, err := exec.LookPath("git")
732 if err != nil {
733 t.Skip("no git to run")
734 }
735 self, err := os.Executable()
736 if err != nil {
737 t.Fatal(err)
738 }
739 starts, bin := filepath.Join(dir, "starts"), filepath.Join(dir, "bin")
740 origin := filepath.Join(dir, "origin", "origin.git")
741 policyProject(t, filepath.Join(dir, "origin"), 1)
742 publish := func(names ...string) { publishSigners(t, origin, names...) }
743 publish("integrator", "worker")
744 // The worker's note about c-1, stored for the digest the attest
745 // stand-in gives every tree (fakeAttest), which verifies a note's
746 // signer when the known-signers file holds its key (fakeVerify).
747 in := bareGit(t, origin)
748 stored := in("predicateType "+predicatePure+"\npredicate.check.name c-1\npredicate.check.runner nix\n"+
749 "predicate.check.attribute c-1\npredicate.result passed\nsigner worker+00000001\n\n— worker signature\n",
750 "hash-object", "-w", "--stdin")
751 check := in(fmt.Sprintf("100644 blob %s\tstatement.note\n", stored), "mktree")
752 in("", "update-ref", attestationRefs+strings.Repeat("ab", 32)+"/00000001",
753 in(fmt.Sprintf("040000 tree %s\tc-1\n", check), "mktree"))
754 if err := os.MkdirAll(bin, 0o755); err != nil {
755 t.Fatal(err)
756 }
757 shim := fmt.Sprintf("#!/bin/sh\necho \"$*\" >> '%s'\nexec '%s' \"$@\"\n", starts, real)
758 if err := os.WriteFile(filepath.Join(bin, "git"), []byte(shim), 0o755); err != nil {
759 t.Fatal(err)
760 }
761 if err := os.Symlink(self, filepath.Join(bin, "attest")); err != nil {
762 t.Fatal(err)
763 }
764 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
765 t.Setenv("VALLEY_TEST_ATTEST_VERIFY", "batch")
766 reads := func() int {
767 log, _ := os.ReadFile(starts)
768 n := 0
769 for _, line := range strings.Split(string(log), "\n") {
770 if f := strings.Fields(line); slices.Contains(f, "ls-remote") && slices.Contains(f, signersRef) {
771 n++
772 }
773 }
774 return n
775 }
776
777 g := git{env: gitEnvironment(os.Environ()), stderr: io.Discard}
778 before := verification
779 verification = &signerSource{g: g, stderr: io.Discard}
780 defer func() { verification = before }()
781 tip, err := g.output(true, "rev-parse", "HEAD")
782 if err != nil {
783 t.Fatal(err)
784 }
785 checks := []nixCheck{{"c-1", "c-1"}}
786 covered := func(e evidence, err error) bool {
787 t.Helper()
788 if err != nil {
789 t.Fatal(err)
790 }
791 return e.covered["c-1"] != ""
792 }
793
794 approving := &approval{}
795 first := covered(approving.coverage(g, tip, checks, io.Discard))
796 publish("integrator")
797 revoked := covered(approving.coverage(g, tip, checks, io.Discard))
798 publish("integrator", "worker")
799 restored := covered(approving.coverage(g, tip, checks, io.Discard))
800 if !first || revoked || !restored || reads() != 3 {
801 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",
802 first, revoked, restored, reads())
803 }
804
805 building := newAsking(g, io.Discard, io.Discard)
806 building.head = tip
807 first = covered(building.cover(checks))
808 publish("integrator")
809 revoked = covered(building.cover(checks))
810 if !first || revoked || reads() != 5 {
811 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",
812 first, revoked, reads())
813 }
814
815 publish("integrator", "worker")
816 _, name, _ := verification.resolve() // transfer verification
817 walk := hostKeys{use: listEvidence} // main's walk
818 defer walk.done()
819 _, walked, why := walk.read(g)
820 publish("integrator")
821 keys, listedP, unsigned := hostSignersFrom(g, listEvidence.signers()) // a listing's evidence
822 if unsigned == "" {
823 defer os.Remove(keys)
824 }
825 if why != "" || unsigned != "" || walked == nil || walked != listedP || name != "integrator" || reads() != 6 {
826 t.Errorf("a listing read the signers %d times, not once more: transfers %q, the walk %p (%s), the evidence %p (%s)",
827 reads()-5, name, walked, why, listedP, unsigned)
828 }
829}