gunk-dev/the-valley

run.go

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