gunk-dev/the-valley

transfer.go

source89496f97a023main's published tip history
12.7 KiB
1// How a snapshot reads and verifies the integrator's transfer statements,
2// in this process.
3//
4// Only the attestation refs the integrator writes are read: those named
5// for a key the known-signers file holds under the integrator's name
6// (refs/the-valley/attestations/<tree>/<key hash>). A statement counts
7// when all of these hold, which are the checks `attest verify --repo
8// --rev` makes, each made here with the code attest makes it with:
9//
10// - the note opens under every key the known-signers file holds, and a
11// signature by a key under the integrator's name verifies (note.Open);
12// - its text is the one written form of what it says (statement.Parse);
13// - every field the landing decision reads has its schema's form: the
14// predicate type, the change, the base digest set and the subject's
15// digest set (transferFields);
16// - its subject's valley-tree-v1 digest is that of the landing commit's
17// tree (statement.GitTree).
18//
19// attest verify also vets a statement against schema/attestation.cue. A
20// read here does not: the integrator vets every transfer statement against
21// that schema before it signs one (integrator/transfer.go), so a statement
22// whose signature verifies as the integrator's passed it when it was made,
23// and the fields a landing is decided on are checked here.
24//
25// What passes every content check is remembered (cache.go), so each
26// landing's tree digests and merge are computed once per machine. The
27// signature and the key that made it are checked on every read, so a key
28// the known-signers file no longer holds stops its statements counting at
29// once.
30
31package rebase
32
33import (
34 "bytes"
35 "crypto/sha256"
36 "encoding/hex"
37 "fmt"
38 "os"
39 "os/exec"
40 "sort"
41 "strings"
42
43 "the-valley/change"
44 "the-valley/note"
45 "the-valley/note/statement"
46)
47
48// transferStatement is one transfer statement found under the integrator's
49// attestation refs, whose text is the written form of a transfer, with the
50// values a landing is decided on.
51type transferStatement struct {
52 note []byte
53 change string // predicate.change: the request's change name
54 base string // predicate.base.valley-tree-v1: the tree the evidence was over
55 landed string // subject.digest.git-sha1: the commit that landed
56 tree string // subject.digest.valley-tree-v1: that commit's tree
57}
58
59// keyring is the verifier a snapshot resolved: every key the known-signers
60// file holds, the integrator's name, and the key hashes of the keys held
61// under that name, as the integrator's attestation refs are named. ok is
62// false when no statement can be verified: no keys, no name, no key under
63// the name, or a name the signer projects file restricts.
64type keyring struct {
65 ok bool
66 known []note.VerifierKey
67 signer string
68 hashes map[string]bool
69}
70
71// keyring resolves the verifier once, when statements are first needed.
72func (s *Snapshot) keyring() keyring {
73 if s.keys != nil {
74 return *s.keys
75 }
76 v := s.verify
77 if v.Resolve != nil {
78 v.Keys, v.Signer, v.SignerProjects = v.Resolve()
79 }
80 k := keyring{signer: v.Signer, hashes: map[string]bool{}}
81 if _, restricted := v.SignerProjects[v.Signer]; !restricted && v.Keys != "" && v.Signer != "" {
82 if data, err := os.ReadFile(v.Keys); err == nil {
83 if known, err := note.ParseVerifierKeys(data); err == nil {
84 k.known = known
85 for _, key := range known {
86 if key.Name == v.Signer {
87 k.hashes[fmt.Sprintf("%08x", key.Hash)] = true
88 }
89 }
90 }
91 }
92 }
93 k.ok = len(k.hashes) > 0
94 s.keys = &k
95 return k
96}
97
98// signedBy is the integrator's key that signed a note: the note opens
99// under every known key, as attest verify opens it, and a signature by a
100// key under the integrator's name verifies.
101func (k keyring) signedBy(n []byte) (note.VerifierKey, bool) {
102 _, checked, err := note.Open(n, k.known)
103 if err != nil {
104 return note.VerifierKey{}, false
105 }
106 for _, c := range checked {
107 if !c.Verified || c.Name != k.signer {
108 continue
109 }
110 for _, key := range k.known {
111 if key.Name == c.Name && key.Hash == c.Hash {
112 return key, true
113 }
114 }
115 }
116 return note.VerifierKey{}, false
117}
118
119// transferStatements reads every transfer statement under the integrator's
120// attestation refs, once. A transfer statement is a note at
121// change.TransferPath of a landed commit, under the transfer.d directory
122// at the top of an attestation ref's tree, or a single transfer.note at
123// the top of the tree, as a ref written before statements were kept per
124// landing holds it. Anything unreadable, or not the written form of a
125// transfer, is skipped: what is not read is not believed. When origin
126// holds attestation refs and the verifier cannot verify a statement, none
127// is read, and the snapshot is unverified.
128func (s *Snapshot) transferStatements() []transferStatement {
129 if s.read {
130 return s.transfers
131 }
132 s.read = true
133 defer s.g.phase("transfers")()
134 any := false
135 for ref := range s.Refs {
136 any = any || strings.HasPrefix(ref, AttestationRefs)
137 }
138 if !any {
139 return nil
140 }
141 k := s.keyring()
142 if !k.ok {
143 s.unverified = true
144 return nil
145 }
146 var trees []string
147 for ref, oid := range s.Refs {
148 if rest, ok := strings.CutPrefix(ref, AttestationRefs); ok {
149 if _, hash, ok := strings.Cut(rest, "/"); ok && k.hashes[hash] {
150 trees = append(trees, oid)
151 }
152 }
153 }
154 if len(trees) == 0 {
155 return nil
156 }
157 sort.Strings(trees)
158 if err := Fetch(s.ctx, s.g, trees...); err != nil {
159 s.unverified = true
160 return nil
161 }
162 var query bytes.Buffer
163 for _, tree := range trees {
164 fmt.Fprintf(&query, "%s:%s\n%s:%s\n", tree, change.TransferNote, tree, change.TransferDir)
165 }
166 out, err := s.g.input(s.ctx, true, &query, "cat-file", "--batch-check=%(objectname) %(objecttype)")
167 if err != nil {
168 s.unverified = true
169 return nil
170 }
171 type found struct{ oid, kind string }
172 var at []found
173 var dirs []string
174 for _, line := range strings.Split(out, "\n") {
175 oid, kind, _ := strings.Cut(line, " ")
176 at = append(at, found{oid, kind})
177 if kind == "tree" {
178 dirs = append(dirs, oid)
179 }
180 }
181 listed := s.transferBlobs(dirs)
182 var blobs []string
183 for _, f := range at {
184 switch f.kind {
185 case "blob":
186 blobs = append(blobs, f.oid)
187 case "tree":
188 notes, ok := listed[f.oid]
189 if !ok {
190 s.unverified = true
191 continue
192 }
193 blobs = append(blobs, notes...)
194 }
195 }
196 read := s.g.blobs(s.ctx, blobs)
197 for _, oid := range blobs {
198 data, ok := read[oid]
199 if !ok {
200 var err error
201 if data, err = s.g.output(s.ctx, true, "cat-file", "blob", oid); err != nil {
202 continue
203 }
204 }
205 if t, ok := readTransfer([]byte(data + "\n")); ok {
206 s.transfers = append(s.transfers, t)
207 }
208 }
209 return s.transfers
210}
211
212// transferBlobs lists, for each transfer.d tree, the blobs at the paths
213// change.TransferPath gives, in the order `ls-tree -r` lists them. The
214// three levels of the directory are read with one `cat-file --batch` each,
215// for every tree at once. A tree some object of which does not read is
216// left out.
217func (s *Snapshot) transferBlobs(dirs []string) map[string][]string {
218 levels := [3]map[string][]treeEntry{}
219 want := dirs
220 for i := range levels {
221 levels[i] = s.g.trees(s.ctx, want)
222 want = nil
223 for _, entries := range levels[i] {
224 for _, e := range entries {
225 if e.mode == "40000" && i < 2 {
226 want = append(want, e.oid)
227 }
228 }
229 }
230 }
231 listed := map[string][]string{}
232 for _, dir := range dirs {
233 var notes []string
234 ok := true
235 top, read := levels[0][dir]
236 ok = ok && read
237 for _, a := range top {
238 if a.mode != "40000" {
239 continue
240 }
241 mid, read := levels[1][a.oid]
242 ok = ok && read
243 for _, b := range mid {
244 if b.mode != "40000" {
245 continue
246 }
247 leaves, read := levels[2][b.oid]
248 ok = ok && read
249 for _, c := range leaves {
250 if c.mode != "40000" && c.mode != "160000" && isTransferPath(a.name+"/"+b.name+"/"+c.name) {
251 notes = append(notes, c.oid)
252 }
253 }
254 }
255 }
256 if ok {
257 listed[dir] = notes
258 }
259 }
260 return listed
261}
262
263// isTransferPath reports whether a path within the transfer.d directory is
264// where change.TransferPath puts the statement for some commit:
265// <2 hex>/<2 hex>/<rest>.note, the three parts a full object ID.
266func isTransferPath(path string) bool {
267 parts := strings.Split(strings.TrimSuffix(path, ".note"), "/")
268 if len(parts) != 3 || len(parts[0]) != 2 || len(parts[1]) != 2 || !strings.HasSuffix(path, ".note") {
269 return false
270 }
271 return IsObjectID(parts[0] + parts[1] + parts[2])
272}
273
274// readTransfer reads a note as a transfer statement: a note whose text is
275// the written form of a transfer, every field of which a landing is
276// decided on has its schema's form. Its signature is not checked here.
277func readTransfer(n []byte) (transferStatement, bool) {
278 text, _, err := note.Split(n)
279 if err != nil {
280 return transferStatement{}, false
281 }
282 doc, err := statement.Parse(text)
283 if err != nil {
284 return transferStatement{}, false
285 }
286 t, ok := transferFields(doc)
287 t.note = n
288 return t, ok
289}
290
291// transferFields reads the fields a landing is decided on from a parsed
292// statement, held to schema/attestation.cue's forms for them: the
293// predicate type is a transfer's; the change is a line, as the parse
294// already holds every value; the base is a digest set holding a
295// valley-tree-v1 digest; and the subject's primary is valley-tree-v1, in a
296// digest set holding that digest and the commit's git-sha1 ID.
297func transferFields(doc map[string]any) (transferStatement, bool) {
298 if doc["predicateType"] != statement.PredicateTransfer {
299 return transferStatement{}, false
300 }
301 predicate, _ := doc["predicate"].(map[string]any)
302 subject, _ := doc["subject"].(map[string]any)
303 name, _ := predicate["change"].(string)
304 base, okBase := digestSet(predicate["base"])
305 digests, okSubject := digestSet(subject["digest"])
306 t := transferStatement{change: name, base: base[statement.TreeScheme], landed: digests["git-sha1"], tree: digests[statement.TreeScheme]}
307 ok := name != "" && okBase && okSubject && subject["primary"] == statement.TreeScheme &&
308 t.base != "" && t.landed != "" && t.tree != ""
309 return t, ok
310}
311
312// digestForms are the schemes a digest set may hold, as #DigestSet closes
313// it, and the length of each one's lowercase hex value.
314var digestForms = map[string]int{
315 statement.TreeScheme: 64, "valley-inputs-v1": 64, "sha256": 64, "git-sha1": 40, "git-sha256": 64,
316}
317
318// digestSet reads a digest set: an object whose every member is a scheme
319// #DigestSet names, with a value of its form.
320func digestSet(v any) (map[string]string, bool) {
321 members, ok := v.(map[string]any)
322 if !ok {
323 return nil, false
324 }
325 set := map[string]string{}
326 for scheme, value := range members {
327 s, ok := value.(string)
328 if n, known := digestForms[scheme]; !ok || !known || !isHex(s, n) {
329 return nil, false
330 }
331 set[scheme] = s
332 }
333 return set, true
334}
335
336// verifierVersion is the version of the checks verified makes. A
337// remembered landing names it, so one remembered under other checks is
338// verified again. Bump it whenever what verified checks changes.
339const verifierVersion = "1"
340
341// verified reports whether t, a statement whose records bind head to it,
342// is the integrator's statement that head landed as t.landed: signed by a
343// key the known-signers file holds under the integrator's name, with the
344// head's tree as its base and the landing commit's as its subject, and
345// with the integrator's merge of head onto the landing commit's parent
346// giving that tree. A landing that passed every check is remembered, and
347// only its signature is checked again.
348func (s *Snapshot) verified(t transferStatement, head string) bool {
349 defer s.g.phase("transfers")()
350 key, ok := s.keyring().signedBy(t.note)
351 if !ok {
352 return false
353 }
354 sum := sha256.Sum256(t.note)
355 remembered := fmt.Sprintf("the-valley transfer landing %s\nnote %s\nlanded %s\nhead %s\nrequest %s\nkey %s\n",
356 verifierVersion, hex.EncodeToString(sum[:]), t.landed, head, t.change, key)
357 if s.cache.landing(remembered) {
358 return true
359 }
360 digest, ok := s.digest(head)
361 if !ok {
362 s.unverified = true
363 return false
364 }
365 if t.base != digest {
366 return false
367 }
368 if tree, ok := s.digest(t.landed); !ok || tree != t.tree || !s.mergesTo(head, t.landed) {
369 return false
370 }
371 s.cache.putLanding(remembered)
372 return true
373}
374
375// digest is the valley-tree-v1 digest of a commit's tree, read with
376// replacement refs off, so the tree is the one the commit names.
377func (s *Snapshot) digest(commit string) (string, bool) {
378 if d, ok := s.digestOf[commit]; ok {
379 return d, d != ""
380 }
381 git := func(args ...string) *exec.Cmd {
382 return s.g.command(s.ctx, append([]string{"--no-replace-objects"}, args...)...)
383 }
384 d := ""
385 if tree, err := s.g.output(s.ctx, true, "--no-replace-objects", "rev-parse", "--verify", "--quiet", commit+"^{tree}"); err == nil && IsObjectID(tree) {
386 if cached, ok := s.cache.tree(tree); ok {
387 d = cached
388 } else if entries, err := statement.GitTree(git, tree); err == nil {
389 d = statement.TreeDigest(entries)
390 s.cache.putTree(tree, d)
391 }
392 }
393 s.digestOf[commit] = d
394 return d, d != ""
395}