gunk-dev/the-valley

transfer.go

source4782e3b7d319main's published tip history
8.0 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
19import (
20 "the-valley/integrator/verdict"
21
22 "encoding/json"
23 "fmt"
24 "os"
25 "os/exec"
26 "path/filepath"
27 "sort"
28 "strings"
29)
30
31const transferNote = "transfer.note"
32
33// landedEvidence is the note set the integrator stores for a landing.
34type landedEvidence struct {
35 // refs maps a ref name to the blobs beneath it, keyed by their path.
36 refs map[string]map[string]string
37}
38
39// composeTransfer builds the transfer statement, vets it against the
40// attestation schema, renders it as the bytes a signature covers, and signs
41// it. Nothing is stored before the schema passes: a statement no verifier
42// could read is not a thing to publish.
43func (in *integrator) composeTransfer(ch verdict.Change, v verdict.Verdict, landedTree, landedCommit, tip, policyDigest string) ([]byte, error) {
44 type digestSet map[string]string
45 type checkTransfer struct {
46 Name string `json:"name"`
47 Rule string `json:"rule"`
48 Evidence digestSet `json:"evidence"`
49 Inputs digestSet `json:"inputs,omitempty"`
50 }
51 checks := make([]checkTransfer, 0, len(v.Checks))
52 for _, cv := range v.Checks {
53 entry := checkTransfer{Name: cv.Name, Rule: cv.Rule, Evidence: digestSet{"sha256": cv.Evidence}}
54 if cv.Inputs != "" {
55 entry.Inputs = digestSet{"valley-inputs-v1": cv.Inputs}
56 }
57 checks = append(checks, entry)
58 }
59 predicate := map[string]any{
60 "change": ch.ID,
61 "target": ch.Target,
62 "base": digestSet{"valley-tree-v1": ch.Attested},
63 "policy": digestSet{"sha256": policyDigest, "git-sha1": tip},
64 }
65 // A policy that required nothing of this diff says so, rather than
66 // carrying a list with nothing in it. An empty array has no lines and
67 // so no written form (dcr-de9d996), so a statement composed that way
68 // could be vetted and never signed — which is how a landing with no
69 // required checks used to strand. The zero case is an ordinary
70 // outcome, so it gets an ordinary line.
71 if len(checks) == 0 {
72 predicate["required"] = "none"
73 } else {
74 predicate["checks"] = checks
75 }
76 doc := map[string]any{
77 "statementType": "the-valley/attestation/v1",
78 "subject": map[string]any{
79 "primary": "valley-tree-v1",
80 "digest": digestSet{"valley-tree-v1": landedTree, "git-sha1": landedCommit},
81 },
82 "predicateType": predicateTransfer,
83 "predicate": predicate,
84 }
85 raw, err := json.Marshal(doc)
86 if err != nil {
87 return nil, err
88 }
89 if err := in.vet(raw); err != nil {
90 return nil, err
91 }
92 text, err := in.pipe(raw, in.attest, "render")
93 if err != nil {
94 return nil, fmt.Errorf("rendering the transfer statement: %w", err)
95 }
96 return in.sign(text)
97}
98
99// vet holds a composed statement to schema/attestation.cue before it is
100// rendered or signed, exactly as attest holds its own.
101func (in *integrator) vet(doc []byte) error {
102 dir, err := scratch("valley-integrator-vet")
103 if err != nil {
104 return err
105 }
106 defer os.RemoveAll(dir)
107 if err := os.WriteFile(filepath.Join(dir, "statement.json"), doc, 0o644); err != nil {
108 return err
109 }
110 cmd := exec.Command(in.cue, "vet", "-c", in.attestSchema, "statement.json")
111 cmd.Dir = dir
112 if out, err := cmd.CombinedOutput(); err != nil {
113 return fmt.Errorf("the transfer statement does not satisfy %s:\n%s", in.attestSchema, strings.TrimSpace(string(out)))
114 }
115 return nil
116}
117
118// sign turns statement text into a note, or adds the integrator's
119// signature to a note that already carries one. `attest sign` decides which
120// from the input, so both cases are the same call.
121func (in *integrator) sign(document []byte) ([]byte, error) {
122 return in.pipe(document, in.attest, "sign", "--key", in.key, "--name", in.signerName)
123}
124
125func (in *integrator) pipe(stdin []byte, name string, args ...string) ([]byte, error) {
126 cmd := exec.Command(name, args...)
127 cmd.Stdin = strings.NewReader(string(stdin))
128 var errb strings.Builder
129 cmd.Stderr = &errb
130 out, err := cmd.Output()
131 if err != nil {
132 return nil, fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
133 }
134 return out, nil
135}
136
137// countersign builds the note set a landing stores: every transferring
138// check's note with the integrator's sibling signature added, keyed by the
139// subject it is about, plus the transfer statement keyed by the tree that
140// landed.
141func (in *integrator) countersign(ch verdict.Change, v verdict.Verdict, l landing, transfer []byte) (landedEvidence, error) {
142 out := landedEvidence{refs: map[string]map[string]string{}}
143 add := func(ref, path string, content []byte) error {
144 blob, err := in.writeBlob(content)
145 if err != nil {
146 return err
147 }
148 if out.refs[ref] == nil {
149 out.refs[ref] = map[string]string{}
150 }
151 out.refs[ref][path] = blob
152 return nil
153 }
154 original := fmt.Sprintf("%s/%s/%s", attestationPrefix, ch.Attested, in.keyHash)
155 for _, cv := range v.Checks {
156 note, ok := l.notes[cv.Name]
157 if !ok || !cv.Transferred {
158 continue
159 }
160 signed, err := in.sign(note)
161 if err != nil {
162 return out, fmt.Errorf("countersigning %s: %w", cv.Name, err)
163 }
164 if err := add(original, cv.Name+"/"+statementNote, signed); err != nil {
165 return out, err
166 }
167 }
168 landed := fmt.Sprintf("%s/%s/%s", attestationPrefix, l.digest, in.keyHash)
169 if err := add(landed, transferNote, transfer); err != nil {
170 return out, err
171 }
172 return out, nil
173}
174
175// store writes the note set into the repository as one ref per subject.
176// Deterministic by construction: a ref's value is a function of the notes
177// beneath it and nothing else.
178func (in *integrator) store(e landedEvidence) ([]string, error) {
179 var written []string
180 for ref := range e.refs {
181 written = append(written, ref)
182 }
183 sort.Strings(written)
184 for _, ref := range written {
185 top, err := in.writeTree(e.refs[ref])
186 if err != nil {
187 return nil, err
188 }
189 if _, err := git(in.repo, "update-ref", ref, top); err != nil {
190 return nil, err
191 }
192 }
193 return written, nil
194}
195
196func (in *integrator) writeBlob(content []byte) (string, error) {
197 cmd := exec.Command("git", "hash-object", "-w", "--stdin")
198 cmd.Dir = in.repo
199 cmd.Stdin = strings.NewReader(string(content))
200 out, err := cmd.Output()
201 if err != nil {
202 return "", fmt.Errorf("storing a note: %w", err)
203 }
204 return strings.TrimSpace(string(out)), nil
205}
206
207// writeTree builds a tree from paths to blob ids, creating a subtree per
208// path segment. Paths here are one or two segments deep — "transfer.note",
209// "<check>/statement.note" — so the recursion is shallow by construction.
210func (in *integrator) writeTree(blobs map[string]string) (string, error) {
211 here := map[string]string{}
212 under := map[string]map[string]string{}
213 for path, blob := range blobs {
214 dir, rest, nested := strings.Cut(path, "/")
215 if !nested {
216 here[path] = blob
217 continue
218 }
219 if under[dir] == nil {
220 under[dir] = map[string]string{}
221 }
222 under[dir][rest] = blob
223 }
224 var lines []string
225 for name, blob := range here {
226 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", blob, name))
227 }
228 for name, sub := range under {
229 oid, err := in.writeTree(sub)
230 if err != nil {
231 return "", err
232 }
233 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
234 }
235 sort.Strings(lines)
236 cmd := exec.Command("git", "mktree")
237 cmd.Dir = in.repo
238 cmd.Stdin = strings.NewReader(strings.Join(lines, "\n") + "\n")
239 out, err := cmd.Output()
240 if err != nil {
241 return "", fmt.Errorf("building an attestation tree: %w", err)
242 }
243 return strings.TrimSpace(string(out)), nil
244}