gunk-dev/the-valley

evidence.go

source6a6791929c36main's published tip history
13.6 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 Runner: statementValue(text, "predicate.check.runner"),
112 Attribute: statementValue(text, "predicate.check.attribute"),
113 Result: statementValue(text, "predicate.result"),
114 }
115 switch statementValue(text, "predicateType") {
116 case predicatePure:
117 ev.Kind = verdict.Pure
118 ev.Inputs = statementValue(text, "predicate.inputs.valley-inputs-v1")
119 ev.Derivation = statementValue(text, "predicate.derivation.sha256")
120 case predicateEffect:
121 ev.Kind = verdict.Effectful
122 if at := statementValue(text, "predicate.observedAt"); at != "" {
123 if t, err := time.Parse("2006-01-02T15:04:05Z", at); err == nil {
124 ev.ObservedAt = t
125 }
126 }
127 }
128 if ev.Check == "" {
129 ev.Check = "(unnamed)"
130 }
131
132 file, err := os.CreateTemp("", "valley-integrator-note")
133 if err != nil {
134 return ev, err
135 }
136 defer os.Remove(file.Name())
137 if _, err := file.Write(note); err != nil {
138 return ev, err
139 }
140 file.Close()
141
142 cmd := exec.Command(in.attest, "verify",
143 "--note", file.Name(),
144 "--known-keys", in.knownSigners,
145 "--schema", in.attestSchema,
146 "--repo", wt.dir, "--rev", rev)
147 out, err := cmd.CombinedOutput()
148 switch {
149 case err == nil:
150 // A key in the known-signers file signed the note. Its signer
151 // counts here only if the signer projects file lets it count in
152 // this project; a note no such signer signed is a stranger's.
153 //
154 // A signature under the integrator's own name is its
155 // countersignature, added when the note landed (transfer.go). It
156 // vouches for that landing, in the project it landed in, and is
157 // never the check's own signer: a countersigned note copied into
158 // another project counts there only through the signer who made
159 // the claim. Nothing in a note marks another controller's
160 // signature as a countersignature, so the host declares each
161 // other controller whose key it holds: the signer projects file
162 // names it with no project, and it counts nowhere.
163 ev.Admissible = verdict.UnknownSigner
164 for _, signer := range verifiedSigners(string(out)) {
165 name, _, _ := strings.Cut(signer, "+")
166 if name != in.signerName && in.signerProjects.Counts(name, in.project) {
167 ev.Admissible, ev.Signer = verdict.Admissible, signer
168 break
169 }
170 }
171 case strings.Contains(string(out), unknownSigner):
172 ev.Admissible = verdict.UnknownSigner
173 default:
174 ev.Admissible = verdict.Tampered
175 ev.Refusal = refusalLine(string(out))
176 }
177 return ev, nil
178}
179
180// verifiedSigners reads the signers whose signatures checked out, as
181// name+hash, in the order of the verifier's own report.
182func verifiedSigners(out string) []string {
183 var signers []string
184 for _, line := range strings.Split(out, "\n") {
185 if fields := strings.Fields(line); len(fields) == 3 && fields[0] == "signature" && fields[1] == "ok" {
186 signers = append(signers, fields[2])
187 }
188 }
189 return signers
190}
191
192// noteText returns the bytes a signature covers: everything before the
193// blank line that separates the text from the signature block. The last
194// blank line wins, so text holding one of its own does not move the split
195// — the rule dcr-de9d996 fixes.
196func noteText(note []byte) ([]byte, error) {
197 split := bytes.LastIndex(note, []byte("\n\n"))
198 if split < 0 {
199 return nil, fmt.Errorf("this is not a note: no blank line separates the text from its signatures")
200 }
201 return note[:split+1], nil
202}
203
204// statementValue reads one line's value out of statement text. Sound only
205// because the form has no escapes and `attest verify` has established the
206// text is the written form of what it says: one line, one key, one value.
207func statementValue(text []byte, key string) string {
208 for _, line := range strings.Split(string(text), "\n") {
209 if k, v, ok := strings.Cut(line, " "); ok && k == key {
210 return v
211 }
212 }
213 return ""
214}
215
216func sha256hex(b []byte) string {
217 sum := sha256.Sum256(b)
218 return hex.EncodeToString(sum[:])
219}
220
221// treeDigest asks attest for a revision's valley tree digest. One
222// implementation of the content-addressing scheme, in the program that
223// defines it.
224func (in *integrator) treeDigest(wt *worktree, rev string) (string, error) {
225 out, err := exec.Command(in.attest, "digest", "--repo", wt.dir, "--rev", rev).Output()
226 if err != nil {
227 return "", fmt.Errorf("digesting %s: %w", verdict.Short(rev), err)
228 }
229 digest := strings.TrimSpace(string(out))
230 scheme, value, ok := strings.Cut(digest, ":")
231 if !ok || scheme != "valley-tree-v1" {
232 return "", fmt.Errorf("attest digest printed %q", digest)
233 }
234 return value, nil
235}
236
237// closures recomputes the input-closure digest of each pure check over the
238// tree that would land. `attest inputs` evaluates and digests; it builds
239// nothing, so this stays off the latency path the commit point serializes.
240//
241// Every required pure check is asked for in one `attest inputs`, which
242// exports the tree once and evaluates the checks together. Its answer is
243// taken only when it exited zero and printed exactly the checks asked for.
244// Otherwise every line of it is dropped and each check is asked for alone,
245// so a check that does not evaluate is an error for that check only, and
246// the checks beside it still get their closures. One check alone is not
247// asked for twice. Each check asked for ends up in exactly one of the two
248// maps returned.
249func (in *integrator) closures(wt *worktree, rev string, required []verdict.Required) (map[string]verdict.Closure, map[string]string) {
250 got, bad := map[string]verdict.Closure{}, map[string]string{}
251 var names []string
252 attrs := map[string]string{}
253 for _, r := range required {
254 if r.Runner != "nix" {
255 continue
256 }
257 if _, seen := attrs[r.Name]; !seen {
258 names = append(names, r.Name)
259 }
260 attrs[r.Name] = r.Attribute
261 }
262 if len(names) == 0 {
263 // Without a --check, attest inputs would digest every flake check.
264 return got, bad
265 }
266 sort.Strings(names)
267 all, err := in.attestInputs(wt, rev, names, attrs)
268 switch {
269 case err == nil:
270 return all, bad
271 case len(names) == 1:
272 bad[names[0]] = err.Error()
273 return got, bad
274 }
275 for _, name := range names {
276 one, err := in.attestInputs(wt, rev, []string{name}, attrs)
277 if err != nil {
278 bad[name] = err.Error()
279 continue
280 }
281 got[name] = one[name]
282 }
283 return got, bad
284}
285
286// attestInputs runs one `attest inputs` over the named checks, each as
287// name=attribute, and reads the closures it printed on standard output.
288// Standard error is only ever a diagnostic: when the command fails, its
289// first line is the error.
290func (in *integrator) attestInputs(wt *worktree, rev string, names []string, attrs map[string]string) (map[string]verdict.Closure, error) {
291 args := []string{"inputs", "--repo", wt.dir, "--rev", rev}
292 for _, name := range names {
293 args = append(args, "--check", name+"="+attrs[name])
294 }
295 if in.system != "" {
296 args = append(args, "--system", in.system)
297 }
298 cmd := exec.Command(in.attest, args...)
299 var stdout, stderr bytes.Buffer
300 cmd.Stdout, cmd.Stderr = &stdout, &stderr
301 if err := cmd.Run(); err != nil {
302 if line := firstLine(stderr.String()); line != "" {
303 return nil, fmt.Errorf("%s", line)
304 }
305 return nil, fmt.Errorf("attest inputs: %w", err)
306 }
307 return parseInputs(stdout.String(), names)
308}
309
310// parseInputs reads what `attest inputs` printed for the named checks: one
311// line per check, "<name> valley-inputs-v1:<closure> sha256:<derivation>",
312// each digest 64 lowercase hex digits. Both digests are read, because the
313// pure rule compares the whole of what the attestation claims. A line is
314// matched to its check by name, never by where it is. Any line that is not
315// that form, names a check not asked for or one already read, or a check
316// asked for and not printed, makes the whole answer an error.
317func parseInputs(out string, names []string) (map[string]verdict.Closure, error) {
318 asked := map[string]bool{}
319 for _, name := range names {
320 asked[name] = true
321 }
322 got := map[string]verdict.Closure{}
323 for _, line := range strings.Split(strings.TrimSuffix(out, "\n"), "\n") {
324 fields := strings.Split(line, " ")
325 if len(fields) != 3 {
326 return nil, fmt.Errorf("attest inputs printed %q", firstLine(line))
327 }
328 name := fields[0]
329 inputs, isInputs := strings.CutPrefix(fields[1], "valley-inputs-v1:")
330 derivation, isDerivation := strings.CutPrefix(fields[2], "sha256:")
331 _, twice := got[name]
332 switch {
333 case !asked[name]:
334 return nil, fmt.Errorf("attest inputs printed %q, a check not asked for", name)
335 case twice:
336 return nil, fmt.Errorf("attest inputs printed %s twice", name)
337 case !isInputs || !isDigest(inputs) || !isDerivation || !isDigest(derivation):
338 return nil, fmt.Errorf("attest inputs printed %q", line)
339 }
340 got[name] = verdict.Closure{Inputs: inputs, Derivation: derivation}
341 }
342 for _, name := range names {
343 if _, ok := got[name]; !ok {
344 return nil, fmt.Errorf("attest inputs printed nothing for %s", name)
345 }
346 }
347 return got, nil
348}
349
350// isDigest is whether s is a SHA-256 digest as attest writes one: 64
351// lowercase hex digits.
352func isDigest(s string) bool {
353 if len(s) != 64 {
354 return false
355 }
356 for _, c := range s {
357 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
358 return false
359 }
360 }
361 return true
362}
363
364func firstLine(s string) string {
365 s = strings.TrimSpace(s)
366 if i := strings.IndexByte(s, '\n'); i >= 0 {
367 return s[:i]
368 }
369 return s
370}
371
372// refusalLine is the sentence a verifier refused with. `attest` reports what
373// it checked, then the refusal prefixed with its own name, then whatever
374// elaborates it; a reader of a verdict wants the sentence. This convention
375// belongs to the command being driven, so it is read here, at the boundary
376// that drives it, and the verdict is handed a result rather than a
377// transcript to parse.
378func refusalLine(out string) string {
379 var last string
380 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
381 if why, ok := strings.CutPrefix(line, "attest: "); ok {
382 return strings.TrimSpace(why)
383 }
384 if strings.TrimSpace(line) != "" {
385 last = strings.TrimSpace(line)
386 }
387 }
388 return last
389}