gunk-dev/the-valley

coverage.go

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