gunk-dev/the-valley

evidence.go

sourcec0fb7f7caad5main's published tip history
13.5 KiB
1package main
2
3// Reading a change's evidence. Every judgement about whether an attestation
4// is what it claims to be is `attest verify`'s: the note's signatures, the
5// text being the one written form of what it says, the statement satisfying
6// the schema, and its subject digest being the tree in front of the
7// verifier. This file runs that verifier and classifies what it said.
8//
9// Nothing here re-implements the envelope or the written form. What it does
10// do is read values out of text that `attest verify` has already established
11// is the written form of what it says — where a line is a key, one space,
12// and a value, with no escapes. That is a lookup, not a parser, and it is
13// sound only in that order: verify first, read second.
14
15import (
16 "the-valley/change"
17 "the-valley/integrator/verdict"
18
19 "bytes"
20 "crypto/sha256"
21 "encoding/hex"
22 "fmt"
23 "os"
24 "os/exec"
25 "path"
26 "sort"
27 "strings"
28 "time"
29)
30
31const (
32 attestationPrefix = "refs/the-valley/attestations"
33 statementNote = "statement.note"
34
35 predicatePure = "the-valley/check/pure/v1"
36 predicateEffect = "the-valley/check/effectful/v1"
37 predicateTransfer = "the-valley/integration/transfer/v1"
38)
39
40// unknownSigner is the one sentence `attest verify` refuses a well-formed
41// note with when nobody who signed it is a key the verifier holds. Every
42// other refusal is a forgery as far as the integrator is concerned, so this
43// classification fails closed: an unrecognised message is a rejection.
44const unknownSigner = "no signature on this note is by a key the verifier holds"
45
46// collectEvidence finds every attestation stored for a subject digest and
47// classifies it. Attestations are stored one ref per signer
48// (dcr-0de694f), so a subject may carry several notes for one check.
49// Which one a check is judged by is change.SelectNotes's choice, the one
50// approve makes too: the first admissible note, whatever it records, or
51// else the last note read, so a note that does not verify is reported and
52// the verdict can reject rather than quietly look past it.
53func (in *integrator) collectEvidence(wt *worktree, rev, subject string) (map[string]verdict.Evidence, map[string][]byte, error) {
54 // Each ref is read through the object it held when listed, never by its
55 // name again: a ref deleted since would have git try other names for it.
56 refs, err := git(in.repo, "for-each-ref", "--format=%(objectname)", attestationPrefix+"/"+subject)
57 if err != nil {
58 return nil, nil, err
59 }
60 if in.evidenceListed != nil {
61 in.evidenceListed()
62 }
63 type read struct {
64 ev verdict.Evidence
65 note []byte
66 }
67 var all []read
68 for _, oid := range strings.Fields(refs) {
69 listing, err := git(in.repo, "ls-tree", "-r", "--name-only", oid)
70 if err != nil {
71 return nil, nil, err
72 }
73 for _, entry := range strings.Fields(listing) {
74 if path.Base(entry) != statementNote {
75 continue
76 }
77 note, err := git(in.repo, "cat-file", "blob", oid+":"+entry)
78 if err != nil {
79 return nil, nil, err
80 }
81 ev, err := in.classify(wt, rev, []byte(note))
82 if err != nil {
83 return nil, nil, err
84 }
85 all = append(all, read{ev, []byte(note)})
86 }
87 }
88 picked := change.SelectNotes(all,
89 func(r read) string { return r.ev.Check },
90 func(r read) bool { return r.ev.Admissible == verdict.Admissible })
91 found := map[string]verdict.Evidence{}
92 notes := map[string][]byte{}
93 for check, r := range picked {
94 found[check], notes[check] = r.ev, r.note
95 }
96 return found, notes, nil
97}
98
99// classify runs `attest verify` over one note and reads the statement back.
100// A note with no verified signer who counts in this project
101// (note/signerprojects.go) is classified as signed by an unknown signer.
102// The integrator's own signature never counts here.
103func (in *integrator) classify(wt *worktree, rev string, note []byte) (verdict.Evidence, error) {
104 text, err := noteText(note)
105 if err != nil {
106 return verdict.Evidence{}, err
107 }
108 ev := verdict.Evidence{
109 TextDigest: sha256hex(text),
110 Check: statementValue(text, "predicate.check.name"),
111 Result: statementValue(text, "predicate.result"),
112 }
113 switch statementValue(text, "predicateType") {
114 case predicatePure:
115 ev.Kind = verdict.Pure
116 ev.Inputs = statementValue(text, "predicate.inputs.valley-inputs-v1")
117 ev.Derivation = statementValue(text, "predicate.derivation.sha256")
118 case predicateEffect:
119 ev.Kind = verdict.Effectful
120 if at := statementValue(text, "predicate.observedAt"); at != "" {
121 if t, err := time.Parse("2006-01-02T15:04:05Z", at); err == nil {
122 ev.ObservedAt = t
123 }
124 }
125 }
126 if ev.Check == "" {
127 ev.Check = "(unnamed)"
128 }
129
130 file, err := os.CreateTemp("", "valley-integrator-note")
131 if err != nil {
132 return ev, err
133 }
134 defer os.Remove(file.Name())
135 if _, err := file.Write(note); err != nil {
136 return ev, err
137 }
138 file.Close()
139
140 cmd := exec.Command(in.attest, "verify",
141 "--note", file.Name(),
142 "--known-keys", in.knownSigners,
143 "--schema", in.attestSchema,
144 "--repo", wt.dir, "--rev", rev)
145 out, err := cmd.CombinedOutput()
146 switch {
147 case err == nil:
148 // A key in the known-signers file signed the note. Its signer
149 // counts here only if the signer projects file lets it count in
150 // this project; a note no such signer signed is a stranger's.
151 //
152 // A signature under the integrator's own name is its
153 // countersignature, added when the note landed (transfer.go). It
154 // vouches for that landing, in the project it landed in, and is
155 // never the check's own signer: a countersigned note copied into
156 // another project counts there only through the signer who made
157 // the claim. Nothing in a note marks another controller's
158 // signature as a countersignature, so the host declares each
159 // other controller whose key it holds: the signer projects file
160 // names it with no project, and it counts nowhere.
161 ev.Admissible = verdict.UnknownSigner
162 for _, signer := range verifiedSigners(string(out)) {
163 name, _, _ := strings.Cut(signer, "+")
164 if name != in.signerName && in.signerProjects.Counts(name, in.project) {
165 ev.Admissible, ev.Signer = verdict.Admissible, signer
166 break
167 }
168 }
169 case strings.Contains(string(out), unknownSigner):
170 ev.Admissible = verdict.UnknownSigner
171 default:
172 ev.Admissible = verdict.Tampered
173 ev.Refusal = refusalLine(string(out))
174 }
175 return ev, nil
176}
177
178// verifiedSigners reads the signers whose signatures checked out, as
179// name+hash, in the order of the verifier's own report.
180func verifiedSigners(out string) []string {
181 var signers []string
182 for _, line := range strings.Split(out, "\n") {
183 if fields := strings.Fields(line); len(fields) == 3 && fields[0] == "signature" && fields[1] == "ok" {
184 signers = append(signers, fields[2])
185 }
186 }
187 return signers
188}
189
190// noteText returns the bytes a signature covers: everything before the
191// blank line that separates the text from the signature block. The last
192// blank line wins, so text holding one of its own does not move the split
193// — the rule dcr-de9d996 fixes.
194func noteText(note []byte) ([]byte, error) {
195 split := bytes.LastIndex(note, []byte("\n\n"))
196 if split < 0 {
197 return nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
198 }
199 return note[:split+1], nil
200}
201
202// statementValue reads one line's value out of statement text. Sound only
203// because the form has no escapes and `attest verify` has established the
204// text is the written form of what it says: one line, one key, one value.
205func statementValue(text []byte, key string) string {
206 for _, line := range strings.Split(string(text), "\n") {
207 if k, v, ok := strings.Cut(line, " "); ok && k == key {
208 return v
209 }
210 }
211 return ""
212}
213
214func sha256hex(b []byte) string {
215 sum := sha256.Sum256(b)
216 return hex.EncodeToString(sum[:])
217}
218
219// treeDigest asks attest for a revision's valley tree digest. One
220// implementation of the content-addressing scheme, in the program that
221// defines it.
222func (in *integrator) treeDigest(wt *worktree, rev string) (string, error) {
223 out, err := exec.Command(in.attest, "digest", "--repo", wt.dir, "--rev", rev).Output()
224 if err != nil {
225 return "", fmt.Errorf("digesting %s: %w", verdict.Short(rev), err)
226 }
227 digest := strings.TrimSpace(string(out))
228 scheme, value, ok := strings.Cut(digest, ":")
229 if !ok || scheme != "valley-tree-v1" {
230 return "", fmt.Errorf("attest digest printed %q", digest)
231 }
232 return value, nil
233}
234
235// closures recomputes the input-closure digest of each pure check over the
236// tree that would land. `attest inputs` evaluates and digests; it builds
237// nothing, so this stays off the latency path the commit point serializes.
238//
239// Every required pure check is asked for in one `attest inputs`, which
240// exports the tree once and evaluates the checks together. Its answer is
241// taken only when it exited zero and printed exactly the checks asked for.
242// Otherwise every line of it is dropped and each check is asked for alone,
243// so a check that does not evaluate is an error for that check only, and
244// the checks beside it still get their closures. One check alone is not
245// asked for twice. Each check asked for ends up in exactly one of the two
246// maps returned.
247func (in *integrator) closures(wt *worktree, rev string, required []verdict.Required) (map[string]verdict.Closure, map[string]string) {
248 got, bad := map[string]verdict.Closure{}, map[string]string{}
249 var names []string
250 attrs := map[string]string{}
251 for _, r := range required {
252 if r.Runner != "nix" {
253 continue
254 }
255 if _, seen := attrs[r.Name]; !seen {
256 names = append(names, r.Name)
257 }
258 attrs[r.Name] = r.Attribute
259 }
260 if len(names) == 0 {
261 // Without a --check, attest inputs would digest every flake check.
262 return got, bad
263 }
264 sort.Strings(names)
265 all, err := in.attestInputs(wt, rev, names, attrs)
266 switch {
267 case err == nil:
268 return all, bad
269 case len(names) == 1:
270 bad[names[0]] = err.Error()
271 return got, bad
272 }
273 for _, name := range names {
274 one, err := in.attestInputs(wt, rev, []string{name}, attrs)
275 if err != nil {
276 bad[name] = err.Error()
277 continue
278 }
279 got[name] = one[name]
280 }
281 return got, bad
282}
283
284// attestInputs runs one `attest inputs` over the named checks, each as
285// name=attribute, and reads the closures it printed on standard output.
286// Standard error is only ever a diagnostic: when the command fails, its
287// first line is the error.
288func (in *integrator) attestInputs(wt *worktree, rev string, names []string, attrs map[string]string) (map[string]verdict.Closure, error) {
289 args := []string{"inputs", "--repo", wt.dir, "--rev", rev}
290 for _, name := range names {
291 args = append(args, "--check", name+"="+attrs[name])
292 }
293 if in.system != "" {
294 args = append(args, "--system", in.system)
295 }
296 cmd := exec.Command(in.attest, args...)
297 var stdout, stderr bytes.Buffer
298 cmd.Stdout, cmd.Stderr = &stdout, &stderr
299 if err := cmd.Run(); err != nil {
300 if line := firstLine(stderr.String()); line != "" {
301 return nil, fmt.Errorf("%s", line)
302 }
303 return nil, fmt.Errorf("attest inputs: %w", err)
304 }
305 return parseInputs(stdout.String(), names)
306}
307
308// parseInputs reads what `attest inputs` printed for the named checks: one
309// line per check, "<name> valley-inputs-v1:<closure> sha256:<derivation>",
310// each digest 64 lowercase hex digits. Both digests are read, because the
311// pure rule compares the whole of what the attestation claims. A line is
312// matched to its check by name, never by where it is. Any line that is not
313// that form, names a check not asked for or one already read, or a check
314// asked for and not printed, makes the whole answer an error.
315func parseInputs(out string, names []string) (map[string]verdict.Closure, error) {
316 asked := map[string]bool{}
317 for _, name := range names {
318 asked[name] = true
319 }
320 got := map[string]verdict.Closure{}
321 for _, line := range strings.Split(strings.TrimSuffix(out, "\n"), "\n") {
322 fields := strings.Split(line, " ")
323 if len(fields) != 3 {
324 return nil, fmt.Errorf("attest inputs printed %q", firstLine(line))
325 }
326 name := fields[0]
327 inputs, isInputs := strings.CutPrefix(fields[1], "valley-inputs-v1:")
328 derivation, isDerivation := strings.CutPrefix(fields[2], "sha256:")
329 _, twice := got[name]
330 switch {
331 case !asked[name]:
332 return nil, fmt.Errorf("attest inputs printed %q, a check not asked for", name)
333 case twice:
334 return nil, fmt.Errorf("attest inputs printed %s twice", name)
335 case !isInputs || !isDigest(inputs) || !isDerivation || !isDigest(derivation):
336 return nil, fmt.Errorf("attest inputs printed %q", line)
337 }
338 got[name] = verdict.Closure{Inputs: inputs, Derivation: derivation}
339 }
340 for _, name := range names {
341 if _, ok := got[name]; !ok {
342 return nil, fmt.Errorf("attest inputs printed nothing for %s", name)
343 }
344 }
345 return got, nil
346}
347
348// isDigest is whether s is a SHA-256 digest as attest writes one: 64
349// lowercase hex digits.
350func isDigest(s string) bool {
351 if len(s) != 64 {
352 return false
353 }
354 for _, c := range s {
355 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
356 return false
357 }
358 }
359 return true
360}
361
362func firstLine(s string) string {
363 s = strings.TrimSpace(s)
364 if i := strings.IndexByte(s, '\n'); i >= 0 {
365 return s[:i]
366 }
367 return s
368}
369
370// refusalLine is the sentence a verifier refused with. `attest` reports what
371// it checked, then the refusal prefixed with its own name, then whatever
372// elaborates it; a reader of a verdict wants the sentence. This convention
373// belongs to the command being driven, so it is read here, at the boundary
374// that drives it, and the verdict is handed a result rather than a
375// transcript to parse.
376func refusalLine(out string) string {
377 var last string
378 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
379 if why, ok := strings.CutPrefix(line, "attest: "); ok {
380 return strings.TrimSpace(why)
381 }
382 if strings.TrimSpace(line) != "" {
383 last = strings.TrimSpace(line)
384 }
385 }
386 return last
387}