gunk-dev/the-valley

attest_test.go

sourceca98fdc29fbfmain's published tip history
7.8 KiB
1package main
2
3import (
4 "crypto/ed25519"
5 "encoding/base64"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "the-valley/note/statement"
13)
14
15// The note envelope and the keys it is signed with are the pieces of
16// genuinely tricky logic here: they decide what a signature is checked
17// against. The written form and the tree digest are note/statement's, and
18// its tests hold them. Everything else in this program is exercised end to
19// end by the flake checks against the real binary.
20
21// The key hash is the note format's own, and getting it wrong means
22// signing notes nothing else can find the key for. sum.golang.org
23// publishes its verifier key, so its name and public key are an input the
24// reference implementation has already computed the answer for.
25func TestKeyHashMatchesTheReferenceImplementation(t *testing.T) {
26 const (
27 name = "sum.golang.org"
28 public = "Ac4zctda0e5eza+HJyk9SxEdh+s3Ux18htTTAD8OuAn8"
29 want = "033de0ae"
30 )
31 raw, err := base64.StdEncoding.DecodeString(public)
32 if err != nil {
33 t.Fatal(err)
34 }
35 if got := keyHash(name, raw[1:]); hex8(got) != want {
36 t.Errorf("keyHash(%s) = %s, want %s", name, hex8(got), want)
37 }
38 // And the same fact from the other side: the published verifier key
39 // parses, which checks its hash against the one this code computes.
40 if _, err := parseVerifierKey(name + "+" + want + "+" + public); err != nil {
41 t.Errorf("the published verifier key of %s does not parse: %v", name, err)
42 }
43}
44
45func TestNoteCarriesSiblingSignatures(t *testing.T) {
46 first := testSigner(t, "one.example/attestations")
47 second := testSigner(t, "two.example/attestations")
48 text := []byte(statementType + "\nsubject.primary valley-tree-v1\n")
49
50 note, err := signNote(text, first)
51 if err != nil {
52 t.Fatal(err)
53 }
54 if note, err = addSignature(note, second); err != nil {
55 t.Fatal(err)
56 }
57 if lines := strings.Count(string(note), "\n— "); lines != 2 {
58 t.Errorf("note does not carry two sibling signature lines:\n%s", note)
59 }
60
61 known := []verifierKey{first.verifierKey(), second.verifierKey()}
62 got, sigs, err := openNote(note, known)
63 if err != nil {
64 t.Fatal(err)
65 }
66 if string(got) != string(text) {
67 t.Errorf("openNote returned %q, want %q", got, text)
68 }
69 if len(sigs) != 2 || !sigs[0].verified || !sigs[1].verified {
70 t.Errorf("both signatures should verify over one text: %+v", sigs)
71 }
72
73 // A verifier holding one of the two keys accepts the note and reports
74 // the other signature as one it cannot speak to.
75 _, sigs, err = openNote(note, known[:1])
76 if err != nil {
77 t.Fatal(err)
78 }
79 if !sigs[0].verified || sigs[1].known {
80 t.Errorf("a signature by an unheld key is unknown, not bad: %+v", sigs)
81 }
82
83 // A signature cannot be lifted onto another statement: it covers the
84 // text it sits under.
85 moved := strings.Replace(string(note), "valley-tree-v1\n", "valley-tree-v2\n", 1)
86 if _, _, err := openNote([]byte(moved), known); err == nil {
87 t.Error("a signature verified over text it was not made over")
88 }
89
90 // One good signature standing beside a forgery is not a note to read
91 // past.
92 forged := flipLastSignatureByte(t, string(note))
93 if _, _, err := openNote([]byte(forged), known); err == nil {
94 t.Error("a note with one bad signature by a known key must be refused")
95 }
96}
97
98func TestOpenSSHKeyIsReadAsSshKeygenWroteIt(t *testing.T) {
99 dir := t.TempDir()
100 path := filepath.Join(dir, "host")
101 if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "t", "-f", path).CombinedOutput(); err != nil {
102 t.Skipf("ssh-keygen is not available: %v: %s", err, out)
103 }
104 s, err := loadSigner(path, "host.example/attestations")
105 if err != nil {
106 t.Fatal(err)
107 }
108 // The public half ssh-keygen wrote beside it is the public half this
109 // parse produced, or the key was read wrong in a way that only shows
110 // up as signatures nobody can check.
111 pub, err := os.ReadFile(path + ".pub")
112 if err != nil {
113 t.Fatal(err)
114 }
115 blob, err := base64.StdEncoding.DecodeString(strings.Fields(string(pub))[1])
116 if err != nil {
117 t.Fatal(err)
118 }
119 want := blob[len(blob)-ed25519.PublicKeySize:]
120 if got := s.priv.Public().(ed25519.PublicKey); string(got) != string(want) {
121 t.Errorf("parsed public key %x, want %x", got, want)
122 }
123}
124
125func TestInputsManifestSortsAndDeduplicates(t *testing.T) {
126 want := "valley-inputs-v1\n1 a\n1 b\n"
127 if got := string(inputsManifest([]string{"b", "a", "b"})); got != want {
128 t.Errorf("inputsManifest = %q, want %q", got, want)
129 }
130}
131
132// The digest of a committed tree must equal the digest of that tree
133// written to disk — the two enumerators are the same scheme or the check
134// output digest and the subject digest mean different things.
135func TestGitTreeAndFilesystemAgree(t *testing.T) {
136 repo := t.TempDir()
137 run := func(args ...string) string {
138 cmd := exec.Command("git", args...)
139 cmd.Dir = repo
140 cmd.Env = append(os.Environ(),
141 "GIT_CONFIG_NOSYSTEM=1", "HOME="+t.TempDir(),
142 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@l",
143 "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@l")
144 out, err := cmd.CombinedOutput()
145 if err != nil {
146 t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out)
147 }
148 return strings.TrimSpace(string(out))
149 }
150 write := func(name, content string, mode os.FileMode) {
151 p := filepath.Join(repo, name)
152 if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
153 t.Fatal(err)
154 }
155 if err := os.WriteFile(p, []byte(content), mode); err != nil {
156 t.Fatal(err)
157 }
158 }
159
160 run("init", "--quiet", "-b", "main")
161 write("plain.txt", "hello\n", 0o644)
162 write("nested/dir/script.sh", "#!/bin/sh\n", 0o755)
163 if err := os.Symlink("plain.txt", filepath.Join(repo, "link")); err != nil {
164 t.Fatal(err)
165 }
166 run("add", "-A")
167 run("commit", "--quiet", "-m", "seed")
168
169 entries, err := gitTreeEntries(repo, "HEAD")
170 if err != nil {
171 t.Fatal(err)
172 }
173 fromGit := statement.TreeDigest(entries)
174
175 export := t.TempDir()
176 if err := exportTree(repo, "HEAD", export); err != nil {
177 t.Fatal(err)
178 }
179 fsEnts, err := fsEntries(export)
180 if err != nil {
181 t.Fatal(err)
182 }
183 if fromFS := statement.TreeDigest(fsEnts); fromFS != fromGit {
184 t.Errorf("git tree digest %s != filesystem digest %s\n git: %s\n fs: %s",
185 fromGit, fromFS, statement.TreeManifest(entries), statement.TreeManifest(fsEnts))
186 }
187
188 // The exec bit and the symlink are the two entries a naive walk gets
189 // wrong, so pin that they are actually present.
190 modes := map[string]string{}
191 for _, e := range entries {
192 modes[e.Path] = e.Mode
193 }
194 for path, want := range map[string]string{
195 "plain.txt": statement.ModeFile,
196 "nested/dir/script.sh": statement.ModeExec,
197 "link": statement.ModeSymlink,
198 } {
199 if modes[path] != want {
200 t.Errorf("%s has mode %q, want %q", path, modes[path], want)
201 }
202 }
203}
204
205func hex8(v uint32) string {
206 const digits = "0123456789abcdef"
207 out := make([]byte, 8)
208 for i := 7; i >= 0; i-- {
209 out[i] = digits[v&0xf]
210 v >>= 4
211 }
212 return string(out)
213}
214
215func testSigner(t *testing.T, name string) signer {
216 t.Helper()
217 pub, priv, err := ed25519.GenerateKey(nil)
218 if err != nil {
219 t.Fatal(err)
220 }
221 return signer{name: name, priv: priv, hash: keyHash(name, pub)}
222}
223
224// flipLastSignatureByte changes one byte of the last signature line's
225// signature, leaving the key hash in front of it alone. That is what a
226// forgery by a key the verifier holds looks like — as opposed to a
227// signature it simply has no key for.
228func flipLastSignatureByte(t *testing.T, note string) string {
229 t.Helper()
230 body := strings.TrimSuffix(note, "\n")
231 head, last := "", body
232 if cut := strings.LastIndex(body, "\n"); cut >= 0 {
233 head, last = body[:cut+1], body[cut+1:]
234 }
235 cut := strings.LastIndex(last, " ")
236 if cut < 0 {
237 t.Fatalf("no signature to perturb in %q", note)
238 }
239 blob, err := base64.StdEncoding.DecodeString(last[cut+1:])
240 if err != nil || len(blob) < 5 {
241 t.Fatalf("no signature to perturb in %q: %v", note, err)
242 }
243 blob[len(blob)-1] ^= 1
244 return head + last[:cut+1] + base64.StdEncoding.EncodeToString(blob) + "\n"
245}