gunk-dev/the-valley

coverage.go

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