gunk-dev/the-valley

approve.go

source6a6791929c36main's published tip history
54.5 KiB
1package main
2
3// approve files a change's integration request: the whole of `valley
4// approve`, and review's [a]pprove (review.go). Both run one attempt (approval.attempt), so the verb and
5// the key cannot drift apart.
6//
7// An attempt binds the head it files, derives what the policy at main's
8// tip requires of it (../derive), reuses the evidence origin already
9// holds for the head's tree (coverage.go), runs the rest in a throwaway
10// worktree through attest run, and files the request and the evidence in
11// one atomic push. attest run stores each note in this repository and
12// pushes nothing, so no evidence stands published for a change nobody has
13// approved, and the request is never filed without its evidence. Nothing
14// here writes the protected ref: the integrator judges the request and
15// lands it. Every way it ends is said in one verdict line
16// (verdict.go). With valley.telemetry on, each attempt is a telemetry run
17// of its own, recording approve.start, approve.policy, approve.coverage,
18// approve.checks, approve.request and approve.end, and attest records the
19// checks it runs under the linked run <run>-checks. A record is never
20// evidence, nothing reads one to decide anything, and a record that cannot
21// be stored costs that record alone.
22//
23// Review's [a]pprove is told the change review bound (reviewApproval), and
24// runs on review's own terminal. It leaves how the attempt ended in its
25// result, as fields:
26//
27// approved <change ID> <handle> <version> <head>
28// checks-failed <head>
29// refused
30// unknown
31// interrupted
32//
33// The approved result names what was filed, after the attempt's own reads
34// of the record, with empty fields for a plain branch. unknown is a
35// request whose state the attempt could not establish after the push.
36//
37// With an approval key selected, the attempt also signs an approval of the
38// version it files and publishes the note in the same push
39// (approvalsign.go). With none, it says that no signed approval was
40// written, and does nothing else differently.
41
42import (
43 "context"
44 "errors"
45 "fmt"
46 "io"
47 "os"
48 "os/exec"
49 "os/signal"
50 "regexp"
51 "sort"
52 "strconv"
53 "strings"
54 "sync"
55 "syscall"
56 "time"
57
58 approvals "the-valley/approval"
59 "the-valley/derive"
60 "the-valley/telemetry"
61)
62
63const approveUsage = "usage: valley approve [-v] [--head <sha>] [--build-here] [--approval-key <file> | --approval-piv] <change>"
64
65// interruptedStatus is the exit status of an approval cut short by a
66// signal, as a shell reports a process SIGINT ended.
67const interruptedStatus = 130
68
69// headArgument is the shape a --head value must have before it is read
70// as a commit: an object ID, or an abbreviation of one.
71var headArgument = regexp.MustCompile(`^[0-9a-f]{4,64}$`)
72
73// changeRequest is the request name of a change with a record, which no
74// branch is filed under.
75var changeRequest = regexp.MustCompile(`^c-[k-z]{32}$`)
76
77// approval is one approval attempt and what it was told.
78type approval struct {
79 g git
80 stdin *os.File // the terminal: the confirmation, and the checks' stdin
81 stdout, stderr io.Writer
82 v verifier // what reading what the head would bring verifies a transfer statement with
83
84 // exit ends the process once a signal has interrupted the attempt: the
85 // approve verb's records the command, and review's ends the review
86 // first (review.go). It does not return.
87 exit func(int)
88
89 verbose, buildHere bool
90 reviewing bool
91 result []string // how the attempt ended, for review
92
93 // key is the approval key the approval is signed with, or nil when
94 // none is selected (approvalsign.go). auth is what the host published
95 // about approval keys when the attempt read it, and hardware whether
96 // the policy requires a hardware key. frozenRecord and frozenVersion
97 // are the record commit the bound head's version was first read from,
98 // and that version, which the statement names.
99 key *approvalKey
100 auth *approvalAuthority
101 hardware bool
102 frozenRecord, frozenVersion string
103
104 // carriedVersion is the later version review's answer carried to, and
105 // carriedHead its head: the version that lands, which the verdict
106 // names (carriedVerdict).
107 carriedVersion, carriedHead string
108
109 // name is the change as it was named, read again before filing in case
110 // a plain branch has come to name a change. For a change, id, handle,
111 // version, head, branch, state and owner are what resolving that name
112 // read; head is the active version's head.
113 name string
114 id, handle, version, head, branch string
115 state, owner string
116 bound, boundVersion, title string // the head filed, its version and title
117 failedAt string // the head whose checks failed
118 filedID, filedHandle, filedVersion string // what the approved line names
119 tel *approveTelemetry
120 mu sync.Mutex
121 interrupted, finished bool
122 child *os.Process // the checks, or the PIV signer's helper
123 childDone chan struct{}
124 tty *ttyState // the terminal's settings while the PIV signer runs
125 worktree string
126 signals chan os.Signal
127 unwatched chan struct{}
128}
129
130// errRefused is an attempt that ended without filing, having said why.
131var errRefused = errors.New("refused")
132
133// errUnknown is a request whose state could not be established after the
134// push, having said so.
135var errUnknown = errors.New("unknown")
136
137func runApprove(g git, args []string, stdout, stderr io.Writer, end func(int)) int {
138 a := &approval{g: g, stdin: os.Stdin, stdout: stdout, stderr: stderr, v: newVerifier(),
139 exit: func(status int) {
140 verification.done()
141 end(status)
142 }}
143 want, err := a.verbFlags(args)
144 if err != nil {
145 fmt.Fprintf(stderr, "valley: %s\n", err)
146 return 1
147 }
148 if !g.succeeds(true, "rev-parse", "--git-dir") {
149 fmt.Fprintln(stderr, "valley: not a git repository")
150 return 1
151 }
152 // The name is read before the fetch, as review reads it.
153 r, err := resolveRecorded(g, a.name)
154 if err != nil {
155 fmt.Fprintf(stderr, "valley: %s\n", err)
156 return 1
157 }
158 a.id, a.handle, a.head, a.branch, a.state, a.owner = r.id, r.handle, r.head, r.branch, r.state, r.owner
159 if r.id != "" {
160 a.version = strconv.Itoa(r.version)
161 }
162 fetch := g.command("fetch", "--prune", "--quiet", "origin")
163 fetch.Stdout, fetch.Stderr = stderr, stderr
164 processStarted()
165 if err := fetch.Run(); err != nil {
166 return exitCode(err)
167 }
168 a.watch(os.Interrupt, syscall.SIGTERM)
169 if a.id != "" {
170 if a.bindHead(want) != nil {
171 return 1
172 }
173 } else {
174 tip, ok, err := g.ref("refs/remotes/origin/" + a.branch)
175 if err != nil || !ok {
176 fmt.Fprintf(stderr, "valley: no such branch on origin: %s\n", a.branch)
177 return 1
178 }
179 if want != "" {
180 at, _ := g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
181 if at != tip {
182 a.declined(fmt.Sprintf("origin/%s is at %s, not %s", a.branch, a.short(tip), want),
183 act{run: "valley approve " + shellQuote(a.branch)})
184 return 1
185 }
186 }
187 }
188 return a.run()
189}
190
191// verbFlags reads the approve verb's arguments, selects the approval key
192// they and the environment select, and returns --head's value.
193func (a *approval) verbFlags(args []string) (want string, err error) {
194 var keyFlags approvalFlags
195 for i := 0; i < len(args); i++ {
196 last, isKey, err := keyFlags.take(args, i)
197 if err != nil {
198 return "", err
199 }
200 if isKey {
201 i = last
202 continue
203 }
204 switch arg := args[i]; {
205 case arg == "--build-here":
206 a.buildHere = true
207 case arg == "-v" || arg == "--verbose":
208 a.verbose = true
209 case arg == "--head" && i+1 < len(args):
210 want = args[i+1]
211 i++
212 case strings.HasPrefix(arg, "--head="):
213 want = strings.TrimPrefix(arg, "--head=")
214 case strings.HasPrefix(arg, "-") || a.name != "":
215 return "", failure(approveUsage)
216 default:
217 a.name = arg
218 }
219 }
220 if a.name == "" {
221 return "", failure(approveUsage)
222 }
223 a.key, err = keyFlags.key()
224 return want, err
225}
226
227// reviewApproval is review r's [a]pprove of the change it shows, c, bound
228// to the head r bound and, for a change with a record, to its version.
229// c's name is the change as review was given it, read again before
230// filing. A plain branch's attempt is told the branch, and the head review
231// showed when it showed one. r's carried version and head are given when
232// review's answer carried to that later version, whose line ended the one
233// review's prompt left open. The attempt runs in r's repository, on its
234// terminal, and an interrupt ends it through r's exit.
235func reviewApproval(r *review, c shownChange) *approval {
236 head, version := r.approveHead, r.approveVersion
237 a := &approval{g: r.g, stdin: r.stdin, stdout: r.stdout, stderr: r.stderr, v: r.verifier(), exit: r.exit,
238 reviewing: true, carriedVersion: r.carriedVersion, carriedHead: r.carriedHead,
239 verbose: r.verbose, buildHere: r.buildHere, key: r.key, name: c.name, bound: head}
240 if c.id == "" {
241 a.branch = c.branch
242 return a
243 }
244 // Review shows a change at its active version's head, and binds
245 // [a]pprove to it.
246 a.id, a.handle, a.version, a.head, a.boundVersion = c.id, c.handle, version, head, version
247 return a
248}
249
250// run is one attempt, its telemetry run, and its outcome: 0 when it
251// filed, 1 when it did not.
252func (a *approval) run() int {
253 // Off a terminal, the answer to review's prompt ends no line, so the
254 // verdict starts its own, unless the carry line has ended it.
255 if a.reviewing && a.carriedHead == "" {
256 if _, tty := windowColumns(a.stdin); !tty {
257 fmt.Fprintln(a.stdout)
258 }
259 }
260 t := a.beginTelemetry()
261 a.mu.Lock()
262 a.tel = t
263 a.mu.Unlock()
264 return a.ended(a.attempt())
265}
266
267// ended records how the attempt ended, err being what it returned, and
268// keeps that result: 0 when it filed, 1 when it did not.
269func (a *approval) ended(err error) int {
270 if !a.finish() {
271 select {} // the signal handler ends the process
272 }
273 switch {
274 case err == nil:
275 a.tel.end("filed")
276 a.writeOutcome("approved", a.filedID, a.filedHandle, a.filedVersion, a.bound)
277 return 0
278 case a.failedAt != "":
279 a.tel.end("refused")
280 a.writeOutcome("checks-failed", a.failedAt)
281 case errors.Is(err, errUnknown):
282 a.tel.end("refused")
283 a.writeOutcome("unknown")
284 default:
285 a.tel.end("refused")
286 a.writeOutcome("refused")
287 }
288 return 1
289}
290
291// writeOutcome keeps how the attempt ended, for review.
292func (a *approval) writeOutcome(fields ...string) {
293 a.mu.Lock()
294 a.result = fields
295 a.mu.Unlock()
296}
297
298// watch takes over the signals given until unwatch: one interrupts the
299// attempt. The approve verb is interrupted by SIGINT and SIGTERM. Review's
300// [a]pprove is interrupted by SIGINT alone, which a terminal's Ctrl-C sends
301// to the checks as well, and review acts on a SIGTERM once the attempt has
302// ended (review.go).
303func (a *approval) watch(signals ...os.Signal) {
304 a.signals, a.unwatched = make(chan os.Signal, 2), make(chan struct{})
305 signal.Notify(a.signals, signals...)
306 go func() {
307 select {
308 case <-a.signals:
309 a.interrupt()
310 case <-a.unwatched:
311 }
312 }()
313}
314
315// unwatch gives the signals back once the attempt has ended. Review holds
316// every signal while the attempt runs, so one the attempt took and did not
317// act on is review's to act on.
318func (a *approval) unwatch() {
319 signal.Stop(a.signals)
320 close(a.unwatched)
321}
322
323// interrupt ends an attempt a signal cut short: it stops the checks or the
324// PIV signer running, if any, waits for them to end, puts back the
325// terminal settings the signer started on, removes the worktree, records
326// the attempt's end as interrupted, keeps that result, and ends with 130
327// through exit. A second signal while the checks are ending kills them. A
328// signal that reaches the checks first ends them, and checking's caller
329// interrupts the attempt itself; whichever comes first ends it.
330func (a *approval) interrupt() {
331 interruptBegins(a)
332 a.mu.Lock()
333 if a.finished {
334 a.mu.Unlock()
335 a.exit(interruptedStatus)
336 }
337 if a.interrupted {
338 a.mu.Unlock()
339 select {} // the first interrupt ends the process
340 }
341 a.interrupted = true
342 child, done, t, tty := a.child, a.childDone, a.tel, a.tty
343 a.mu.Unlock()
344 if child != nil {
345 _ = child.Signal(os.Interrupt)
346 select {
347 case <-done:
348 case <-a.signals:
349 _ = child.Kill()
350 <-done
351 }
352 }
353 tty.restore()
354 a.removeWorktree()
355 t.end("interrupted")
356 a.writeOutcome("interrupted")
357 a.exit(interruptedStatus)
358}
359
360// interruptBegins is told of each interrupt as it begins, before it takes
361// a.mu. A test observes an interrupt arriving through it.
362var interruptBegins = func(*approval) {}
363
364// finish marks the attempt ended, unless a signal has interrupted it,
365// when it reports false and the signal handler ends the process.
366func (a *approval) finish() bool {
367 a.mu.Lock()
368 defer a.mu.Unlock()
369 a.finished = !a.interrupted
370 return a.finished
371}
372
373func (a *approval) stopped() bool {
374 a.mu.Lock()
375 defer a.mu.Unlock()
376 return a.interrupted
377}
378
379// act is what a refusal tells the person to do next: a command to run,
380// one to read, or what to do when it is no command.
381type act struct{ run, see, then string }
382
383// declined says what stops the approval, as a verdict on stderr, and
384// returns errRefused. A change is named by its handle and the version
385// being approved, a plain branch by its name.
386func (a *approval) declined(why string, next act) error {
387 return a.refused(verdict{why: why, run: next.run, see: next.see, then: next.then, required: -1, passed: -1})
388}
389
390func (a *approval) refused(v verdict) error {
391 if a.stopped() {
392 return errRefused
393 }
394 v.outcome, v.target, v.name = "refused", "main", a.label()
395 if a.id != "" {
396 v.version = a.boundVersion
397 if v.version == "" {
398 v.version = a.version
399 }
400 }
401 fmt.Fprint(a.stderr, v.lines(terminalOf(a.stderr)))
402 return errRefused
403}
404
405// label is the change as the verdict names it: its handle, or a plain
406// branch's name.
407func (a *approval) label() string {
408 if a.handle != "" {
409 return a.handle
410 }
411 return a.branch
412}
413
414// quoted is the change as a command offered names it.
415func (a *approval) quoted() string { return shellQuote(a.label()) }
416
417func (a *approval) short(oid string) string {
418 s, _ := a.g.output(true, "rev-parse", "--short", oid)
419 return s
420}
421
422// subject is one line of a commit, for saying which commit is meant. A
423// request being replaced is usually this operator's own pre-rebase head;
424// one another operator filed may not be in this repository.
425func (a *approval) subject(oid string) string {
426 if s, err := a.g.output(true, "log", "-1", "--format=%s", oid); err == nil && s != "" {
427 return s
428 }
429 return "subject not in this repository"
430}
431
432// notReady refuses a change that is not ready, offering its owner, as
433// git config valley.principal names them, the command that readies it
434// again. A review is the operator's and the change is usually someone
435// else's, so review is offered nothing.
436func (a *approval) notReady(state, id, branch, owner string) error {
437 why := "change is " + state
438 if state == "draft" {
439 why = "change is a draft"
440 }
441 return a.declined(why, a.readyHint(id, branch, owner))
442}
443
444func (a *approval) readyHint(id, branch, owner string) act {
445 if a.reviewing || owner == "" {
446 return act{}
447 }
448 if principal, _ := a.g.output(true, "config", "valley.principal"); principal != owner {
449 return act{}
450 }
451 run := "valley ready --change " + id
452 if branch != "" {
453 run += " " + shellQuote(branch)
454 }
455 return act{run: run}
456}
457
458// bindHead binds the head approve files for a change with a record. With
459// --head it is exactly that head, which must be one of the record's
460// version heads while the change is ready, the active one or not: a front
461// end that shows the change its own way passes the head it showed, so
462// what is approved is what was seen. Without --head the person is shown
463// the active version's head and title and asked to confirm them, which
464// needs a terminal.
465func (a *approval) bindHead(want string) error {
466 if a.state != "ready" {
467 return a.notReady(a.state, a.id, a.branch, a.owner)
468 }
469 if want != "" {
470 var sha string
471 var err error
472 if headArgument.MatchString(want) {
473 sha, err = a.g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
474 }
475 if sha == "" || err != nil {
476 return a.declined("--head "+want+" names no commit here", act{see: "valley status " + a.handle})
477 }
478 if err := a.checkVersion(sha); err != nil {
479 return err
480 }
481 a.bound = sha
482 return nil
483 }
484 if err := a.checkVersion(a.head); err != nil {
485 return err
486 }
487 if _, tty := windowColumns(a.stdin); !tty {
488 return a.declined("no terminal to confirm the head, "+a.title,
489 act{run: "valley approve --head " + a.head + " " + a.handle})
490 }
491 fmt.Fprintf(a.stdout, "approve change %s v%s at %s, %s? [y/N] ", a.handle, a.boundVersion, a.head, a.title)
492 switch readLine(a.stdin) {
493 case "y", "Y", "yes":
494 a.bound = a.head
495 return nil
496 }
497 return a.declined("not confirmed", act{})
498}
499
500// readLine reads one line, a byte at a time so that nothing after it is
501// taken from whatever reads the input next.
502func readLine(r io.Reader) string {
503 var line []byte
504 b := make([]byte, 1)
505 for {
506 n, err := r.Read(b)
507 if n == 1 {
508 if b[0] == '\n' {
509 break
510 }
511 line = append(line, b[0])
512 }
513 if err != nil {
514 break
515 }
516 }
517 return strings.TrimSuffix(string(line), "\r")
518}
519
520// checkVersion reads the change's versions from origin again, and
521// refuses unless the change is ready and head is one of its versions'
522// heads, whichever version is active by then: a record that moves after
523// review cannot change what lands, since the request names the head
524// approved. It binds that version's number and title.
525//
526// A signed approval names the record commit the version was first read
527// from, and that version. The first read freezes both; a later read only
528// checks that the head is still that version's.
529func (a *approval) checkVersion(head string) error {
530 a.boundVersion, a.title = "", ""
531 n, err := versionsOf(a.g, a.id)
532 if err != nil {
533 fmt.Fprintf(a.stderr, "valley: %s\n", err)
534 return a.declined("could not read the change's versions", act{})
535 }
536 r := n.record
537 var known []string
538 for _, v := range r.Versions {
539 known = append(known, fmt.Sprintf("v%d at %s", v.N, headOf(v)))
540 if headOf(v) == head {
541 a.boundVersion, a.title = strconv.Itoa(v.N), v.Title
542 }
543 }
544 if r.State != "ready" {
545 return a.notReady(r.State, a.id, a.branch, a.owner)
546 }
547 if a.boundVersion == "" {
548 return a.declined(fmt.Sprintf("%s is none of its versions (%s)", a.short(head), strings.Join(known, ", ")),
549 act{see: "valley status " + a.handle})
550 }
551 switch {
552 case a.key == nil:
553 case a.frozenRecord == "":
554 a.frozenRecord, a.frozenVersion = n.commit, a.boundVersion
555 case a.boundVersion != a.frozenVersion:
556 return a.declined(fmt.Sprintf("its record now lists %s as v%s, not v%s", a.short(head), a.boundVersion, a.frozenVersion),
557 act{see: "valley status " + a.handle})
558 }
559 return nil
560}
561
562// checkRecord reads the change's record again from origin, and refuses
563// unless the change is still ready with the bound head among its
564// versions. The record was read when review or approve began, and another
565// principal may unready, withdraw or ready a new version of the change
566// while a review is open or the checks run. These reads save a run that
567// would come to nothing: the integrator makes the same check on origin.
568//
569// A name that read as a plain branch can come to name a change
570// meanwhile, so the last read before filing, given the head about to be
571// filed as acting, reads the name again: when it names a change now, the
572// change must be ready, and its active head must be that head.
573func (a *approval) checkRecord(acting string) error {
574 if a.id == "" {
575 if acting == "" {
576 return nil
577 }
578 r, err := resolveRecorded(a.g, a.name)
579 if err != nil {
580 fmt.Fprintf(a.stderr, "valley: %s\n", err)
581 return a.declined("could not read origin's records again", act{})
582 }
583 if r.id == "" {
584 return nil
585 }
586 if r.state != "ready" {
587 return a.declined(fmt.Sprintf("now change %s v%d, which is %s", r.handle, r.version, r.state),
588 a.readyHint(r.id, r.branch, r.owner))
589 }
590 if r.head != acting {
591 return a.declined(fmt.Sprintf("now change %s v%d, at another head", r.handle, r.version),
592 act{run: "valley review " + r.handle})
593 }
594 return nil
595 }
596 r, err := resolveRecorded(a.g, a.id)
597 if err != nil {
598 fmt.Fprintf(a.stderr, "valley: %s\n", err)
599 return a.declined("could not read the change's record again", act{})
600 }
601 if r.id != a.id {
602 return a.declined("origin no longer holds the change's record", act{})
603 }
604 if r.state != "ready" {
605 return a.notReady(r.state, a.id, r.branch, r.owner)
606 }
607 return a.checkVersion(a.bound)
608}
609
610// branchAtShown refuses unless the plain branch on origin is still at the
611// head bound to this approval. The operator reviewed a branch, and a
612// branch that moved holds commits nobody has read. origin itself is read,
613// not the tracking ref: a push from another checkout moves the branch
614// without moving this clone's ref.
615func (a *approval) branchAtShown() error {
616 now, err := a.remoteRef("refs/heads/" + a.branch)
617 switch {
618 case err != nil:
619 return a.declined("could not read origin/"+a.branch+" again", act{})
620 case now == "":
621 return a.declined("origin/"+a.branch+" is gone", act{})
622 case now != a.bound:
623 return a.declined(fmt.Sprintf("origin/%s moved from %s, the head shown, to %s", a.branch, a.short(a.bound), a.short(now)),
624 act{run: "valley review " + shellQuote(a.branch)})
625 }
626 return nil
627}
628
629// lsRemote lists origin's refs matching the patterns. ls-remote matches a
630// pattern against the tail of a ref name, so a caller compares each ref
631// it lists whole. A listing that fails is an error, never an empty one.
632func (a *approval) lsRemote(patterns ...string) (map[string]string, error) {
633 out, err := a.g.output(true, append([]string{"ls-remote", "origin"}, patterns...)...)
634 if err != nil {
635 return nil, err
636 }
637 refs := map[string]string{}
638 for _, line := range strings.Split(out, "\n") {
639 if oid, ref, ok := strings.Cut(line, "\t"); ok {
640 refs[ref] = oid
641 }
642 }
643 return refs, nil
644}
645
646// remoteRef is the value of a ref on origin, or "" when origin has none.
647func (a *approval) remoteRef(ref string) (string, error) {
648 refs, err := a.lsRemote(ref)
649 return refs[ref], err
650}
651
652// pushLookalike is a ref origin holds whose name ends in one of these,
653// other than the ref itself, or "". git push matches a destination as
654// rev-parse matches a name: with the ref missing on origin, a push to it
655// writes refs/heads/<ref> instead, and with both there it is refused as
656// ambiguous. So nothing is pushed while origin holds such a ref.
657func (a *approval) pushLookalike(refs ...string) (string, error) {
658 var patterns []string
659 exact := map[string]bool{}
660 for _, ref := range refs {
661 patterns = append(patterns, ref, ref+"/HEAD")
662 exact[ref] = true
663 }
664 listed, err := a.lsRemote(patterns...)
665 if err != nil {
666 return "", err
667 }
668 var others []string
669 for ref := range listed {
670 if !exact[ref] {
671 others = append(others, ref)
672 }
673 }
674 sort.Strings(others)
675 if len(others) == 0 {
676 return "", nil
677 }
678 return others[0], nil
679}
680
681// reportEvidence says, with -v, where the checks this run signed are
682// stored, for every failure after they have run.
683func (a *approval) reportEvidence(refs []string) {
684 if len(refs) == 0 || !a.verbose || a.stopped() {
685 return
686 }
687 fmt.Fprintln(a.stderr, "valley: the evidence is stored locally at:")
688 for _, ref := range refs {
689 fmt.Fprintf(a.stderr, " %s\n", ref)
690 }
691}
692
693// attestationStandsElsewhere reports whether origin holds one of these
694// attestation refs at a value other than the one being pushed. approve
695// pushes a ref of its own notes alone, and origin takes an existing one
696// only with every note it holds kept, so that is the one refusal
697// approving again will never clear.
698func (a *approval) attestationStandsElsewhere(digest string, refs []string) bool {
699 remote, err := a.lsRemote(attestationRefs + digest + "/*")
700 if err != nil {
701 return false
702 }
703 for _, ref := range refs {
704 have := remote[ref]
705 if have == "" {
706 continue
707 }
708 if want, err := a.g.output(true, "rev-parse", ref); err == nil && have != want {
709 return true
710 }
711 }
712 return false
713}
714
715// diagnosePush says why a push carrying the request ref failed, as
716// precisely as the state allows. Every such push is leased, and a lease
717// refuses when the ref is not where the read before it saw it: the
718// request was consumed, or another approval filed or moved it. Reading
719// the ref again tells them apart. Anything else is origin's own refusal,
720// which git has already printed.
721func (a *approval) diagnosePush(ref, pending string) error {
722 now, err := a.remoteRef(ref)
723 switch {
724 case err != nil || now == pending:
725 return a.declined("origin refused the push", act{})
726 case now == "":
727 return a.declined("the pending request was consumed meanwhile", act{see: "valley status " + a.quoted()})
728 }
729 return a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(now), a.subject(now)),
730 act{run: "valley approve " + a.quoted()})
731}
732
733// requestName is the change segment of a request ref for a plain branch.
734// The integrator refuses a segment holding a slash (integrator/refs.go),
735// so a slash is written as a dash. The mapping is lossy: topic/x and
736// topic-x are one request, and approve cannot tell a sibling's request
737// from its own, so it prints the subject of any request it replaces.
738func requestName(branch string) string { return strings.ReplaceAll(branch, "/", "-") }
739
740// attempt is one approval attempt, from main's tip to the verdict.
741func (a *approval) attempt() error {
742 g := a.g
743 root, err := g.output(true, "rev-parse", "--show-toplevel")
744 if err != nil {
745 return a.declined("not in a git repository", act{})
746 }
747 // main's tip as the fetch left it, read once by its exact name. The
748 // merge base, the fast-forward and both policy layers are read at
749 // that one commit.
750 tip, ok, err := g.ref("refs/remotes/origin/main")
751 switch {
752 case err != nil:
753 return a.declined("could not read origin/main", act{run: "git fetch origin"})
754 case !ok:
755 return a.declined("origin has no main to approve onto", act{})
756 }
757
758 // A change with a record is filed at exactly the bound head, under its
759 // own request name, c-<change ID>, and only while its record says it
760 // is ready and lists that head as a version's. Where its branch is
761 // does not matter: the request names the head. A plain branch is
762 // filed at the head review showed, or else at its tip on origin.
763 var head, request, what, named string
764 switch {
765 case a.id != "":
766 if a.bound == "" {
767 return a.declined("no head is bound to this approval", act{})
768 }
769 if err := a.checkRecord(""); err != nil {
770 return err
771 }
772 head, request, named = a.bound, "c-"+a.id, a.handle
773 what = a.handle + " v" + a.boundVersion
774 case a.bound != "":
775 head, request, what, named = a.bound, requestName(a.branch), a.branch, a.branch
776 default:
777 oid, ok, err := g.ref("refs/remotes/origin/" + a.branch)
778 if err != nil || !ok {
779 return a.declined("origin has no branch "+a.branch, act{})
780 }
781 head, request, what, named = oid, requestName(a.branch), a.branch, a.branch
782 }
783 if a.id == "" && changeRequest.MatchString(request) {
784 return a.declined("the branch's request name "+request+" is change "+strings.TrimPrefix(request, "c-")+"'s",
785 act{then: "rename the branch, or name the change by its ID"})
786 }
787 // A signed approval names a recorded version, and a plain branch has
788 // none to name.
789 if a.key != nil && a.id == "" {
790 return a.declined("no recorded version to sign", act{run: "valley ready " + a.quoted()})
791 }
792 base, err := g.output(true, "merge-base", tip, head)
793 if err != nil || !isObjectID(base) {
794 return a.declined("shares no history with main", act{})
795 }
796 ref := "refs/the-valley/integration-requests/main/" + request
797 a.tel.context(a.id, a.boundVersion, head)
798 a.tel.emit("approve.start", map[string]any{"what": what, "request": ref})
799
800 // A head that does not fast-forward from main, and would bring a
801 // version of another change that has not landed, is a layer above the
802 // bottom of a stale stack. The integrator could land it all the same,
803 // as one commit recorded against this request alone, and the changes
804 // under it would have no landing record of their own. So the stack is
805 // rebased first. This is the project's choice, not a rule the
806 // integrator needs: a stale head with no change under it is approved
807 // as it is, and the integrator merges it onto main.
808 if !g.succeeds(true, "merge-base", "--is-ancestor", tip, head) {
809 under, err := bringsOf(g, a.v, a.id, head)
810 if err != nil {
811 fmt.Fprintf(a.stderr, "valley: %s\n", err)
812 return a.declined("could not read which changes it would bring to main", act{})
813 }
814 if len(under) > 0 {
815 return a.declined("stack is behind main (includes "+strings.Join(under, ", ")+")",
816 act{run: "valley rebase " + shellQuote(named)})
817 }
818 }
819
820 // What the policy requires of the change, read out of exactly the
821 // sources the integrator reads: both layers at the target's tip, and
822 // the floor from the owning valley's own tip when the tip names one. A
823 // change never supplies the policy that gates it, and neither does
824 // the checkout this runs from.
825 res, label, plabel, hardware, err := a.derive(root, tip, base, head)
826 if err != nil {
827 fmt.Fprintf(a.stderr, "valley: %s\n", err)
828 return a.declined("the policy did not derive", act{})
829 }
830 if a.key != nil {
831 if err := a.prepareSigning(hardware); err != nil {
832 return err
833 }
834 }
835 required := res.Required
836 names := make([]string, len(required))
837 for i, q := range required {
838 names[i] = q.Name
839 }
840 a.tel.emit("approve.policy", map[string]any{"required": names, "instance": label, "project": plabel})
841
842 // A change the policy asks nothing of is still a change, and the
843 // integrator lands a request that requires no check: nothing is
844 // signed, no key is needed, and one request ref is published.
845 //
846 // A required nix check whose evidence origin already holds is reused,
847 // not built again: a check worker, or an earlier approval, may have
848 // published it. A read of origin that fails ends the approval rather
849 // than reading as no evidence.
850 var reused, missing, unbuilt []string
851 var e evidence
852 if len(required) > 0 {
853 if _, err := exec.LookPath("attest"); err != nil {
854 return a.declined("the attest helper is not installed", act{then: "nix run .#valley bundles it"})
855 }
856 var asked []nixCheck
857 for _, q := range required {
858 if q.Runner == "nix" {
859 asked = append(asked, nixCheck{q.Name, q.Attribute})
860 }
861 }
862 // What coverage and the git it runs say is shown only with -v.
863 quiet := g
864 var said io.Writer = io.Discard
865 if a.verbose {
866 said = a.stderr
867 } else {
868 quiet.stderr = io.Discard
869 }
870 if e, err = a.coverage(quiet, head, asked, said); err != nil {
871 if a.verbose {
872 fmt.Fprintf(a.stderr, "valley: %s\n", err)
873 }
874 return a.declined("could not read the evidence origin holds", act{run: "valley approve -v " + a.quoted()})
875 }
876 // A check whose evidence on origin records a failure is judged by
877 // that evidence, so building it again changes nothing for this
878 // tree, and nothing is filed.
879 var failed []string
880 for _, c := range asked {
881 if _, ok := e.failed[c.name]; ok {
882 failed = append(failed, c.name)
883 }
884 }
885 if len(failed) > 0 {
886 a.failedAt = head
887 return a.refused(verdict{required: len(required), passed: -1, failed: failed})
888 }
889 var signedBy []string
890 for _, q := range required {
891 if by, ok := e.covered[q.Name]; ok {
892 reused = append(reused, q.Name)
893 signedBy = append(signedBy, q.Name+"="+signerOf(by))
894 } else {
895 missing = append(missing, q.Name)
896 }
897 }
898 a.tel.emit("approve.coverage", map[string]any{"tree": e.digest, "reused": list(reused),
899 "reused_by": list(signedBy), "missing": list(missing)})
900 if a.verbose && len(reused) > 0 {
901 fmt.Fprintf(a.stdout, "reusing the evidence origin holds for %s at %s, tree %s:\n", what, a.short(head), e.digest)
902 for _, check := range reused {
903 fmt.Fprintf(a.stdout, " %-24s signed by %s\n", check, signerOf(e.covered[check]))
904 }
905 }
906 }
907
908 // A required nix check with no evidence on origin is built here only
909 // with --build-here. The host's check worker builds the same checks
910 // for a ready change and publishes the evidence, so without the flag
911 // approve files the request at once without it, and the integrator
912 // holds the request until the evidence arrives. Whether the worker
913 // publishes at all is not assured. A command check is never reused and
914 // no worker runs one, so it runs here either way. From here on,
915 // missing is what runs here, and unbuilt what nothing here builds.
916 runner := map[string]derive.Required{}
917 for _, q := range required {
918 runner[q.Name] = q
919 }
920 if !a.buildHere {
921 var here []string
922 for _, check := range missing {
923 if runner[check].Runner == "nix" {
924 unbuilt = append(unbuilt, check)
925 } else {
926 here = append(here, check)
927 }
928 }
929 missing = here
930 }
931
932 var evidenceRefs []string
933 took := ""
934 if len(missing) > 0 {
935 if evidenceRefs, took, err = a.check(head, e, required, reused, missing, runner); err != nil {
936 return err
937 }
938 } else if len(required) == 0 && a.verbose {
939 fmt.Fprintf(a.stdout, "%s requires no check under %s + %s; filing the request with no evidence\n", what, label, plabel)
940 }
941
942 // The approval is signed once the checks have passed, so a refusal
943 // costs no touch.
944 var signed *signedApproval
945 aref := approvals.Ref(recordTarget, a.id)
946 if a.key != nil {
947 if signed, err = a.sign(); err != nil {
948 a.reportEvidence(evidenceRefs)
949 return err
950 }
951 }
952
953 // What origin holds for this request, read once. Approving the same
954 // change twice is ordinary: evidence expires, and a change whose input
955 // closure moved under it is told to re-attest. So the request ref may
956 // already exist. A ref whose name ends in the request's, or in an
957 // evidence ref's, would take the push in its place.
958 // A signed approval reads the request and the approval in one listing,
959 // so the two values it leases are ones origin held together.
960 var pending, standingApproval string
961 if signed != nil {
962 var refs map[string]string
963 refs, err = a.lsRemote(ref, aref)
964 pending, standingApproval = refs[ref], refs[aref]
965 } else {
966 pending, err = a.remoteRef(ref)
967 }
968 lookalike := ""
969 if err == nil {
970 written := append([]string{ref}, evidenceRefs...)
971 if signed != nil {
972 written = append(written, aref)
973 }
974 lookalike, err = a.pushLookalike(written...)
975 }
976 if err != nil {
977 a.declined("could not read the request ref on origin", act{})
978 a.reportEvidence(evidenceRefs)
979 return errRefused
980 }
981 if lookalike != "" {
982 a.declined("origin holds "+lookalike+", which git would push to in place of a ref approve pushes",
983 act{then: "delete " + lookalike + " on origin"})
984 a.reportEvidence(evidenceRefs)
985 return errRefused
986 }
987
988 // The one push: every evidence ref, and the request ref wherever it
989 // has to go, --atomic, so a hook that refuses any of them leaves
990 // origin as it was.
991 //
992 // Every write of the request ref is leased against what the read above
993 // saw, including nothing: --force-with-lease=<ref>: refuses if the ref
994 // exists at all, so filing for the first time is a compare-and-swap
995 // too, and two operators filing one change at once cannot have the
996 // second silently replace the first. The lease is the whole of the
997 // force and no refspec carries a +, which would defeat the lease.
998 //
999 // A request already at this head is a re-attestation: the ref does not
1000 // move, so it is left out of the push, which carries no
1001 // compare-and-swap on a ref it does not change. Where it stands
1002 // afterwards is read again below. A request at another head is
1003 // replaced: a rebased head is no descendant of the old one.
1004 var push, lease []string
1005 for _, spec := range evidenceRefs {
1006 push = append(push, spec+":"+spec)
1007 }
1008 if pending != head {
1009 lease = append(lease, "--force-with-lease="+ref+":"+pending)
1010 push = append(push, head+":"+ref)
1011 }
1012 // The approval note replaces whatever approval stood for the change,
1013 // under a lease on what was read there, as the request is written, and
1014 // in the same atomic push, so another approver's pair written meanwhile
1015 // fails this push at the note's ref rather than splitting the pair.
1016 if signed != nil {
1017 lease = append(lease, "--force-with-lease="+aref+":"+standingApproval)
1018 push = append(push, signed.blob+":"+aref)
1019 }
1020
1021 // The checks can take minutes, and the record may have moved
1022 // meanwhile, so it is read once more just before anything is filed.
1023 //
1024 // A window remains between this read and the push. A change unreadied
1025 // or withdrawn in it is filed all the same: git compares only the refs
1026 // a push changes, and the record ref is not one of them, so no client
1027 // can make the filing conditional on the record. The integrator
1028 // narrows the window: it lands no request that would bring a version
1029 // of a change that is not ready, and reads the records last just
1030 // before it moves the target, so only a record written in that moment
1031 // is missed.
1032 if err := a.checkRecord(head); err != nil {
1033 a.reportEvidence(evidenceRefs)
1034 return err
1035 }
1036 if a.id == "" && a.bound != "" {
1037 if err := a.branchAtShown(); err != nil {
1038 a.reportEvidence(evidenceRefs)
1039 return err
1040 }
1041 }
1042 // The keys the approval was checked against are the ones the host
1043 // still publishes, or nothing is pushed.
1044 if signed != nil {
1045 if same, err := a.auth.unchanged(a.g); err != nil || !same {
1046 why := "the published approval keys changed meanwhile"
1047 if err != nil {
1048 why = "could not read the published approval keys again"
1049 }
1050 a.declined(why, act{run: "valley approve " + a.quoted()})
1051 a.reportEvidence(evidenceRefs)
1052 return errRefused
1053 }
1054 }
1055
1056 // With no new evidence and the request already at this head there is
1057 // nothing to push, and a push with no refspec would fall back to
1058 // origin's default one, so none is made.
1059 pushed := false
1060 if len(push) > 0 {
1061 pushed = true
1062 args := append(append([]string{"push", "--atomic", "--quiet"}, lease...), "origin")
1063 cmd := g.command(append(args, push...)...)
1064 cmd.Stdout, cmd.Stderr = a.stderr, a.stderr
1065 processStarted()
1066 if err := cmd.Run(); err != nil {
1067 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "refused"})
1068 switch {
1069 case pending == head && a.attestationStandsElsewhere(e.digest, evidenceRefs):
1070 a.declined("this key's evidence for the tree is on origin already",
1071 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
1072 case signed != nil && a.approvalMoved(aref, standingApproval):
1073 a.declined("another approval of the change was published meanwhile",
1074 act{run: "valley approve " + a.quoted()})
1075 default:
1076 a.diagnosePush(ref, pending)
1077 }
1078 a.reportEvidence(evidenceRefs)
1079 return errRefused
1080 }
1081 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "pushed"})
1082 }
1083
1084 // The lines -v adds under the request line.
1085 var standing []string
1086 if pending == head {
1087 // The request ref was not in that push, so where it stands now is
1088 // read again: the integrator may have landed the change and
1089 // consumed it, or another approval replaced it. Nothing here
1090 // writes it back. Re-creating a consumed request would file a
1091 // change already in the stream, replacing another approval's
1092 // would clobber the winner, and either would be a second push. The
1093 // approval stood before this run, so a request that cannot be read
1094 // leaves its state unknown rather than unapproved; approving again
1095 // takes the create or replace path against what is there.
1096 after, err := a.remoteRef(ref)
1097 if err != nil || after == "" {
1098 v := verdict{outcome: "unknown", name: a.label(), required: -1, passed: -1}
1099 if a.id != "" {
1100 v.version = a.boundVersion
1101 }
1102 if err == nil {
1103 v.why = "request consumed meanwhile"
1104 }
1105 v.signed = signed != nil
1106 if !a.stopped() {
1107 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
1108 a.sayUnsigned()
1109 }
1110 a.reportEvidence(evidenceRefs)
1111 return errUnknown
1112 }
1113 if after != head {
1114 a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(after), a.subject(after)),
1115 act{run: "valley approve " + a.quoted()})
1116 a.reportEvidence(evidenceRefs)
1117 return errRefused
1118 }
1119 switch {
1120 case pushed && signed != nil && len(evidenceRefs) == 0:
1121 standing = append(standing, "the request already stood at this head; the signed approval is what was published")
1122 case pushed && signed != nil:
1123 standing = append(standing, "the request already stood at this head; the evidence and the signed approval are what was published")
1124 case pushed:
1125 standing = append(standing, "the request already stood at this head; the evidence is what was published")
1126 case len(unbuilt) > 0:
1127 standing = append(standing, "the request already stood at this head, and nothing was built or published")
1128 case len(required) > 0:
1129 standing = append(standing, "the request already stood at this head and origin already held the evidence, so nothing needed publishing")
1130 default:
1131 standing = append(standing, "the request already stood at this head and nothing was required, so nothing needed publishing")
1132 }
1133 } else if pending != "" {
1134 standing = append(standing, fmt.Sprintf("replaced the pending request, which stood at %s (%s)", a.short(pending), a.subject(pending)))
1135 }
1136
1137 if a.verbose {
1138 w := a.stdout
1139 fmt.Fprintf(w, " request %s -> %s\n", ref, a.short(head))
1140 for _, s := range standing {
1141 fmt.Fprintf(w, " %s\n", s)
1142 }
1143 if len(required) == 0 {
1144 fmt.Fprintln(w, " evidence none — nothing was required, so nothing was signed")
1145 fmt.Fprintln(w, " checks none — the policy requires no check of this change")
1146 } else {
1147 fmt.Fprintf(w, " tree %s\n", e.digest)
1148 for _, spec := range evidenceRefs {
1149 fmt.Fprintf(w, " evidence %s\n", spec)
1150 }
1151 // The refs on origin whose evidence was reused, each once.
1152 shown := map[string]bool{}
1153 for _, check := range reused {
1154 spec, _, _ := strings.Cut(e.covered[check], " ")
1155 if !shown[spec] {
1156 shown[spec] = true
1157 fmt.Fprintf(w, " reused %s\n", spec)
1158 }
1159 }
1160 if len(unbuilt) > 0 {
1161 fmt.Fprintf(w, " missing %s\n", strings.Join(unbuilt, ", "))
1162 }
1163 fmt.Fprintf(w, " checks %s\n", strings.Join(names, ", "))
1164 }
1165 if signed != nil {
1166 listed := "not listed as a hardware key"
1167 if signed.hardware {
1168 listed = "listed as a hardware key"
1169 }
1170 fmt.Fprintf(w, " approval %s -> %s\n", aref, signed.blob)
1171 fmt.Fprintf(w, " signed %s, key %08x, %s\n", signed.principal, signed.keyhash, listed)
1172 }
1173 }
1174
1175 // The verdict. Checks with no evidence yet are built by a check
1176 // worker only for a ready change's active version. Elsewhere approve
1177 // offers to build them here, unless a command check that ran here put
1178 // this signer's evidence for the tree on origin, which approve cannot
1179 // add to, so a plain branch is offered readying instead, which lets a
1180 // worker build it.
1181 v := verdict{outcome: "approved", name: a.label(), target: "main", required: len(required),
1182 passed: len(required) - len(unbuilt), took: took, waiting: unbuilt}
1183 if a.id != "" {
1184 v.version = a.boundVersion
1185 }
1186 if len(unbuilt) > 0 {
1187 switch {
1188 case a.id != "" && head == a.head:
1189 v.worker = true
1190 case len(missing) == 0:
1191 at := ""
1192 if a.id != "" {
1193 at = "--head " + a.short(head) + " "
1194 }
1195 v.run = "valley approve --build-here " + at + a.quoted()
1196 case a.id == "":
1197 v.run = "valley ready " + a.quoted()
1198 default:
1199 v.see = "valley status " + a.quoted()
1200 }
1201 }
1202 if a.carriedHead != "" && !a.stopped() {
1203 v = a.carriedVerdict()
1204 }
1205 v.signed = signed != nil
1206 if !a.stopped() {
1207 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
1208 a.sayUnsigned()
1209 }
1210 a.filedID, a.filedHandle, a.filedVersion = a.id, a.handle, a.boundVersion
1211 if a.id == "" {
1212 a.filedVersion = ""
1213 }
1214 return nil
1215}
1216
1217// sayUnsigned says, under the verdict of an approval no approval key was
1218// selected for, that it published no signed approval.
1219func (a *approval) sayUnsigned() {
1220 if a.key == nil {
1221 fmt.Fprintln(a.stdout, "no signed approval was written: no approval key is selected")
1222 }
1223}
1224
1225// approvalMoved reports whether origin's approval ref for the change is
1226// no longer where the read before the push saw it, which is what makes
1227// its lease refuse.
1228func (a *approval) approvalMoved(ref, read string) bool {
1229 now, err := a.remoteRef(ref)
1230 return err == nil && now != read
1231}
1232
1233// carriedVerdict is the verdict on an approval whose answer carried to a
1234// later version. The request names the head shown, and the integrator
1235// lands its delta once there is evidence for the tree it lands: the later
1236// version's, the change's active one. So the verdict names that version,
1237// and tells its checks as review's checks line reads them for the active
1238// version (activeChecks, versionchecks.go). What that read says goes to
1239// stderr with -v alone.
1240func (a *approval) carriedVerdict() verdict {
1241 said := io.Discard
1242 if a.verbose {
1243 said = a.stderr
1244 }
1245 var checks *jsonVersionChecks
1246 changes, err := activeChecks(a.g, []string{a.id}, nil, said)
1247 if err != nil {
1248 fmt.Fprintf(said, "valley: %s\n", err)
1249 }
1250 for _, c := range changes {
1251 if v := c.Versions[c.Active-1]; c.ChangeID == a.id && v.Head == a.carriedHead {
1252 checks = v.Checks
1253 }
1254 }
1255 return carriedVerdictOf(a.label(), a.carriedVersion, checks)
1256}
1257
1258// carriedVerdictOf is the verdict that names version, the one that lands,
1259// from its check state, or nil when that was not read. The host's worker
1260// builds the version's nix checks, as the change's active version. It runs
1261// no check of another runner, which the checks line does not judge, so
1262// such a check waits with no worker building it, and approving the change
1263// runs it here.
1264func carriedVerdictOf(name, version string, checks *jsonVersionChecks) verdict {
1265 v := verdict{outcome: "approved", name: name, version: version, target: "main", carried: true, worker: true}
1266 if checks == nil {
1267 v.outcome, v.why, v.required, v.passed = "unknown", "checks unknown", -1, -1
1268 return v
1269 }
1270 for _, q := range checks.Required {
1271 switch q.State {
1272 case checkPassed:
1273 v.passed++
1274 case checkFailed:
1275 v.failed = append(v.failed, q.Name)
1276 case checkPending:
1277 v.waiting = append(v.waiting, q.Name)
1278 default:
1279 v.waiting, v.worker = append(v.waiting, q.Name), false
1280 v.run = "valley approve " + shellQuote(name)
1281 }
1282 v.required++
1283 }
1284 return v
1285}
1286
1287// coverage is the evidence origin holds for head and the checks asked,
1288// judged under the host's signers as they are now: each assessment reads
1289// the publication afresh (assessEvidence), so a key revoked during a long
1290// review is not trusted by the approval that ends it.
1291func (a *approval) coverage(g git, head string, asked []nixCheck, said io.Writer) (evidence, error) {
1292 return coverageOf(g, head, asked, assessEvidence, said)
1293}
1294
1295// derive is what the policy at main's tip requires of the change from
1296// base to head, where each layer was read from, and whether the policy
1297// requires an approval to be signed with a hardware key.
1298func (a *approval) derive(root, tip, base, head string) (res *derive.Result, label, plabel string, hardware bool, err error) {
1299 g := a.g
1300 schema, err := schemaFile(g, "")
1301 if err != nil {
1302 return nil, "", "", false, err
1303 }
1304 src, done, err := resolveLayers(g, tip, "", "")
1305 defer done()
1306 if err != nil {
1307 return nil, "", "", false, fmt.Errorf("%v; nothing derived", err)
1308 }
1309 model, err := policyModel(schema, src.instance, src.project, false)
1310 if err != nil {
1311 return nil, "", "", false, err
1312 }
1313 paths, err := derive.Diff(context.Background(), g.at(), g.env, base, head)
1314 if err != nil {
1315 return nil, "", "", false, fmt.Errorf("%v; nothing derived", err)
1316 }
1317 if res, err = derive.Derive(model, paths); err != nil {
1318 return nil, "", "", false, fmt.Errorf("%v; nothing derived", err)
1319 }
1320 label, plabel = src.labels(root, "", "", "origin/main "+a.short(tip))
1321 return res, label, plabel, model.HardwareApproval, nil
1322}
1323
1324// check runs the missing checks over head in a throwaway worktree, signed
1325// with this host's key, and returns every attestation ref stored here for
1326// the head's tree and how long the checks took.
1327func (a *approval) check(head string, e evidence, required []derive.Required, reused, missing []string, runner map[string]derive.Required) (refs []string, took string, err error) {
1328 key := os.Getenv("VALLEY_ATTEST_KEY")
1329 if key == "" {
1330 return nil, "", a.declined("no signing key", act{then: "set VALLEY_ATTEST_KEY to the ed25519 key this host attests with"})
1331 }
1332 if st, err := os.Stat(key); err != nil || !st.Mode().IsRegular() {
1333 return nil, "", a.declined("no signing key at "+key, act{})
1334 }
1335 signer := []string{"--key", key}
1336 if name := os.Getenv("VALLEY_ATTEST_NAME"); name != "" {
1337 signer = append(signer, "--name", name)
1338 }
1339
1340 // The ref this run's evidence goes to is keyed by the tree and this
1341 // signer's key hash, and approve pushes it holding this run's notes
1342 // alone, which origin refuses once it holds the ref. So origin
1343 // holding it is refused before anything is built.
1344 keyCmd := a.g.program("attest", append([]string{"key"}, signer...)...)
1345 keyCmd.Stderr = a.stderr
1346 processStarted()
1347 verifier, err := keyCmd.Output()
1348 if err != nil {
1349 return nil, "", a.declined("could not read the signing key at "+key, act{})
1350 }
1351 _, keyhash, _ := strings.Cut(strings.TrimRight(string(verifier), "\n"), "+")
1352 keyhash, _, _ = strings.Cut(keyhash, "+")
1353 if e.listed[attestationRefs+e.digest+"/"+keyhash] != "" {
1354 return nil, "", a.declined("this key's evidence for the tree, on origin, lacks "+strings.Join(missing, ", "),
1355 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
1356 }
1357
1358 // attest logs how long each check took, on this machine and outside
1359 // the evidence. What it cannot know itself is passed in: the change,
1360 // and each check's declared cost.
1361 timing := []string{"--timings"}
1362 if a.id != "" {
1363 timing = append(timing, "--change", a.id)
1364 }
1365 if a.boundVersion != "" {
1366 timing = append(timing, "--change-version", a.boundVersion)
1367 }
1368 var run []string
1369 for _, check := range missing {
1370 q := runner[check]
1371 switch q.Runner {
1372 case "nix":
1373 run = append(run, "--check", check+"="+q.Attribute)
1374 case "command":
1375 run = append(run, "--command", check+"="+q.Command)
1376 default:
1377 return nil, "", a.declined("the policy requires "+check+" but says no way to run it", act{})
1378 }
1379 if q.Cost != "" {
1380 timing = append(timing, "--cost", check+"="+q.Cost)
1381 }
1382 }
1383
1384 wt, err := os.MkdirTemp("", "valley-approve-")
1385 if err != nil {
1386 return nil, "", a.declined("no scratch directory to check it in", act{})
1387 }
1388 a.mu.Lock()
1389 a.worktree = wt
1390 a.mu.Unlock()
1391 defer a.removeWorktree()
1392 add := a.g.command("worktree", "add", "--quiet", "--detach", wt, head)
1393 add.Stdout, add.Stderr = a.stderr, a.stderr
1394 processStarted()
1395 if add.Run() != nil {
1396 a.removeWorktree()
1397 return nil, "", a.declined("could not check the head out to run its checks", act{})
1398 }
1399
1400 if a.tel != nil {
1401 timing = append(timing, "--telemetry", a.tel.spool, "--telemetry-run", a.tel.run+"-checks", "--project", a.tel.project)
1402 a.tel.emit("approve.checks", map[string]any{"attest_run": a.tel.run + "-checks", "checks": list(missing)})
1403 }
1404 v := verdict{name: a.label(), required: len(required), passed: len(reused)}
1405 if a.id != "" {
1406 v.version = a.boundVersion
1407 }
1408 args := append(append(append([]string{"run", "--repo", wt}, signer...), timing...), run...)
1409 // attest runs the checks in the worktree --repo names; its directory
1410 // and environment are the repository's, as for every program here.
1411 cmd := a.g.program("attest", args...)
1412 cmd.Stdin = a.stdin
1413 began := time.Now()
1414 done := make(chan struct{})
1415 a.mu.Lock()
1416 a.childDone = done
1417 a.mu.Unlock()
1418 status := v.checking(missing, cmd, a.verbose, droppable(a.stdout), droppable(a.stderr), a.started, a.stopped)
1419 a.mu.Lock()
1420 a.child = nil
1421 close(done)
1422 a.mu.Unlock()
1423 if a.stopped() || status == 128+int(syscall.SIGINT) || status == 128+int(syscall.SIGTERM) {
1424 a.interrupt()
1425 }
1426 if status != 0 {
1427 a.failedAt = head
1428 return nil, "", errRefused
1429 }
1430 took = fmt.Sprintf("%ds", int(time.Since(began).Seconds()))
1431 a.removeWorktree()
1432
1433 // Every attestation stored here for the tree, whoever signed it: the
1434 // evidence for this change is what the tree's digest keys, not what
1435 // this run happened to add.
1436 out, err := a.g.output(true, "for-each-ref", "--format=%(refname)", attestationRefs+e.digest)
1437 if err == nil && out != "" {
1438 refs = strings.Split(out, "\n")
1439 }
1440 if len(refs) == 0 {
1441 return nil, "", a.declined("no attestation is stored for the tree", act{})
1442 }
1443 return refs, took, nil
1444}
1445
1446// started is told of the attest run checking starts, so a signal can stop
1447// it.
1448func (a *approval) started(p *os.Process) {
1449 a.mu.Lock()
1450 a.child = p
1451 a.mu.Unlock()
1452}
1453
1454// removeWorktree removes the checks' worktree, if there is one.
1455func (a *approval) removeWorktree() {
1456 a.mu.Lock()
1457 wt := a.worktree
1458 a.worktree = ""
1459 a.mu.Unlock()
1460 if wt == "" {
1461 return
1462 }
1463 remove := a.g.command("worktree", "remove", "--force", wt)
1464 _ = remove.Run()
1465 _ = os.RemoveAll(wt)
1466}
1467
1468// signerOf is the signer of a covered check, as coverage maps it to
1469// "<ref> <signer>".
1470func signerOf(by string) string {
1471 _, signer, _ := strings.Cut(by, " ")
1472 return signer
1473}
1474
1475// list is a list as a telemetry record holds one: empty rather than null.
1476func list(items []string) []string {
1477 if items == nil {
1478 return []string{}
1479 }
1480 return items
1481}
1482
1483// approveTelemetry is an approval attempt's telemetry run, when the
1484// checkout has valley.telemetry on.
1485type approveTelemetry struct {
1486 emitter *telemetry.Emitter
1487 run, spool, project string
1488 began time.Time
1489 mu sync.Mutex
1490 about telemetry.Record
1491 ended bool
1492}
1493
1494// beginTelemetry starts the attempt's run, bound to the spool of the
1495// destination the checkout's telemetry remote names, and a flusher that
1496// sends it. Telemetry off is nil.
1497func (a *approval) beginTelemetry() *approveTelemetry {
1498 if on, _ := a.g.output(true, "config", "--get", "--bool", "valley.telemetry"); on != "true" {
1499 return nil
1500 }
1501 dest, err := telemetryRemote(a.g, "")
1502 if err == nil {
1503 var dir string
1504 if dir, err = bindSpool(dest); err == nil {
1505 version := versionStamp
1506 if version == "" {
1507 version = "unstamped"
1508 }
1509 t := &approveTelemetry{run: telemetry.NewRunID(), spool: dir, project: dest.project(), began: time.Now()}
1510 t.emitter = telemetry.NewEmitter(dir, telemetry.Self("valley", version), t.run)
1511 t.about.Project = t.project
1512 startFlusher()
1513 return t
1514 }
1515 }
1516 fmt.Fprintf(a.stderr, "valley: telemetry: %s\n", err)
1517 return nil
1518}
1519
1520// context is what every record of the attempt from here on is about.
1521func (t *approveTelemetry) context(id, version, head string) {
1522 if t == nil {
1523 return
1524 }
1525 n, _ := strconv.Atoi(version)
1526 t.mu.Lock()
1527 t.about.Change, t.about.Version, t.about.Head = id, n, head
1528 t.mu.Unlock()
1529}
1530
1531// emit records one step of the attempt. elapsed_ms is this machine's wall
1532// clock since the attempt began.
1533func (t *approveTelemetry) emit(typ string, data map[string]any) {
1534 if t == nil {
1535 return
1536 }
1537 t.mu.Lock()
1538 defer t.mu.Unlock()
1539 if t.ended {
1540 return
1541 }
1542 data["elapsed_ms"] = time.Since(t.began).Milliseconds()
1543 t.emitter.Emit(typ, t.about, data)
1544}
1545
1546// end records how the attempt ended: filed, refused or interrupted. Only
1547// the first end is recorded.
1548func (t *approveTelemetry) end(result string) {
1549 if t == nil {
1550 return
1551 }
1552 t.emit("approve.end", map[string]any{"result": result})
1553 t.mu.Lock()
1554 t.ended = true
1555 t.mu.Unlock()
1556}