gunk-dev/the-valley

run.go

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