gunk-dev/the-valley

run.go

sourcedd3d6fba36ddmain'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 and built together first (runPure),
111 // and are reported in the order given once the build is over. The
112 // command checks then run one at a time, each reported as it ends. A
113 // check that fails or cannot run stops no other.
114 var pure, effectful []checkSpec
115 for _, spec := range specs {
116 if spec.runner() == "nix" {
117 pure = append(pure, spec)
118 } else {
119 effectful = append(effectful, spec)
120 }
121 }
122 outcomes := make([]checkOutcome, 0, len(specs))
123 var errs []error
124 failed := 0
125 report := func(r ranCheck) {
126 result := "passed"
127 switch {
128 case r.err != nil:
129 result = "error"
130 case !r.out.passed:
131 result = "failed"
132 failed++
133 }
134 t := checkTiming{
135 Time: r.began.UTC().Format("2006-01-02T15:04:05.000Z"),
136 Repository: repository,
137 Change: *changeID,
138 Version: *changeVersion,
139 Head: commit,
140 Check: r.out.spec.name,
141 Runner: r.out.spec.runner(),
142 Cost: classes[r.out.spec.name],
143 Result: result,
144 Satisfied: r.out.satisfied,
145 DurationMS: r.took.Milliseconds(),
146 EvalMS: r.eval.Milliseconds(),
147 }
148 if t.Satisfied == "" {
149 t.Satisfied = satisfiedUnknown
150 }
151 log.append(t)
152 if r.err != nil {
153 fmt.Fprintln(timingStdout(), timingLine(t, r.took))
154 errs = append(errs, r.err)
155 return
156 }
157 fmt.Printf("check %-24s %-8s %s\n", r.out.spec.name, r.out.spec.runner(), result)
158 fmt.Fprintln(timingStdout(), timingLine(t, r.took))
159 outcomes = append(outcomes, r.out)
160 }
161 for _, r := range runPure(tree, *system, pure, *timings) {
162 report(r)
163 }
164 for _, spec := range effectful {
165 began := time.Now()
166 out := runEffectful(tree, spec)
167 report(ranCheck{out: out, began: began, took: time.Since(began)})
168 }
169 if failed > 0 {
170 for _, out := range outcomes {
171 if !out.passed && out.log != "" {
172 fmt.Fprintf(os.Stderr, "\n--- %s ---\n%s\n", out.spec.name, out.log)
173 }
174 }
175 }
176 if len(errs) > 0 {
177 return errors.Join(errs...)
178 }
179 if failed > 0 {
180 return fmt.Errorf("%d of %d checks failed; nothing published", failed, len(specs))
181 }
182
183 // Compose, validate, render. Every statement is vetted before any of
184 // them is written out, so a malformed one cannot leave a half-signed
185 // set behind. The schema is the gate and it reads JSON; the text is
186 // what a signature covers, and it carries exactly what the JSON does.
187 texts := make([][]byte, len(outcomes))
188 for i, out := range outcomes {
189 st := composeStatement(subj, out, *environment, prov)
190 doc, err := json.Marshal(st)
191 if err != nil {
192 return err
193 }
194 if err := vetStatement(schema, doc); err != nil {
195 return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err)
196 }
197 if texts[i], err = renderJSON(doc); err != nil {
198 return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err)
199 }
200 }
201
202 subtrees := map[string]string{}
203 for i, out := range outcomes {
204 note, err := signNote(texts[i], host)
205 if err != nil {
206 return err
207 }
208 noteBlob, err := writeBlob(root, note)
209 if err != nil {
210 return err
211 }
212 sub, err := mkTree(root, map[string]string{"statement.note": noteBlob}, nil)
213 if err != nil {
214 return err
215 }
216 subtrees[out.spec.name] = sub
217 }
218 top, err := mkTree(root, nil, subtrees)
219 if err != nil {
220 return err
221 }
222 ref := attestationRef(subj.Digest[subj.Primary], fmt.Sprintf("%08x", host.hash))
223 if _, err := git(root, "update-ref", ref, top); err != nil {
224 return err
225 }
226 fmt.Printf("stored %s -> %s\n", ref, top)
227
228 if *push == "" {
229 return nil
230 }
231 head := *branch
232 if head == "" {
233 head, err = gitLine(root, "symbolic-ref", "--short", "HEAD")
234 if err != nil {
235 return fmt.Errorf("no branch to push: %w", err)
236 }
237 }
238 head = strings.TrimPrefix(head, "refs/heads/")
239 branchSpec := fmt.Sprintf("refs/heads/%s:refs/heads/%s", head, head)
240 refSpec := ref + ":" + ref
241 out, err := gitPush(root, "--atomic", *push, branchSpec, refSpec)
242 if err != nil {
243 return err
244 }
245 fmt.Printf("pushed %s --atomic %s %s\n%s", *push, branchSpec, refSpec, out)
246 return nil
247}
248
249// composeSubject builds the digest set: the content-addressed tree digest
250// as the member that IS the identity, and the commit as an advisory member
251// for finding the change.
252func composeSubject(root, rev string) (subject, error) {
253 entries, err := gitTreeEntries(root, rev)
254 if err != nil {
255 return subject{}, err
256 }
257 commit, err := gitLine(root, "rev-parse", rev+"^{commit}")
258 if err != nil {
259 return subject{}, err
260 }
261 subj := subject{Primary: treeScheme, Digest: map[string]string{treeScheme: treeDigest(entries)}}
262 switch len(commit) {
263 case 40:
264 subj.Digest["git-sha1"] = commit
265 case 64:
266 subj.Digest["git-sha256"] = commit
267 default:
268 return subject{}, fmt.Errorf("unexpected object id %q", commit)
269 }
270 return subj, nil
271}
272
273func composeStatement(subj subject, out checkOutcome, environment string, prov json.RawMessage) statement {
274 result := "failed"
275 if out.passed {
276 result = "passed"
277 }
278 st := statement{
279 StatementType: statementType,
280 Subject: subj,
281 Provenance: prov,
282 Predicate: predicate{
283 Check: checkRun{
284 Name: out.spec.name,
285 Runner: out.spec.runner(),
286 Attribute: out.spec.attribute,
287 Command: out.spec.command,
288 },
289 Result: result,
290 },
291 }
292 if out.spec.runner() == "nix" {
293 st.PredicateType = predicatePure
294 st.Predicate.Inputs = map[string]string{inputsScheme: out.inputs}
295 st.Predicate.Derivation = map[string]string{"sha256": out.derivation}
296 st.Predicate.Output = map[string]string{treeScheme: out.output}
297 } else {
298 st.PredicateType = predicateEffect
299 st.Predicate.Environment = environment
300 st.Predicate.ObservedAt = out.observedAt
301 }
302 return st
303}
304
305// checkSpecs resolves what to run. Naming no check means the repo's whole
306// canonical set: every check the flake defines for this system.
307func checkSpecs(tree, system string, checks, commands repeatable) ([]checkSpec, error) {
308 var specs []checkSpec
309 for _, c := range checks {
310 name, attr, found := strings.Cut(c, "=")
311 if !found {
312 attr = name
313 }
314 specs = append(specs, checkSpec{name: name, attribute: attr})
315 }
316 for _, c := range commands {
317 name, command, found := strings.Cut(c, "=")
318 if !found {
319 return nil, fmt.Errorf("--command %q: expected NAME=COMMAND", c)
320 }
321 specs = append(specs, checkSpec{name: name, command: command})
322 }
323 if len(specs) > 0 {
324 return specs, nil
325 }
326 names, err := flakeChecks(tree, system)
327 if err != nil {
328 return nil, err
329 }
330 for _, n := range names {
331 specs = append(specs, checkSpec{name: n, attribute: n})
332 }
333 return specs, nil
334}
335
336func sortedKeys(m map[string]string) []string {
337 keys := make([]string, 0, len(m))
338 for k := range m {
339 keys = append(keys, k)
340 }
341 sort.Strings(keys)
342 return keys
343}