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