gunk-dev/the-valley

transfer.go

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