gunk-dev/the-valley

coverage.go

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