gunk-dev/the-valley

run_test.go

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