gunk-dev/the-valley

run_test.go

sourcedd3d6fba36ddmain's published tip history
12.9 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, and skip where
19// there is none, as inside a nix build. attest itself is this test binary,
20// run again with ATTEST_AS_MAIN set, so what is run is the program's own
21// main with real standard output and error.
22
23func TestMain(m *testing.M) {
24 if os.Getenv("ATTEST_AS_MAIN") != "" {
25 main()
26 os.Exit(0)
27 }
28 os.Exit(m.Run())
29}
30
31// nixFixture is a scratch repository whose flake defines the checks it is
32// given, and a bare repository to publish to. Each check is a nix
33// expression in which `check NAME SCRIPT` is a derivation that runs SCRIPT
34// 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
35// derivation carries a nonce, so nothing a test builds is in the store
36// before it runs.
37type nixFixture struct {
38 repo string
39 origin string
40 state string
41 key string
42 name string
43 env []string
44}
45
46func newNixFixture(t *testing.T, checks map[string]string) nixFixture {
47 t.Helper()
48 for _, tool := range []string{"nix", "nix-store", "git", "cue", "ssh-keygen"} {
49 if _, err := exec.LookPath(tool); err != nil {
50 t.Skipf("%s is not available: %v", tool, err)
51 }
52 }
53 // A client may send max-jobs to the daemon, so the side-by-side test
54 // does not depend on how this machine is configured.
55 nixConfig := os.Getenv("NIX_CONFIG") + "\nextra-experimental-features = nix-command flakes\nmax-jobs = 4\n"
56 if out, err := exec.Command("env", "NIX_CONFIG="+nixConfig, "nix", "store", "info").CombinedOutput(); err != nil {
57 t.Skipf("no nix store to build in: %v: %s", err, out)
58 }
59 t.Setenv("NIX_CONFIG", nixConfig)
60
61 dir := t.TempDir()
62 f := nixFixture{
63 repo: filepath.Join(dir, "repo"),
64 origin: filepath.Join(dir, "origin.git"),
65 state: filepath.Join(dir, "state"),
66 key: filepath.Join(dir, "key"),
67 name: "test.example/attestations",
68 }
69 f.env = append(os.Environ(),
70 "ATTEST_AS_MAIN=1",
71 "XDG_STATE_HOME="+f.state,
72 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
73 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@l",
74 "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@l")
75 if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "t", "-f", f.key).CombinedOutput(); err != nil {
76 t.Fatalf("ssh-keygen: %v: %s", err, out)
77 }
78
79 nonce := make([]byte, 8)
80 if _, err := rand.Read(nonce); err != nil {
81 t.Fatal(err)
82 }
83 names := make([]string, 0, len(checks))
84 for name := range checks {
85 names = append(names, name)
86 }
87 sort.Strings(names)
88 var defs strings.Builder
89 for _, name := range names {
90 fmt.Fprintf(&defs, " %s = %s;\n", name, checks[name])
91 }
92 flake := fmt.Sprintf(`{
93 outputs = { self }:
94 let
95 system = "%s";
96 check = name: script: derivation {
97 inherit name system;
98 builder = "/bin/sh";
99 args = [ (builtins.toFile "${name}.sh" script) ];
100 nonce = "%s";
101 };
102 in {
103 checks.${system} = {
104%s };
105 };
106}
107`, nixSystem(), hex.EncodeToString(nonce), defs.String())
108 if err := os.MkdirAll(f.repo, 0o755); err != nil {
109 t.Fatal(err)
110 }
111 if err := os.WriteFile(filepath.Join(f.repo, "flake.nix"), []byte(flake), 0o644); err != nil {
112 t.Fatal(err)
113 }
114 f.git(t, "", "init", "--quiet", "-b", "main", f.repo)
115 f.git(t, f.repo, "add", "flake.nix")
116 f.git(t, f.repo, "commit", "--quiet", "-m", "checks")
117 f.git(t, "", "init", "--quiet", "--bare", f.origin)
118 return f
119}
120
121func (f nixFixture) git(t *testing.T, dir string, args ...string) string {
122 t.Helper()
123 cmd := exec.Command("git", args...)
124 cmd.Dir = dir
125 cmd.Env = f.env
126 out, err := cmd.CombinedOutput()
127 if err != nil {
128 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)
129 }
130 return strings.TrimSpace(string(out))
131}
132
133// attest runs `attest run` over the fixture's HEAD, publishing to its
134// bare repository, with the flags given.
135func (f nixFixture) attest(t *testing.T, flags ...string) (stdout, stderr string, err error) {
136 t.Helper()
137 schema, err := filepath.Abs(filepath.Join("..", "schema", "attestation.cue"))
138 if err != nil {
139 t.Fatal(err)
140 }
141 args := append([]string{"run", "--repo", f.repo, "--key", f.key, "--name", f.name,
142 "--schema", schema, "--push", f.origin, "--branch", "main"}, flags...)
143 cmd := exec.Command(os.Args[0], args...)
144 cmd.Env = f.env
145 var out, errb strings.Builder
146 cmd.Stdout, cmd.Stderr = &out, &errb
147 err = cmd.Run()
148 return out.String(), errb.String(), err
149}
150
151// published is every ref under refs/the-valley/ in the fixture's bare
152// repository and in the repository itself.
153func (f nixFixture) published(t *testing.T) string {
154 t.Helper()
155 return f.git(t, f.origin, "for-each-ref", "refs/the-valley/") + f.git(t, f.repo, "for-each-ref", "refs/the-valley/")
156}
157
158// sequentialOutcome is what the sequential run made of one pure check that
159// passes: an evaluation of the check alone, then a nix build of its
160// derivation alone, whose printed output path is digested. A batch must
161// decide each check as this did.
162func sequentialOutcome(t *testing.T, tree string, spec checkSpec) checkOutcome {
163 t.Helper()
164 c, err := evalClosure(tree, nixSystem(), spec)
165 if err != nil {
166 t.Fatal(err)
167 }
168 built, errb, err := nix(tree, "build", "--no-link", "--print-out-paths", c.drv+"^*")
169 if err != nil {
170 t.Fatalf("building %s alone: %v: %s", spec.name, err, errb)
171 }
172 paths := strings.Fields(built)
173 if len(paths) != 1 {
174 t.Fatalf("%s built %d outputs", spec.name, len(paths))
175 }
176 entries, err := fsEntries(paths[0])
177 if err != nil {
178 t.Fatal(err)
179 }
180 return checkOutcome{spec: spec, passed: true, derivation: c.derivation, inputs: c.inputs, output: treeDigest(entries)}
181}
182
183// checkLine is the line run prints for a pure check with a result.
184func checkLine(name, result string) string {
185 return fmt.Sprintf("check %-24s %-8s %s\n", name, "nix", result)
186}
187
188func statementText(t *testing.T, subj subject, out checkOutcome) string {
189 t.Helper()
190 doc, err := json.Marshal(composeStatement(subj, out, "local", nil))
191 if err != nil {
192 t.Fatal(err)
193 }
194 text, err := renderJSON(doc)
195 if err != nil {
196 t.Fatal(err)
197 }
198 return string(text)
199}
200
201// Three checks built together, one of which fails. The two that pass are
202// recorded exactly as the sequential run recorded them, the one that fails
203// keeps its own log, and nothing is published. The same two checks without
204// the failing one publish statements a sequential run would have signed.
205func TestABatchDecidesEachCheckAlone(t *testing.T) {
206 f := newNixFixture(t, map[string]string{
207 "one": `check "one" "echo one > $out"`,
208 "two": `check "two" "echo two > $out"`,
209 "broken": `check "broken" "echo the broken check says why; exit 3"`,
210 })
211 stdout, stderr, err := f.attest(t, "--check", "one", "--check", "broken", "--check", "two", "--timings")
212 if err == nil {
213 t.Fatalf("a run with a failing check succeeded:\n%s%s", stdout, stderr)
214 }
215 for _, want := range []string{checkLine("one", "passed"), checkLine("broken", "failed"), checkLine("two", "passed")} {
216 if !strings.Contains(stdout, want) {
217 t.Errorf("the run did not report %q:\n%s", want, stdout)
218 }
219 }
220 if !strings.Contains(stderr, "\n--- broken ---\nthe broken check says why\n") {
221 t.Errorf("the failing check's log was lost:\n%s", stderr)
222 }
223 if !strings.Contains(stderr, "1 of 3 checks failed; nothing published") {
224 t.Errorf("the run did not say that nothing was published:\n%s", stderr)
225 }
226 if refs := f.published(t); refs != "" {
227 t.Errorf("a run with a failing check published:\n%s", refs)
228 }
229
230 // Each check is logged on its own line, with the fields it always had
231 // and its evaluation time. The two that were built share one duration:
232 // the build's.
233 data, err := os.ReadFile(filepath.Join(f.state, "valley", "timings.jsonl"))
234 if err != nil {
235 t.Fatal(err)
236 }
237 lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
238 if len(lines) != 3 {
239 t.Fatalf("the timing log holds %d lines, want 3:\n%s", len(lines), data)
240 }
241 results := map[string]string{}
242 durations := map[int64]bool{}
243 for _, line := range lines {
244 var timing checkTiming
245 if err := json.Unmarshal([]byte(line), &timing); err != nil {
246 t.Fatal(err)
247 }
248 results[timing.Check] = timing.Result
249 durations[timing.DurationMS] = true
250 if timing.EvalMS <= 0 || timing.EvalMS > timing.DurationMS || timing.Satisfied != satisfiedRan {
251 t.Errorf("a pure check's timing reads %s", line)
252 }
253 }
254 if results["one"] != "passed" || results["two"] != "passed" || results["broken"] != "failed" {
255 t.Errorf("the timing log records the results %v", results)
256 }
257 if len(durations) != 1 {
258 t.Errorf("checks built together logged different durations: %s", data)
259 }
260
261 // The two that passed, decided in the batch with the failing one, are
262 // the 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)
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 in a batch:\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 TestABatchBuildsChecksSideBySide(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}