gunk-dev/the-valley

coverage.go

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