gunk-dev/the-valley

transfer_test.go

sourcecfedff357a41main's published tip history
20.4 KiB
1package rebase
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "sort"
12 "strings"
13 "testing"
14
15 "the-valley/change"
16 "the-valley/note"
17 "the-valley/note/statement"
18)
19
20// signer is a key that signs notes under a name, as the integrator and the
21// check worker do.
22type signer struct {
23 name string
24 priv ed25519.PrivateKey
25 key note.VerifierKey
26}
27
28func newSigner(t *testing.T, name string) signer {
29 t.Helper()
30 pub, priv, err := ed25519.GenerateKey(nil)
31 if err != nil {
32 t.Fatal(err)
33 }
34 return signer{name: name, priv: priv, key: note.NewVerifierKey(name, pub)}
35}
36
37func (s signer) hash() string { return fmt.Sprintf("%08x", s.key.Hash) }
38
39// host writes to the test's origin what a valley host's integrator writes
40// when it lands a change: the landing commit on main, the transfer
41// statement under an attestation ref, the landing record and the outcome
42// record. Nothing here starts attest.
43type host struct {
44 w *world
45 integrator signer
46 worker signer
47 refs map[string]map[string]string // attestation ref → path → blob
48}
49
50func newHost(w *world) *host {
51 return &host{w: w, integrator: newSigner(w.t, "valley-host.example.org/attestations"),
52 worker: newSigner(w.t, "worker/attestations"), refs: map[string]map[string]string{}}
53}
54
55// origin runs git in the origin repository, with stdin and more
56// environment, and returns its output.
57func (h *host) origin(stdin []byte, env []string, args ...string) string {
58 h.w.t.Helper()
59 cmd := exec.Command("git", args...)
60 cmd.Dir, cmd.Env = h.w.origin, append(append([]string{}, h.w.env...), env...)
61 if stdin != nil {
62 cmd.Stdin = bytes.NewReader(stdin)
63 }
64 out, err := cmd.CombinedOutput()
65 if err != nil {
66 h.w.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
67 }
68 return strings.TrimSpace(string(out))
69}
70
71// digest is the valley-tree-v1 digest of a commit's tree on origin.
72func (h *host) digest(commit string) string {
73 h.w.t.Helper()
74 entries, err := statement.GitTree(func(args ...string) *exec.Cmd {
75 cmd := exec.Command("git", args...)
76 cmd.Dir, cmd.Env = h.w.origin, h.w.env
77 return cmd
78 }, commit)
79 if err != nil {
80 h.w.t.Fatal(err)
81 }
82 return statement.TreeDigest(entries)
83}
84
85// land lands head onto origin's main as the integrator does: one new
86// commit whose tree is the merge of head onto main's tip, and whose one
87// parent is that tip. It returns the landing commit.
88func (h *host) land(head string) string {
89 h.w.t.Helper()
90 tip := h.w.at("refs/heads/main")
91 base := h.origin(nil, nil, "merge-base", tip, head)
92 tree, _, _ := strings.Cut(h.origin(nil, nil, "merge-tree", "--write-tree", "--merge-base="+base, tip, head), "\n")
93 landed := h.origin(nil, nil, "commit-tree", tree, "-p", tip, "-m", "land "+short(head))
94 h.origin(nil, nil, "update-ref", "refs/heads/main", landed, tip)
95 return landed
96}
97
98// transfer is the written form of a transfer statement saying head's tree
99// landed as landed under the request name.
100func (h *host) transfer(name, head, landed, policy string) []byte {
101 h.w.t.Helper()
102 text, err := statement.Render(map[string]any{
103 "statementType": statement.Type,
104 "subject": map[string]any{
105 "primary": statement.TreeScheme,
106 "digest": map[string]any{statement.TreeScheme: h.digest(landed), "git-sha1": landed},
107 },
108 "predicateType": statement.PredicateTransfer,
109 "predicate": map[string]any{
110 "change": name,
111 "target": "refs/heads/main",
112 "base": map[string]any{statement.TreeScheme: h.digest(head)},
113 "policy": map[string]any{"sha256": policy},
114 "required": "none",
115 },
116 })
117 if err != nil {
118 h.w.t.Fatal(err)
119 }
120 return text
121}
122
123func (s signer) sign(t *testing.T, text []byte) []byte {
124 t.Helper()
125 n, err := note.Sign(text, s.name, s.priv)
126 if err != nil {
127 t.Fatal(err)
128 }
129 return n
130}
131
132// store keeps a note at change.TransferPath of landed, under the
133// attestation ref for landed's tree and the key hash given, keeping every
134// note the ref already holds.
135func (h *host) store(hash, landed string, n []byte) {
136 h.w.t.Helper()
137 ref := AttestationRefs + h.digest(landed) + "/" + hash
138 if h.refs[ref] == nil {
139 h.refs[ref] = map[string]string{}
140 }
141 h.refs[ref][change.TransferPath(landed)] = h.origin(n, nil, "hash-object", "-w", "--stdin")
142 index := filepath.Join(h.w.t.TempDir(), "index")
143 var paths []string
144 for p := range h.refs[ref] {
145 paths = append(paths, p)
146 }
147 sort.Strings(paths)
148 for _, p := range paths {
149 h.origin(nil, []string{"GIT_INDEX_FILE=" + index}, "update-index", "--add", "--cacheinfo", "100644,"+h.refs[ref][p]+","+p)
150 }
151 h.origin(nil, nil, "update-ref", ref, h.origin(nil, []string{"GIT_INDEX_FILE=" + index}, "write-tree"))
152}
153
154// record writes the landing record for head.
155func (h *host) record(head, landed, name string) {
156 h.w.t.Helper()
157 l := change.Landing{Landed: landed, Request: name, Head: head}
158 blob := h.origin(l.Format(), nil, "hash-object", "-w", "--stdin")
159 tree := h.origin([]byte("100644 blob "+blob+"\t"+change.LandingFile+"\n"), nil, "mktree")
160 commit := h.origin(nil, nil, "commit-tree", tree, "-m", "landing")
161 h.origin(nil, nil, "update-ref", LandingPrefix+head, commit)
162}
163
164// outcome writes the outcome record land for head under the request name.
165func (h *host) outcome(name, head, tip string) {
166 h.w.t.Helper()
167 blob := h.origin([]byte(head+" "+tip+" 0123456789abcdef land\n"), nil, "hash-object", "-w", "--stdin")
168 h.origin(nil, nil, "update-ref", OutcomePrefix+name, blob)
169}
170
171// keys writes a known-signers file holding the keys given.
172func keysFile(t *testing.T, keys ...note.VerifierKey) string {
173 t.Helper()
174 var b strings.Builder
175 for _, k := range keys {
176 b.WriteString(k.String() + "\n")
177 }
178 path := filepath.Join(t.TempDir(), "known-signers")
179 if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
180 t.Fatal(err)
181 }
182 return path
183}
184
185// The changes a landings world holds, by ID.
186var (
187 idRecorded = strings.Repeat("m", 32) // landed, with a landing record
188 idOutcome = strings.Repeat("n", 32) // landed before landing records: its outcome record binds it
189 idTwoHeads = strings.Repeat("p", 32) // landed as v1; v2 has v1's tree on another parent; v3's landing record names v1's landing
190 idForged = strings.Repeat("q", 32) // its records bind it, and only the worker signed a statement
191 idDirect = strings.Repeat("r", 32) // its head is on main
192 idOpen = strings.Repeat("s", 32) // not landed
193)
194
195// landings is a world whose origin holds several landings by the
196// integrator, each a different case of the landing rules.
197type landings struct {
198 *world
199 host *host
200 // statements is each recorded landing's statement as the integrator
201 // signed and stored it: the landing commit and the request name.
202 statements map[string][2]string
203}
204
205func newLandings(t *testing.T) *landings {
206 t.Helper()
207 w := newWorld(t)
208 h := newHost(w)
209 l := &landings{world: w, host: h, statements: map[string][2]string{}}
210 base := w.at("refs/heads/main")
211
212 recorded := w.layer("recorded", base)
213 outcome := w.layer("outcome", base)
214 v1 := w.layer("two-heads", base)
215 forged := w.layer("forged", base)
216 w.layer("open", base)
217 // v2 has v1's tree on another parent: an honest mix-up the records
218 // and the merge tell apart from v1's landing.
219 w.git("checkout", "--quiet", "-b", "two-heads-v2", base)
220 w.commit("another parent", "other.txt", "other\n")
221 w.git("checkout", "--quiet", v1, "--", ".")
222 w.git("rm", "--quiet", "other.txt")
223 w.git("commit", "--quiet", "-m", "v1's tree")
224 v2 := w.git("rev-parse", "HEAD")
225 w.git("push", "--quiet", "origin", "two-heads-v2")
226 if w.git("rev-parse", v1+"^{tree}") != w.git("rev-parse", v2+"^{tree}") {
227 t.Fatal("the two heads have different trees")
228 }
229 // v3 has another tree, and a landing record binds it to v1's landing
230 // commit and request name: the statement's checks for v1 do not hold
231 // for it, though the integrator remembered them for v1.
232 w.git("checkout", "--quiet", "-b", "two-heads-v3", base)
233 v3 := w.commit("another tree", "two-heads.txt", "v3\n")
234 w.git("push", "--quiet", "origin", "two-heads-v3")
235 for id, branch := range map[string]string{idRecorded: "recorded", idOutcome: "outcome", idTwoHeads: "two-heads", idForged: "forged", idOpen: "open"} {
236 w.ready(id, branch)
237 }
238 r := w.record(idTwoHeads)
239 old := w.at(change.Ref(Target, idTwoHeads))
240 r.Versions = append(r.Versions,
241 change.Version{N: 2, Head: change.HeadPrefix + v2, Title: "v2", Branch: "two-heads", Uploader: "author"},
242 change.Version{N: 3, Head: change.HeadPrefix + v3, Title: "v3", Branch: "two-heads", Uploader: "author"})
243 r.Active, r.Seq = 3, r.Seq+1
244 w.write(idTwoHeads, r, old, old, v2, v3)
245
246 policy := strings.Repeat("ab", 32)
247 for _, c := range []struct {
248 head, name string
249 record bool
250 }{{recorded, "recorded", true}, {outcome, "outcome", false}, {v1, "two-heads", true}} {
251 tip := w.at("refs/heads/main")
252 landed := h.land(c.head)
253 h.store(h.integrator.hash(), landed, h.integrator.sign(t, h.transfer(c.name, c.head, landed, policy)))
254 if c.record {
255 h.record(c.head, landed, c.name)
256 }
257 h.outcome(c.name, c.head, tip)
258 l.statements[c.head] = [2]string{landed, c.name}
259 }
260 h.record(v3, l.statements[v1][0], "two-heads")
261 // The worker signs a statement for the forged change's landing, and
262 // stores it under its own key hash and under the integrator's.
263 landed := h.land(forged)
264 text := h.transfer("forged", forged, landed, policy)
265 h.store(h.worker.hash(), landed, h.worker.sign(t, text))
266 h.store(h.integrator.hash(), landed, h.worker.sign(t, text))
267 h.record(forged, landed, "forged")
268
269 // A head written to main directly.
270 w.git("fetch", "--quiet", "origin")
271 w.git("checkout", "--quiet", "-b", "direct", "origin/main")
272 w.commit("direct", "direct.txt", "direct\n")
273 w.git("push", "--quiet", "origin", "direct", "direct:main")
274 w.ready(idDirect, "direct")
275 return l
276}
277
278// kinds reads a snapshot with v and returns every version's landing
279// evidence and commit, and whether the snapshot is unverified.
280func (l *landings) kinds(v Verifier) (map[string]string, bool) {
281 l.t.Helper()
282 s, err := ReadSnapshot(context.Background(), l.g, v)
283 if err != nil {
284 l.t.Fatal(err)
285 }
286 got := map[string]string{}
287 for _, n := range s.Changes {
288 for _, ver := range n.Record.Versions {
289 kind, commit := s.Landing(n.ID, ver)
290 got[fmt.Sprintf("%s v%d", n.ID[:1], ver.N)] = kind + " " + short(commit)
291 }
292 }
293 return got, s.Unverified()
294}
295
296// verifier is the verifier the integrator's statements are believed
297// under: both keys known, the integrator's name, and the cache given.
298func (l *landings) verifier(cache string) Verifier {
299 return Verifier{Keys: keysFile(l.t, l.host.integrator.key, l.host.worker.key), Signer: l.host.integrator.name, Cache: cache}
300}
301
302// shim puts git, attest and cue on PATH as programs that log each call
303// to the file it returns; git then runs the real git, and attest and cue
304// fail.
305func shim(t *testing.T) string {
306 t.Helper()
307 real, err := exec.LookPath("git")
308 if err != nil {
309 t.Fatal(err)
310 }
311 dir, calls := t.TempDir(), filepath.Join(t.TempDir(), "calls")
312 for name, then := range map[string]string{"git": "exec '" + real + "' \"$@\"", "attest": "exit 1", "cue": "exit 1"} {
313 script := fmt.Sprintf("#!/bin/sh\necho \"%s $*\" >> '%s'\n%s\n", name, calls, then)
314 if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil {
315 t.Fatal(err)
316 }
317 }
318 t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
319 return calls
320}
321
322// calls reads the shim's log and empties it.
323func calls(t *testing.T, path string) string {
324 t.Helper()
325 data, _ := os.ReadFile(path)
326 os.Remove(path)
327 return string(data)
328}
329
330var wantKinds = map[string]string{
331 "m v1": LandedRecorded,
332 "n v1": LandedRecorded,
333 "p v1": LandedRecorded,
334 "p v2": NotLanded,
335 "p v3": LandingUncertain,
336 "q v1": LandingUncertain,
337 "r v1": Landed,
338 "s v1": NotLanded,
339}
340
341// A landing reads the same with an empty cache, a warm one and none: a
342// landing with a landing record, one made before landing records, a head
343// with another head's tree on another parent, a head with another tree
344// that a landing record binds to a remembered landing, and a landing only
345// a non-integrator key signed for. No read starts attest or cue, and a warm
346// read recomputes no merge.
347func TestALandingReadsTheSameColdWarmAndWithoutACache(t *testing.T) {
348 l := newLandings(t)
349 log := shim(t)
350 cache := filepath.Join(t.TempDir(), "cache")
351
352 cold, coldUnverified := l.kinds(l.verifier(cache))
353 coldCalls := calls(t, log)
354 warm, warmUnverified := l.kinds(l.verifier(cache))
355 warmCalls := calls(t, log)
356 none, noneUnverified := l.kinds(l.verifier(""))
357 noneCalls := calls(t, log)
358
359 for key, want := range wantKinds {
360 if kind, _, _ := strings.Cut(cold[key], " "); kind != want {
361 t.Errorf("%s reads %s cold, want %s", key, cold[key], want)
362 }
363 }
364 if fmt.Sprint(cold) != fmt.Sprint(warm) || fmt.Sprint(cold) != fmt.Sprint(none) {
365 t.Errorf("the reads disagree:\n cold %v\n warm %v\n none %v", cold, warm, none)
366 }
367 if coldUnverified || warmUnverified || noneUnverified {
368 t.Errorf("a read with the integrator's key is unverified: %v %v %v", coldUnverified, warmUnverified, noneUnverified)
369 }
370 for name, log := range map[string]string{"cold": coldCalls, "warm": warmCalls, "uncached": noneCalls} {
371 if strings.Contains(log, "\nattest ") || strings.HasPrefix(log, "attest ") || strings.Contains(log, "\ncue ") || strings.HasPrefix(log, "cue ") {
372 t.Errorf("a %s read started attest or cue:\n%s", name, log)
373 }
374 }
375 if n := strings.Count(coldCalls, "merge-tree"); n != 3 {
376 t.Errorf("a cold read recomputed %d merges, want one per recorded landing:\n%s", n, coldCalls)
377 }
378 if strings.Contains(warmCalls, "merge-tree") || strings.Contains(warmCalls, "ls-tree") {
379 t.Errorf("a warm read verified a landing again:\n%s", warmCalls)
380 }
381 if strings.Count(warmCalls, "\n") >= strings.Count(coldCalls, "\n") {
382 t.Errorf("a warm read started %d processes, and a cold one %d", strings.Count(warmCalls, "\n"), strings.Count(coldCalls, "\n"))
383 }
384}
385
386// What the cache remembers stops counting the moment what it was checked
387// with changes: a statement whose bytes differ by one byte, an entry under
388// another version of the checks, and a damaged entry are verified again; a
389// landing commit that has left main, and a key the known-signers file no
390// longer holds, stop the landing counting whatever the cache holds.
391func TestTheCacheNeverOutlivesWhatItChecked(t *testing.T) {
392 l := newLandings(t)
393 log := shim(t)
394 cache := filepath.Join(t.TempDir(), "cache")
395 want, _ := l.kinds(l.verifier(cache))
396 calls(t, log)
397 again := func(what string, merges int) {
398 t.Helper()
399 got, _ := l.kinds(l.verifier(cache))
400 if fmt.Sprint(got) != fmt.Sprint(want) {
401 t.Errorf("after %s the reads disagree:\n got %v\n want %v", what, got, want)
402 }
403 if n := strings.Count(calls(t, log), "merge-tree"); n != merges {
404 t.Errorf("after %s a read recomputed %d merges, want %d", what, n, merges)
405 }
406 }
407 entries := func() []string {
408 t.Helper()
409 found, err := filepath.Glob(filepath.Join(cache, "landings", "*"))
410 if err != nil || len(found) < 3 {
411 t.Fatalf("the cache holds %d landing entries, want one per recorded landing at least: %v", len(found), err)
412 }
413 return found
414 }
415
416 // The recorded change's statement, signed again over text one byte
417 // different, is verified again; the other two are remembered.
418 head := HeadOf(l.record(idRecorded).Versions[0])
419 s := l.statements[head]
420 text := l.host.transfer(s[1], head, s[0], strings.Repeat("ab", 31)+"ac")
421 l.host.store(l.host.integrator.hash(), s[0], l.host.integrator.sign(t, text))
422 again("a statement one byte different", 1)
423
424 // Entries written under another version of the checks.
425 for _, path := range entries() {
426 data, err := os.ReadFile(path)
427 if err != nil {
428 t.Fatal(err)
429 }
430 other := strings.Replace(string(data), "landing "+verifierVersion+"\n", "landing 0\n", 1)
431 os.Remove(path)
432 remembered{cache}.putLanding(other)
433 }
434 again("entries under another version", 3)
435
436 // Damaged entries, and damaged tree digests.
437 for _, path := range entries() {
438 if err := os.WriteFile(path, []byte("the-valley transfer landing"), 0o600); err != nil {
439 t.Fatal(err)
440 }
441 }
442 // A tree entry keeps its checksum line, and its digest has one hex
443 // digit changed: only the checksum tells it from a sound entry.
444 trees, _ := filepath.Glob(filepath.Join(cache, "trees", "*"))
445 if len(trees) == 0 {
446 t.Fatal("the cache holds no tree entries")
447 }
448 for _, path := range trees {
449 data, _ := os.ReadFile(path)
450 line, sum, _ := strings.Cut(string(data), "\n")
451 digit := "0"
452 if strings.HasSuffix(line, digit) {
453 digit = "1"
454 }
455 if err := os.WriteFile(path, []byte(line[:len(line)-1]+digit+"\n"+sum), 0o600); err != nil {
456 t.Fatal(err)
457 }
458 }
459 again("damaged entries", 3)
460 again("entries written again", 0)
461
462 // A key the known-signers file no longer holds: the integrator's key
463 // is gone, or another key holds its name.
464 for what, keys := range map[string]string{
465 "the integrator's key is removed": keysFile(t, l.host.worker.key),
466 "the integrator's key is replaced": keysFile(t, newSigner(t, l.host.integrator.name).key, l.host.worker.key),
467 } {
468 got, unverified := l.kinds(Verifier{Keys: keys, Signer: l.host.integrator.name, Cache: cache})
469 for _, key := range []string{"m v1", "n v1", "p v1"} {
470 if got[key] != LandingUncertain+" " {
471 t.Errorf("once %s, %s reads %s, want uncertain", what, key, got[key])
472 }
473 }
474 if what == "the integrator's key is removed" && !unverified {
475 t.Errorf("once %s, the read is not unverified", what)
476 }
477 }
478 calls(t, log)
479
480 // Main rewritten without the landings: the cache still holds them, and
481 // none reads landed.
482 l.host.origin(nil, nil, "update-ref", "refs/heads/main", l.host.origin(nil, nil, "commit-tree",
483 l.at("refs/heads/main")+"^{tree}", "-m", "main rewritten"))
484 got, _ := l.kinds(l.verifier(cache))
485 for _, key := range []string{"m v1", "n v1", "p v1"} {
486 if kind, _, _ := strings.Cut(got[key], " "); kind == Landed || kind == LandedRecorded {
487 t.Errorf("once main no longer holds its landing commit, %s reads %s", key, got[key])
488 }
489 }
490}
491
492// A replacement ref in the reading repository changes no landing: a cold
493// read with a recorded head replaced by a commit that merges to another
494// tree agrees with a warm read of what was remembered without it.
495func TestAReplacementRefChangesNoLanding(t *testing.T) {
496 l := newLandings(t)
497 cache := filepath.Join(t.TempDir(), "cache")
498 want, _ := l.kinds(l.verifier(cache))
499 head := HeadOf(l.record(idRecorded).Versions[0])
500 tree := l.git("rev-parse", head+"^{tree}")
501 l.git("replace", head, l.git("commit-tree", "-p", head+"^", "-m", "replacement", head+"^^{tree}"))
502 if l.git("rev-parse", head+"^{tree}") == tree {
503 t.Fatal("the replacement ref is not read")
504 }
505 cold, _ := l.kinds(l.verifier(filepath.Join(t.TempDir(), "cold")))
506 warm, _ := l.kinds(l.verifier(cache))
507 if fmt.Sprint(cold) != fmt.Sprint(warm) || fmt.Sprint(cold) != fmt.Sprint(want) {
508 t.Errorf("with the head replaced the reads disagree:\n cold %v\n warm %v\n want %v", cold, warm, want)
509 }
510}
511
512// A tree's modes read in one form however the object writes them: git
513// walks a tree written 040000 as one written 40000.
514func TestATreeModeReadsWithoutLeadingZeros(t *testing.T) {
515 id := bytes.Repeat([]byte{0xab}, 20)
516 var raw []byte
517 for _, entry := range []string{"040000 a", "40000 b", "0100644 c", "100755 d", "0160000 e"} {
518 raw = append(append(append(raw, entry...), 0), id...)
519 }
520 entries, ok := parseTree(raw, len(id))
521 var modes []string
522 for _, e := range entries {
523 modes = append(modes, e.mode)
524 }
525 if got, want := strings.Join(modes, " "), "40000 40000 100644 100755 160000"; !ok || got != want {
526 t.Errorf("the modes read %q (%v), want %q", got, ok, want)
527 }
528}
529
530// remembered is a cache directory, for a test to plant an entry in.
531type remembered struct{ dir string }
532
533func (r remembered) putLanding(text string) { cache{dir: r.dir}.putLanding(text) }
534
535// A statement signed by the worker, a key the known-signers file holds,
536// is not believed as the integrator's, under its own key hash or the
537// integrator's, cold or warm, though the landing record binds the head.
538func TestAStatementByAnotherKnownKeyIsNotTheIntegrators(t *testing.T) {
539 l := newLandings(t)
540 cache := filepath.Join(t.TempDir(), "cache")
541 for _, read := range []string{"cold", "warm"} {
542 got, _ := l.kinds(l.verifier(cache))
543 if got["q v1"] != LandingUncertain+" " {
544 t.Errorf("a %s read believes the worker's statement: %s", read, got["q v1"])
545 }
546 }
547 // The worker named as the integrator believes it: the statement itself
548 // is sound, and only the signer kept it out.
549 got, _ := l.kinds(Verifier{Keys: keysFile(t, l.host.integrator.key, l.host.worker.key), Signer: l.host.worker.name, Cache: cache})
550 if kind, _, _ := strings.Cut(got["q v1"], " "); kind != LandedRecorded {
551 t.Errorf("under the worker's name, the worker's statement reads %s", got["q v1"])
552 }
553}