gunk-dev/the-valley

run.go

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