| 1 | package main |
| 2 | |
| 3 | // What the integrator writes down when a change lands. |
| 4 | // |
| 5 | // Two things, side by side in one attestation ref per subject |
| 6 | // (dcr-439b771). The contributor's original notes gain the integrator's |
| 7 | // signature as sibling lines under the text they already carry — several |
| 8 | // parties attesting to one statement, which is the composition |
| 9 | // dcr-0de694f already provides. And the integrator's own transfer |
| 10 | // statement records what it decided: the change, the stream, the base the |
| 11 | // evidence was produced over, the policy the verdict was derived under, and |
| 12 | // the per-check verdicts. |
| 13 | // |
| 14 | // The two are separate statements because they are about different trees. |
| 15 | // A contributor's statement is about the tree it was produced over; the |
| 16 | // transfer statement is about the tree that landed. When nothing |
| 17 | // intervened those are the same tree and the two notes share one ref. |
| 18 | // |
| 19 | // One tree can land more than once, as when a change lands and a later |
| 20 | // change reverts its revert. An attestation ref can therefore hold several |
| 21 | // transfer statements. Each statement is stored under the commit it |
| 22 | // records landing, at change.TransferPath. Storing a landing adds its notes |
| 23 | // to the ref and keeps every note already there that it does not |
| 24 | // overwrite: other landings' statements, and every other path. |
| 25 | |
| 26 | import ( |
| 27 | "the-valley/change" |
| 28 | "the-valley/integrator/verdict" |
| 29 | |
| 30 | "encoding/json" |
| 31 | "fmt" |
| 32 | "os" |
| 33 | "os/exec" |
| 34 | "path/filepath" |
| 35 | "sort" |
| 36 | "strconv" |
| 37 | "strings" |
| 38 | ) |
| 39 | |
| 40 | // landedEvidence is the note set the integrator stores for a landing. |
| 41 | type landedEvidence struct { |
| 42 | // refs maps a ref name to the blobs beneath it, keyed by their path. |
| 43 | refs map[string]map[string]string |
| 44 | } |
| 45 | |
| 46 | // composeTransfer builds the transfer statement, vets it against the |
| 47 | // attestation schema, renders it as the bytes a signature covers, and signs |
| 48 | // it. Nothing is stored before the schema passes: a statement no verifier |
| 49 | // could read is not a thing to publish. |
| 50 | func (in *integrator) composeTransfer(ch verdict.Change, v verdict.Verdict, landedTree, landedCommit, tip, policyDigest string) ([]byte, error) { |
| 51 | type digestSet map[string]string |
| 52 | type checkTransfer struct { |
| 53 | Name string `json:"name"` |
| 54 | Rule string `json:"rule"` |
| 55 | Evidence digestSet `json:"evidence"` |
| 56 | Inputs digestSet `json:"inputs,omitempty"` |
| 57 | } |
| 58 | checks := make([]checkTransfer, 0, len(v.Checks)) |
| 59 | for _, cv := range v.Checks { |
| 60 | entry := checkTransfer{Name: cv.Name, Rule: cv.Rule, Evidence: digestSet{"sha256": cv.Evidence}} |
| 61 | if cv.Inputs != "" { |
| 62 | entry.Inputs = digestSet{"valley-inputs-v1": cv.Inputs} |
| 63 | } |
| 64 | checks = append(checks, entry) |
| 65 | } |
| 66 | predicate := map[string]any{ |
| 67 | "change": ch.ID, |
| 68 | "target": ch.Target, |
| 69 | "base": digestSet{"valley-tree-v1": ch.Attested}, |
| 70 | "policy": digestSet{"sha256": policyDigest, "git-sha1": tip}, |
| 71 | } |
| 72 | // A policy that required nothing of this diff says so, rather than |
| 73 | // carrying a list with nothing in it. An empty array has no lines and |
| 74 | // so no written form (dcr-de9d996), so a statement composed that way |
| 75 | // could be vetted and never signed — which is how a landing with no |
| 76 | // required checks used to strand. The zero case is an ordinary |
| 77 | // outcome, so it gets an ordinary line. |
| 78 | if len(checks) == 0 { |
| 79 | predicate["required"] = "none" |
| 80 | } else { |
| 81 | predicate["checks"] = checks |
| 82 | } |
| 83 | doc := map[string]any{ |
| 84 | "statementType": "the-valley/attestation/v1", |
| 85 | "subject": map[string]any{ |
| 86 | "primary": "valley-tree-v1", |
| 87 | "digest": digestSet{"valley-tree-v1": landedTree, "git-sha1": landedCommit}, |
| 88 | }, |
| 89 | "predicateType": predicateTransfer, |
| 90 | "predicate": predicate, |
| 91 | } |
| 92 | raw, err := json.Marshal(doc) |
| 93 | if err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | if err := in.vet(raw); err != nil { |
| 97 | return nil, err |
| 98 | } |
| 99 | text, err := in.pipe(raw, in.attest, "render") |
| 100 | if err != nil { |
| 101 | return nil, fmt.Errorf("rendering the transfer statement: %w", err) |
| 102 | } |
| 103 | return in.sign(text) |
| 104 | } |
| 105 | |
| 106 | // vet holds a composed statement to schema/attestation.cue before it is |
| 107 | // rendered or signed, exactly as attest holds its own. |
| 108 | func (in *integrator) vet(doc []byte) error { |
| 109 | dir, err := scratch("valley-integrator-vet") |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | defer os.RemoveAll(dir) |
| 114 | if err := os.WriteFile(filepath.Join(dir, "statement.json"), doc, 0o644); err != nil { |
| 115 | return err |
| 116 | } |
| 117 | cmd := exec.Command(in.cue, "vet", "-c", in.attestSchema, "statement.json") |
| 118 | cmd.Dir = dir |
| 119 | if out, err := cmd.CombinedOutput(); err != nil { |
| 120 | return fmt.Errorf("the transfer statement does not satisfy %s:\n%s", in.attestSchema, strings.TrimSpace(string(out))) |
| 121 | } |
| 122 | return nil |
| 123 | } |
| 124 | |
| 125 | // sign turns statement text into a note, or adds the integrator's |
| 126 | // signature to a note that already carries one. `attest sign` decides which |
| 127 | // from the input, so both cases are the same call. |
| 128 | func (in *integrator) sign(document []byte) ([]byte, error) { |
| 129 | return in.pipe(document, in.attest, "sign", "--key", in.key, "--name", in.signerName) |
| 130 | } |
| 131 | |
| 132 | func (in *integrator) pipe(stdin []byte, name string, args ...string) ([]byte, error) { |
| 133 | cmd := exec.Command(name, args...) |
| 134 | cmd.Stdin = strings.NewReader(string(stdin)) |
| 135 | var errb strings.Builder |
| 136 | cmd.Stderr = &errb |
| 137 | out, err := cmd.Output() |
| 138 | if err != nil { |
| 139 | return nil, fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(errb.String())) |
| 140 | } |
| 141 | return out, nil |
| 142 | } |
| 143 | |
| 144 | // countersign builds the note set a landing stores: every transferring |
| 145 | // check's note with the integrator's sibling signature added, keyed by the |
| 146 | // subject it is about, plus the transfer statement keyed by the landed tree |
| 147 | // and the commit it landed as. |
| 148 | func (in *integrator) countersign(ch verdict.Change, v verdict.Verdict, l landing, transfer []byte) (landedEvidence, error) { |
| 149 | out := landedEvidence{refs: map[string]map[string]string{}} |
| 150 | add := func(ref, path string, content []byte) error { |
| 151 | blob, err := in.writeBlob(content) |
| 152 | if err != nil { |
| 153 | return err |
| 154 | } |
| 155 | if out.refs[ref] == nil { |
| 156 | out.refs[ref] = map[string]string{} |
| 157 | } |
| 158 | out.refs[ref][path] = blob |
| 159 | return nil |
| 160 | } |
| 161 | original := fmt.Sprintf("%s/%s/%s", attestationPrefix, ch.Attested, in.keyHash) |
| 162 | for _, cv := range v.Checks { |
| 163 | note, ok := l.notes[cv.Name] |
| 164 | if !ok || !cv.Transferred { |
| 165 | continue |
| 166 | } |
| 167 | signed, err := in.sign(note) |
| 168 | if err != nil { |
| 169 | return out, fmt.Errorf("countersigning %s: %w", cv.Name, err) |
| 170 | } |
| 171 | if err := add(original, cv.Name+"/"+statementNote, signed); err != nil { |
| 172 | return out, err |
| 173 | } |
| 174 | } |
| 175 | landed := fmt.Sprintf("%s/%s/%s", attestationPrefix, l.digest, in.keyHash) |
| 176 | // A check's name never holds a dot, so no check's directory is named |
| 177 | // change.TransferDir. |
| 178 | if err := add(landed, change.TransferPath(l.commit), transfer); err != nil { |
| 179 | return out, err |
| 180 | } |
| 181 | return out, nil |
| 182 | } |
| 183 | |
| 184 | // evidenceUpdates builds the tree each ref of the note set moves to, and |
| 185 | // returns the ref updates in the order of the refs' names. Nothing is |
| 186 | // written to a ref here: the updates go into the landing's one ref |
| 187 | // transaction (refs.go). A ref that exists keeps every note this landing |
| 188 | // does not overwrite, so an earlier landing's transfer statement stays in |
| 189 | // place. Each update names the value the ref was read at, so a note |
| 190 | // written to the ref since is never dropped: the transaction fails, and is |
| 191 | // built again from what the ref holds then. |
| 192 | // |
| 193 | // A tree's value is a function of the notes beneath it and nothing else. |
| 194 | // A tree the push hook would refuse to read is not written, and nothing |
| 195 | // lands. |
| 196 | func (in *integrator) evidenceUpdates(e landedEvidence, zero string) ([]refUpdate, error) { |
| 197 | var refs []string |
| 198 | for ref := range e.refs { |
| 199 | refs = append(refs, ref) |
| 200 | } |
| 201 | sort.Strings(refs) |
| 202 | var updates []refUpdate |
| 203 | for _, ref := range refs { |
| 204 | old, found, err := resolveRef(in.repo, ref) |
| 205 | if err != nil { |
| 206 | return nil, err |
| 207 | } |
| 208 | blobs := map[string]string{} |
| 209 | if found { |
| 210 | if blobs, err = in.readNotes(old); err != nil { |
| 211 | return nil, err |
| 212 | } |
| 213 | } else { |
| 214 | old = zero |
| 215 | } |
| 216 | for path, blob := range e.refs[ref] { |
| 217 | blobs[path] = blob |
| 218 | } |
| 219 | sizes, err := in.blobSizes(blobs) |
| 220 | if err != nil { |
| 221 | return nil, err |
| 222 | } |
| 223 | if err := hookReadable(blobs, sizes, len(zero)/2); err != nil { |
| 224 | return nil, fmt.Errorf("the evidence for %s cannot be stored: %w", ref, err) |
| 225 | } |
| 226 | top, err := in.writeTree(blobs) |
| 227 | if err != nil { |
| 228 | return nil, err |
| 229 | } |
| 230 | updates = append(updates, refUpdate{ref: ref, new: top, old: old}) |
| 231 | } |
| 232 | return updates, nil |
| 233 | } |
| 234 | |
| 235 | // hookReadable refuses a note set whose tree the push hook would refuse |
| 236 | // to read: a tree past change.AttestationDepth or any bound beside it. |
| 237 | // It counts what the hook's walk reads. Every entry of every tree counts, |
| 238 | // a directory's own entry in its parent included. A tree object's bytes |
| 239 | // are its entries as git stores them: the mode, a space, the name, a NUL |
| 240 | // and the raw object ID, hashSize bytes long. Every note counts once for |
| 241 | // each path it sits at. sizes holds each blob's size in bytes. |
| 242 | func hookReadable(blobs map[string]string, sizes map[string]int, hashSize int) error { |
| 243 | paths := make([]string, 0, len(blobs)) |
| 244 | for path := range blobs { |
| 245 | paths = append(paths, path) |
| 246 | } |
| 247 | sort.Strings(paths) |
| 248 | read := 0 // bytes the walk reads |
| 249 | entries := map[string]map[string]bool{} // a directory's path → its names, each true for a tree |
| 250 | for _, path := range paths { |
| 251 | segments := strings.Split(path, "/") |
| 252 | if len(segments) > change.AttestationDepth { |
| 253 | return fmt.Errorf("%s would nest trees deeper than the %d the push hook reads", path, change.AttestationDepth) |
| 254 | } |
| 255 | size := sizes[blobs[path]] |
| 256 | if size > change.AttestationNoteBytes { |
| 257 | return fmt.Errorf("the note at %s would be %d bytes, and the push hook reads at most %d in one note", path, size, change.AttestationNoteBytes) |
| 258 | } |
| 259 | read += size |
| 260 | dir := "" |
| 261 | for i, name := range segments { |
| 262 | if entries[dir] == nil { |
| 263 | entries[dir] = map[string]bool{} |
| 264 | } |
| 265 | entries[dir][name] = i < len(segments)-1 |
| 266 | dir = strings.TrimPrefix(dir+"/"+name, "/") |
| 267 | } |
| 268 | } |
| 269 | dirs := make([]string, 0, len(entries)) |
| 270 | for dir := range entries { |
| 271 | dirs = append(dirs, dir) |
| 272 | } |
| 273 | sort.Strings(dirs) |
| 274 | total := 0 |
| 275 | for _, dir := range dirs { |
| 276 | names := entries[dir] |
| 277 | where := dir |
| 278 | if where == "" { |
| 279 | where = "the top of the tree" |
| 280 | } |
| 281 | if len(names) > change.AttestationTreeEntries { |
| 282 | return fmt.Errorf("%s would hold %d entries, and the push hook reads at most %d in one tree", where, len(names), change.AttestationTreeEntries) |
| 283 | } |
| 284 | total += len(names) |
| 285 | size := 0 |
| 286 | for name, tree := range names { |
| 287 | mode := "100644" |
| 288 | if tree { |
| 289 | mode = "40000" |
| 290 | } |
| 291 | size += len(mode) + 1 + len(name) + 1 + hashSize |
| 292 | } |
| 293 | if size > change.AttestationTreeBytes { |
| 294 | return fmt.Errorf("%s would be a tree of %d bytes, and the push hook reads at most %d in one tree", where, size, change.AttestationTreeBytes) |
| 295 | } |
| 296 | read += size |
| 297 | } |
| 298 | if total > change.AttestationEntries { |
| 299 | return fmt.Errorf("its trees would hold %d entries, and the push hook reads at most %d in all", total, change.AttestationEntries) |
| 300 | } |
| 301 | if read > change.AttestationBytes { |
| 302 | return fmt.Errorf("its trees and notes would come to %d bytes, and the push hook reads at most %d in all", read, change.AttestationBytes) |
| 303 | } |
| 304 | return nil |
| 305 | } |
| 306 | |
| 307 | // blobSizes asks git, in one call, for the size in bytes of each blob |
| 308 | // blobs names. |
| 309 | func (in *integrator) blobSizes(blobs map[string]string) (map[string]int, error) { |
| 310 | sizes := map[string]int{} |
| 311 | var ids []string |
| 312 | for _, id := range blobs { |
| 313 | if _, seen := sizes[id]; !seen { |
| 314 | sizes[id] = -1 |
| 315 | ids = append(ids, id) |
| 316 | } |
| 317 | } |
| 318 | if len(ids) == 0 { |
| 319 | return sizes, nil |
| 320 | } |
| 321 | out, err := gitInput(in.repo, []byte(strings.Join(ids, "\n")+"\n"), |
| 322 | "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)") |
| 323 | if err != nil { |
| 324 | return nil, fmt.Errorf("sizing the notes: %w", err) |
| 325 | } |
| 326 | for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| 327 | fields := strings.Fields(line) |
| 328 | if len(fields) != 3 || fields[1] != "blob" { |
| 329 | return nil, fmt.Errorf("sizing the notes: git answered %q", line) |
| 330 | } |
| 331 | size, err := strconv.Atoi(fields[2]) |
| 332 | if err != nil { |
| 333 | return nil, fmt.Errorf("sizing the notes: git answered %q", line) |
| 334 | } |
| 335 | sizes[fields[0]] = size |
| 336 | } |
| 337 | for _, id := range ids { |
| 338 | if sizes[id] < 0 { |
| 339 | return nil, fmt.Errorf("sizing the notes: git gave no size for %s", id) |
| 340 | } |
| 341 | } |
| 342 | return sizes, nil |
| 343 | } |
| 344 | |
| 345 | // readNotes lists the note blobs beneath an attestation ref's tree, keyed |
| 346 | // by their path. |
| 347 | func (in *integrator) readNotes(tree string) (map[string]string, error) { |
| 348 | out, err := git(in.repo, "ls-tree", "-r", "-z", tree) |
| 349 | if err != nil { |
| 350 | return nil, err |
| 351 | } |
| 352 | blobs := map[string]string{} |
| 353 | for _, entry := range strings.Split(out, "\x00") { |
| 354 | meta, path, ok := strings.Cut(entry, "\t") |
| 355 | if fields := strings.Fields(meta); ok && len(fields) == 3 && fields[1] == "blob" { |
| 356 | blobs[path] = fields[2] |
| 357 | } |
| 358 | } |
| 359 | return blobs, nil |
| 360 | } |
| 361 | |
| 362 | func (in *integrator) writeBlob(content []byte) (string, error) { |
| 363 | cmd := exec.Command("git", "hash-object", "-w", "--stdin") |
| 364 | cmd.Dir = in.repo |
| 365 | cmd.Stdin = strings.NewReader(string(content)) |
| 366 | out, err := cmd.Output() |
| 367 | if err != nil { |
| 368 | return "", fmt.Errorf("storing a note: %w", err) |
| 369 | } |
| 370 | return strings.TrimSpace(string(out)), nil |
| 371 | } |
| 372 | |
| 373 | // writeTree builds a tree from paths to blob ids, creating a subtree per |
| 374 | // path segment. Paths here are at most change.AttestationDepth segments |
| 375 | // deep — "<check>/statement.note", "transfer.d/<2 hex>/<2 hex>/<rest>.note", |
| 376 | // and in a ref written before statements were kept per landing, |
| 377 | // "transfer.note" — so the recursion is shallow by construction. |
| 378 | func (in *integrator) writeTree(blobs map[string]string) (string, error) { |
| 379 | here := map[string]string{} |
| 380 | under := map[string]map[string]string{} |
| 381 | for path, blob := range blobs { |
| 382 | dir, rest, nested := strings.Cut(path, "/") |
| 383 | if !nested { |
| 384 | here[path] = blob |
| 385 | continue |
| 386 | } |
| 387 | if under[dir] == nil { |
| 388 | under[dir] = map[string]string{} |
| 389 | } |
| 390 | under[dir][rest] = blob |
| 391 | } |
| 392 | var lines []string |
| 393 | for name, blob := range here { |
| 394 | lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", blob, name)) |
| 395 | } |
| 396 | for name, sub := range under { |
| 397 | oid, err := in.writeTree(sub) |
| 398 | if err != nil { |
| 399 | return "", err |
| 400 | } |
| 401 | lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name)) |
| 402 | } |
| 403 | sort.Strings(lines) |
| 404 | cmd := exec.Command("git", "mktree") |
| 405 | cmd.Dir = in.repo |
| 406 | cmd.Stdin = strings.NewReader(strings.Join(lines, "\n") + "\n") |
| 407 | out, err := cmd.Output() |
| 408 | if err != nil { |
| 409 | return "", fmt.Errorf("building an attestation tree: %w", err) |
| 410 | } |
| 411 | return strings.TrimSpace(string(out)), nil |
| 412 | } |