gunk-dev/the-valley

compile_test.go

source4cbb5ec9c5dbmain's published tip history
11.2 KiB
1package main
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "encoding/base64"
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "slices"
14 "strings"
15 "testing"
16 "time"
17
18 "the-valley/approval"
19)
20
21// A run compiles until a reading taken after a compilation matches the one
22// it compiled. Each case changes the inputs from inside a compilation, as a
23// push landing or midnight passing while the compiler runs would.
24func TestARunCompilesUntilTheRefAndTheDayHoldStill(t *testing.T) {
25 monday, tuesday := day(t, "2026-11-16"), day(t, "2026-11-17")
26 for _, c := range []struct {
27 name string
28 // change is called inside the nth compilation, and may change the
29 // inputs or fail it.
30 change func(n int, in *reading) error
31 want []reading
32 wantErr bool
33 }{
34 {
35 name: "nothing changes",
36 change: func(int, *reading) error { return nil },
37 want: []reading{{"a", monday}},
38 },
39 {
40 name: "the ref moves during the first compilation",
41 change: func(n int, in *reading) error {
42 if n == 1 {
43 in.oid = "b"
44 }
45 return nil
46 },
47 want: []reading{{"a", monday}, {"b", monday}},
48 },
49 {
50 name: "the day turns during the first compilation",
51 change: func(n int, in *reading) error {
52 if n == 1 {
53 in.day = tuesday
54 }
55 return nil
56 },
57 want: []reading{{"a", monday}, {"a", tuesday}},
58 },
59 {
60 name: "the ref moves during every compilation",
61 change: func(n int, in *reading) error {
62 in.oid = string(rune('a' + n))
63 return nil
64 },
65 want: []reading{{"a", monday}, {"b", monday}, {"c", monday}},
66 wantErr: true,
67 },
68 {
69 name: "a compilation fails on a commit the ref has left",
70 change: func(n int, in *reading) error {
71 if n == 1 {
72 in.oid = "b"
73 return errors.New("does not compile")
74 }
75 return nil
76 },
77 want: []reading{{"a", monday}, {"b", monday}},
78 },
79 {
80 name: "a compilation fails while the day turns",
81 change: func(n int, in *reading) error {
82 if n == 1 {
83 in.day = tuesday
84 return errors.New("does not compile")
85 }
86 return nil
87 },
88 want: []reading{{"a", monday}, {"a", tuesday}},
89 },
90 {
91 name: "the commit the ref moved to does not compile",
92 change: func(n int, in *reading) error {
93 if n == 2 {
94 return errors.New("does not compile")
95 }
96 in.oid = "b"
97 return nil
98 },
99 want: []reading{{"a", monday}, {"b", monday}},
100 wantErr: true,
101 },
102 } {
103 t.Run(c.name, func(t *testing.T) {
104 in := reading{"a", monday}
105 var compiled []reading
106 err := converge("refs/heads/main", 3,
107 func() (reading, error) { return in, nil },
108 func(at reading) error {
109 compiled = append(compiled, at)
110 return c.change(len(compiled), &in)
111 })
112 if (err != nil) != c.wantErr {
113 t.Errorf("err = %v, want an error: %t", err, c.wantErr)
114 }
115 if !slices.EqualFunc(compiled, c.want, reading.equal) {
116 t.Errorf("compiled %v, want %v", compiled, c.want)
117 }
118 })
119 }
120}
121
122// A ref that cannot be read after a compilation fails the run. Its
123// artifacts stay as that compilation wrote them.
124func TestARunWhoseRefCannotBeReadAgainFails(t *testing.T) {
125 reads := 0
126 err := converge("refs/heads/main", 3,
127 func() (reading, error) {
128 reads++
129 if reads > 1 {
130 return reading{}, errors.New("has no refs/heads/main")
131 }
132 return reading{"a", day(t, "2026-11-16")}, nil
133 },
134 func(reading) error { return nil })
135 if err == nil {
136 t.Error("a run whose ref vanished after its compilation succeeded")
137 }
138}
139
140// A push landing while a run reads the registry cannot mix two registries,
141// and the run compiles the commit the push moved the ref to before it
142// exits. The ref moves right after the run's first reading, before its
143// first compilation reads a document. That compilation must render the
144// commit the reading resolved, under that commit's name, and stamp the
145// approval signers file with it; a compilation reading through the ref
146// would render the forged registry, whose intruder pushes. It runs over a real repository with git and cue, which
147// the compiler shells out to.
148func TestAPushMidReadIsCompiledUnmixedByTheSameRun(t *testing.T) {
149 dir := t.TempDir()
150 repo := filepath.Join(dir, "instance.git")
151 work := filepath.Join(dir, "work")
152 runGit(t, "", "init", "--quiet", "--bare", repo)
153 runGit(t, "", "init", "--quiet", work)
154 operator, intruder := sshPublicKey(t), sshPublicKey(t)
155 landed := commitRegistry(t, work, repo, "refs/heads/main", testRegistry(operator, ""))
156 forged := commitRegistry(t, work, repo, "refs/heads/forged", testRegistry(operator, intruder))
157
158 keys := filepath.Join(dir, "authorized_keys")
159 approvers := filepath.Join(dir, "approval-signers")
160 c := compilation{
161 repo: repo, ref: "refs/heads/main", dir: "identity", schema: "../schema/identity.cue",
162 knownSigners: filepath.Join(dir, "known-signers"), authorizedKeys: keys,
163 grants: filepath.Join(dir, "grants"), approvalSigners: approvers,
164 today: func() time.Time { return day(t, "2026-11-16") },
165 }
166 stamp := func() string {
167 body, err := os.ReadFile(approvers)
168 if err != nil {
169 t.Fatal(err)
170 }
171 a, err := approval.ReadAuthority(bytes.NewReader(body))
172 if err != nil {
173 t.Fatal(err)
174 }
175 return a.Commit
176 }
177 var readings []reading
178 var first []byte
179 var firstStamp string
180 err := converge(c.ref, 2,
181 func() (reading, error) {
182 r, err := c.read()
183 readings = append(readings, r)
184 if len(readings) == 1 {
185 runGit(t, "", "-C", repo, "update-ref", "refs/heads/main", forged)
186 }
187 return r, err
188 },
189 func(at reading) error {
190 err := c.compileAt(at)
191 if first == nil {
192 first, _ = os.ReadFile(keys)
193 firstStamp = stamp()
194 }
195 return err
196 })
197 if err != nil {
198 t.Fatal(err)
199 }
200 if readings[0].oid != landed {
201 t.Fatalf("the first reading resolved %s, want the landed %s", readings[0].oid, landed)
202 }
203 blob := func(key string) []byte { return []byte(strings.Fields(key)[1]) }
204 if bytes.Contains(first, blob(intruder)) || !bytes.Contains(first, blob(operator)) {
205 t.Errorf("the first compilation mixed in the registry the ref moved to:\n%s", first)
206 }
207 if firstStamp != landed {
208 t.Errorf("the first compilation stamped its approval signers with %s, want the commit it resolved, %s", firstStamp, landed)
209 }
210 if last := stamp(); last != forged {
211 t.Errorf("the run's last compilation stamped its approval signers with %s, want the commit the ref moved to, %s", last, forged)
212 }
213 final, err := os.ReadFile(keys)
214 if err != nil {
215 t.Fatal(err)
216 }
217 if !bytes.Contains(final, blob(intruder)) {
218 t.Errorf("the run ended without compiling the commit the ref moved to:\n%s", final)
219 }
220}
221
222// testRegistry is the smallest registry the schema takes: the operator
223// governs it and pushes, and an intruder, when given a key, pushes too.
224func testRegistry(operator, intruder string) string {
225 r := fmt.Sprintf(`package identity
226
227boundaries: {
228 "push": kind: "git-push"
229 "registry": kind: "registry"
230}
231genesis: "operator"
232principals: "operator": {
233 kind: "human"
234 keys: [{class: "ssh-ed25519", bound: "hardware", public: %q}]
235 grants: {
236 push: boundary: "push"
237 govern: boundary: "registry"
238 }
239}
240`, operator)
241 if intruder != "" {
242 r += fmt.Sprintf(`principals: "intruder": {
243 kind: "human"
244 keys: [{class: "ssh-ed25519", bound: "hardware", public: %q}]
245 grants: push: boundary: "push"
246}
247`, intruder)
248 }
249 return r
250}
251
252// commitRegistry commits registry as identity/registry.cue in work, pushes
253// it to ref in repo, and returns the commit.
254func commitRegistry(t *testing.T, work, repo, ref, registry string) string {
255 t.Helper()
256 if err := os.MkdirAll(filepath.Join(work, "identity"), 0o755); err != nil {
257 t.Fatal(err)
258 }
259 if err := os.WriteFile(filepath.Join(work, "identity", "registry.cue"), []byte(registry), 0o644); err != nil {
260 t.Fatal(err)
261 }
262 runGit(t, work, "add", "-A")
263 runGit(t, work, "commit", "--quiet", "-m", ref)
264 runGit(t, work, "push", "--quiet", repo, "HEAD:"+ref)
265 return runGit(t, work, "rev-parse", "HEAD")
266}
267
268// runGit runs git with no user or system configuration, as a fixed author.
269func runGit(t *testing.T, dir string, args ...string) string {
270 t.Helper()
271 cmd := exec.Command("git", args...)
272 cmd.Dir = dir
273 cmd.Env = append(os.Environ(),
274 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
275 "GIT_AUTHOR_NAME=valley-check", "GIT_AUTHOR_EMAIL=valley-check@localhost",
276 "GIT_COMMITTER_NAME=valley-check", "GIT_COMMITTER_EMAIL=valley-check@localhost",
277 )
278 out, err := cmd.CombinedOutput()
279 if err != nil {
280 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
281 }
282 return strings.TrimSpace(string(out))
283}
284
285// sshPublicKey is a fresh ed25519 key in authorized_keys form.
286func sshPublicKey(t *testing.T) string {
287 t.Helper()
288 pub, _, err := ed25519.GenerateKey(nil)
289 if err != nil {
290 t.Fatal(err)
291 }
292 var blob []byte
293 for _, field := range [][]byte{[]byte("ssh-ed25519"), pub} {
294 blob = binary.BigEndian.AppendUint32(blob, uint32(len(field)))
295 blob = append(blob, field...)
296 }
297 return "ssh-ed25519 " + base64.StdEncoding.EncodeToString(blob)
298}
299
300// Each round of a run stamps the approval signers files it installs with
301// the commit it compiled and the day it judged expiry on: the first round,
302// one rerun because the ref moved, and one rerun because only the day
303// turned.
304func TestEachRoundStampsTheApprovalFilesWithItsCommitAndDay(t *testing.T) {
305 dir := t.TempDir()
306 repo := filepath.Join(dir, "instance.git")
307 work := filepath.Join(dir, "work")
308 runGit(t, "", "init", "--quiet", "--bare", repo)
309 runGit(t, "", "init", "--quiet", work)
310 operator, intruder := sshPublicKey(t), sshPublicKey(t)
311 first := commitRegistry(t, work, repo, "refs/heads/main", testRegistry(operator, ""))
312 second := commitRegistry(t, work, repo, "refs/heads/next", testRegistry(operator, intruder))
313 monday, tuesday := day(t, "2026-11-16"), day(t, "2026-11-17")
314
315 today := monday
316 files := []string{filepath.Join(dir, "approval-signers"), filepath.Join(dir, "approval-signers-hardware")}
317 c := compilation{
318 repo: repo, ref: "refs/heads/main", dir: "identity", schema: "../schema/identity.cue",
319 knownSigners: filepath.Join(dir, "known-signers"), authorizedKeys: filepath.Join(dir, "authorized_keys"),
320 grants: filepath.Join(dir, "grants"), approvalSigners: files[0], approvalHardware: files[1],
321 today: func() time.Time { return today },
322 }
323 var stamped [][]approval.Authority
324 err := converge(c.ref, 3, c.read, func(at reading) error {
325 if err := c.compileAt(at); err != nil {
326 return err
327 }
328 var round []approval.Authority
329 for _, f := range files {
330 body, err := os.ReadFile(f)
331 if err != nil {
332 return err
333 }
334 stamp, err := approval.ReadAuthority(bytes.NewReader(body))
335 if err != nil {
336 return fmt.Errorf("%s: %w", f, err)
337 }
338 round = append(round, stamp)
339 }
340 stamped = append(stamped, round)
341 switch len(stamped) {
342 case 1:
343 runGit(t, "", "-C", repo, "update-ref", "refs/heads/main", second)
344 case 2:
345 today = tuesday
346 }
347 return nil
348 })
349 if err != nil {
350 t.Fatal(err)
351 }
352 want := []struct {
353 commit string
354 day time.Time
355 }{{first, monday}, {second, monday}, {second, tuesday}}
356 if len(stamped) != len(want) {
357 t.Fatalf("the run compiled %d rounds, want %d", len(stamped), len(want))
358 }
359 for i, w := range want {
360 for j, stamp := range stamped[i] {
361 if stamp.Ref != c.ref || stamp.Commit != w.commit || !stamp.Day.Equal(w.day) {
362 t.Errorf("round %d stamped %s with %s at %s on %s, want %s on %s",
363 i+1, files[j], stamp.Ref, stamp.Commit, stamp.Day.Format(dateLayout), w.commit, w.day.Format(dateLayout))
364 }
365 }
366 }
367}