gunk-dev/the-valley

transfer.go

sourceca98fdc29fbfmain's published tip history
14.4 KiB
1package 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
26import (
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.
41type 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.
50func (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.
108func (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.
128func (in *integrator) sign(document []byte) ([]byte, error) {
129 return in.pipe(document, in.attest, "sign", "--key", in.key, "--name", in.signerName)
130}
131
132func (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 (the change's tree, or the landing tree for evidence
147// stored for that tree), plus the transfer statement keyed by the landed tree
148// and the commit it landed as.
149func (in *integrator) countersign(ch verdict.Change, v verdict.Verdict, l landing, transfer []byte) (landedEvidence, error) {
150 out := landedEvidence{refs: map[string]map[string]string{}}
151 add := func(ref, path string, content []byte) error {
152 blob, err := in.writeBlob(content)
153 if err != nil {
154 return err
155 }
156 if out.refs[ref] == nil {
157 out.refs[ref] = map[string]string{}
158 }
159 out.refs[ref][path] = blob
160 return nil
161 }
162 original := fmt.Sprintf("%s/%s/%s", attestationPrefix, ch.Attested, in.keyHash)
163 landed := fmt.Sprintf("%s/%s/%s", attestationPrefix, l.digest, in.keyHash)
164 for _, cv := range v.Checks {
165 // A check that stood on the landing tree's own evidence is
166 // countersigned under the landing tree, beside the transfer
167 // statement that cites it.
168 notes, ref := l.notes, original
169 if cv.Direct {
170 notes, ref = l.direct, landed
171 }
172 note, ok := notes[cv.Name]
173 if !ok || !cv.Transferred {
174 continue
175 }
176 signed, err := in.sign(note)
177 if err != nil {
178 return out, fmt.Errorf("countersigning %s: %w", cv.Name, err)
179 }
180 if err := add(ref, cv.Name+"/"+statementNote, signed); err != nil {
181 return out, err
182 }
183 }
184 // A check's name never holds a dot, so no check's directory is named
185 // change.TransferDir.
186 if err := add(landed, change.TransferPath(l.commit), transfer); err != nil {
187 return out, err
188 }
189 return out, nil
190}
191
192// evidenceUpdates builds the tree each ref of the note set moves to, and
193// returns the ref updates in the order of the refs' names. Nothing is
194// written to a ref here: the updates go into the landing's one ref
195// transaction (refs.go). A ref that exists keeps every note this landing
196// does not overwrite, so an earlier landing's transfer statement stays in
197// place. Each update names the value the ref was read at, so a note
198// written to the ref since is never dropped: the transaction fails, and is
199// built again from what the ref holds then.
200//
201// A tree's value is a function of the notes beneath it and nothing else.
202// A tree the push hook would refuse to read is not written, and nothing
203// lands.
204func (in *integrator) evidenceUpdates(e landedEvidence, zero string) ([]refUpdate, error) {
205 var refs []string
206 for ref := range e.refs {
207 refs = append(refs, ref)
208 }
209 sort.Strings(refs)
210 var updates []refUpdate
211 for _, ref := range refs {
212 old, found, err := resolveRef(in.repo, ref)
213 if err != nil {
214 return nil, err
215 }
216 blobs := map[string]string{}
217 if found {
218 if blobs, err = in.readNotes(old); err != nil {
219 return nil, err
220 }
221 } else {
222 old = zero
223 }
224 for path, blob := range e.refs[ref] {
225 blobs[path] = blob
226 }
227 sizes, err := in.blobSizes(blobs)
228 if err != nil {
229 return nil, err
230 }
231 if err := hookReadable(blobs, sizes, len(zero)/2); err != nil {
232 return nil, fmt.Errorf("the evidence for %s cannot be stored: %w", ref, err)
233 }
234 top, err := in.writeTree(blobs)
235 if err != nil {
236 return nil, err
237 }
238 updates = append(updates, refUpdate{ref: ref, new: top, old: old})
239 }
240 return updates, nil
241}
242
243// hookReadable refuses a note set whose tree the push hook would refuse
244// to read: a tree past change.AttestationDepth or any bound beside it.
245// It counts what the hook's walk reads. Every entry of every tree counts,
246// a directory's own entry in its parent included. A tree object's bytes
247// are its entries as git stores them: the mode, a space, the name, a NUL
248// and the raw object ID, hashSize bytes long. Every note counts once for
249// each path it sits at. sizes holds each blob's size in bytes.
250func hookReadable(blobs map[string]string, sizes map[string]int, hashSize int) error {
251 paths := make([]string, 0, len(blobs))
252 for path := range blobs {
253 paths = append(paths, path)
254 }
255 sort.Strings(paths)
256 read := 0 // bytes the walk reads
257 entries := map[string]map[string]bool{} // a directory's path → its names, each true for a tree
258 for _, path := range paths {
259 segments := strings.Split(path, "/")
260 if len(segments) > change.AttestationDepth {
261 return fmt.Errorf("%s would nest trees deeper than the %d the push hook reads", path, change.AttestationDepth)
262 }
263 size := sizes[blobs[path]]
264 if size > change.AttestationNoteBytes {
265 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)
266 }
267 read += size
268 dir := ""
269 for i, name := range segments {
270 if entries[dir] == nil {
271 entries[dir] = map[string]bool{}
272 }
273 entries[dir][name] = i < len(segments)-1
274 dir = strings.TrimPrefix(dir+"/"+name, "/")
275 }
276 }
277 dirs := make([]string, 0, len(entries))
278 for dir := range entries {
279 dirs = append(dirs, dir)
280 }
281 sort.Strings(dirs)
282 total := 0
283 for _, dir := range dirs {
284 names := entries[dir]
285 where := dir
286 if where == "" {
287 where = "the top of the tree"
288 }
289 if len(names) > change.AttestationTreeEntries {
290 return fmt.Errorf("%s would hold %d entries, and the push hook reads at most %d in one tree", where, len(names), change.AttestationTreeEntries)
291 }
292 total += len(names)
293 size := 0
294 for name, tree := range names {
295 mode := "100644"
296 if tree {
297 mode = "40000"
298 }
299 size += len(mode) + 1 + len(name) + 1 + hashSize
300 }
301 if size > change.AttestationTreeBytes {
302 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)
303 }
304 read += size
305 }
306 if total > change.AttestationEntries {
307 return fmt.Errorf("its trees would hold %d entries, and the push hook reads at most %d in all", total, change.AttestationEntries)
308 }
309 if read > change.AttestationBytes {
310 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)
311 }
312 return nil
313}
314
315// blobSizes asks git, in one call, for the size in bytes of each blob
316// blobs names.
317func (in *integrator) blobSizes(blobs map[string]string) (map[string]int, error) {
318 sizes := map[string]int{}
319 var ids []string
320 for _, id := range blobs {
321 if _, seen := sizes[id]; !seen {
322 sizes[id] = -1
323 ids = append(ids, id)
324 }
325 }
326 if len(ids) == 0 {
327 return sizes, nil
328 }
329 out, err := gitInput(in.repo, []byte(strings.Join(ids, "\n")+"\n"),
330 "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)")
331 if err != nil {
332 return nil, fmt.Errorf("sizing the notes: %w", err)
333 }
334 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
335 fields := strings.Fields(line)
336 if len(fields) != 3 || fields[1] != "blob" {
337 return nil, fmt.Errorf("sizing the notes: git answered %q", line)
338 }
339 size, err := strconv.Atoi(fields[2])
340 if err != nil {
341 return nil, fmt.Errorf("sizing the notes: git answered %q", line)
342 }
343 sizes[fields[0]] = size
344 }
345 for _, id := range ids {
346 if sizes[id] < 0 {
347 return nil, fmt.Errorf("sizing the notes: git gave no size for %s", id)
348 }
349 }
350 return sizes, nil
351}
352
353// readNotes lists the note blobs beneath an attestation ref's tree, keyed
354// by their path.
355func (in *integrator) readNotes(tree string) (map[string]string, error) {
356 out, err := git(in.repo, "ls-tree", "-r", "-z", tree)
357 if err != nil {
358 return nil, err
359 }
360 blobs := map[string]string{}
361 for _, entry := range strings.Split(out, "\x00") {
362 meta, path, ok := strings.Cut(entry, "\t")
363 if fields := strings.Fields(meta); ok && len(fields) == 3 && fields[1] == "blob" {
364 blobs[path] = fields[2]
365 }
366 }
367 return blobs, nil
368}
369
370func (in *integrator) writeBlob(content []byte) (string, error) {
371 cmd := exec.Command("git", "hash-object", "-w", "--stdin")
372 cmd.Dir = in.repo
373 cmd.Stdin = strings.NewReader(string(content))
374 out, err := cmd.Output()
375 if err != nil {
376 return "", fmt.Errorf("storing a note: %w", err)
377 }
378 return strings.TrimSpace(string(out)), nil
379}
380
381// writeTree builds a tree from paths to blob ids, creating a subtree per
382// path segment. Paths here are at most change.AttestationDepth segments
383// deep — "<check>/statement.note", "transfer.d/<2 hex>/<2 hex>/<rest>.note",
384// and in a ref written before statements were kept per landing,
385// "transfer.note" — so the recursion is shallow by construction.
386func (in *integrator) writeTree(blobs map[string]string) (string, error) {
387 here := map[string]string{}
388 under := map[string]map[string]string{}
389 for path, blob := range blobs {
390 dir, rest, nested := strings.Cut(path, "/")
391 if !nested {
392 here[path] = blob
393 continue
394 }
395 if under[dir] == nil {
396 under[dir] = map[string]string{}
397 }
398 under[dir][rest] = blob
399 }
400 var lines []string
401 for name, blob := range here {
402 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", blob, name))
403 }
404 for name, sub := range under {
405 oid, err := in.writeTree(sub)
406 if err != nil {
407 return "", err
408 }
409 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
410 }
411 sort.Strings(lines)
412 cmd := exec.Command("git", "mktree")
413 cmd.Dir = in.repo
414 cmd.Stdin = strings.NewReader(strings.Join(lines, "\n") + "\n")
415 out, err := cmd.Output()
416 if err != nil {
417 return "", fmt.Errorf("building an attestation tree: %w", err)
418 }
419 return strings.TrimSpace(string(out)), nil
420}