gunk-dev/the-valley

attest_test.go

source86efaaa992fcmain's published tip history
17.9 KiB
1package main
2
3import (
4 "crypto/ed25519"
5 "encoding/base64"
6 "encoding/json"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "reflect"
12 "strings"
13 "testing"
14)
15
16// The written form, the note envelope and the tree digest are the pieces
17// of genuinely tricky logic here: they decide which bytes get signed, what
18// a signature is checked against, and what a subject is. All three must
19// agree with any other implementation. Everything else in this program is
20// exercised end to end by the flake checks against the real binary.
21
22// pureStatement is a whole statement, which is the only thing that has a
23// written form: order is defined per predicate type, so a fragment has no
24// order at all.
25func pureStatement() map[string]any {
26 return map[string]any{
27 "statementType": statementType,
28 "predicateType": predicatePure,
29 "subject": map[string]any{
30 "primary": treeScheme,
31 "digest": map[string]any{
32 treeScheme: strings.Repeat("a", 64),
33 "git-sha1": strings.Repeat("b", 40),
34 },
35 },
36 "predicate": map[string]any{
37 "check": map[string]any{"name": "prose-format", "runner": "nix", "attribute": "prose-format"},
38 "result": "passed",
39 "inputs": map[string]any{inputsScheme: strings.Repeat("c", 64)},
40 "derivation": map[string]any{"sha256": strings.Repeat("d", 64)},
41 "output": map[string]any{treeScheme: strings.Repeat("e", 64)},
42 },
43 "provenance": map[string]any{
44 "harness": "a harness",
45 "model": "a model",
46 "delegation": []any{
47 map[string]any{"principal": "human:integrator", "grant": "land changes"},
48 map[string]any{"principal": "agent:run"},
49 },
50 },
51 }
52}
53
54func TestRenderTextWritesLinesInNarrativeOrder(t *testing.T) {
55 // The reader's first question — what is this about — is answered
56 // first, and what produced the change comes last. Within the digest
57 // set, whose keys are naming schemes rather than positions, entries
58 // sort by key.
59 got, err := renderText(pureStatement())
60 if err != nil {
61 t.Fatal(err)
62 }
63 want := statementType + "\n" +
64 "subject.primary valley-tree-v1\n" +
65 "subject.digest.git-sha1 " + strings.Repeat("b", 40) + "\n" +
66 "subject.digest.valley-tree-v1 " + strings.Repeat("a", 64) + "\n" +
67 "predicateType " + predicatePure + "\n" +
68 "predicate.check.name prose-format\n" +
69 "predicate.check.runner nix\n" +
70 "predicate.check.attribute prose-format\n" +
71 "predicate.result passed\n" +
72 "predicate.inputs.valley-inputs-v1 " + strings.Repeat("c", 64) + "\n" +
73 "predicate.derivation.sha256 " + strings.Repeat("d", 64) + "\n" +
74 "predicate.output.valley-tree-v1 " + strings.Repeat("e", 64) + "\n" +
75 "provenance.harness a harness\n" +
76 "provenance.model a model\n" +
77 "provenance.delegation.0.principal human:integrator\n" +
78 "provenance.delegation.0.grant land changes\n" +
79 "provenance.delegation.1.principal agent:run\n"
80 if string(got) != want {
81 t.Errorf("renderText =\n%s\nwant\n%s", got, want)
82 }
83}
84
85func TestRenderTextWritesArrayElementsInIndexOrder(t *testing.T) {
86 // An array is positional, so its elements are written in index order.
87 // Eleven of them is where an order taken from the key's bytes rather
88 // than from the index would put the tenth in the wrong place.
89 doc := pureStatement()
90 var steps []any
91 for i := 0; i < 11; i++ {
92 steps = append(steps, map[string]any{"principal": fmt.Sprintf("step-%d", i)})
93 }
94 doc["provenance"].(map[string]any)["delegation"] = steps
95 got, err := renderText(doc)
96 if err != nil {
97 t.Fatal(err)
98 }
99 var seen []string
100 for _, l := range strings.Split(string(got), "\n") {
101 if strings.HasPrefix(l, "provenance.delegation.") {
102 seen = append(seen, strings.TrimPrefix(l, "provenance.delegation."))
103 }
104 }
105 if len(seen) != 11 || seen[1] != "1.principal step-1" || seen[10] != "10.principal step-10" {
106 t.Errorf("delegation steps are not in index order: %q", seen)
107 }
108}
109
110func TestRenderTextWritesValuesLiterally(t *testing.T) {
111 // The form has no escapes, which is what leaves two implementations
112 // nothing to disagree about. Every character below is one a JSON
113 // encoder would have had a choice about.
114 const odd = `a<b>c&d "q" \ / ü😀`
115 doc := pureStatement()
116 doc["provenance"].(map[string]any)["harness"] = odd
117 got, err := renderText(doc)
118 if err != nil {
119 t.Fatal(err)
120 }
121 if !strings.Contains(string(got), "\nprovenance.harness "+odd+"\n") {
122 t.Errorf("renderText did not write the value as its own bytes:\n%s", got)
123 }
124}
125
126func TestRenderTextRefusesWhatItCannotWrite(t *testing.T) {
127 // Each of these is a document with no written form. Refusing beats
128 // guessing, and beats dropping something that was validated a moment
129 // earlier and would then not be in the bytes that got signed.
130 for name, spoil := range map[string]func(map[string]any){
131 "a number": func(d map[string]any) { d["provenance"] = map[string]any{"model": json.Number("1.5")} },
132 "a boolean": func(d map[string]any) { d["provenance"] = map[string]any{"model": true} },
133 "a null": func(d map[string]any) { d["provenance"] = map[string]any{"model": nil} },
134 "an empty object": func(d map[string]any) { d["provenance"] = map[string]any{} },
135 "an empty array": func(d map[string]any) { d["provenance"] = map[string]any{"delegation": []any{}} },
136 "an empty string": func(d map[string]any) { d["provenance"] = map[string]any{"model": ""} },
137 "a newline in a value": func(d map[string]any) { d["provenance"] = map[string]any{"model": "two\nlines"} },
138 "a tab in a value": func(d map[string]any) { d["provenance"] = map[string]any{"model": "a\tb"} },
139 "invalid utf-8": func(d map[string]any) { d["provenance"] = map[string]any{"model": "\xff"} },
140 "a key with a dot": func(d map[string]any) { d["provenance"] = map[string]any{"a.b": "x"} },
141 "a key with a space": func(d map[string]any) { d["provenance"] = map[string]any{"a b": "x"} },
142 "a non-ascii key": func(d map[string]any) { d["provenance"] = map[string]any{"café": "x"} },
143 "an index-shaped key": func(d map[string]any) { d["provenance"] = map[string]any{"0": "x"} },
144
145 // A field the order table has no position for cannot be placed, so
146 // it is refused rather than written somewhere a second
147 // implementation would not look for it.
148 "a field with no position": func(d map[string]any) { d["provenance"] = map[string]any{"authority": "root"} },
149 "an unknown predicate type": func(d map[string]any) {
150 d["predicateType"] = "the-valley/check/pure/v2"
151 },
152 "an unknown statement type": func(d map[string]any) {
153 d["statementType"] = "the-valley/attestation/v2"
154 },
155 } {
156 doc := pureStatement()
157 spoil(doc)
158 if _, err := renderText(doc); err == nil {
159 t.Errorf("renderText accepted %s", name)
160 }
161 }
162}
163
164func TestParseTextRoundTrips(t *testing.T) {
165 doc := pureStatement()
166 text, err := renderText(doc)
167 if err != nil {
168 t.Fatal(err)
169 }
170 back, err := parseText(text)
171 if err != nil {
172 t.Fatalf("parseText(%q): %v", text, err)
173 }
174 if !reflect.DeepEqual(back, doc) {
175 t.Errorf("parseText(renderText(doc)) =\n %#v\nwant\n %#v", back, doc)
176 }
177 // The form is a fixed point, or a statement written out again anywhere
178 // downstream stops matching what was signed.
179 again, err := renderText(back)
180 if err != nil {
181 t.Fatal(err)
182 }
183 if string(again) != string(text) {
184 t.Errorf("rendering a parsed statement changed it:\n%q\n%q", again, text)
185 }
186}
187
188func TestParseTextAcceptsOnlyTheWrittenForm(t *testing.T) {
189 // Text that parses is text the renderer would have produced. That is
190 // what lets a verifier settle "these bytes are the written form of what
191 // they say" by reading, rather than trusting the sender.
192 good, err := renderText(pureStatement())
193 if err != nil {
194 t.Fatal(err)
195 }
196 swap := func(a, b string) string {
197 lines := strings.Split(string(good), "\n")
198 i, j := indexOfPrefix(t, lines, a), indexOfPrefix(t, lines, b)
199 lines[i], lines[j] = lines[j], lines[i]
200 return strings.Join(lines, "\n")
201 }
202 for name, text := range map[string]string{
203 "no header": strings.TrimPrefix(string(good), statementType+"\n"),
204 "another header": "the-valley/attestation/v2\n" + strings.TrimPrefix(string(good), statementType+"\n"),
205 "no closing newline": strings.TrimSuffix(string(good), "\n"),
206 "a key with no value": string(good) + "provenance.model\n",
207 "a blank line": strings.Replace(string(good), "predicateType ", "\npredicateType ", 1),
208 "a repeated key": string(good) + "provenance.model twice\n",
209 "nothing at all": statementType + "\n",
210
211 // The claim before what it is about, which is the order a reader
212 // does not read in.
213 "sections out of order": swap("subject.primary ", "predicateType "),
214 // A set whose entries carry no order of their own, out of the one
215 // order they have.
216 "a set out of order": swap("subject.digest.git-sha1 ", "subject.digest.valley-tree-v1 "),
217 // An array element out of its position.
218 "an array out of order": swap("provenance.delegation.0.principal ", "provenance.delegation.1.principal "),
219 // A field the order table has no position for.
220 "a field with no position": string(good) + "provenance.authority root\n",
221
222 "a sparse array": statementType + "\np.0 one\np.2 three\n",
223 "index and field": statementType + "\np.0 one\np.name two\n",
224 "value and path": statementType + "\np one\np.q two\n",
225 "a leading zero": statementType + "\np.00 one\n",
226 } {
227 if _, err := parseText([]byte(text)); err == nil {
228 t.Errorf("parseText accepted %s: %q", name, text)
229 }
230 }
231}
232
233func indexOfPrefix(t *testing.T, lines []string, prefix string) int {
234 t.Helper()
235 for i, l := range lines {
236 if strings.HasPrefix(l, prefix) {
237 return i
238 }
239 }
240 t.Fatalf("no line starting %q", prefix)
241 return -1
242}
243
244// The key hash is the note format's own, and getting it wrong means
245// signing notes nothing else can find the key for. sum.golang.org
246// publishes its verifier key, so its name and public key are an input the
247// reference implementation has already computed the answer for.
248func TestKeyHashMatchesTheReferenceImplementation(t *testing.T) {
249 const (
250 name = "sum.golang.org"
251 public = "Ac4zctda0e5eza+HJyk9SxEdh+s3Ux18htTTAD8OuAn8"
252 want = "033de0ae"
253 )
254 raw, err := base64.StdEncoding.DecodeString(public)
255 if err != nil {
256 t.Fatal(err)
257 }
258 if got := keyHash(name, raw[1:]); hex8(got) != want {
259 t.Errorf("keyHash(%s) = %s, want %s", name, hex8(got), want)
260 }
261 // And the same fact from the other side: the published verifier key
262 // parses, which checks its hash against the one this code computes.
263 if _, err := parseVerifierKey(name + "+" + want + "+" + public); err != nil {
264 t.Errorf("the published verifier key of %s does not parse: %v", name, err)
265 }
266}
267
268func TestNoteCarriesSiblingSignatures(t *testing.T) {
269 first := testSigner(t, "one.example/attestations")
270 second := testSigner(t, "two.example/attestations")
271 text := []byte(statementType + "\nsubject.primary valley-tree-v1\n")
272
273 note, err := signNote(text, first)
274 if err != nil {
275 t.Fatal(err)
276 }
277 if note, err = addSignature(note, second); err != nil {
278 t.Fatal(err)
279 }
280 if lines := strings.Count(string(note), "\n— "); lines != 2 {
281 t.Errorf("note does not carry two sibling signature lines:\n%s", note)
282 }
283
284 known := []verifierKey{first.verifierKey(), second.verifierKey()}
285 got, sigs, err := openNote(note, known)
286 if err != nil {
287 t.Fatal(err)
288 }
289 if string(got) != string(text) {
290 t.Errorf("openNote returned %q, want %q", got, text)
291 }
292 if len(sigs) != 2 || !sigs[0].verified || !sigs[1].verified {
293 t.Errorf("both signatures should verify over one text: %+v", sigs)
294 }
295
296 // A verifier holding one of the two keys accepts the note and reports
297 // the other signature as one it cannot speak to.
298 _, sigs, err = openNote(note, known[:1])
299 if err != nil {
300 t.Fatal(err)
301 }
302 if !sigs[0].verified || sigs[1].known {
303 t.Errorf("a signature by an unheld key is unknown, not bad: %+v", sigs)
304 }
305
306 // A signature cannot be lifted onto another statement: it covers the
307 // text it sits under.
308 moved := strings.Replace(string(note), "valley-tree-v1\n", "valley-tree-v2\n", 1)
309 if _, _, err := openNote([]byte(moved), known); err == nil {
310 t.Error("a signature verified over text it was not made over")
311 }
312
313 // One good signature standing beside a forgery is not a note to read
314 // past.
315 forged := flipLastSignatureByte(t, string(note))
316 if _, _, err := openNote([]byte(forged), known); err == nil {
317 t.Error("a note with one bad signature by a known key must be refused")
318 }
319}
320
321func TestOpenSSHKeyIsReadAsSshKeygenWroteIt(t *testing.T) {
322 dir := t.TempDir()
323 path := filepath.Join(dir, "host")
324 if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "t", "-f", path).CombinedOutput(); err != nil {
325 t.Skipf("ssh-keygen is not available: %v: %s", err, out)
326 }
327 s, err := loadSigner(path, "host.example/attestations")
328 if err != nil {
329 t.Fatal(err)
330 }
331 // The public half ssh-keygen wrote beside it is the public half this
332 // parse produced, or the key was read wrong in a way that only shows
333 // up as signatures nobody can check.
334 pub, err := os.ReadFile(path + ".pub")
335 if err != nil {
336 t.Fatal(err)
337 }
338 blob, err := base64.StdEncoding.DecodeString(strings.Fields(string(pub))[1])
339 if err != nil {
340 t.Fatal(err)
341 }
342 want := blob[len(blob)-ed25519.PublicKeySize:]
343 if got := s.priv.Public().(ed25519.PublicKey); string(got) != string(want) {
344 t.Errorf("parsed public key %x, want %x", got, want)
345 }
346}
347
348func TestTreeManifestIsUnambiguous(t *testing.T) {
349 // A path holding the manifest's own separators must not be able to
350 // forge an entry boundary: the byte length is what delimits it.
351 entries := []entry{
352 {mode: modeFile, path: "b\n100644 x 1 c", sum: [32]byte{}},
353 {mode: modeExec, path: "a", sum: [32]byte{0xff}},
354 }
355 want := "valley-tree-v1\n" +
356 "100755 ff00000000000000000000000000000000000000000000000000000000000000 1 a\n" +
357 "100644 0000000000000000000000000000000000000000000000000000000000000000 14 b\n100644 x 1 c\n"
358 if got := string(treeManifest(entries)); got != want {
359 t.Errorf("treeManifest =\n%q\nwant\n%q", got, want)
360 }
361}
362
363func TestTreeDigestIsPinned(t *testing.T) {
364 // The digest of a fixed tree is a wire format: changing it invalidates
365 // every attestation ever made. This value may only change with the
366 // scheme's version.
367 entries := []entry{{mode: modeFile, path: "a.txt", sum: sha256of("hi\n")}}
368 const want = "74781d4ba499b9896e97f2fdd38815d5723cb7b12e448ef0ce5788a1e72c2220"
369 if got := treeDigest(entries); got != want {
370 t.Errorf("treeDigest = %s, want %s", got, want)
371 }
372}
373
374func TestInputsManifestSortsAndDeduplicates(t *testing.T) {
375 want := "valley-inputs-v1\n1 a\n1 b\n"
376 if got := string(inputsManifest([]string{"b", "a", "b"})); got != want {
377 t.Errorf("inputsManifest = %q, want %q", got, want)
378 }
379}
380
381// The digest of a committed tree must equal the digest of that tree
382// written to disk — the two enumerators are the same scheme or the check
383// output digest and the subject digest mean different things.
384func TestGitTreeAndFilesystemAgree(t *testing.T) {
385 repo := t.TempDir()
386 run := func(args ...string) string {
387 cmd := exec.Command("git", args...)
388 cmd.Dir = repo
389 cmd.Env = append(os.Environ(),
390 "GIT_CONFIG_NOSYSTEM=1", "HOME="+t.TempDir(),
391 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@l",
392 "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@l")
393 out, err := cmd.CombinedOutput()
394 if err != nil {
395 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)
396 }
397 return strings.TrimSpace(string(out))
398 }
399 write := func(name, content string, mode os.FileMode) {
400 p := filepath.Join(repo, name)
401 if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
402 t.Fatal(err)
403 }
404 if err := os.WriteFile(p, []byte(content), mode); err != nil {
405 t.Fatal(err)
406 }
407 }
408
409 run("init", "--quiet", "-b", "main")
410 write("plain.txt", "hello\n", 0o644)
411 write("nested/dir/script.sh", "#!/bin/sh\n", 0o755)
412 if err := os.Symlink("plain.txt", filepath.Join(repo, "link")); err != nil {
413 t.Fatal(err)
414 }
415 run("add", "-A")
416 run("commit", "--quiet", "-m", "seed")
417
418 entries, err := gitTreeEntries(repo, "HEAD")
419 if err != nil {
420 t.Fatal(err)
421 }
422 fromGit := treeDigest(entries)
423
424 export := t.TempDir()
425 if err := exportTree(repo, "HEAD", export); err != nil {
426 t.Fatal(err)
427 }
428 fsEnts, err := fsEntries(export)
429 if err != nil {
430 t.Fatal(err)
431 }
432 if fromFS := treeDigest(fsEnts); fromFS != fromGit {
433 t.Errorf("git tree digest %s != filesystem digest %s\n git: %s\n fs: %s",
434 fromGit, fromFS, treeManifest(entries), treeManifest(fsEnts))
435 }
436
437 // The exec bit and the symlink are the two entries a naive walk gets
438 // wrong, so pin that they are actually present.
439 modes := map[string]string{}
440 for _, e := range entries {
441 modes[e.path] = e.mode
442 }
443 for path, want := range map[string]string{
444 "plain.txt": modeFile,
445 "nested/dir/script.sh": modeExec,
446 "link": modeSymlink,
447 } {
448 if modes[path] != want {
449 t.Errorf("%s has mode %q, want %q", path, modes[path], want)
450 }
451 }
452}
453
454func sha256of(s string) [32]byte {
455 var out [32]byte
456 copy(out[:], sha256sum([]byte(s)))
457 return out
458}
459
460func hex8(v uint32) string {
461 const digits = "0123456789abcdef"
462 out := make([]byte, 8)
463 for i := 7; i >= 0; i-- {
464 out[i] = digits[v&0xf]
465 v >>= 4
466 }
467 return string(out)
468}
469
470func testSigner(t *testing.T, name string) signer {
471 t.Helper()
472 pub, priv, err := ed25519.GenerateKey(nil)
473 if err != nil {
474 t.Fatal(err)
475 }
476 return signer{name: name, priv: priv, hash: keyHash(name, pub)}
477}
478
479// flipLastSignatureByte changes one byte of the last signature line's
480// signature, leaving the key hash in front of it alone. That is what a
481// forgery by a key the verifier holds looks like — as opposed to a
482// signature it simply has no key for.
483func flipLastSignatureByte(t *testing.T, note string) string {
484 t.Helper()
485 body := strings.TrimSuffix(note, "\n")
486 head, last := "", body
487 if cut := strings.LastIndex(body, "\n"); cut >= 0 {
488 head, last = body[:cut+1], body[cut+1:]
489 }
490 cut := strings.LastIndex(last, " ")
491 if cut < 0 {
492 t.Fatalf("no signature to perturb in %q", note)
493 }
494 blob, err := base64.StdEncoding.DecodeString(last[cut+1:])
495 if err != nil || len(blob) < 5 {
496 t.Fatalf("no signature to perturb in %q: %v", note, err)
497 }
498 blob[len(blob)-1] ^= 1
499 return head + last[:cut+1] + base64.StdEncoding.EncodeToString(blob) + "\n"
500}