gunk-dev/the-valley

run_test.go

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