gunk-dev/the-valley

run_test.go

sourcecfedff357a41main's published tip history
19.0 KiB
1package main
2
3import (
4 "context"
5 "crypto/rand"
6 "encoding/hex"
7 "encoding/json"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "sort"
13 "strconv"
14 "strings"
15 "testing"
16 "time"
17
18 "the-valley/note/statement"
19 "the-valley/telemetry"
20)
21
22// These tests run attest against the machine's real nix: they evaluate and
23// build flake checks, so they need a nix daemon to talk to. They skip where
24// there is none, as inside a nix build, unless ATTEST_NIX_TESTS=require,
25// which makes a missing nix fail them instead. attest itself is this test
26// binary, run again with ATTEST_AS_MAIN set, so what is run is the
27// program's own main with real standard output and error.
28
29// TestMain runs this test binary as attest when ATTEST_AS_MAIN is set,
30// and as a stand-in for cue when it is run by that name (verify_test.go).
31func TestMain(m *testing.M) {
32 if filepath.Base(os.Args[0]) == "cue" {
33 os.Exit(cueStandIn(os.Args[1:]))
34 }
35 if os.Getenv("ATTEST_AS_MAIN") != "" {
36 main()
37 os.Exit(0)
38 }
39 os.Exit(m.Run())
40}
41
42// nixFixture is a scratch repository whose flake defines the checks it is
43// given, and a bare repository to publish to. Each check is a nix
44// expression in which `check NAME SCRIPT` is a derivation that runs SCRIPT
45// with /bin/sh, from a file in the store, so the derivation has an input. The flake has no inputs, so nothing is fetched, and every
46// derivation carries a nonce, so nothing a test builds is in the store
47// before it runs.
48type nixFixture struct {
49 repo string
50 origin string
51 state string
52 key string
53 name string
54 env []string
55}
56
57func newNixFixture(t *testing.T, checks map[string]string) nixFixture {
58 t.Helper()
59 skip := t.Skipf
60 if os.Getenv("ATTEST_NIX_TESTS") == "require" {
61 skip = t.Fatalf
62 }
63 for _, tool := range []string{"nix", "nix-store", "git", "cue", "ssh-keygen"} {
64 if _, err := exec.LookPath(tool); err != nil {
65 skip("%s is not available: %v", tool, err)
66 }
67 }
68 // A client may send max-jobs to the daemon, so how this machine is
69 // configured does not decide what the tests see.
70 nixConfig := os.Getenv("NIX_CONFIG") + "\nextra-experimental-features = nix-command flakes\nmax-jobs = 4\n"
71 if out, err := exec.Command("env", "NIX_CONFIG="+nixConfig, "nix", "store", "info").CombinedOutput(); err != nil {
72 skip("no nix store to build in: %v: %s", err, out)
73 }
74 t.Setenv("NIX_CONFIG", nixConfig)
75
76 dir := t.TempDir()
77 f := nixFixture{
78 repo: filepath.Join(dir, "repo"),
79 origin: filepath.Join(dir, "origin.git"),
80 state: filepath.Join(dir, "state"),
81 key: filepath.Join(dir, "key"),
82 name: "test.example/attestations",
83 }
84 f.env = append(os.Environ(),
85 "ATTEST_AS_MAIN=1",
86 "XDG_STATE_HOME="+f.state,
87 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
88 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@l",
89 "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@l")
90 if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "t", "-f", f.key).CombinedOutput(); err != nil {
91 t.Fatalf("ssh-keygen: %v: %s", err, out)
92 }
93
94 nonce := make([]byte, 8)
95 if _, err := rand.Read(nonce); err != nil {
96 t.Fatal(err)
97 }
98 names := make([]string, 0, len(checks))
99 for name := range checks {
100 names = append(names, name)
101 }
102 sort.Strings(names)
103 var defs strings.Builder
104 for _, name := range names {
105 fmt.Fprintf(&defs, " %s = %s;\n", name, checks[name])
106 }
107 flake := fmt.Sprintf(`{
108 outputs = { self }:
109 let
110 system = "%s";
111 check = name: script: derivation {
112 inherit name system;
113 builder = "/bin/sh";
114 args = [ (builtins.toFile "${name}.sh" script) ];
115 nonce = "%s";
116 };
117 in {
118 checks.${system} = {
119%s };
120 };
121}
122`, nixSystem(), hex.EncodeToString(nonce), defs.String())
123 if err := os.MkdirAll(f.repo, 0o755); err != nil {
124 t.Fatal(err)
125 }
126 if err := os.WriteFile(filepath.Join(f.repo, "flake.nix"), []byte(flake), 0o644); err != nil {
127 t.Fatal(err)
128 }
129 f.git(t, "", "init", "--quiet", "-b", "main", f.repo)
130 f.git(t, f.repo, "add", "flake.nix")
131 f.git(t, f.repo, "commit", "--quiet", "-m", "checks")
132 f.git(t, "", "init", "--quiet", "--bare", f.origin)
133 return f
134}
135
136func (f nixFixture) git(t *testing.T, dir string, args ...string) string {
137 t.Helper()
138 cmd := exec.Command("git", args...)
139 cmd.Dir = dir
140 cmd.Env = f.env
141 out, err := cmd.CombinedOutput()
142 if err != nil {
143 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)
144 }
145 return strings.TrimSpace(string(out))
146}
147
148// attest runs `attest run` over the fixture's HEAD, publishing to its
149// bare repository, with the flags given.
150func (f nixFixture) attest(t *testing.T, flags ...string) (stdout, stderr string, err error) {
151 t.Helper()
152 schema, err := filepath.Abs(filepath.Join("..", "schema", "attestation.cue"))
153 if err != nil {
154 t.Fatal(err)
155 }
156 args := append([]string{"run", "--repo", f.repo, "--key", f.key, "--name", f.name,
157 "--schema", schema, "--push", f.origin, "--branch", "main"}, flags...)
158 cmd := exec.Command(os.Args[0], args...)
159 cmd.Env = f.env
160 var out, errb strings.Builder
161 cmd.Stdout, cmd.Stderr = &out, &errb
162 err = cmd.Run()
163 return out.String(), errb.String(), err
164}
165
166// published is every ref under refs/the-valley/ in the fixture's bare
167// repository and in the repository itself.
168func (f nixFixture) published(t *testing.T) string {
169 t.Helper()
170 return f.git(t, f.origin, "for-each-ref", "refs/the-valley/") + f.git(t, f.repo, "for-each-ref", "refs/the-valley/")
171}
172
173// sequentialOutcome is what the sequential run made of one pure check that
174// passes: an evaluation of the check alone, then a nix build of its
175// derivation alone, whose printed output path is digested. A run of many
176// checks must decide each one as this did.
177func sequentialOutcome(t *testing.T, tree string, spec checkSpec) checkOutcome {
178 t.Helper()
179 c, _, err := evalClosure(tree, nixSystem(), spec, nil)
180 if err != nil {
181 t.Fatal(err)
182 }
183 built, errb, err := nix(tree, "build", "--no-link", "--print-out-paths", c.drv+"^*")
184 if err != nil {
185 t.Fatalf("building %s alone: %v: %s", spec.name, err, errb)
186 }
187 paths := strings.Fields(built)
188 if len(paths) != 1 {
189 t.Fatalf("%s built %d outputs", spec.name, len(paths))
190 }
191 entries, err := fsEntries(paths[0])
192 if err != nil {
193 t.Fatal(err)
194 }
195 return checkOutcome{spec: spec, passed: true, derivation: c.derivation, inputs: c.inputs, output: statement.TreeDigest(entries)}
196}
197
198// checkLine is the line run prints for a pure check with a result.
199func checkLine(name, result string) string {
200 return fmt.Sprintf("check %-24s %-8s %s\n", name, "nix", result)
201}
202
203func statementText(t *testing.T, subj subject, out checkOutcome) string {
204 t.Helper()
205 doc, err := json.Marshal(composeStatement(subj, out, "local", nil))
206 if err != nil {
207 t.Fatal(err)
208 }
209 text, err := statement.RenderJSON(doc)
210 if err != nil {
211 t.Fatal(err)
212 }
213 return string(text)
214}
215
216// Three checks built side by side, one of which fails. The two that pass
217// are recorded exactly as the sequential run recorded them, the one that
218// fails keeps its own log, and nothing is published. The same two checks
219// without the failing one publish statements a sequential run would have
220// signed.
221func TestEachCheckKeepsItsOwnOutcome(t *testing.T) {
222 f := newNixFixture(t, map[string]string{
223 "one": `check "one" "echo one > $out"`,
224 "two": `check "two" "echo two > $out"`,
225 "broken": `check "broken" "echo the broken check says why; exit 3"`,
226 })
227 stdout, stderr, err := f.attest(t, "--check", "one", "--check", "broken", "--check", "two", "--timings")
228 if err == nil {
229 t.Fatalf("a run with a failing check succeeded:\n%s%s", stdout, stderr)
230 }
231 for _, want := range []string{checkLine("one", "passed"), checkLine("broken", "failed"), checkLine("two", "passed")} {
232 if !strings.Contains(stdout, want) {
233 t.Errorf("the run did not report %q:\n%s", want, stdout)
234 }
235 }
236 if _, log, _ := strings.Cut(stderr, "\n--- broken ---\n"); !strings.Contains(log, "the broken check says why") {
237 t.Errorf("the failing check's log was lost:\n%s", stderr)
238 }
239 if !strings.Contains(stderr, "1 of 3 checks failed; nothing published") {
240 t.Errorf("the run did not say that nothing was published:\n%s", stderr)
241 }
242 if refs := f.published(t); refs != "" {
243 t.Errorf("a run with a failing check published:\n%s", refs)
244 }
245
246 // Each check is logged on its own line, with the fields it always had
247 // and its evaluation time, which is part of its duration.
248 data, err := os.ReadFile(filepath.Join(f.state, "valley", "timings.jsonl"))
249 if err != nil {
250 t.Fatal(err)
251 }
252 lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
253 if len(lines) != 3 {
254 t.Fatalf("the timing log holds %d lines, want 3:\n%s", len(lines), data)
255 }
256 results := map[string]string{}
257 for _, line := range lines {
258 var timing checkTiming
259 if err := json.Unmarshal([]byte(line), &timing); err != nil {
260 t.Fatal(err)
261 }
262 results[timing.Check] = timing.Result
263 if timing.EvalMS <= 0 || timing.EvalMS > timing.DurationMS || timing.Satisfied != satisfiedRan {
264 t.Errorf("a pure check's timing reads %s", line)
265 }
266 }
267 if results["one"] != "passed" || results["two"] != "passed" || results["broken"] != "failed" {
268 t.Errorf("the timing log records the results %v", results)
269 }
270
271 // The two that passed, decided beside the failing one, are the
272 // outcomes the sequential run made of them.
273 tree := t.TempDir()
274 if err := exportTree(f.repo, "HEAD", tree); err != nil {
275 t.Fatal(err)
276 }
277 subj, err := composeSubject(f.repo, "HEAD")
278 if err != nil {
279 t.Fatal(err)
280 }
281 specs := []checkSpec{{name: "one", attribute: "one"}, {name: "broken", attribute: "broken"}, {name: "two", attribute: "two"}}
282 runs, _ := runPure(tree, nixSystem(), specs, false, defaultSlots, "", nil, "", nil, nil)
283 for i, r := range runs {
284 if r.err != nil {
285 t.Fatalf("%s: %v", specs[i].name, r.err)
286 }
287 }
288 if runs[1].out.passed || !strings.Contains(runs[1].out.log, "the broken check says why") {
289 t.Errorf("the failing check passed, or lost its log: %+v", runs[1].out)
290 }
291 sequential := map[string]string{}
292 for _, i := range []int{0, 2} {
293 want := statementText(t, subj, sequentialOutcome(t, tree, specs[i]))
294 if got := statementText(t, subj, runs[i].out); got != want {
295 t.Errorf("%s beside the others:\n%s\nalone:\n%s", specs[i].name, got, want)
296 }
297 sequential[specs[i].name] = want
298 }
299
300 // Without the failing check, the run publishes, and what it signed is
301 // what the sequential run would have.
302 stdout, stderr, err = f.attest(t, "--check", "one", "--check", "two")
303 if err != nil {
304 t.Fatalf("a run whose checks pass failed: %v\n%s%s", err, stdout, stderr)
305 }
306 host, err := loadSigner(f.key, f.name)
307 if err != nil {
308 t.Fatal(err)
309 }
310 ref := attestationRef(subj.Digest[subj.Primary], fmt.Sprintf("%08x", host.hash))
311 for name, want := range sequential {
312 note := f.git(t, f.origin, "cat-file", "blob", ref+":"+name+"/statement.note") + "\n"
313 text, _, err := openNote([]byte(note), []verifierKey{host.verifierKey()})
314 if err != nil {
315 t.Fatalf("%s: %v", name, err)
316 }
317 if string(text) != want {
318 t.Errorf("%s was published as:\n%s\nthe sequential run signs:\n%s", name, text, want)
319 }
320 }
321}
322
323// Two slow checks build side by side when attest may run two builds at
324// once: the run takes about as long as one of them. Allowed one build at a
325// time, the same run takes as long as both. --slots sets the capacity, so
326// the machine's CPU count does not decide either.
327func TestChecksBuildSideBySide(t *testing.T) {
328 // The sandbox's /bin/sh may have no sleep, so each check waits on a
329 // read that never ends a line and times out.
330 const sleep = 5 * time.Second
331 script := fmt.Sprintf("read -t %d line < /dev/zero; echo done > $out", int(sleep.Seconds()))
332 for _, c := range []struct {
333 slots int
334 min, max time.Duration
335 }{
336 {slots: 2, min: sleep, max: 2*sleep - time.Second},
337 {slots: 1, min: 2 * sleep, max: 3 * sleep},
338 } {
339 // A fixture of its own, so the second run does not find the
340 // first one's outputs built.
341 f := newNixFixture(t, map[string]string{
342 "slow-one": fmt.Sprintf("check %q %q", "slow-one", script),
343 "slow-two": fmt.Sprintf("check %q %q", "slow-two", script),
344 })
345 began := time.Now()
346 stdout, stderr, err := f.attest(t, "--slots", strconv.Itoa(c.slots), "--check", "slow-one", "--check", "slow-two")
347 took := time.Since(began)
348 if err != nil {
349 t.Fatalf("the slow checks did not pass: %v\n%s%s", err, stdout, stderr)
350 }
351 if took < c.min || took >= c.max {
352 t.Errorf("two %v checks, %d build at a time, took %v together", sleep, c.slots, took)
353 }
354 }
355}
356
357// A check that does not evaluate is an error for that check alone: every
358// other check is still built and reported, and nothing is published. An
359// error nix can catch leaves the shared evaluation standing; one it
360// cannot, such as a type error, ends it, and every check is evaluated
361// alone.
362func TestAnEvaluationErrorStopsNoOtherCheck(t *testing.T) {
363 for name, broken := range map[string]string{
364 "a throw": `throw "the broken check does not evaluate"`,
365 "a type error": `check "broken" (1 + "the broken check does not evaluate")`,
366 } {
367 t.Run(name, func(t *testing.T) {
368 f := newNixFixture(t, map[string]string{
369 "fine": `check "fine" "echo fine > $out"`,
370 "broken": broken,
371 "also": `check "also" "echo also > $out"`,
372 })
373 stream := &telemetry.Stream{Dir: t.TempDir()}
374 stdout, stderr, err := f.attest(t, "--telemetry", stream.Dir, "--check", "fine", "--check", "broken", "--check", "also")
375 if err == nil {
376 t.Fatalf("a run with a check that does not evaluate succeeded:\n%s%s", stdout, stderr)
377 }
378 // The broken check's result carries its error and names no
379 // derivation; a check that built names the one it built.
380 records, _, err := stream.Read(0, 100, 1<<20)
381 if err != nil {
382 t.Fatal(err)
383 }
384 results := map[string]map[string]any{}
385 for _, r := range records {
386 if r.Type == "check.result" {
387 results[r.Check] = r.Data
388 }
389 }
390 if drv, named := results["broken"]["drv"]; named || results["broken"]["error"] == nil {
391 t.Errorf("the broken check's result names derivation %v, error %v", drv, results["broken"]["error"])
392 }
393 if drv, _ := results["fine"]["drv"].(string); !strings.HasPrefix(drv, "/nix/store/") || !strings.HasSuffix(drv, ".drv") {
394 t.Errorf("the fine check's result names derivation %q", drv)
395 }
396 for _, want := range []string{
397 checkLine("fine", "passed"),
398 checkLine("also", "passed"),
399 fmt.Sprintf("time %-24s %-8s ", "broken", "error"),
400 } {
401 if !strings.Contains(stdout, want) {
402 t.Errorf("the run did not report %q:\n%s", want, stdout)
403 }
404 }
405 if !strings.Contains(stderr, "evaluating ") || !strings.Contains(stderr, "the broken check does not evaluate") {
406 t.Errorf("the evaluation error is not reported:\n%s", stderr)
407 }
408 if refs := f.published(t); refs != "" {
409 t.Errorf("a run with a check that does not evaluate published:\n%s", refs)
410 }
411 })
412 }
413}
414
415// A check attribute produces exactly one output, so a derivation with two
416// is an error for that check alone, and the check beside it still passes.
417func TestACheckWithTwoOutputsIsAnError(t *testing.T) {
418 f := newNixFixture(t, map[string]string{
419 "fine": `check "fine" "echo fine > $out"`,
420 "split": `derivation {
421 name = "split";
422 inherit system;
423 builder = "/bin/sh";
424 args = [ (builtins.toFile "split.sh" "echo a > $out; echo b > $dev") ];
425 outputs = [ "out" "dev" ];
426 }`,
427 })
428 stdout, stderr, err := f.attest(t, "--check", "split", "--check", "fine")
429 if err == nil {
430 t.Fatalf("a run with a two-output check succeeded:\n%s%s", stdout, stderr)
431 }
432 if !strings.Contains(stdout, checkLine("fine", "passed")) || !strings.Contains(stdout, fmt.Sprintf("time %-24s %-8s ", "split", "error")) {
433 t.Errorf("the run did not report the two checks apart:\n%s", stdout)
434 }
435 if !strings.Contains(stderr, "split produced 2 outputs; a check attribute must produce exactly one") {
436 t.Errorf("the two-output check's error is not reported:\n%s", stderr)
437 }
438 if refs := f.published(t); refs != "" {
439 t.Errorf("a run with a two-output check published:\n%s", refs)
440 }
441}
442
443// A run with --gc-roots roots every output of every flake check it builds
444// in the directory it names, one symlink per output named by its store
445// path's basename, and a later run that finds the outputs already built
446// makes each symlink afresh. A run without it roots nothing.
447func TestGCRootsRootEveryOutputAndAreRefreshedOnReuse(t *testing.T) {
448 f := newNixFixture(t, map[string]string{
449 "one": `check "one" "echo one > $out"`,
450 "split": `derivation {
451 name = "split";
452 inherit system;
453 builder = "/bin/sh";
454 args = [ (builtins.toFile "split.sh" "echo a > $out; echo b > $dev") ];
455 outputs = [ "out" "dev" ];
456 }`,
457 })
458 checks := []string{"--check", "one", "--check", "split"}
459 // The two-output check is an error, but it is built all the same.
460 if stdout, stderr, err := f.attest(t, checks...); !strings.Contains(stdout, checkLine("one", "passed")) {
461 t.Fatalf("the run without --gc-roots did not pass one: %v\n%s%s", err, stdout, stderr)
462 }
463 var outputs []string
464 for _, attr := range []string{"one.out", "split.out", "split.dev"} {
465 out, errb, err := nix(f.repo, "eval", "--raw", ".#checks."+nixSystem()+"."+attr+".outPath")
466 if err != nil {
467 t.Fatalf("evaluating %s: %v: %s", attr, err, errb)
468 }
469 outputs = append(outputs, out)
470 }
471 roots := func(path string) string {
472 out, errb, err := nixStore(context.Background(), "--query", "--roots", path)
473 if err != nil {
474 t.Fatalf("nix-store --query --roots %s: %v: %s", path, err, errb)
475 }
476 return out
477 }
478 for _, path := range outputs {
479 if r := roots(path); r != "" {
480 t.Errorf("a run without --gc-roots rooted %s:\n%s", path, r)
481 }
482 }
483
484 dir := filepath.Join(t.TempDir(), "roots")
485 rooted := func(run string) map[string]time.Time {
486 t.Helper()
487 entries, err := os.ReadDir(dir)
488 if err != nil {
489 t.Fatal(err)
490 }
491 if len(entries) != len(outputs) {
492 t.Errorf("the %s run left %d roots for %d outputs: %v", run, len(entries), len(outputs), entries)
493 }
494 times := map[string]time.Time{}
495 for _, path := range outputs {
496 link := filepath.Join(dir, filepath.Base(path))
497 if target, err := os.Readlink(link); err != nil || target != path {
498 t.Errorf("after the %s run, %s points to %q (%v), not %s", run, link, target, err, path)
499 continue
500 }
501 if r := roots(path); !strings.Contains(r, link) {
502 t.Errorf("after the %s run, the daemon does not know %s as a root of %s:\n%s", run, link, path, r)
503 }
504 info, err := os.Lstat(link)
505 if err != nil {
506 t.Fatal(err)
507 }
508 times[link] = info.ModTime()
509 }
510 return times
511 }
512 if stdout, stderr, _ := f.attest(t, append(checks, "--gc-roots", dir)...); strings.Contains(stderr, "is not rooted") {
513 t.Fatalf("the run could not root an output:\n%s%s", stdout, stderr)
514 }
515 for link := range rooted("first") {
516 if out, err := exec.Command("touch", "-h", "-d", "2000-01-01", link).CombinedOutput(); err != nil {
517 t.Fatalf("touch %s: %v: %s", link, err, out)
518 }
519 }
520 reused := time.Now().Add(-time.Minute)
521 if stdout, stderr, _ := f.attest(t, append(checks, "--gc-roots", dir)...); !strings.Contains(stdout, checkLine("one", "passed")) {
522 t.Fatalf("the second run did not pass one:\n%s%s", stdout, stderr)
523 }
524 for link, used := range rooted("second") {
525 if used.Before(reused) {
526 t.Errorf("the second run used %s but left its last use at %s", link, used)
527 }
528 }
529}