gunk-dev/the-valley

coverage.go

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