gunk-dev/the-valley

run_test.go

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