gunk-dev/the-valley

run.go

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