gunk-dev/the-valley

verify.go

source6a6791929c36main's published tip history
12.7 KiB
1package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "os"
9 "slices"
10 "strconv"
11 "strings"
12
13 "the-valley/note/statement"
14)
15
16// cmdVerify checks an attestation, in the order the protocol states it:
17// parse, validate, verify. The note's text is parsed back into a
18// statement, which admits nothing but the one written form of what it
19// says; that statement is vetted against the schema; and every signature
20// by a key the verifier holds is checked over those exact bytes. Given
21// --repo, the tree the statement names is then compared with the tree in
22// front of the verifier.
23//
24// With --verdicts it takes --note once or more, and checks each note as a
25// run for that note alone would, reading the keys and the tree once. The
26// statements are vetted in one cue run, which checks each file against the
27// schema on its own; when that run fails, each statement is vetted alone,
28// so a refusal says what it would say for that note alone. It prints
29// nothing until every note is checked, and then only its verdicts
30// (verdictLines), so no line it prints carries text it did not write. The
31// run exits 1 when any note is refused.
32//
33// Re-running a pure check and confirming its output digest is deliberately
34// not here. That is witness re-verification, and it belongs to the trust
35// backstop of a later phase; what this verifies is the claim's
36// authenticity and its binding to a tree.
37func cmdVerify(args []string) error {
38 fs := newFlagSet("verify")
39 var notes repeatable
40 fs.Var(&notes, "note", "the signed note, repeatable")
41 known := fs.String("known-keys", "", "verifier keys the reader accepts")
42 schemaFlag := fs.String("schema", "", "attestation schema")
43 repo := fs.String("repo", "", "repository to re-check against")
44 rev := fs.String("rev", "HEAD", "revision in it")
45 var required repeatable
46 fs.Var(&required, "signer", "signer whose signature must be present")
47 verdicts := fs.Bool("verdicts", false, "print one verdict line for each note")
48 if err := fs.Parse(args); err != nil {
49 return err
50 }
51 if len(notes) == 0 || slices.Contains(notes, "") {
52 return fmt.Errorf("--note is required")
53 }
54 if *known == "" {
55 return fmt.Errorf("--known-keys is required")
56 }
57 v := &verifying{known: *known, schemaFlag: *schemaFlag, repo: *repo, rev: *rev, required: required}
58 switch {
59 case *verdicts:
60 return v.each(notes)
61 case len(notes) > 1:
62 return fmt.Errorf("--note is given more than once, which only --verdicts reads")
63 }
64 return v.alone(notes[0])
65}
66
67// verifying is one verify run's inputs, and what it has read of them. A
68// value is read when the first note needs it and kept for the rest, so a
69// run over several notes reads the keys, the repository, the schema and
70// the tree once, and each note gets the answer a run of its own would.
71type verifying struct {
72 known, schemaFlag, repo, rev string
73 required []string
74
75 keysRead bool
76 keys []verifierKey
77 keysErr error
78 rootRead bool
79 root string
80 rootErr error
81 schemaRead bool
82 schema string
83 schemaErr error
84 treeRead bool
85 tree string
86 treeErr error
87 vetted map[string]bool // statements, as JSON, that cue has vetted
88}
89
90func (v *verifying) readKeys() ([]verifierKey, error) {
91 if !v.keysRead {
92 v.keysRead = true
93 v.keys, v.keysErr = readVerifierKeys(v.known)
94 }
95 return v.keys, v.keysErr
96}
97
98func (v *verifying) readRoot() (string, error) {
99 if !v.rootRead {
100 v.rootRead = true
101 if v.repo != "" {
102 v.root, v.rootErr = repoRoot(v.repo)
103 }
104 }
105 return v.root, v.rootErr
106}
107
108func (v *verifying) readSchema(root string) (string, error) {
109 if !v.schemaRead {
110 v.schemaRead = true
111 v.schema, v.schemaErr = schemaPath(v.schemaFlag, root)
112 }
113 return v.schema, v.schemaErr
114}
115
116// readTree is the digest of the revision's tree in root.
117func (v *verifying) readTree(root string) (string, error) {
118 if !v.treeRead {
119 v.treeRead = true
120 entries, err := gitTreeEntries(root, v.rev)
121 if err != nil {
122 v.treeErr = err
123 } else {
124 v.tree = statement.TreeDigest(entries)
125 }
126 }
127 return v.tree, v.treeErr
128}
129
130// alone verifies one note, printing its lines on stdout as each step
131// passes.
132func (v *verifying) alone(path string) error {
133 note, err := os.ReadFile(path)
134 if err != nil {
135 return err
136 }
137 keys, err := v.readKeys()
138 if err != nil {
139 return err
140 }
141 fmt.Printf("note %s\n", path)
142 _, err = v.check(path, note, keys, os.Stdout)
143 return err
144}
145
146// each verifies each note as alone would, after vetting their statements
147// together, and prints the verdicts once every note is checked.
148func (v *verifying) each(paths []string) error {
149 notes := make([][]byte, len(paths))
150 unread := make([]error, len(paths))
151 for i, path := range paths {
152 notes[i], unread[i] = os.ReadFile(path)
153 }
154 keys, unkeyed := v.readKeys()
155 if unkeyed == nil {
156 v.vetTogether(notes, unread, keys)
157 }
158 signers := make([][]string, len(paths))
159 refusals := make([]error, len(paths))
160 for i, path := range paths {
161 switch {
162 case unread[i] != nil:
163 refusals[i] = unread[i]
164 case unkeyed != nil:
165 refusals[i] = unkeyed
166 default:
167 signers[i], refusals[i] = v.check(path, notes[i], keys, io.Discard)
168 }
169 }
170 // A reader that does not get every verdict line gets no verdict, so a
171 // write that fails ends the run with an error.
172 if _, err := os.Stdout.WriteString(verdictLines(signers, refusals)); err != nil {
173 return err
174 }
175 refused := 0
176 for _, err := range refusals {
177 if err != nil {
178 refused++
179 }
180 }
181 if refused > 0 {
182 return fmt.Errorf("%d of %d notes refused", refused, len(paths))
183 }
184 return nil
185}
186
187// verdictLines are the verdicts of the notes given, the first note's
188// first, one line each, then a line that counts them:
189//
190// verdict 1 verified "worker/attestations+74a84b34"
191// verdict 2 refused "tree digest mismatch: the statement is about a different tree\n recorded …"
192// end 2
193//
194// A note is named by its place among the --note flags rather than by its
195// object ID, since two notes may hold the same bytes. A verified note's
196// line names every signer whose signature checked out, in the note's
197// order; a refused note's gives why, the error a run for that note alone
198// ends with. Every value is a Go string literal, so a newline in a path,
199// a name or a tool's output stays inside its line.
200func verdictLines(signers [][]string, refusals []error) string {
201 var b strings.Builder
202 for i := range refusals {
203 if refusals[i] != nil {
204 fmt.Fprintf(&b, "verdict %d refused %s\n", i+1, strconv.Quote(refusals[i].Error()))
205 continue
206 }
207 fmt.Fprintf(&b, "verdict %d verified", i+1)
208 for _, s := range signers[i] {
209 b.WriteString(" " + strconv.Quote(s))
210 }
211 b.WriteString("\n")
212 }
213 fmt.Fprintf(&b, "end %d\n", len(refusals))
214 return b.String()
215}
216
217// vetTogether vets in one cue run the statements of the notes that open
218// and parse, and remembers them as vetted when every one passes. When any
219// fails, it remembers none, and check vets each alone.
220func (v *verifying) vetTogether(notes [][]byte, unread []error, keys []verifierKey) {
221 root, err := v.readRoot()
222 if err != nil {
223 return
224 }
225 schema, err := v.readSchema(root)
226 if err != nil {
227 return
228 }
229 var docs [][]byte
230 for i := range notes {
231 if unread[i] != nil {
232 continue
233 }
234 text, _, err := openNote(notes[i], keys)
235 if err != nil {
236 continue
237 }
238 doc, err := statement.Parse(text)
239 if err != nil {
240 continue
241 }
242 raw, err := json.Marshal(doc)
243 if err != nil {
244 continue
245 }
246 docs = append(docs, raw)
247 }
248 if len(docs) < 2 || vetStatements(schema, docs) != nil {
249 return
250 }
251 v.vetted = map[string]bool{}
252 for _, raw := range docs {
253 v.vetted[string(raw)] = true
254 }
255}
256
257// check verifies one note's bytes, read from path, under keys, prints its
258// lines to w as each step passes, and returns the signers whose signatures
259// checked out, as name+hash, once every step has passed.
260func (v *verifying) check(path string, note []byte, keys []verifierKey, w io.Writer) ([]string, error) {
261 // The signature covers the text, so the text is what everything below
262 // is about. Parsing it admits no rendering but the one written form of
263 // what it says: a statement stored some other way would verify here and
264 // fail to verify wherever it was written out again.
265 text, sigs, err := openNote(note, keys)
266 if err != nil {
267 return nil, err
268 }
269 doc, err := statement.Parse(text)
270 if err != nil {
271 return nil, fmt.Errorf("%s: %w", path, err)
272 }
273 fmt.Fprintf(w, "text ok (%d bytes signed)\n", len(text))
274
275 raw, err := json.Marshal(doc)
276 if err != nil {
277 return nil, err
278 }
279 root, err := v.readRoot()
280 if err != nil {
281 return nil, err
282 }
283 schema, err := v.readSchema(root)
284 if err != nil {
285 return nil, err
286 }
287 if !v.vetted[string(raw)] {
288 if err := vetStatement(schema, raw); err != nil {
289 return nil, err
290 }
291 }
292 fmt.Fprintf(w, "schema ok (%s)\n", schema)
293
294 signed := map[string]bool{}
295 var signers []string
296 for _, s := range sigs {
297 state := "unknown"
298 if s.verified {
299 state = "ok"
300 signed[s.name] = true
301 signers = append(signers, fmt.Sprintf("%s+%08x", s.name, s.hash))
302 }
303 fmt.Fprintf(w, "signature %-7s %s+%08x\n", state, s.name, s.hash)
304 }
305 for _, want := range v.required {
306 if !signed[want] {
307 return nil, fmt.Errorf("no signature on this note is by %s", want)
308 }
309 }
310
311 var st document
312 if err := json.Unmarshal(raw, &st); err != nil {
313 return nil, err
314 }
315 recorded := st.Subject.Digest[st.Subject.Primary]
316 fmt.Fprintf(w, "subject %s:%s\n", st.Subject.Primary, recorded)
317 fmt.Fprintf(w, "predicate %s (%s %s: %s)\n", st.PredicateType, st.Predicate.Check.Runner, st.Predicate.Check.Name, st.Predicate.Result)
318
319 if root == "" {
320 fmt.Fprintf(w, "tree not re-checked; pass --repo to bind this statement to a tree\n")
321 return signers, nil
322 }
323 got, err := v.readTree(root)
324 if err != nil {
325 return nil, err
326 }
327 fmt.Fprintf(w, "tree %s@%s %s:%s\n", root, v.rev, statement.TreeScheme, got)
328 if got != recorded {
329 return nil, fmt.Errorf("tree digest mismatch: the statement is about a different tree\n recorded %s\n found %s", recorded, got)
330 }
331 fmt.Fprintf(w, " matches the recorded subject digest\n")
332 return signers, nil
333}
334
335// cmdRender writes a document as the statement text a signature covers.
336//
337// It takes either a JSON document or statement text, told apart by the
338// first character a JSON object has to open with. Text in, text out is how
339// a reader checks that a stored statement is in the one written form of
340// what it says: the form is a fixed point, so anything this command
341// changes was not it.
342func cmdRender(args []string) error {
343 fs := newFlagSet("render")
344 if err := fs.Parse(args); err != nil {
345 return err
346 }
347 raw, err := readInput(fs.Args(), "render takes one file, or none to read stdin")
348 if err != nil {
349 return err
350 }
351 var out []byte
352 if isJSON(raw) {
353 if out, err = statement.RenderJSON(raw); err != nil {
354 return err
355 }
356 } else {
357 doc, err := statement.Parse(raw)
358 if err != nil {
359 return err
360 }
361 if out, err = statement.Render(doc); err != nil {
362 return err
363 }
364 }
365 _, err = os.Stdout.Write(out)
366 return err
367}
368
369// cmdSign signs statement text, or adds a signature to a note that already
370// carries one. Which of the two it is doing is decided by the input:
371// statement text holds no blank line, and a note is a text and a signature
372// block with a blank line between them.
373func cmdSign(args []string) error {
374 fs := newFlagSet("sign")
375 key := fs.String("key", "", "ed25519 private key to sign with")
376 name := fs.String("name", defaultSignerName(), "the name this key signs under")
377 if err := fs.Parse(args); err != nil {
378 return err
379 }
380 raw, err := readInput(fs.Args(), "sign takes one file, or none to read stdin")
381 if err != nil {
382 return err
383 }
384 s, err := loadSigner(*key, *name)
385 if err != nil {
386 return err
387 }
388 var note []byte
389 if bytes.Contains(raw, []byte("\n\n")) {
390 note, err = addSignature(raw, s)
391 } else {
392 note, err = signNote(raw, s)
393 }
394 if err != nil {
395 return err
396 }
397 _, err = os.Stdout.Write(note)
398 return err
399}
400
401// cmdKey prints the verifier key for a signing key: the one line a
402// verifier is given in order to accept this signer, and nothing else.
403func cmdKey(args []string) error {
404 fs := newFlagSet("key")
405 key := fs.String("key", "", "ed25519 private key")
406 name := fs.String("name", defaultSignerName(), "the name this key signs under")
407 if err := fs.Parse(args); err != nil {
408 return err
409 }
410 s, err := loadSigner(*key, *name)
411 if err != nil {
412 return err
413 }
414 fmt.Println(s.verifierKey())
415 return nil
416}
417
418// isJSON says whether input is a JSON document rather than statement text.
419// A statement is an object, so a JSON one opens with a brace and statement
420// text never does.
421func isJSON(raw []byte) bool {
422 return bytes.HasPrefix(bytes.TrimLeft(raw, " \t\r\n"), []byte("{"))
423}
424
425func readInput(args []string, misuse string) ([]byte, error) {
426 switch len(args) {
427 case 0:
428 return io.ReadAll(os.Stdin)
429 case 1:
430 return os.ReadFile(args[0])
431 default:
432 return nil, fmt.Errorf("%s", misuse)
433 }
434}