gunk-dev/the-valley

coverage.go

sourcea4ba77eaef6dmain's published tip history
18.1 KiB
1package main
2
3// coverage says which of a head's required nix checks already have evidence
4// on origin that approval can reuse, so that approve (bin/valley) runs only
5// the rest. A check worker publishes such evidence, and so does an earlier
6// approval.
7//
8// Approve skips a check only where the integrator will accept the same
9// evidence. So coverage judges each check by the note the integrator
10// judges it by, read the way the integrator reads it:
11//
12// - Only what origin holds counts. coverage lists origin's attestation
13// refs for the head's tree, fetches the objects they name by ID, and
14// reads every note in them, byte for byte. It never reads a local ref,
15// so a note stored here and never published is not mistaken for
16// evidence the integrator will see. A listing or a fetch that fails is
17// an error, never an empty answer.
18// - Of the notes about a check, the one judged is change.SelectNotes's
19// choice, in the order the integrator reads them: the first that
20// verifies, whatever it records.
21// - It verifies when attest verify accepts it under the known-signers
22// file the serving host publishes (signers.go), which is the host's
23// current authorization as far as a client can read it. With no
24// publication, nothing is reused.
25// - And one of the signers attest verify accepted must count in this
26// project, as the integrator's classify decides it: the signer
27// projects file in the same publication (note/signerprojects.go) lets
28// it count here, and it is not the publication's integrator name,
29// since the integrator's signature on a note is its countersignature.
30// A note no such signer signed is a stranger's to the integrator, so a
31// later note may replace it. A publication whose signer projects file
32// is not a file, or does not read, is not used, so nothing is reused.
33// - The project is named as the other verbs name it, after origin's URL
34// (changes.go). The host's controllers name it after their
35// repository's directory, so the two agree when origin's URL ends in
36// that directory's name.
37//
38// The note judged is reused only when it also meets every one of these:
39//
40// - it is pure evidence, from the nix runner, for this check's name and
41// this check's flake attribute, and it records the check as passed;
42// - when VALLEY_KNOWN_SIGNERS is set, attest verify accepts it under that
43// file too, by a signer that counts in this project. An override can
44// narrow what is reused, never widen it.
45//
46// The integrator applies the same runner and attribute test to every
47// note it judges (integrator/verdict/verdict.go). A command check is
48// never covered: approve runs it again. The integrator judges every note again
49// when it decides the request, so coverage decides only what approve
50// builds, never what lands.
51//
52// The answer is one line per fact, fields separated by single spaces:
53//
54// digest <valley-tree-v1 digest of the head's tree>
55// stored <ref> <object ID> one per attestation ref origin holds for it
56// covered <check> <ref> <signer>+<key hash>
57// missing <check>
58//
59// with a covered or a missing line for every check asked about, in the
60// order asked.
61
62import (
63 "bytes"
64 "errors"
65 "fmt"
66 "io"
67 "os"
68 "os/exec"
69 "path"
70 "regexp"
71 "sort"
72 "strings"
73
74 "the-valley/change"
75 "the-valley/note"
76)
77
78const coverageUsage = "usage: valley-go coverage --head <sha> [--check <name>=<attribute>]..."
79
80const predicatePure = "the-valley/check/pure/v1"
81
82// checkName is a check's name or flake attribute as the policy schema
83// admits one (#Name in schema/verification.cue).
84var checkName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
85
86// nixCheck is one required check the nix runner runs: its name, and the
87// flake attribute the policy builds it from.
88type nixCheck struct{ name, attribute string }
89
90func runCoverage(g git, args []string, w, stderr io.Writer) error {
91 var head string
92 var checks []nixCheck
93 for i := 0; i < len(args); i++ {
94 opt, value, inline := strings.Cut(args[i], "=")
95 if opt != "--head" && opt != "--check" {
96 return failure(coverageUsage)
97 }
98 if !inline {
99 if i+1 == len(args) {
100 return failure(coverageUsage)
101 }
102 i++
103 value = args[i]
104 }
105 if opt == "--head" {
106 head = value
107 continue
108 }
109 name, attribute, ok := strings.Cut(value, "=")
110 if !ok || !checkName.MatchString(name) || !checkName.MatchString(attribute) {
111 return failure(fmt.Sprintf("--check %q: expected <name>=<attribute>", value))
112 }
113 checks = append(checks, nixCheck{name, attribute})
114 }
115 if head == "" {
116 return failure(coverageUsage)
117 }
118 e, err := coverageOf(g, head, checks, stderr)
119 if err != nil {
120 return err
121 }
122 var lines []string
123 lines = append(lines, "digest "+e.digest)
124 for _, ref := range e.stored {
125 lines = append(lines, "stored "+ref+" "+e.listed[ref])
126 }
127 for _, c := range checks {
128 if by, ok := e.covered[c.name]; ok {
129 lines = append(lines, "covered "+c.name+" "+by)
130 } else {
131 lines = append(lines, "missing "+c.name)
132 }
133 }
134 _, err = io.WriteString(w, strings.Join(lines, "\n")+"\n")
135 return err
136}
137
138// evidence is what coverage reads of a head's tree on origin: the tree's
139// digest, every attestation ref origin holds for it, in order, with the
140// object each names, and each check covered, mapped to "<ref> <signer>".
141type evidence struct {
142 digest string
143 stored []string
144 listed map[string]string
145 covered map[string]string
146}
147
148// coverageOf reads the evidence origin holds for a head's tree, and which
149// of the checks asked about it covers. The check worker (worker.go) calls
150// it as coverage does.
151func coverageOf(g git, head string, checks []nixCheck, stderr io.Writer) (evidence, error) {
152 oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", head+"^{commit}")
153 if err != nil || !isObjectID(oid) {
154 return evidence{}, failure("no such commit: " + head)
155 }
156 head = oid
157 repo := g.dir
158 if repo == "" {
159 repo = "."
160 }
161
162 digest, err := treeDigest(g, repo, head)
163 if err != nil {
164 return evidence{}, err
165 }
166
167 // Every attestation ref origin holds for the tree, signer by signer.
168 o, err := listOrigin(g, attestationRefs+digest+"/*")
169 if err != nil {
170 return evidence{}, failure("could not list the evidence origin holds for this tree")
171 }
172 e := evidence{digest: digest, listed: o.refs, stored: storedFor(digest, o.refs)}
173 e.covered, err = cover(g, repo, head, e.stored, e.listed, checks, stderr)
174 return e, err
175}
176
177// treeDigest is the valley-tree-v1 digest of a commit's tree, as attest
178// digests it, without its scheme.
179func treeDigest(g git, repo, head string) (string, error) {
180 out, err := attestTool(g, "digest", "--repo", repo, "--rev", head)
181 digest, ok := strings.CutPrefix(strings.TrimSpace(out), "valley-tree-v1:")
182 if err != nil || !ok || digest == "" {
183 return "", failure("could not digest the tree of " + head)
184 }
185 return digest, nil
186}
187
188// storedFor is every attestation ref listed for a tree, in byte order.
189func storedFor(digest string, listed map[string]string) []string {
190 prefix := attestationRefs + digest + "/"
191 var stored []string
192 for ref := range listed {
193 if rest, ok := strings.CutPrefix(ref, prefix); ok && rest != "" {
194 stored = append(stored, ref)
195 }
196 }
197 sort.Strings(stored)
198 return stored
199}
200
201// cover is the checks the stored refs hold reusable evidence for, each
202// mapped to "<ref> <signer>". It fetches the refs' objects only when there
203// are checks to look for.
204func cover(g git, repo, head string, stored []string, listed map[string]string, checks []nixCheck, stderr io.Writer) (map[string]string, error) {
205 covered := map[string]string{}
206 if len(stored) == 0 || len(checks) == 0 {
207 return covered, nil
208 }
209 var oids []string
210 for _, ref := range stored {
211 oids = append(oids, listed[ref])
212 }
213 if err := fetch(g, oids...); err != nil {
214 return nil, failure("could not fetch the evidence origin holds for this tree")
215 }
216 keys, p, why := hostSigners(g)
217 if why != "" {
218 fmt.Fprintf(stderr, "valley: %s, so none of the evidence on origin is reused\n", why)
219 return covered, nil
220 }
221 defer os.Remove(keys)
222 here := counting{project: project(g), integrator: p.name, projects: p.projects}
223
224 judged, why, err := judge(g, repo, head, keys, os.Getenv("VALLEY_KNOWN_SIGNERS"), here, stored, listed, checks)
225 if err != nil {
226 return nil, err
227 }
228 if why != "" {
229 fmt.Fprintf(stderr, "valley: %s, so the integrator cannot judge this tree's evidence, and none of it is reused\n", why)
230 return covered, nil
231 }
232 for _, c := range checks {
233 j, ok := judged[c.name]
234 if !ok {
235 continue // origin holds no note about this check
236 }
237 if j.why != "" {
238 fmt.Fprintf(stderr, "valley: not reusing %s: the integrator judges it by %s:%s, and %s\n", c.name, j.note.ref, j.note.path, j.why)
239 continue
240 }
241 covered[c.name] = j.note.ref + " " + j.note.signer
242 }
243 return covered, nil
244}
245
246// judgment is the note the integrator judges a check by, and why approve
247// may not skip the check on it, or "" when it may.
248type judgment struct {
249 note storedNote
250 why string
251}
252
253// judge reads the notes the stored refs hold about the checks asked, whose
254// objects have been fetched, and verifies each under keys, the host's
255// known-signers file. It returns the note the integrator judges each check
256// by, for each check origin holds a note about, with why it is not
257// reusable. local is a known-signers file that narrows what is reusable,
258// or "" for none. unjudged says why the integrator cannot judge the tree's
259// evidence at all.
260func judge(g git, repo, head, keys, local string, here counting, stored []string, listed map[string]string, checks []nixCheck) (judged map[string]judgment, unjudged string, err error) {
261 asked := map[string]bool{}
262 for _, c := range checks {
263 asked[c.name] = true
264 }
265 notes, why, err := readNotes(g, stored, listed, asked)
266 if err != nil || why != "" {
267 return nil, why, err
268 }
269 for i := range notes {
270 signers, refusal, err := verify(g, repo, head, keys, notes[i].note)
271 if err != nil {
272 return nil, "", err
273 }
274 if refusal != "" {
275 notes[i].refusal = "attest verify refuses it under the host's signers: " + refusal
276 continue
277 }
278 notes[i].signer, notes[i].refusal = here.signer(signers)
279 }
280 picked := change.SelectNotes(notes,
281 func(n storedNote) string { return n.check },
282 func(n storedNote) bool { return n.refusal == "" })
283
284 judged = map[string]judgment{}
285 for _, c := range checks {
286 n, ok := picked[c.name]
287 if !ok {
288 continue
289 }
290 why, err := reusable(g, repo, head, local, here, c, n)
291 if err != nil {
292 return nil, "", err
293 }
294 judged[c.name] = judgment{note: n, why: why}
295 }
296 return judged, "", nil
297}
298
299// storedNote is one note an attestation ref on origin holds, as read: where
300// it is, its bytes, the check its text says it is about, and whether the
301// integrator would admit it under the host's signers.
302type storedNote struct {
303 ref, path string
304 note []byte
305 check string
306 signer string // the first verified signer who counts here, when one does
307 refusal string // why the integrator would not admit it; "" when it would
308}
309
310// counting is who counts as a check's signer in a project, by the rule the
311// integrator's classify applies (integrator/evidence.go): a signer the
312// signer projects file lets count in the project, other than the host's
313// integrator.
314type counting struct {
315 project, integrator string
316 projects note.SignerProjects
317}
318
319// signer is the first of the verified signers, each name+hash in the order
320// attest verify reported them, who counts in the project, or why none
321// does.
322func (c counting) signer(verified []string) (signer, why string) {
323 var not []string
324 for _, s := range verified {
325 name, _, _ := strings.Cut(s, "+")
326 switch {
327 case name == c.integrator:
328 not = append(not, name+" is the host's integrator, whose signature is a countersignature")
329 case !c.projects.Counts(name, c.project):
330 not = append(not, fmt.Sprintf("the published %s lets %s count %s", signersProjects, name, c.only(name)))
331 default:
332 return s, ""
333 }
334 }
335 return "", fmt.Sprintf("none of its signers counts in project %s: %s", c.project, strings.Join(not, "; "))
336}
337
338// only is where the signer projects file lets a restricted signer count.
339func (c counting) only(name string) string {
340 var in []string
341 for p := range c.projects[name] {
342 in = append(in, p)
343 }
344 if len(in) == 0 {
345 return "in no project"
346 }
347 sort.Strings(in)
348 return "only in " + strings.Join(in, ", ")
349}
350
351// readNotes reads every note the stored refs hold about a check asked
352// about, in the order the integrator reads them (integrator/evidence.go):
353// the refs in byte order, and each ref's notes in the order git ls-tree -r
354// lists them. A note is any file named statement.note, at any depth. The
355// integrator reads every note under the tree, and a note it cannot split
356// into a text and signatures stops it judging the tree's evidence at all,
357// so why names the first such note.
358func readNotes(g git, stored []string, listed map[string]string, asked map[string]bool) (notes []storedNote, why string, err error) {
359 for _, ref := range stored {
360 listing, err := g.output(true, "ls-tree", "-r", "--name-only", listed[ref])
361 if err != nil {
362 return nil, "", fmt.Errorf("could not list %s", ref)
363 }
364 for _, file := range strings.Fields(listing) {
365 if path.Base(file) != "statement.note" {
366 continue
367 }
368 note, err := blob(g, listed[ref]+":"+file)
369 if err != nil {
370 return nil, "", fmt.Errorf("could not read %s:%s", ref, file)
371 }
372 split := bytes.LastIndex(note, []byte("\n\n"))
373 if split < 0 {
374 return nil, fmt.Sprintf("%s:%s is not a note: no blank line separates its text from its signatures", ref, file), nil
375 }
376 check := statementValue(string(note[:split+1]), "predicate.check.name")
377 if check == "" {
378 check = "(unnamed)"
379 }
380 if asked[check] {
381 notes = append(notes, storedNote{ref: ref, path: file, note: note, check: check})
382 }
383 }
384 }
385 return notes, "", nil
386}
387
388// reusable says why the note a check is judged by is not evidence approve
389// may skip the check on, or "" when it is.
390func reusable(g git, repo, head, local string, here counting, c nixCheck, n storedNote) (string, error) {
391 if n.refusal != "" {
392 return n.refusal, nil
393 }
394 text := string(n.note[:bytes.LastIndex(n.note, []byte("\n\n"))+1])
395 for _, want := range [][2]string{
396 {"predicateType", predicatePure},
397 {"predicate.check.runner", "nix"},
398 {"predicate.check.attribute", c.attribute},
399 {"predicate.result", "passed"},
400 } {
401 if got := statementValue(text, want[0]); got != want[1] {
402 return fmt.Sprintf("its %s is %q, not %q", want[0], got, want[1]), nil
403 }
404 }
405 if local != "" {
406 signers, refusal, err := verify(g, repo, head, local, n.note)
407 if err != nil {
408 return "", err
409 }
410 if refusal != "" {
411 return "attest verify refuses it under VALLEY_KNOWN_SIGNERS: " + refusal, nil
412 }
413 if _, why := here.signer(signers); why != "" {
414 return "under VALLEY_KNOWN_SIGNERS, " + why, nil
415 }
416 }
417 return "", nil
418}
419
420// verify runs attest verify over a note's exact bytes, under a
421// known-signers file. It returns every signer whose signature checked
422// out, in the order attest reported them, or the sentence attest refused
423// the note with.
424func verify(g git, repo, head, keys string, note []byte) (signers []string, refusal string, err error) {
425 file, err := os.CreateTemp("", "valley-coverage-*.note")
426 if err != nil {
427 return nil, "", err
428 }
429 defer os.Remove(file.Name())
430 _, err = file.Write(note)
431 if cerr := file.Close(); err == nil {
432 err = cerr
433 }
434 if err != nil {
435 return nil, "", err
436 }
437 out, err := attestTool(g, "verify", "--note", file.Name(), "--known-keys", keys, "--repo", repo, "--rev", head)
438 if err != nil {
439 var exit *exec.ExitError
440 if !errors.As(err, &exit) {
441 return nil, "", fmt.Errorf("could not run attest verify: %v", err)
442 }
443 return nil, refusalOf(out), nil
444 }
445 for _, line := range strings.Split(out, "\n") {
446 if f := strings.Fields(line); len(f) == 3 && f[0] == "signature" && f[1] == "ok" {
447 signers = append(signers, f[2])
448 }
449 }
450 if len(signers) == 0 {
451 return nil, "attest verify named no signer", nil
452 }
453 return signers, "", nil
454}
455
456// hostSigners writes out the known-signers file the serving host
457// publishes, for attest verify to read, and returns its path and the
458// publication it came from. why says why there is none.
459func hostSigners(g git) (keys string, p *publishedSigners, why string) {
460 p, err := readSigners(g)
461 switch {
462 case err != nil:
463 return "", nil, err.Error()
464 case p == nil:
465 return "", nil, "the serving host publishes no signers at " + signersRef
466 }
467 if _, err := note.ParseVerifierKeys(p.keys); err != nil {
468 return "", nil, fmt.Sprintf("the known-signers file published at %s does not read as verifier keys: %v", p.where, err)
469 }
470 f, err := os.CreateTemp("", "valley-host-signers-*")
471 if err != nil {
472 return "", nil, err.Error()
473 }
474 _, err = f.Write(p.keys)
475 if cerr := f.Close(); err == nil {
476 err = cerr
477 }
478 if err != nil {
479 os.Remove(f.Name())
480 return "", nil, err.Error()
481 }
482 return f.Name(), p, ""
483}
484
485// blob is an object's content exactly as git stores it. g.output trims
486// trailing newlines, and a note's last newline is part of its envelope
487// (note.Split), so a note is never read through it.
488func blob(g git, object string) ([]byte, error) {
489 cmd := exec.Command("git", "cat-file", "blob", object)
490 cmd.Env = g.env
491 cmd.Dir = g.dir
492 return cmd.Output()
493}
494
495// attestTool runs the attest helper in g's repository and environment,
496// and returns what it printed on stdout and stderr together.
497func attestTool(g git, args ...string) (string, error) {
498 cmd := exec.Command("attest", args...)
499 cmd.Env = g.env
500 cmd.Dir = g.dir
501 out, err := cmd.CombinedOutput()
502 return string(out), err
503}
504
505// statementValue reads one key's value from statement text, where each
506// line is a key, one space and a value.
507func statementValue(text, key string) string {
508 for _, line := range strings.Split(text, "\n") {
509 if k, v, ok := strings.Cut(line, " "); ok && k == key {
510 return v
511 }
512 }
513 return ""
514}
515
516// refusalOf is the sentence attest refused with: the line it prefixes
517// with its own name, or else the last line it printed.
518func refusalOf(out string) string {
519 last := ""
520 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
521 if why, ok := strings.CutPrefix(line, "attest: "); ok {
522 return strings.TrimSpace(why)
523 }
524 if strings.TrimSpace(line) != "" {
525 last = strings.TrimSpace(line)
526 }
527 }
528 return last
529}