gunk-dev/the-valley

run.go

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