gunk-dev/the-valley

coverage.go

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