| 1 | package main |
| 2 | |
| 3 | // checks prints which checks a change requires: the Go deriver's answer |
| 4 | // (../derive) over the composed policy (../composed). It is the whole of |
| 5 | // `valley checks`. |
| 6 | // |
| 7 | // It selects checks over two commits, a base and a head, and never over a |
| 8 | // working tree: what is derived is what a commit holds. A layer named with |
| 9 | // --instance or --project is read as given, and nothing is fetched for it. |
| 10 | // A layer left unnamed is read at the target's tip: main on origin as this |
| 11 | // clone last fetched it, or else the local main. The base defaults to the |
| 12 | // merge base of that tip and the head. |
| 13 | // |
| 14 | // It prints a report for a person, the required names alone with --names, |
| 15 | // or the valley-checks/v1 JSON document with --json. |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "context" |
| 20 | "encoding/base64" |
| 21 | "encoding/json" |
| 22 | "fmt" |
| 23 | "io" |
| 24 | "os" |
| 25 | "os/exec" |
| 26 | "path/filepath" |
| 27 | "sort" |
| 28 | "strings" |
| 29 | "unicode/utf8" |
| 30 | |
| 31 | "the-valley/composed" |
| 32 | "the-valley/derive" |
| 33 | ) |
| 34 | |
| 35 | const checksUsage = "usage: valley checks [--schema <file>] [--instance <dir>] [--project <dir>] [--names [--cost quick|slow] | --json] [<base> [<head>]]" |
| 36 | |
| 37 | // checksTargets are the refs whose tip an unnamed layer and an unnamed |
| 38 | // base are read at, first found first. |
| 39 | var checksTargets = []string{"refs/remotes/origin/main", "refs/heads/main"} |
| 40 | |
| 41 | func runChecks(g git, args []string, w io.Writer) error { |
| 42 | var schema, instance, project, cost string |
| 43 | var names, asJSON, costed bool |
| 44 | needs := map[string]string{"--schema": "a file", "--instance": "a directory", "--project": "a directory", "--cost": "quick or slow"} |
| 45 | dests := map[string]*string{"--schema": &schema, "--instance": &instance, "--project": &project, "--cost": &cost} |
| 46 | i := 0 |
| 47 | options: |
| 48 | for ; i < len(args); i++ { |
| 49 | opt, value, inline := strings.Cut(args[i], "=") |
| 50 | switch { |
| 51 | case args[i] == "--": |
| 52 | i++ |
| 53 | break options |
| 54 | case args[i] == "--names": |
| 55 | names = true |
| 56 | case args[i] == "--json": |
| 57 | asJSON = true |
| 58 | case dests[opt] != nil: |
| 59 | if !inline { |
| 60 | if i+1 >= len(args) { |
| 61 | return failure(opt + " needs " + needs[opt]) |
| 62 | } |
| 63 | i++ |
| 64 | value = args[i] |
| 65 | } |
| 66 | *dests[opt] = value |
| 67 | costed = costed || opt == "--cost" |
| 68 | case strings.HasPrefix(args[i], "-"): |
| 69 | return failure("unknown option: " + args[i]) |
| 70 | default: |
| 71 | break options |
| 72 | } |
| 73 | } |
| 74 | revs := args[i:] |
| 75 | if len(revs) > 2 || (asJSON && (names || costed)) { |
| 76 | return failure(checksUsage) |
| 77 | } |
| 78 | if costed { |
| 79 | if cost != "quick" && cost != "slow" { |
| 80 | return failure("--cost takes quick or slow, not '" + cost + "'") |
| 81 | } |
| 82 | if !names { |
| 83 | return failure("--cost filters the --names list; pass --names too") |
| 84 | } |
| 85 | } |
| 86 | root, err := g.output(true, "rev-parse", "--show-toplevel") |
| 87 | if err != nil { |
| 88 | return failure("not a git repository") |
| 89 | } |
| 90 | if schema, err = schemaFile(g, schema); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | headRev := "HEAD" |
| 94 | if len(revs) == 2 { |
| 95 | headRev = revs[1] |
| 96 | } |
| 97 | head, err := commitOf(g, headRev) |
| 98 | if err != nil { |
| 99 | return err |
| 100 | } |
| 101 | |
| 102 | // The target is what the layers are read out of, so it is needed |
| 103 | // whenever either layer is left unnamed, and it is what an unnamed |
| 104 | // base is the merge base with. |
| 105 | var target, tip string |
| 106 | if instance == "" || project == "" || len(revs) == 0 { |
| 107 | // Only a ref that is not there falls through to the next. A read |
| 108 | // of origin's that failed ends here: falling through would read |
| 109 | // the policy out of the local main, which may be older. |
| 110 | for _, ref := range checksTargets { |
| 111 | oid, ok, err := g.ref(ref) |
| 112 | if err != nil { |
| 113 | return failure("could not read the main branch; nothing derived") |
| 114 | } else if ok { |
| 115 | target, tip = ref, oid |
| 116 | break |
| 117 | } |
| 118 | } |
| 119 | if target == "" { |
| 120 | return failure("no main branch: the target's tip is where the policy layers are read from, and there is none here") |
| 121 | } |
| 122 | } |
| 123 | var base string |
| 124 | if len(revs) > 0 { |
| 125 | if base, err = commitOf(g, revs[0]); err != nil { |
| 126 | return err |
| 127 | } |
| 128 | } else if base, err = g.output(true, "merge-base", tip, head); err != nil || !isObjectID(base) { |
| 129 | return failure(fmt.Sprintf("%s and %s do not share history — name a base", head, strings.TrimPrefix(target, "refs/"))) |
| 130 | } |
| 131 | |
| 132 | src, done, err := resolveLayers(g, tip, instance, project) |
| 133 | defer done() |
| 134 | if err != nil { |
| 135 | return failure(err.Error() + "; nothing derived") |
| 136 | } |
| 137 | model, err := policyModel(schema, src.instance, src.project, !names) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | ctx := context.Background() |
| 142 | paths, err := derive.Diff(ctx, g.at(), g.env, base, head) |
| 143 | if err != nil { |
| 144 | return failure(err.Error() + "; nothing derived") |
| 145 | } |
| 146 | res, err := derive.Derive(model, paths) |
| 147 | if err != nil { |
| 148 | return failure(err.Error() + "; nothing derived") |
| 149 | } |
| 150 | |
| 151 | // Each form is written whole once it is made, so a reader gets the |
| 152 | // answer or nothing. |
| 153 | var buf bytes.Buffer |
| 154 | switch { |
| 155 | case asJSON: |
| 156 | enc := json.NewEncoder(&buf) |
| 157 | enc.SetEscapeHTML(false) |
| 158 | enc.SetIndent("", " ") |
| 159 | if err := enc.Encode(checksDocument(base, head, model.Digest, res)); err != nil { |
| 160 | return fmt.Errorf("could not encode the checks: %w", err) |
| 161 | } |
| 162 | case names: |
| 163 | for _, q := range res.Required { |
| 164 | if cost == "" || costOf(q) == cost { |
| 165 | fmt.Fprintln(&buf, q.Name) |
| 166 | } |
| 167 | } |
| 168 | default: |
| 169 | at := "" |
| 170 | if tip != "" { |
| 171 | short, err := g.output(true, "rev-parse", "--short", tip) |
| 172 | if err != nil { |
| 173 | return failure("could not read " + target + "; nothing derived") |
| 174 | } |
| 175 | at = strings.TrimPrefix(strings.TrimPrefix(target, "refs/remotes/"), "refs/heads/") + " " + short |
| 176 | } |
| 177 | label, plabel := src.labels(root, instance, project, at) |
| 178 | shortBase, err1 := g.output(true, "rev-parse", "--short", base) |
| 179 | shortHead, err2 := g.output(true, "rev-parse", "--short", head) |
| 180 | if err1 != nil || err2 != nil { |
| 181 | return failure("could not read the commits; nothing derived") |
| 182 | } |
| 183 | checksReport(&buf, shortBase+".."+shortHead, label+" + "+plabel, res) |
| 184 | } |
| 185 | _, err = w.Write(buf.Bytes()) |
| 186 | return err |
| 187 | } |
| 188 | |
| 189 | // commitOf is the object ID of the commit rev names. |
| 190 | func commitOf(g git, rev string) (string, error) { |
| 191 | oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", rev+"^{commit}") |
| 192 | if err != nil || !isObjectID(oid) { |
| 193 | return "", failure("no such commit: " + rev) |
| 194 | } |
| 195 | return oid, nil |
| 196 | } |
| 197 | |
| 198 | // costOf is a required check's cost as the report groups it: slow, or |
| 199 | // else quick. |
| 200 | func costOf(q derive.Required) string { |
| 201 | if q.Cost == "slow" { |
| 202 | return "slow" |
| 203 | } |
| 204 | return "quick" |
| 205 | } |
| 206 | |
| 207 | // labels say where each layer was read from, as a reader can check it: a |
| 208 | // layer named is named as given, relative to the top level when it is |
| 209 | // under it, and a layer read at the target names the ref and the commit |
| 210 | // it stood at. |
| 211 | func (src layerSource) labels(root, instance, project, at string) (label, plabel string) { |
| 212 | switch { |
| 213 | case instance != "": |
| 214 | label = strings.TrimPrefix(instance, root+"/") |
| 215 | case src.ownValley: |
| 216 | label = instanceLayer + "@" + at + " (this repository is its own valley)" |
| 217 | default: |
| 218 | label = src.valley + " " + instanceLayer + "@refs/heads/main" |
| 219 | } |
| 220 | switch { |
| 221 | case project != "": |
| 222 | plabel = strings.TrimPrefix(project, root+"/") |
| 223 | case src.noProject: |
| 224 | plabel = "no " + projectLayer + "@" + at + " — the floor alone" |
| 225 | default: |
| 226 | plabel = projectLayer + "@" + at |
| 227 | } |
| 228 | return label, plabel |
| 229 | } |
| 230 | |
| 231 | // checksReport writes the report for a person: the change, the policy it |
| 232 | // was read under, what it matched, and each required check with its pin |
| 233 | // and the classes requiring it. A class requiring a check is listed with |
| 234 | // the unclassified set, which requires checks of a path no class covers. |
| 235 | func checksReport(w io.Writer, change, policy string, r *derive.Result) { |
| 236 | fmt.Fprintf(w, "%s: %d changed path(s)\n", change, len(r.Paths)) |
| 237 | fmt.Fprintf(w, "policy: %s\n", policy) |
| 238 | matched := append([]string{}, r.Classes...) |
| 239 | if len(r.Unclassified) > 0 { |
| 240 | matched = append(matched, "unclassified") |
| 241 | } |
| 242 | sort.Strings(matched) |
| 243 | fmt.Fprintf(w, "classes matched: %s\n", joinOrNone(matched)) |
| 244 | // How far an approval of this change carries across a rebase. Nothing |
| 245 | // here acts on it. |
| 246 | fmt.Fprintf(w, "carry mode: %s\n\n", r.Carry) |
| 247 | |
| 248 | width, unclassified := 0, false |
| 249 | var quick, slow []string |
| 250 | for _, q := range r.Required { |
| 251 | width = max(width, len(q.Name)) |
| 252 | unclassified = unclassified || q.Unclassified |
| 253 | if costOf(q) == "slow" { |
| 254 | slow = append(slow, q.Name) |
| 255 | } else { |
| 256 | quick = append(quick, q.Name) |
| 257 | } |
| 258 | } |
| 259 | if len(r.Required) == 0 { |
| 260 | fmt.Fprintln(w, "required checks: none") |
| 261 | } else { |
| 262 | fmt.Fprintln(w, "required checks:") |
| 263 | for _, q := range r.Required { |
| 264 | by := append([]string{}, q.Classes...) |
| 265 | if q.Unclassified { |
| 266 | by = append(by, "unclassified") |
| 267 | } |
| 268 | sort.Strings(by) |
| 269 | fmt.Fprintf(w, " %-*s %-9s %s\n", width, q.Name, q.Pin, strings.Join(by, ", ")) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | if len(r.Unclassified) > 0 { |
| 274 | fmt.Fprintf(w, "\nunclassified: %d path(s) matched no class\n", len(r.Unclassified)) |
| 275 | for _, p := range r.Unclassified { |
| 276 | fmt.Fprintf(w, " %s\n", p) |
| 277 | } |
| 278 | // The failure the unclassified set exists to prevent: paths |
| 279 | // outside every class that the policy then asks nothing of. |
| 280 | if !unclassified { |
| 281 | fmt.Fprintln(w, " the policy requires nothing of them — it is behind the tree") |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // Below every row, and unindented, so neither line reads as a |
| 286 | // required check. The grouping changes nothing required: approve runs |
| 287 | // every required check, and the integrator requires evidence for every |
| 288 | // one, whatever it costs. |
| 289 | if len(r.Required) > 0 { |
| 290 | fmt.Fprintf(w, "\nquick: %s\n", joinOrNone(quick)) |
| 291 | fmt.Fprintf(w, "slow: %s\n", joinOrNone(slow)) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | func joinOrNone(list []string) string { |
| 296 | if len(list) == 0 { |
| 297 | return "none" |
| 298 | } |
| 299 | return strings.Join(list, ", ") |
| 300 | } |
| 301 | |
| 302 | // derivedChecks is the valley-checks/v1 document for the change between |
| 303 | // two commits, under the schema and the two layers named. An empty schema |
| 304 | // is the packaged one, or else the one in this repository's tree. The |
| 305 | // check worker (worker.go) calls it for the checks to build, and reads no |
| 306 | // requirement's pin, so each pin is unknown. |
| 307 | func derivedChecks(g git, schema, instance, project, baseRev, headRev string) (jsonChecks, error) { |
| 308 | if !g.succeeds(true, "rev-parse", "--git-dir") { |
| 309 | return jsonChecks{}, failure("not a git repository") |
| 310 | } |
| 311 | schema, err := schemaFile(g, schema) |
| 312 | if err != nil { |
| 313 | return jsonChecks{}, err |
| 314 | } |
| 315 | var commits [2]string |
| 316 | for i, rev := range []string{baseRev, headRev} { |
| 317 | oid, err := g.output(true, "rev-parse", "--verify", "--quiet", "--end-of-options", rev+"^{commit}") |
| 318 | if err != nil || !isObjectID(oid) { |
| 319 | return jsonChecks{}, failure("no such commit: " + rev) |
| 320 | } |
| 321 | commits[i] = oid |
| 322 | } |
| 323 | model, err := policyModel(schema, instance, project, false) |
| 324 | if err != nil { |
| 325 | return jsonChecks{}, err |
| 326 | } |
| 327 | return deriveUnder(g, model, commits[0], commits[1]) |
| 328 | } |
| 329 | |
| 330 | // schemaFile is the verification schema named, or when none is, the |
| 331 | // packaged one, or else the one in this repository's tree. |
| 332 | func schemaFile(g git, schema string) (string, error) { |
| 333 | // The schema ships with the package, which names it in |
| 334 | // VALLEY_VERIFICATION_SCHEMA; only the-valley's own tree carries one, |
| 335 | // as `valley checks` reads it. |
| 336 | if schema == "" { |
| 337 | schema = os.Getenv("VALLEY_VERIFICATION_SCHEMA") |
| 338 | } |
| 339 | if schema == "" { |
| 340 | root, err := g.output(true, "rev-parse", "--show-toplevel") |
| 341 | if err != nil { |
| 342 | return "", failure("no schema: name one with --schema or VALLEY_VERIFICATION_SCHEMA") |
| 343 | } |
| 344 | schema = filepath.Join(root, "schema", "verification.cue") |
| 345 | } |
| 346 | return schema, nil |
| 347 | } |
| 348 | |
| 349 | // policyModel is the policy the schema and the two layers compose, read |
| 350 | // once for every change derived under it. pinned asks cue which |
| 351 | // requirements are mandatory (composed.Read), one cue vet each, for the |
| 352 | // readers that print a pin: valley checks' report and its document. Every |
| 353 | // other reader leaves them unknown (composed.ReadUnpinned). |
| 354 | func policyModel(schema, instance, project string, pinned bool) (*composed.Model, error) { |
| 355 | if _, err := exec.LookPath("cue"); err != nil { |
| 356 | return nil, failure("this verb needs the cue CLI; nix run .#valley bundles it") |
| 357 | } |
| 358 | read := composed.Read |
| 359 | if !pinned { |
| 360 | read = composed.ReadUnpinned |
| 361 | } |
| 362 | model, err := read(context.Background(), "cue", schema, instance, project) |
| 363 | if err != nil { |
| 364 | return nil, failure(err.Error() + "; nothing derived") |
| 365 | } |
| 366 | return model, nil |
| 367 | } |
| 368 | |
| 369 | // deriveUnder is the valley-checks/v1 document for the change between two |
| 370 | // commits, given as object IDs, under a policy read. |
| 371 | func deriveUnder(g git, model *composed.Model, base, head string) (jsonChecks, error) { |
| 372 | ctx := context.Background() |
| 373 | paths, err := derive.Diff(ctx, g.at(), g.env, base, head) |
| 374 | if err != nil { |
| 375 | return jsonChecks{}, failure(err.Error() + "; nothing derived") |
| 376 | } |
| 377 | res, err := derive.Derive(model, paths) |
| 378 | if err != nil { |
| 379 | return jsonChecks{}, failure(err.Error() + "; nothing derived") |
| 380 | } |
| 381 | return checksDocument(base, head, model.Digest, res), nil |
| 382 | } |
| 383 | |
| 384 | // The valley-checks/v1 document. docs/architecture.md documents it, and a |
| 385 | // change to any field's name or meaning is a new schema version. Every |
| 386 | // list is a list, empty rather than null. |
| 387 | type jsonChecks struct { |
| 388 | Schema string `json:"schema"` |
| 389 | Base string `json:"base"` |
| 390 | Head string `json:"head"` |
| 391 | PolicyDigest string `json:"policy_digest"` |
| 392 | Paths []jsonPath `json:"paths"` |
| 393 | Classes []string `json:"classes"` |
| 394 | UnclassifiedPaths []jsonPath `json:"unclassified_paths"` |
| 395 | Carry string `json:"carry"` |
| 396 | Required []jsonRequired `json:"required"` |
| 397 | Follows []jsonFollow `json:"follows"` |
| 398 | } |
| 399 | |
| 400 | // jsonRequired is one required check. attribute is given for the nix |
| 401 | // runner, command for the command runner, and validity only when the |
| 402 | // policy declares a window. |
| 403 | type jsonRequired struct { |
| 404 | Name string `json:"name"` |
| 405 | Classes []string `json:"classes"` |
| 406 | Unclassified bool `json:"unclassified"` |
| 407 | Pin string `json:"pin"` |
| 408 | Cost string `json:"cost"` |
| 409 | Runner string `json:"runner"` |
| 410 | Attribute string `json:"attribute,omitempty"` |
| 411 | Command string `json:"command,omitempty"` |
| 412 | Validity string `json:"validity,omitempty"` |
| 413 | } |
| 414 | |
| 415 | // jsonFollow is one check the change sets due on main without requiring |
| 416 | // it, with the matched classes it follows. |
| 417 | type jsonFollow struct { |
| 418 | Name string `json:"name"` |
| 419 | Classes []string `json:"classes"` |
| 420 | Cost string `json:"cost"` |
| 421 | Runner string `json:"runner"` |
| 422 | Attribute string `json:"attribute,omitempty"` |
| 423 | Command string `json:"command,omitempty"` |
| 424 | } |
| 425 | |
| 426 | func checksDocument(base, head, digest string, r *derive.Result) jsonChecks { |
| 427 | doc := jsonChecks{ |
| 428 | Schema: "valley-checks/v1", |
| 429 | Base: base, |
| 430 | Head: head, |
| 431 | PolicyDigest: digest, |
| 432 | Paths: jsonPaths(r.Paths), |
| 433 | Classes: append([]string{}, r.Classes...), |
| 434 | UnclassifiedPaths: jsonPaths(r.Unclassified), |
| 435 | Carry: r.Carry, |
| 436 | Required: []jsonRequired{}, |
| 437 | Follows: []jsonFollow{}, |
| 438 | } |
| 439 | for _, q := range r.Required { |
| 440 | doc.Required = append(doc.Required, jsonRequired{ |
| 441 | Name: q.Name, |
| 442 | Classes: append([]string{}, q.Classes...), |
| 443 | Unclassified: q.Unclassified, |
| 444 | Pin: string(q.Pin), |
| 445 | Cost: q.Cost, |
| 446 | Runner: q.Runner, |
| 447 | Attribute: q.Attribute, |
| 448 | Command: q.Command, |
| 449 | Validity: q.Validity, |
| 450 | }) |
| 451 | } |
| 452 | for _, f := range r.Follows { |
| 453 | doc.Follows = append(doc.Follows, jsonFollow{ |
| 454 | Name: f.Name, |
| 455 | Classes: append([]string{}, f.Classes...), |
| 456 | Cost: f.Cost, |
| 457 | Runner: f.Runner, |
| 458 | Attribute: f.Attribute, |
| 459 | Command: f.Command, |
| 460 | }) |
| 461 | } |
| 462 | return doc |
| 463 | } |
| 464 | |
| 465 | // jsonPath is a path as git gave it, which is bytes that need not be |
| 466 | // UTF-8. JSON holds only UTF-8, and json.Marshal writes each byte that is |
| 467 | // not as U+FFFD, so such a path would not read back as git gave it. A path |
| 468 | // that is UTF-8 is written as {"path": "…"}, and any other as {"base64": |
| 469 | // "…"}, in standard base64, which reads back byte for byte. |
| 470 | type jsonPath string |
| 471 | |
| 472 | func jsonPaths(paths []string) []jsonPath { |
| 473 | out := make([]jsonPath, len(paths)) |
| 474 | for i, p := range paths { |
| 475 | out[i] = jsonPath(p) |
| 476 | } |
| 477 | return out |
| 478 | } |
| 479 | |
| 480 | func (p jsonPath) MarshalJSON() ([]byte, error) { |
| 481 | var v any = struct { |
| 482 | Path string `json:"path"` |
| 483 | }{string(p)} |
| 484 | if !utf8.ValidString(string(p)) { |
| 485 | v = struct { |
| 486 | Base64 string `json:"base64"` |
| 487 | }{base64.StdEncoding.EncodeToString([]byte(p))} |
| 488 | } |
| 489 | var buf bytes.Buffer |
| 490 | enc := json.NewEncoder(&buf) |
| 491 | enc.SetEscapeHTML(false) |
| 492 | if err := enc.Encode(v); err != nil { |
| 493 | return nil, err |
| 494 | } |
| 495 | return bytes.TrimRight(buf.Bytes(), "\n"), nil |
| 496 | } |