gunk-dev/the-valley

run_test.go

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