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