gunk-dev/the-valley

verify_test.go

source60ad80d5a5a5main's published tip history
11.5 KiB
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strconv"
10 "strings"
11 "testing"
12 "time"
13
14 "the-valley/note/statement"
15)
16
17// refusedBySchema is the check name the cue stand-in refuses a statement
18// for.
19const refusedBySchema = "refused-by-schema"
20
21// cueStandIn is cue vet as verify runs it: vet -c <schema> <file>...,
22// which checks each file on its own and fails when any one fails. It
23// refuses a statement that names refusedBySchema, and logs how many files
24// each run was given to $ATTEST_CUE_LOG. With $ATTEST_CUE_STALL, a FIFO,
25// it writes its process ID there and stalls instead.
26func cueStandIn(args []string) int {
27 if fifo := os.Getenv("ATTEST_CUE_STALL"); fifo != "" {
28 os.WriteFile(fifo, []byte(strconv.Itoa(os.Getpid())+"\n"), 0)
29 time.Sleep(24 * time.Hour)
30 }
31 if len(args) < 4 || args[0] != "vet" || args[1] != "-c" {
32 fmt.Fprintf(os.Stderr, "cue stand-in: unexpected arguments %q\n", args)
33 return 2
34 }
35 files := args[3:]
36 if log, err := os.OpenFile(os.Getenv("ATTEST_CUE_LOG"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
37 fmt.Fprintln(log, len(files))
38 log.Close()
39 }
40 status := 0
41 for _, f := range files {
42 raw, err := os.ReadFile(f)
43 if err != nil || strings.Contains(string(raw), refusedBySchema) {
44 fmt.Printf("predicate.check.name: the stand-in schema refuses it:\n ./%s\n", f)
45 status = 1
46 }
47 }
48 return status
49}
50
51// verifyRig is a repository named repo inside a scratch directory, with
52// one commit, a known-keys file holding the worker's key, and notes
53// written beside them.
54type verifyRig struct {
55 t *testing.T
56 dir, repo, tree string
57 known, schema, log string
58 bin string // where a stand-in cue goes, or "" for the cue on PATH
59 worker, stranger signer
60}
61
62func newVerifyRig(t *testing.T, repo string, standIn bool) *verifyRig {
63 t.Helper()
64 if _, err := exec.LookPath("git"); err != nil {
65 t.Skip("no git to run")
66 }
67 dir := t.TempDir()
68 r := &verifyRig{t: t, dir: dir, repo: filepath.Join(dir, repo), known: filepath.Join(dir, "known"),
69 schema: filepath.Join(dir, "attestation.cue"), log: filepath.Join(dir, "cue.log"),
70 worker: testSigner(t, "worker.example/attestations"), stranger: testSigner(t, "stranger.example/attestations")}
71 commit := []string{"-c", "user.name=t", "-c", "user.email=t@localhost", "commit", "--quiet"}
72 if out, err := exec.Command("git", "init", "--quiet", r.repo).CombinedOutput(); err != nil {
73 t.Fatalf("git init: %v\n%s", err, out)
74 }
75 if err := os.WriteFile(filepath.Join(r.repo, "f"), []byte("f\n"), 0o644); err != nil {
76 t.Fatal(err)
77 }
78 for _, args := range [][]string{{"add", "f"}, append(commit, "-m", "f")} {
79 if out, err := exec.Command("git", append([]string{"-C", r.repo}, args...)...).CombinedOutput(); err != nil {
80 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
81 }
82 }
83 entries, err := gitTreeEntries(r.repo, "HEAD")
84 if err != nil {
85 t.Fatal(err)
86 }
87 r.tree = statement.TreeDigest(entries)
88 if err := os.WriteFile(r.known, []byte(r.worker.verifierKey().String()+"\n"), 0o644); err != nil {
89 t.Fatal(err)
90 }
91 if err := os.WriteFile(r.schema, []byte("package attestation\n"), 0o644); err != nil {
92 t.Fatal(err)
93 }
94 if standIn {
95 r.bin = filepath.Join(dir, "bin")
96 if err := os.MkdirAll(r.bin, 0o755); err != nil {
97 t.Fatal(err)
98 }
99 if err := os.Symlink(os.Args[0], filepath.Join(r.bin, "cue")); err != nil {
100 t.Fatal(err)
101 }
102 }
103 return r
104}
105
106// statement is a pure statement's JSON about subject, the check and its
107// tree digest; extra adds members to its subject's digests and to the
108// statement itself, each a JSON member.
109func (r *verifyRig) statement(check, subject, digests, extra string) string {
110 d := strings.Repeat("ab", 32)
111 return fmt.Sprintf(`{"predicate": {"result": "passed", "output": {"valley-tree-v1": %q},
112 "derivation": {"sha256": %q}, "inputs": {"valley-inputs-v1": %q},
113 "check": {"runner": "nix", "attribute": %q, "name": %q}},
114 "predicateType": "the-valley/check/pure/v1",
115 "subject": {"digest": {"valley-tree-v1": %q%s}, "primary": "valley-tree-v1"},
116 "statementType": "the-valley/attestation/v1"%s}`, d, d, d, check, check, subject, digests, extra)
117}
118
119// note writes the statement given as JSON, signed by by, to name.note.
120func (r *verifyRig) note(name, statementJSON string, by signer) string {
121 r.t.Helper()
122 text, err := statement.RenderJSON([]byte(statementJSON))
123 if err != nil {
124 r.t.Fatal(err)
125 }
126 n, err := signNote(text, by)
127 if err != nil {
128 r.t.Fatal(err)
129 }
130 path := filepath.Join(r.dir, name+".note")
131 if err := os.WriteFile(path, n, 0o644); err != nil {
132 r.t.Fatal(err)
133 }
134 return path
135}
136
137// verify runs attest verify with flags and a --note for each path, and
138// returns what it printed, its exit status, and how many files each cue
139// run was given.
140func (r *verifyRig) verify(flags []string, paths ...string) (stdout, stderr string, status int, cueRuns []string) {
141 r.t.Helper()
142 os.Remove(r.log)
143 args := append([]string{"verify", "--repo", r.repo}, flags...)
144 for _, p := range paths {
145 args = append(args, "--note", p)
146 }
147 cmd := exec.Command(os.Args[0], args...)
148 cmd.Env = append(os.Environ(), "ATTEST_AS_MAIN=1", "ATTEST_CUE_LOG="+r.log)
149 if r.bin != "" {
150 cmd.Env = append(cmd.Env, "PATH="+r.bin+string(os.PathListSeparator)+os.Getenv("PATH"))
151 }
152 var out, errb strings.Builder
153 cmd.Stdout, cmd.Stderr = &out, &errb
154 err := cmd.Run()
155 if exit, ok := err.(*exec.ExitError); ok {
156 status = exit.ExitCode()
157 } else if err != nil {
158 r.t.Fatal(err)
159 }
160 logged, _ := os.ReadFile(r.log)
161 return out.String(), errb.String(), status, strings.Fields(string(logged))
162}
163
164// verdictOf is the verdict line attest verify --verdicts gives the note
165// at place i, as a run of that note alone judged it.
166func verdictOf(i int, stdout, stderr string, status int) string {
167 if status != 0 {
168 why := strings.TrimSuffix(strings.TrimPrefix(stderr, "attest: "), "\n")
169 return fmt.Sprintf("verdict %d refused %s\n", i, strconv.Quote(why))
170 }
171 line := fmt.Sprintf("verdict %d verified", i)
172 for _, l := range strings.Split(stdout, "\n") {
173 if f := strings.Fields(l); len(f) == 3 && f[0] == "signature" && f[1] == "ok" {
174 line += " " + strconv.Quote(f[2])
175 }
176 }
177 return line + "\n"
178}
179
180// Verifying several notes with --verdicts gives each note the verdict a
181// run of that note alone gives it, whatever refuses it: the schema,
182// another tree, or a signer the reader does not hold. Nothing is printed
183// but the verdicts, every value one line however it is spelt: the
184// repository's path carries a newline, "verified" and a forged verdict,
185// and the correctly signed note about another tree is still refused. The
186// statements are vetted in one cue run when every one passes.
187func TestEachNoteIsVerifiedAsItWouldBeAlone(t *testing.T) {
188 r := newVerifyRig(t, "repo\nverified\nverdict 3 verified \"worker.example/attestations+00000000\"", true)
189 passed := r.note("passed", r.statement("one", r.tree, "", ""), r.worker)
190 again := r.note("again", r.statement("two", r.tree, "", ""), r.worker)
191 notes := []string{
192 passed,
193 r.note("schema", r.statement(refusedBySchema, r.tree, "", ""), r.worker),
194 r.note("elsewhere", r.statement("three", strings.Repeat("ab", 32), "", ""), r.worker),
195 r.note("stranger", r.statement("four", r.tree, "", ""), r.stranger),
196 again,
197 }
198 flags := []string{"--known-keys", r.known, "--schema", r.schema}
199 var want strings.Builder
200 refused := 0
201 for i, n := range notes {
202 stdout, stderr, status, _ := r.verify(flags, n)
203 if status != 0 {
204 refused++
205 }
206 want.WriteString(verdictOf(i+1, stdout, stderr, status))
207 }
208 want.WriteString("end 5\n")
209 if refused != 3 {
210 t.Fatalf("%d of the notes are refused alone, not the three made to be:\n%s", refused, want.String())
211 }
212 stdout, stderr, status, cueRuns := r.verify(append(flags, "--verdicts"), notes...)
213 if stdout != want.String() {
214 t.Errorf("verifying the notes together prints\n%s\nnot each one's verdict alone\n%s", stdout, want.String())
215 }
216 if status != 1 || stderr != "attest: 3 of 5 notes refused\n" {
217 t.Errorf("a run that refuses 3 of 5 notes exits %d and says %q", status, stderr)
218 }
219 // One run of the four statements that parse fails, so each of them
220 // is vetted alone.
221 if strings.Join(cueRuns, " ") != "4 1 1 1 1" {
222 t.Errorf("cue was run with these numbers of files: %v", cueRuns)
223 }
224
225 if stdout, _, status, cueRuns := r.verify(append(flags, "--verdicts"), passed, again); status != 0 ||
226 strings.Join(cueRuns, " ") != "2" || !strings.HasSuffix(stdout, "\nend 2\n") {
227 t.Errorf("two notes that verify exit %d after cue runs of %v files, printing\n%s", status, cueRuns, stdout)
228 }
229 missing := []string{"--known-keys", filepath.Join(r.dir, "missing"), "--schema", r.schema, "--verdicts"}
230 if stdout, _, status, _ := r.verify(missing, passed, again); status != 1 ||
231 !strings.HasPrefix(stdout, "verdict 1 refused \"open ") || !strings.HasSuffix(stdout, "\nend 2\n") {
232 t.Errorf("a known-keys file that does not read exits %d after printing\n%s", status, stdout)
233 }
234 if stdout, _, status, _ := r.verify(flags, passed, again); status == 0 || stdout != "" {
235 t.Errorf("two notes without --verdicts exit %d after printing\n%s", status, stdout)
236 }
237 for _, f := range [][]string{flags, append(flags, "--verdicts")} {
238 if stdout, stderr, status, _ := r.verify(f, ""); status != 1 || stdout != "" || stderr != "attest: --note is required\n" {
239 t.Errorf("an empty --note exits %d, printing %q and saying %q", status, stdout, stderr)
240 }
241 }
242}
243
244// cue vets each statement of a run on its own, never the statements
245// merged: two statements that differ both pass, and two that are each
246// incomplete alone, and complete when merged, are both refused. This is
247// the real cue, under a schema that wants a git-sha1 digest and a
248// provenance model, which only the two together hold.
249func TestCueVetsEachStatementOnItsOwn(t *testing.T) {
250 if _, err := exec.LookPath("cue"); err != nil {
251 if os.Getenv("ATTEST_CUE_TESTS") == "require" {
252 t.Fatal("no cue on PATH, and ATTEST_CUE_TESTS=require")
253 }
254 t.Skip("no cue to run; the nix check provides one")
255 }
256 r := newVerifyRig(t, "repo", false)
257 schema := "package attestation\nsubject: digest: \"git-sha1\": string\nprovenance: model: string\n"
258 if err := os.WriteFile(r.schema, []byte(schema), 0o644); err != nil {
259 t.Fatal(err)
260 }
261 sha := `, "git-sha1": "` + strings.Repeat("9", 40) + `"`
262 provenance := `, "provenance": {"model": "a model", "harness": "a harness"}`
263 flags := []string{"--known-keys", r.known, "--schema", r.schema, "--verdicts"}
264 for _, c := range []struct {
265 name string
266 notes []string
267 want string // each verdict's word, in order
268 }{
269 {"two that differ", []string{
270 r.note("one", r.statement("one", r.tree, sha, provenance), r.worker),
271 r.note("two", r.statement("two", r.tree, sha, provenance), r.worker)}, "verified verified"},
272 {"two each incomplete alone", []string{
273 r.note("digest", r.statement("one", r.tree, sha, ""), r.worker),
274 r.note("model", r.statement("one", r.tree, "", provenance), r.worker)}, "refused refused"},
275 } {
276 stdout, _, _, _ := r.verify(flags, c.notes...)
277 var got []string
278 for _, line := range strings.Split(stdout, "\n") {
279 if f := strings.Fields(line); len(f) > 2 && f[0] == "verdict" {
280 got = append(got, f[2])
281 }
282 }
283 if strings.Join(got, " ") != c.want {
284 t.Errorf("%s: the verdicts are %v, not %s:\n%s", c.name, got, c.want, stdout)
285 }
286 }
287 merged := []byte(r.statement("one", r.tree, sha, provenance))
288 if raw, err := statement.RenderJSON(merged); err != nil {
289 t.Fatal(err)
290 } else if doc, err := statement.Parse(raw); err != nil {
291 t.Fatal(err)
292 } else if js, _ := json.Marshal(doc); vetStatement(r.schema, js) != nil {
293 t.Errorf("the two incomplete statements merged do not satisfy the schema, so the test shows nothing")
294 }
295}