gunk-dev/the-valley

run.go

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