| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "the-valley/telemetry" |
| 14 | ) |
| 15 | |
| 16 | // cmdRun is the whole protocol in order: digest the subject tree, run the |
| 17 | // checks, compose a statement per check, vet each against the schema, |
| 18 | // write each out and sign it as a note, store the notes at one ref keyed |
| 19 | // by the subject digest and the signer, and publish with a single atomic |
| 20 | // push, adding the notes to the ref when the remote holds it (publish.go). Every |
| 21 | // check runs whatever another's result, and then any step failing stops |
| 22 | // the run before the next — a failed check publishes nothing, and neither |
| 23 | // does a statement the schema rejects. How long each check took is |
| 24 | // printed, and logged with --timings (timing.go), whatever the check's |
| 25 | // result. With --telemetry, the run's progress is recorded as it happens |
| 26 | // (progress.go). |
| 27 | func cmdRun(args []string) (err error) { |
| 28 | fs := newFlagSet("run") |
| 29 | repo := fs.String("repo", "", "repository") |
| 30 | rev := fs.String("rev", "HEAD", "revision") |
| 31 | key := fs.String("key", "", "ed25519 private key") |
| 32 | name := fs.String("name", defaultSignerName(), "the name that key signs under") |
| 33 | environment := fs.String("environment", "local", "environment an effectful statement names") |
| 34 | provenanceFile := fs.String("provenance", "", "json run provenance") |
| 35 | schemaFlag := fs.String("schema", "", "attestation schema") |
| 36 | system := fs.String("system", nixSystem(), "flake system") |
| 37 | push := fs.String("push", "", "remote to publish to") |
| 38 | branch := fs.String("branch", "", "branch pushed alongside") |
| 39 | timings := fs.Bool("timings", false, "append each check's timing to the timing log") |
| 40 | changeID := fs.String("change", "", "the change ID a timing names") |
| 41 | changeVersion := fs.Int("change-version", 0, "the change version a timing names") |
| 42 | telemetryDir := fs.String("telemetry", "", "a telemetry stream to record the run's progress in") |
| 43 | telemetryRun := fs.String("telemetry-run", "", "the run ID the progress records name") |
| 44 | project := fs.String("project", "", "the project the progress records name") |
| 45 | capacity := fs.String("capacity", "", "the capacity the builds' progress records name") |
| 46 | slots := fs.Int("slots", defaultSlots, "how many nix builds run at once") |
| 47 | gcRoots := fs.String("gc-roots", "", "a directory to root every built output in") |
| 48 | evalReservations := fs.String("eval-reservations", "", "a directory of reservations the flake checks' evaluation is admitted by") |
| 49 | evalEstimate := fs.Int64("eval-estimate", 0, "the peak memory the evaluation is expected to need, in bytes") |
| 50 | evalBudget := fs.Int64("eval-budget", 0, "the memory the evaluations admitted by --eval-reservations share, in bytes") |
| 51 | evalPeak := fs.String("eval-peak", "", "a file to write the evaluation's peak memory to, in bytes") |
| 52 | var checks, commands, costs repeatable |
| 53 | fs.Var(&checks, "check", "flake check to run") |
| 54 | fs.Var(&commands, "command", "effectful check to run") |
| 55 | fs.Var(&costs, "cost", "a check's declared cost class, for its timing") |
| 56 | if err := fs.Parse(args); err != nil { |
| 57 | return err |
| 58 | } |
| 59 | if *slots < 1 { |
| 60 | return fmt.Errorf("--slots %d: at least one build must run at a time", *slots) |
| 61 | } |
| 62 | classes, err := costClasses(costs) |
| 63 | if err != nil { |
| 64 | return err |
| 65 | } |
| 66 | roots := "" |
| 67 | if *gcRoots != "" { |
| 68 | if roots, err = filepath.Abs(*gcRoots); err != nil { |
| 69 | return fmt.Errorf("--gc-roots %s: %v", *gcRoots, err) |
| 70 | } |
| 71 | if err := os.MkdirAll(roots, 0o755); err != nil { |
| 72 | return fmt.Errorf("--gc-roots %s: %v", *gcRoots, err) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | var adm *admission |
| 77 | if *evalReservations != "" { |
| 78 | if *evalBudget < 1 { |
| 79 | return fmt.Errorf("--eval-reservations needs --eval-budget: the memory the evaluations share, in bytes") |
| 80 | } |
| 81 | if *evalEstimate < 0 { |
| 82 | return fmt.Errorf("--eval-estimate %d: not a number of bytes", *evalEstimate) |
| 83 | } |
| 84 | dir, err := filepath.Abs(*evalReservations) |
| 85 | if err != nil { |
| 86 | return fmt.Errorf("--eval-reservations %s: %v", *evalReservations, err) |
| 87 | } |
| 88 | // An evaluation with no estimate counts as the whole budget, so it |
| 89 | // runs alone. |
| 90 | adm = &admission{dir: dir, estimate: *evalEstimate, budget: *evalBudget} |
| 91 | if adm.estimate == 0 { |
| 92 | adm.estimate = adm.budget |
| 93 | } |
| 94 | } |
| 95 | peakFile := "" |
| 96 | if *evalPeak != "" { |
| 97 | if peakFile, err = filepath.Abs(*evalPeak); err != nil { |
| 98 | return fmt.Errorf("--eval-peak %s: %v", *evalPeak, err) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | root, err := repoRoot(*repo) |
| 103 | if err != nil { |
| 104 | return err |
| 105 | } |
| 106 | schema, err := schemaPath(*schemaFlag, root) |
| 107 | if err != nil { |
| 108 | return err |
| 109 | } |
| 110 | prov, err := loadProvenance(*provenanceFile) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | |
| 115 | // The signer is checked before any work is done: a run that can only |
| 116 | // end in "no key" should say so before it builds anything. |
| 117 | host, err := loadSigner(*key, *name) |
| 118 | if err != nil { |
| 119 | return err |
| 120 | } |
| 121 | |
| 122 | subj, err := composeSubject(root, *rev) |
| 123 | if err != nil { |
| 124 | return err |
| 125 | } |
| 126 | fmt.Printf("subject %s:%s\n", subj.Primary, subj.Digest[subj.Primary]) |
| 127 | for _, alg := range sortedKeys(subj.Digest) { |
| 128 | if alg != subj.Primary { |
| 129 | fmt.Printf(" %s:%s (advisory)\n", alg, subj.Digest[alg]) |
| 130 | } |
| 131 | } |
| 132 | fmt.Printf("signer %s\n", host.verifierKey()) |
| 133 | |
| 134 | tel := telemetry.NewEmitter(*telemetryDir, telemetry.Self("attest", ""), *telemetryRun) |
| 135 | tel.Correlate(telemetry.Record{Project: *project, Change: *changeID, Version: *changeVersion, |
| 136 | Head: subj.Digest["git-sha1"] + subj.Digest["git-sha256"], Tree: subj.Digest[subj.Primary]}) |
| 137 | tel.Emit("run.start", telemetry.Record{}, map[string]any{"checks": append(append([]string{}, checks...), commands...), "slots": *slots, "system": *system}) |
| 138 | defer func() { |
| 139 | result := "passed" |
| 140 | if err != nil { |
| 141 | result = "failed" |
| 142 | } |
| 143 | tel.Emit("run.end", telemetry.Record{}, map[string]any{"result": result}) |
| 144 | }() |
| 145 | obs := newObserver(tel) |
| 146 | if obs != nil { |
| 147 | obs.capacity = *capacity |
| 148 | } |
| 149 | |
| 150 | tree, err := os.MkdirTemp("", "valley-attest-tree") |
| 151 | if err != nil { |
| 152 | return err |
| 153 | } |
| 154 | defer os.RemoveAll(tree) |
| 155 | if err := exportTree(root, *rev, tree); err != nil { |
| 156 | return err |
| 157 | } |
| 158 | |
| 159 | specs, err := checkSpecs(tree, *system, checks, commands) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | if len(specs) == 0 { |
| 164 | return fmt.Errorf("no checks to run") |
| 165 | } |
| 166 | |
| 167 | log := &timingLog{warn: timingStderr()} |
| 168 | repository := "" |
| 169 | if *timings { |
| 170 | path, pathErr := timingsPath() |
| 171 | if pathErr != nil { |
| 172 | fmt.Fprintf(timingStderr(), "attest: warning: timings not logged: %v\n", pathErr) |
| 173 | } |
| 174 | log.path = path |
| 175 | repository = repositoryName(root) |
| 176 | } |
| 177 | commit := subj.Digest["git-sha1"] + subj.Digest["git-sha256"] |
| 178 | |
| 179 | // The pure checks are evaluated together and built side by side first |
| 180 | // (runPure), each reported in the order given as soon as it and those |
| 181 | // before it have ended. The command checks then run one at a time, |
| 182 | // each reported as it ends. A check that fails or cannot run stops no |
| 183 | // other. |
| 184 | var pure, effectful []checkSpec |
| 185 | for _, spec := range specs { |
| 186 | if spec.runner() == "nix" { |
| 187 | pure = append(pure, spec) |
| 188 | } else { |
| 189 | effectful = append(effectful, spec) |
| 190 | } |
| 191 | } |
| 192 | outcomes := make([]checkOutcome, 0, len(specs)) |
| 193 | var errs []error |
| 194 | failed := 0 |
| 195 | report := func(r ranCheck) { |
| 196 | result := "passed" |
| 197 | switch { |
| 198 | case r.err != nil: |
| 199 | result = "error" |
| 200 | case !r.out.passed: |
| 201 | result = "failed" |
| 202 | failed++ |
| 203 | } |
| 204 | t := checkTiming{ |
| 205 | Time: r.began.UTC().Format("2006-01-02T15:04:05.000Z"), |
| 206 | Repository: repository, |
| 207 | Change: *changeID, |
| 208 | Version: *changeVersion, |
| 209 | Head: commit, |
| 210 | Check: r.out.spec.name, |
| 211 | Runner: r.out.spec.runner(), |
| 212 | Cost: classes[r.out.spec.name], |
| 213 | Result: result, |
| 214 | Satisfied: r.out.satisfied, |
| 215 | DurationMS: r.took.Milliseconds(), |
| 216 | EvalMS: r.eval.Milliseconds(), |
| 217 | } |
| 218 | if t.Satisfied == "" { |
| 219 | t.Satisfied = satisfiedUnknown |
| 220 | } |
| 221 | log.append(t) |
| 222 | if r.err != nil { |
| 223 | fmt.Fprintln(timingStdout(), timingLine(t, r.took)) |
| 224 | errs = append(errs, r.err) |
| 225 | return |
| 226 | } |
| 227 | fmt.Printf("check %-24s %-8s %s\n", r.out.spec.name, r.out.spec.runner(), result) |
| 228 | fmt.Fprintln(timingStdout(), timingLine(t, r.took)) |
| 229 | outcomes = append(outcomes, r.out) |
| 230 | } |
| 231 | if _, err := runPure(tree, *system, pure, *timings, *slots, roots, adm, peakFile, report, obs); err != nil { |
| 232 | return err |
| 233 | } |
| 234 | for _, spec := range effectful { |
| 235 | began := time.Now() |
| 236 | obs.emit("check.start", spec.name, nil) |
| 237 | log := tel.Log(spec.name) |
| 238 | out := runEffectful(tree, spec, log) |
| 239 | bytes, truncated := log.Close() |
| 240 | r := ranCheck{out: out, began: began, took: time.Since(began)} |
| 241 | obs.emit("check.result", spec.name, map[string]any{"result": resultOf(r), "check_ms": r.took.Milliseconds(), "log_bytes": bytes, "log_truncated": truncated}) |
| 242 | report(r) |
| 243 | } |
| 244 | if failed > 0 { |
| 245 | for _, out := range outcomes { |
| 246 | if !out.passed && out.log != "" { |
| 247 | fmt.Fprintf(os.Stderr, "\n--- %s ---\n%s\n", out.spec.name, out.log) |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | if len(errs) > 0 { |
| 252 | return errors.Join(errs...) |
| 253 | } |
| 254 | if failed > 0 { |
| 255 | return fmt.Errorf("%d of %d checks failed; nothing published", failed, len(specs)) |
| 256 | } |
| 257 | |
| 258 | // Compose, validate, render. Every statement is vetted before any of |
| 259 | // them is written out, so a malformed one cannot leave a half-signed |
| 260 | // set behind. The schema is the gate and it reads JSON; the text is |
| 261 | // what a signature covers, and it carries exactly what the JSON does. |
| 262 | texts := make([][]byte, len(outcomes)) |
| 263 | for i, out := range outcomes { |
| 264 | st := composeStatement(subj, out, *environment, prov) |
| 265 | doc, err := json.Marshal(st) |
| 266 | if err != nil { |
| 267 | return err |
| 268 | } |
| 269 | if err := vetStatement(schema, doc); err != nil { |
| 270 | return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err) |
| 271 | } |
| 272 | if texts[i], err = renderJSON(doc); err != nil { |
| 273 | return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | subtrees := map[string]string{} |
| 278 | for i, out := range outcomes { |
| 279 | note, err := signNote(texts[i], host) |
| 280 | if err != nil { |
| 281 | return err |
| 282 | } |
| 283 | noteBlob, err := writeBlob(root, note) |
| 284 | if err != nil { |
| 285 | return err |
| 286 | } |
| 287 | sub, err := mkTree(root, map[string]string{"statement.note": noteBlob}, nil) |
| 288 | if err != nil { |
| 289 | return err |
| 290 | } |
| 291 | subtrees[out.spec.name] = sub |
| 292 | } |
| 293 | top, err := mkTree(root, nil, subtrees) |
| 294 | if err != nil { |
| 295 | return err |
| 296 | } |
| 297 | ref := attestationRef(subj.Digest[subj.Primary], fmt.Sprintf("%08x", host.hash)) |
| 298 | if _, err := git(root, "update-ref", ref, top); err != nil { |
| 299 | return err |
| 300 | } |
| 301 | fmt.Printf("stored %s -> %s\n", ref, top) |
| 302 | tel.Emit("evidence.stored", telemetry.Record{}, map[string]any{"ref": ref, "object": top}) |
| 303 | |
| 304 | if *push == "" { |
| 305 | return nil |
| 306 | } |
| 307 | head := *branch |
| 308 | if head == "" { |
| 309 | head, err = gitLine(root, "symbolic-ref", "--short", "HEAD") |
| 310 | if err != nil { |
| 311 | return fmt.Errorf("no branch to push: %w", err) |
| 312 | } |
| 313 | } |
| 314 | head = strings.TrimPrefix(head, "refs/heads/") |
| 315 | branchSpec := fmt.Sprintf("refs/heads/%s:refs/heads/%s", head, head) |
| 316 | return publish(root, *push, branchSpec, ref, subtrees) |
| 317 | } |
| 318 | |
| 319 | // composeSubject builds the digest set: the content-addressed tree digest |
| 320 | // as the member that IS the identity, and the commit as an advisory member |
| 321 | // for finding the change. |
| 322 | func composeSubject(root, rev string) (subject, error) { |
| 323 | entries, err := gitTreeEntries(root, rev) |
| 324 | if err != nil { |
| 325 | return subject{}, err |
| 326 | } |
| 327 | commit, err := gitLine(root, "rev-parse", rev+"^{commit}") |
| 328 | if err != nil { |
| 329 | return subject{}, err |
| 330 | } |
| 331 | subj := subject{Primary: treeScheme, Digest: map[string]string{treeScheme: treeDigest(entries)}} |
| 332 | switch len(commit) { |
| 333 | case 40: |
| 334 | subj.Digest["git-sha1"] = commit |
| 335 | case 64: |
| 336 | subj.Digest["git-sha256"] = commit |
| 337 | default: |
| 338 | return subject{}, fmt.Errorf("unexpected object id %q", commit) |
| 339 | } |
| 340 | return subj, nil |
| 341 | } |
| 342 | |
| 343 | func composeStatement(subj subject, out checkOutcome, environment string, prov json.RawMessage) statement { |
| 344 | result := "failed" |
| 345 | if out.passed { |
| 346 | result = "passed" |
| 347 | } |
| 348 | st := statement{ |
| 349 | StatementType: statementType, |
| 350 | Subject: subj, |
| 351 | Provenance: prov, |
| 352 | Predicate: predicate{ |
| 353 | Check: checkRun{ |
| 354 | Name: out.spec.name, |
| 355 | Runner: out.spec.runner(), |
| 356 | Attribute: out.spec.attribute, |
| 357 | Command: out.spec.command, |
| 358 | }, |
| 359 | Result: result, |
| 360 | }, |
| 361 | } |
| 362 | if out.spec.runner() == "nix" { |
| 363 | st.PredicateType = predicatePure |
| 364 | st.Predicate.Inputs = map[string]string{inputsScheme: out.inputs} |
| 365 | st.Predicate.Derivation = map[string]string{"sha256": out.derivation} |
| 366 | st.Predicate.Output = map[string]string{treeScheme: out.output} |
| 367 | } else { |
| 368 | st.PredicateType = predicateEffect |
| 369 | st.Predicate.Environment = environment |
| 370 | st.Predicate.ObservedAt = out.observedAt |
| 371 | } |
| 372 | return st |
| 373 | } |
| 374 | |
| 375 | // checkSpecs resolves what to run. Naming no check means the repo's whole |
| 376 | // canonical set: every check the flake defines for this system. |
| 377 | func checkSpecs(tree, system string, checks, commands repeatable) ([]checkSpec, error) { |
| 378 | var specs []checkSpec |
| 379 | for _, c := range checks { |
| 380 | name, attr, found := strings.Cut(c, "=") |
| 381 | if !found { |
| 382 | attr = name |
| 383 | } |
| 384 | specs = append(specs, checkSpec{name: name, attribute: attr}) |
| 385 | } |
| 386 | for _, c := range commands { |
| 387 | name, command, found := strings.Cut(c, "=") |
| 388 | if !found { |
| 389 | return nil, fmt.Errorf("--command %q: expected NAME=COMMAND", c) |
| 390 | } |
| 391 | specs = append(specs, checkSpec{name: name, command: command}) |
| 392 | } |
| 393 | if len(specs) > 0 { |
| 394 | return specs, nil |
| 395 | } |
| 396 | names, err := flakeChecks(tree, system) |
| 397 | if err != nil { |
| 398 | return nil, err |
| 399 | } |
| 400 | for _, n := range names { |
| 401 | specs = append(specs, checkSpec{name: n, attribute: n}) |
| 402 | } |
| 403 | return specs, nil |
| 404 | } |
| 405 | |
| 406 | func sortedKeys(m map[string]string) []string { |
| 407 | keys := make([]string, 0, len(m)) |
| 408 | for k := range m { |
| 409 | keys = append(keys, k) |
| 410 | } |
| 411 | sort.Strings(keys) |
| 412 | return keys |
| 413 | } |