gunk-dev/the-valley

run_test.go

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