gunk-dev/the-valley

pending_test.go

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