gunk-dev/the-valley

run.go

source457af037be53main's published tip history
7.6 KiB
1package main
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "sort"
8 "strings"
9)
10
11// cmdRun is the whole protocol in order: digest the subject tree, run the
12// checks, compose a statement per check, vet each against the schema,
13// write each out and sign it as a note, store the notes at one ref keyed
14// by the subject digest, and publish with a single atomic push. Any step
15// failing stops the run before the next — a failed check publishes
16// nothing, and neither does a statement the schema rejects.
17func cmdRun(args []string) error {
18 fs := newFlagSet("run")
19 repo := fs.String("repo", "", "repository")
20 rev := fs.String("rev", "HEAD", "revision")
21 key := fs.String("key", "", "ed25519 private key")
22 name := fs.String("name", defaultSignerName(), "the name that key signs under")
23 environment := fs.String("environment", "local", "environment an effectful statement names")
24 provenanceFile := fs.String("provenance", "", "json run provenance")
25 schemaFlag := fs.String("schema", "", "attestation schema")
26 system := fs.String("system", nixSystem(), "flake system")
27 push := fs.String("push", "", "remote to publish to")
28 branch := fs.String("branch", "", "branch pushed alongside")
29 var checks, commands repeatable
30 fs.Var(&checks, "check", "flake check to run")
31 fs.Var(&commands, "command", "effectful check to run")
32 if err := fs.Parse(args); err != nil {
33 return err
34 }
35
36 root, err := repoRoot(*repo)
37 if err != nil {
38 return err
39 }
40 schema, err := schemaPath(*schemaFlag, root)
41 if err != nil {
42 return err
43 }
44 prov, err := loadProvenance(*provenanceFile)
45 if err != nil {
46 return err
47 }
48
49 // The signer is checked before any work is done: a run that can only
50 // end in "no key" should say so before it builds anything.
51 host, err := loadSigner(*key, *name)
52 if err != nil {
53 return err
54 }
55
56 subj, err := composeSubject(root, *rev)
57 if err != nil {
58 return err
59 }
60 fmt.Printf("subject %s:%s\n", subj.Primary, subj.Digest[subj.Primary])
61 for _, alg := range sortedKeys(subj.Digest) {
62 if alg != subj.Primary {
63 fmt.Printf(" %s:%s (advisory)\n", alg, subj.Digest[alg])
64 }
65 }
66 fmt.Printf("signer %s\n", host.verifierKey())
67
68 tree, err := os.MkdirTemp("", "valley-attest-tree")
69 if err != nil {
70 return err
71 }
72 defer os.RemoveAll(tree)
73 if err := exportTree(root, *rev, tree); err != nil {
74 return err
75 }
76
77 specs, err := checkSpecs(tree, *system, checks, commands)
78 if err != nil {
79 return err
80 }
81 if len(specs) == 0 {
82 return fmt.Errorf("no checks to run")
83 }
84
85 outcomes := make([]checkOutcome, 0, len(specs))
86 failed := 0
87 for _, spec := range specs {
88 var out checkOutcome
89 if spec.runner() == "nix" {
90 out, err = runPure(tree, *system, spec)
91 if err != nil {
92 return err
93 }
94 } else {
95 out = runEffectful(tree, spec)
96 }
97 result := "passed"
98 if !out.passed {
99 result = "failed"
100 failed++
101 }
102 fmt.Printf("check %-24s %-8s %s\n", spec.name, spec.runner(), result)
103 outcomes = append(outcomes, out)
104 }
105 if failed > 0 {
106 for _, out := range outcomes {
107 if !out.passed && out.log != "" {
108 fmt.Fprintf(os.Stderr, "\n--- %s ---\n%s\n", out.spec.name, out.log)
109 }
110 }
111 return fmt.Errorf("%d of %d checks failed; nothing published", failed, len(specs))
112 }
113
114 // Compose, validate, render. Every statement is vetted before any of
115 // them is written out, so a malformed one cannot leave a half-signed
116 // set behind. The schema is the gate and it reads JSON; the text is
117 // what a signature covers, and it carries exactly what the JSON does.
118 texts := make([][]byte, len(outcomes))
119 for i, out := range outcomes {
120 st := composeStatement(subj, out, *environment, prov)
121 doc, err := json.Marshal(st)
122 if err != nil {
123 return err
124 }
125 if err := vetStatement(schema, doc); err != nil {
126 return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err)
127 }
128 if texts[i], err = renderJSON(doc); err != nil {
129 return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err)
130 }
131 }
132
133 subtrees := map[string]string{}
134 for i, out := range outcomes {
135 note, err := signNote(texts[i], host)
136 if err != nil {
137 return err
138 }
139 noteBlob, err := writeBlob(root, note)
140 if err != nil {
141 return err
142 }
143 sub, err := mkTree(root, map[string]string{"statement.note": noteBlob}, nil)
144 if err != nil {
145 return err
146 }
147 subtrees[out.spec.name] = sub
148 }
149 top, err := mkTree(root, nil, subtrees)
150 if err != nil {
151 return err
152 }
153 ref := attestationRef(subj.Digest[subj.Primary], fmt.Sprintf("%08x", host.hash))
154 if _, err := git(root, "update-ref", ref, top); err != nil {
155 return err
156 }
157 fmt.Printf("stored %s -> %s\n", ref, top)
158
159 if *push == "" {
160 return nil
161 }
162 head := *branch
163 if head == "" {
164 head, err = gitLine(root, "symbolic-ref", "--short", "HEAD")
165 if err != nil {
166 return fmt.Errorf("no branch to push: %w", err)
167 }
168 }
169 head = strings.TrimPrefix(head, "refs/heads/")
170 branchSpec := fmt.Sprintf("refs/heads/%s:refs/heads/%s", head, head)
171 refSpec := ref + ":" + ref
172 out, err := gitPush(root, "--atomic", *push, branchSpec, refSpec)
173 if err != nil {
174 return err
175 }
176 fmt.Printf("pushed %s --atomic %s %s\n%s", *push, branchSpec, refSpec, out)
177 return nil
178}
179
180// composeSubject builds the digest set: the content-addressed tree digest
181// as the member that IS the identity, and the commit as an advisory member
182// for finding the change.
183func composeSubject(root, rev string) (subject, error) {
184 entries, err := gitTreeEntries(root, rev)
185 if err != nil {
186 return subject{}, err
187 }
188 commit, err := gitLine(root, "rev-parse", rev+"^{commit}")
189 if err != nil {
190 return subject{}, err
191 }
192 subj := subject{Primary: treeScheme, Digest: map[string]string{treeScheme: treeDigest(entries)}}
193 switch len(commit) {
194 case 40:
195 subj.Digest["git-sha1"] = commit
196 case 64:
197 subj.Digest["git-sha256"] = commit
198 default:
199 return subject{}, fmt.Errorf("unexpected object id %q", commit)
200 }
201 return subj, nil
202}
203
204func composeStatement(subj subject, out checkOutcome, environment string, prov json.RawMessage) statement {
205 result := "failed"
206 if out.passed {
207 result = "passed"
208 }
209 st := statement{
210 StatementType: statementType,
211 Subject: subj,
212 Provenance: prov,
213 Predicate: predicate{
214 Check: checkRun{
215 Name: out.spec.name,
216 Runner: out.spec.runner(),
217 Attribute: out.spec.attribute,
218 Command: out.spec.command,
219 },
220 Result: result,
221 },
222 }
223 if out.spec.runner() == "nix" {
224 st.PredicateType = predicatePure
225 st.Predicate.Inputs = map[string]string{inputsScheme: out.inputs}
226 st.Predicate.Derivation = map[string]string{"sha256": out.derivation}
227 st.Predicate.Output = map[string]string{treeScheme: out.output}
228 } else {
229 st.PredicateType = predicateEffect
230 st.Predicate.Environment = environment
231 st.Predicate.ObservedAt = out.observedAt
232 }
233 return st
234}
235
236// checkSpecs resolves what to run. Naming no check means the repo's whole
237// canonical set: every check the flake defines for this system.
238func checkSpecs(tree, system string, checks, commands repeatable) ([]checkSpec, error) {
239 var specs []checkSpec
240 for _, c := range checks {
241 name, attr, found := strings.Cut(c, "=")
242 if !found {
243 attr = name
244 }
245 specs = append(specs, checkSpec{name: name, attribute: attr})
246 }
247 for _, c := range commands {
248 name, command, found := strings.Cut(c, "=")
249 if !found {
250 return nil, fmt.Errorf("--command %q: expected NAME=COMMAND", c)
251 }
252 specs = append(specs, checkSpec{name: name, command: command})
253 }
254 if len(specs) > 0 {
255 return specs, nil
256 }
257 names, err := flakeChecks(tree, system)
258 if err != nil {
259 return nil, err
260 }
261 for _, n := range names {
262 specs = append(specs, checkSpec{name: n, attribute: n})
263 }
264 return specs, nil
265}
266
267func sortedKeys(m map[string]string) []string {
268 keys := make([]string, 0, len(m))
269 for k := range m {
270 keys = append(keys, k)
271 }
272 sort.Strings(keys)
273 return keys
274}