gunk-dev/the-valley

transfer.go

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