gunk-dev/the-valley

coverage.go

source171dbbb226c0main's published tip history
21.5 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// failed <check> <ref> <signer>+<key hash>
58// missing <check>
59//
60// with a covered, a failed or a missing line for every check asked about,
61// in the order asked. A check is failed when the note judged verifies, is
62// signed by a signer who counts in this project, and records something
63// other than a pass of this check, as valley pending --checks reads it
64// (versionchecks.go): the integrator judges the check by that note, so
65// building the check again does not change the verdict on this tree.
66
67import (
68 "bytes"
69 "errors"
70 "fmt"
71 "io"
72 "os"
73 "os/exec"
74 "path"
75 "regexp"
76 "sort"
77 "strconv"
78 "strings"
79
80 "the-valley/change"
81 "the-valley/note"
82)
83
84const coverageUsage = "usage: valley-go coverage --head <sha> [--check <name>=<attribute>]..."
85
86const predicatePure = "the-valley/check/pure/v1"
87
88// checkName is a check's name or flake attribute as the policy schema
89// admits one (#Name in schema/verification.cue).
90var checkName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
91
92// nixCheck is one required check the nix runner runs: its name, and the
93// flake attribute the policy builds it from.
94type nixCheck struct{ name, attribute string }
95
96func runCoverage(g git, args []string, w, stderr io.Writer) error {
97 var head string
98 var checks []nixCheck
99 for i := 0; i < len(args); i++ {
100 opt, value, inline := strings.Cut(args[i], "=")
101 if opt != "--head" && opt != "--check" {
102 return failure(coverageUsage)
103 }
104 if !inline {
105 if i+1 == len(args) {
106 return failure(coverageUsage)
107 }
108 i++
109 value = args[i]
110 }
111 if opt == "--head" {
112 head = value
113 continue
114 }
115 name, attribute, ok := strings.Cut(value, "=")
116 if !ok || !checkName.MatchString(name) || !checkName.MatchString(attribute) {
117 return failure(fmt.Sprintf("--check %q: expected <name>=<attribute>", value))
118 }
119 checks = append(checks, nixCheck{name, attribute})
120 }
121 if head == "" {
122 return failure(coverageUsage)
123 }
124 e, err := coverageOf(g, head, checks, stderr)
125 if err != nil {
126 return err
127 }
128 var lines []string
129 lines = append(lines, "digest "+e.digest)
130 for _, ref := range e.stored {
131 lines = append(lines, "stored "+ref+" "+e.listed[ref])
132 }
133 for _, c := range checks {
134 if by, ok := e.covered[c.name]; ok {
135 lines = append(lines, "covered "+c.name+" "+by)
136 } else if by, ok := e.failed[c.name]; ok {
137 lines = append(lines, "failed "+c.name+" "+by)
138 } else {
139 lines = append(lines, "missing "+c.name)
140 }
141 }
142 _, err = io.WriteString(w, strings.Join(lines, "\n")+"\n")
143 return err
144}
145
146// evidence is what coverage reads of a head's tree on origin: the tree's
147// digest, every attestation ref origin holds for it, in order, with the
148// object each names, and each check covered or failed, mapped to
149// "<ref> <signer>".
150type evidence struct {
151 digest string
152 stored []string
153 listed map[string]string
154 covered map[string]string
155 failed map[string]string
156}
157
158// coverageOf reads the evidence origin holds for a head's tree, and which
159// of the checks asked about it covers. The check worker (worker.go) calls
160// it as coverage does.
161func coverageOf(g git, head string, checks []nixCheck, stderr io.Writer) (evidence, error) {
162 var keys hostKeys
163 defer keys.done()
164 return coverageIn(g, head, nil, checks, &keys, stderr)
165}
166
167// coverageIn is coverageOf for a reader that judges many trees, as the
168// main walk does (mainstate.go): listed is origin's attestation refs,
169// listed once for every tree, or nil to list this tree's alone, and keys
170// reads the host's signers once for every tree judged under it.
171func coverageIn(g git, head string, listed map[string]string, checks []nixCheck, keys *hostKeys, stderr io.Writer) (evidence, error) {
172 oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", head+"^{commit}")
173 if err != nil || !isObjectID(oid) {
174 return evidence{}, failure("no such commit: " + head)
175 }
176 head = oid
177 repo := g.dir
178 if repo == "" {
179 repo = "."
180 }
181
182 digest, err := treeDigest(g, repo, head)
183 if err != nil {
184 return evidence{}, err
185 }
186
187 // Every attestation ref origin holds for the tree, signer by signer.
188 if listed == nil {
189 o, err := listOrigin(g, attestationRefs+digest+"/*")
190 if err != nil {
191 return evidence{}, failure("could not list the evidence origin holds for this tree")
192 }
193 listed = o.refs
194 }
195 e := evidence{digest: digest, listed: map[string]string{}, stored: storedFor(digest, listed)}
196 for _, ref := range e.stored {
197 e.listed[ref] = listed[ref]
198 }
199 e.covered, e.failed, err = cover(g, repo, head, e.stored, e.listed, checks, keys, stderr)
200 return e, err
201}
202
203// treeDigest is the valley-tree-v1 digest of a commit's tree, as attest
204// digests it, without its scheme.
205func treeDigest(g git, repo, head string) (string, error) {
206 out, err := attestTool(g, "digest", "--repo", repo, "--rev", head)
207 digest, ok := strings.CutPrefix(strings.TrimSpace(out), "valley-tree-v1:")
208 if err != nil || !ok || digest == "" {
209 return "", failure("could not digest the tree of " + head)
210 }
211 return digest, nil
212}
213
214// storedFor is every attestation ref listed for a tree, in byte order.
215func storedFor(digest string, listed map[string]string) []string {
216 prefix := attestationRefs + digest + "/"
217 var stored []string
218 for ref := range listed {
219 if rest, ok := strings.CutPrefix(ref, prefix); ok && rest != "" {
220 stored = append(stored, ref)
221 }
222 }
223 sort.Strings(stored)
224 return stored
225}
226
227// cover is the checks the stored refs hold reusable evidence for, and the
228// checks whose judged note records a failure, each mapped to
229// "<ref> <signer>". It fetches the refs' objects only when there are
230// checks to look for.
231func cover(g git, repo, head string, stored []string, listed map[string]string, checks []nixCheck, signers *hostKeys, stderr io.Writer) (covered, failed map[string]string, err error) {
232 covered, failed = map[string]string{}, map[string]string{}
233 if len(stored) == 0 || len(checks) == 0 {
234 return covered, failed, nil
235 }
236 var oids []string
237 for _, ref := range stored {
238 oids = append(oids, listed[ref])
239 }
240 if err := fetch(g, oids...); err != nil {
241 return nil, nil, failure("could not fetch the evidence origin holds for this tree")
242 }
243 keys, p, why := signers.read(g)
244 if why != "" {
245 fmt.Fprintf(stderr, "valley: %s, so none of the evidence on origin is reused\n", why)
246 return covered, failed, nil
247 }
248 here := counting{project: project(g), integrator: p.name, projects: p.projects}
249
250 judged, why, err := judge(g, repo, head, keys, os.Getenv("VALLEY_KNOWN_SIGNERS"), here, stored, listed, checks)
251 if err != nil {
252 return nil, nil, err
253 }
254 if why != "" {
255 fmt.Fprintf(stderr, "valley: %s, so the integrator cannot judge this tree's evidence, and none of it is reused\n", why)
256 return covered, failed, nil
257 }
258 for _, c := range checks {
259 j, ok := judged[c.name]
260 if !ok {
261 continue // origin holds no note about this check
262 }
263 if j.why != "" {
264 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)
265 if j.note.refusal == "" && mismatch(j.note, c) != "" {
266 failed[c.name] = j.note.ref + " " + j.note.signer
267 }
268 continue
269 }
270 covered[c.name] = j.note.ref + " " + j.note.signer
271 }
272 return covered, failed, nil
273}
274
275// judgment is the note the integrator judges a check by, and why approve
276// may not skip the check on it, or "" when it may.
277type judgment struct {
278 note storedNote
279 why string
280}
281
282// judge reads the notes the stored refs hold about the checks asked, whose
283// objects have been fetched, and verifies each under keys, the host's
284// known-signers file. It returns the note the integrator judges each check
285// by, for each check origin holds a note about, with why it is not
286// reusable. local is a known-signers file that narrows what is reusable,
287// or "" for none. unjudged says why the integrator cannot judge the tree's
288// evidence at all.
289func 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) {
290 asked := map[string]bool{}
291 for _, c := range checks {
292 asked[c.name] = true
293 }
294 notes, why, err := readNotes(g, stored, listed, asked)
295 if err != nil || why != "" {
296 return nil, why, err
297 }
298 for i := range notes {
299 signers, refusal, err := verify(g, repo, head, keys, notes[i].note)
300 if err != nil {
301 return nil, "", err
302 }
303 if refusal != "" {
304 notes[i].refusal = "attest verify refuses it under the host's signers: " + refusal
305 continue
306 }
307 notes[i].signer, notes[i].refusal = here.signer(signers)
308 }
309 picked := change.SelectNotes(notes,
310 func(n storedNote) string { return n.check },
311 func(n storedNote) bool { return n.refusal == "" })
312
313 judged = map[string]judgment{}
314 for _, c := range checks {
315 n, ok := picked[c.name]
316 if !ok {
317 continue
318 }
319 why, err := reusable(g, repo, head, local, here, c, n)
320 if err != nil {
321 return nil, "", err
322 }
323 judged[c.name] = judgment{note: n, why: why}
324 }
325 return judged, "", nil
326}
327
328// storedNote is one note an attestation ref on origin holds, as read: where
329// it is, its bytes, the check its text says it is about, and whether the
330// integrator would admit it under the host's signers.
331type storedNote struct {
332 ref, path string
333 note []byte
334 check string
335 signer string // the first verified signer who counts here, when one does
336 refusal string // why the integrator would not admit it; "" when it would
337}
338
339// counting is who counts as a check's signer in a project, by the rule the
340// integrator's classify applies (integrator/evidence.go): a signer the
341// signer projects file lets count in the project, other than the host's
342// integrator.
343type counting struct {
344 project, integrator string
345 projects note.SignerProjects
346}
347
348// signer is the first of the verified signers, each name+hash in the order
349// attest verify reported them, who counts in the project, or why none
350// does.
351func (c counting) signer(verified []string) (signer, why string) {
352 var not []string
353 for _, s := range verified {
354 name, _, _ := strings.Cut(s, "+")
355 switch {
356 case name == c.integrator:
357 not = append(not, name+" is the host's integrator, whose signature is a countersignature")
358 case !c.projects.Counts(name, c.project):
359 not = append(not, fmt.Sprintf("the published %s lets %s count %s", signersProjects, name, c.only(name)))
360 default:
361 return s, ""
362 }
363 }
364 return "", fmt.Sprintf("none of its signers counts in project %s: %s", c.project, strings.Join(not, "; "))
365}
366
367// only is where the signer projects file lets a restricted signer count.
368func (c counting) only(name string) string {
369 var in []string
370 for p := range c.projects[name] {
371 in = append(in, p)
372 }
373 if len(in) == 0 {
374 return "in no project"
375 }
376 sort.Strings(in)
377 return "only in " + strings.Join(in, ", ")
378}
379
380// readNotes reads every note the stored refs hold about a check asked
381// about, in the order the integrator reads them (integrator/evidence.go):
382// the refs in byte order, and each ref's notes in the order git ls-tree -r
383// lists them. A note is any file named statement.note, at any depth. The
384// integrator reads every note under the tree, and a note it cannot split
385// into a text and signatures stops it judging the tree's evidence at all,
386// so why names the first such note.
387func readNotes(g git, stored []string, listed map[string]string, asked map[string]bool) (notes []storedNote, why string, err error) {
388 type file struct{ ref, path string }
389 var files []file
390 var objects []string
391 for _, ref := range stored {
392 listing, err := g.output(true, "ls-tree", "-r", "--name-only", listed[ref])
393 if err != nil {
394 return nil, "", fmt.Errorf("could not list %s", ref)
395 }
396 for _, p := range strings.Fields(listing) {
397 if path.Base(p) == "statement.note" {
398 files = append(files, file{ref, p})
399 objects = append(objects, listed[ref]+":"+p)
400 }
401 }
402 }
403 read, err := blobs(g, objects)
404 if err != nil {
405 return nil, "", err
406 }
407 for i, f := range files {
408 note := read[i]
409 if note == nil {
410 return nil, "", fmt.Errorf("could not read %s:%s", f.ref, f.path)
411 }
412 split := bytes.LastIndex(note, []byte("\n\n"))
413 if split < 0 {
414 return nil, fmt.Sprintf("%s:%s is not a note: no blank line separates its text from its signatures", f.ref, f.path), nil
415 }
416 check := statementValue(string(note[:split+1]), "predicate.check.name")
417 if check == "" {
418 check = "(unnamed)"
419 }
420 if asked[check] {
421 notes = append(notes, storedNote{ref: f.ref, path: f.path, note: note, check: check})
422 }
423 }
424 return notes, "", nil
425}
426
427// reusable says why the note a check is judged by is not evidence approve
428// may skip the check on, or "" when it is.
429func reusable(g git, repo, head, local string, here counting, c nixCheck, n storedNote) (string, error) {
430 if n.refusal != "" {
431 return n.refusal, nil
432 }
433 if why := mismatch(n, c); why != "" {
434 return why, nil
435 }
436 if local != "" {
437 signers, refusal, err := verify(g, repo, head, local, n.note)
438 if err != nil {
439 return "", err
440 }
441 if refusal != "" {
442 return "attest verify refuses it under VALLEY_KNOWN_SIGNERS: " + refusal, nil
443 }
444 if _, why := here.signer(signers); why != "" {
445 return "under VALLEY_KNOWN_SIGNERS, " + why, nil
446 }
447 }
448 return "", nil
449}
450
451// mismatch says why a note is not a pass of this check, or "" when it
452// is one: pure evidence, from the nix runner, for the check's attribute,
453// recording that it passed.
454func mismatch(n storedNote, c nixCheck) string {
455 text := string(n.note[:bytes.LastIndex(n.note, []byte("\n\n"))+1])
456 for _, want := range [][2]string{
457 {"predicateType", predicatePure},
458 {"predicate.check.runner", "nix"},
459 {"predicate.check.attribute", c.attribute},
460 {"predicate.result", "passed"},
461 } {
462 if got := statementValue(text, want[0]); got != want[1] {
463 return fmt.Sprintf("its %s is %q, not %q", want[0], got, want[1])
464 }
465 }
466 return ""
467}
468
469// verify runs attest verify over a note's exact bytes, under a
470// known-signers file. It returns every signer whose signature checked
471// out, in the order attest reported them, or the sentence attest refused
472// the note with.
473func verify(g git, repo, head, keys string, note []byte) (signers []string, refusal string, err error) {
474 file, err := os.CreateTemp("", "valley-coverage-*.note")
475 if err != nil {
476 return nil, "", err
477 }
478 defer os.Remove(file.Name())
479 _, err = file.Write(note)
480 if cerr := file.Close(); err == nil {
481 err = cerr
482 }
483 if err != nil {
484 return nil, "", err
485 }
486 out, err := attestTool(g, "verify", "--note", file.Name(), "--known-keys", keys, "--repo", repo, "--rev", head)
487 if err != nil {
488 var exit *exec.ExitError
489 if !errors.As(err, &exit) {
490 return nil, "", fmt.Errorf("could not run attest verify: %v", err)
491 }
492 return nil, refusalOf(out), nil
493 }
494 for _, line := range strings.Split(out, "\n") {
495 if f := strings.Fields(line); len(f) == 3 && f[0] == "signature" && f[1] == "ok" {
496 signers = append(signers, f[2])
497 }
498 }
499 if len(signers) == 0 {
500 return nil, "attest verify named no signer", nil
501 }
502 return signers, "", nil
503}
504
505// hostKeys is the host's known-signers file, read by the first tree that
506// needs it and kept for every later one, until done removes it.
507type hostKeys struct {
508 keys, why string
509 p *publishedSigners
510 once bool
511}
512
513// read is hostSigners, read once.
514func (h *hostKeys) read(g git) (keys string, p *publishedSigners, why string) {
515 if !h.once {
516 h.keys, h.p, h.why = hostSigners(g)
517 h.once = true
518 }
519 return h.keys, h.p, h.why
520}
521
522// done removes the file read wrote, if it wrote one.
523func (h *hostKeys) done() {
524 if h.keys != "" {
525 os.Remove(h.keys)
526 }
527}
528
529// hostSigners writes out the known-signers file the serving host
530// publishes, for attest verify to read, and returns its path and the
531// publication it came from. why says why there is none.
532func hostSigners(g git) (keys string, p *publishedSigners, why string) {
533 p, err := readSigners(g)
534 switch {
535 case err != nil:
536 return "", nil, err.Error()
537 case p == nil:
538 return "", nil, "the serving host publishes no signers at " + signersRef
539 }
540 if _, err := note.ParseVerifierKeys(p.keys); err != nil {
541 return "", nil, fmt.Sprintf("the known-signers file published at %s does not read as verifier keys: %v", p.where, err)
542 }
543 f, err := os.CreateTemp("", "valley-host-signers-*")
544 if err != nil {
545 return "", nil, err.Error()
546 }
547 _, err = f.Write(p.keys)
548 if cerr := f.Close(); err == nil {
549 err = cerr
550 }
551 if err != nil {
552 os.Remove(f.Name())
553 return "", nil, err.Error()
554 }
555 return f.Name(), p, ""
556}
557
558// blobs are the contents of the objects named, each exactly as git
559// stores it, read by one git cat-file --batch rather than a process each.
560// An object that is no blob is nil. g.output trims trailing newlines, and
561// a note's last newline is part of its envelope (note.Split), so a note is
562// never read through it.
563func blobs(g git, objects []string) ([][]byte, error) {
564 out := make([][]byte, len(objects))
565 if len(objects) == 0 {
566 return out, nil
567 }
568 cmd := exec.Command("git", "cat-file", "--batch")
569 cmd.Env = g.env
570 cmd.Dir = g.dir
571 cmd.Stdin = strings.NewReader(strings.Join(objects, "\n") + "\n")
572 stdout, err := cmd.Output()
573 if err != nil {
574 return nil, fmt.Errorf("could not read the notes origin holds: %v", err)
575 }
576 for i := range objects {
577 header, rest, ok := bytes.Cut(stdout, []byte("\n"))
578 if !ok {
579 return nil, errors.New("git cat-file --batch ended early")
580 }
581 f := strings.Fields(string(header))
582 stdout = rest
583 if len(f) != 3 {
584 continue // "<object> missing" or "ambiguous"
585 }
586 size, err := strconv.Atoi(f[2])
587 if err != nil || size < 0 || len(stdout) < size+1 {
588 return nil, fmt.Errorf("git cat-file --batch gave an unreadable answer for %s", objects[i])
589 }
590 if f[1] == "blob" {
591 out[i] = stdout[:size:size]
592 }
593 stdout = stdout[size+1:]
594 }
595 return out, nil
596}
597
598// attestTool runs the attest helper in g's repository and environment,
599// and returns what it printed on stdout and stderr together.
600func attestTool(g git, args ...string) (string, error) {
601 cmd := exec.Command("attest", args...)
602 cmd.Env = g.env
603 cmd.Dir = g.dir
604 out, err := cmd.CombinedOutput()
605 return string(out), err
606}
607
608// statementValue reads one key's value from statement text, where each
609// line is a key, one space and a value.
610func statementValue(text, key string) string {
611 for _, line := range strings.Split(text, "\n") {
612 if k, v, ok := strings.Cut(line, " "); ok && k == key {
613 return v
614 }
615 }
616 return ""
617}
618
619// refusalOf is the sentence attest refused with: the line it prefixes
620// with its own name, or else the last line it printed.
621func refusalOf(out string) string {
622 last := ""
623 for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
624 if why, ok := strings.CutPrefix(line, "attest: "); ok {
625 return strings.TrimSpace(why)
626 }
627 if strings.TrimSpace(line) != "" {
628 last = strings.TrimSpace(line)
629 }
630 }
631 return last
632}