gunk-dev/the-valley

attest_test.go

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