gunk-dev/the-valley

coverage.go

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