gunk-dev/the-valley

coverage.go

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