gunk-dev/the-valley

walk_test.go

sourced9f7bacd171bmain's published tip history
14.7 KiB
1package main
2
3import (
4 "bytes"
5 "os"
6 "os/exec"
7 "os/signal"
8 "path/filepath"
9 "runtime"
10 "slices"
11 "strings"
12 "syscall"
13 "testing"
14)
15
16// The configuration a step borrows goes after the entries the caller's
17// environment gives git already, which are kept, and the count covers
18// both.
19func TestWithConfigAppendsToTheCallersEntries(t *testing.T) {
20 env := []string{"HOME=/home/operator", "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=core.pager", "GIT_CONFIG_VALUE_0=cat"}
21 got := withConfig(env, [][2]string{{"valley.principal", "alice"}, {"user.name", "alice"}})
22 want := []string{"HOME=/home/operator", "GIT_CONFIG_KEY_0=core.pager", "GIT_CONFIG_VALUE_0=cat",
23 "GIT_CONFIG_KEY_1=valley.principal", "GIT_CONFIG_VALUE_1=alice",
24 "GIT_CONFIG_KEY_2=user.name", "GIT_CONFIG_VALUE_2=alice", "GIT_CONFIG_COUNT=3"}
25 if !slices.Equal(got, want) {
26 t.Fatalf("withConfig gave\n%q\nwant\n%q", got, want)
27 }
28 if got := withConfig(env, nil); !slices.Equal(got, env) {
29 t.Fatalf("withConfig with nothing to borrow changed the environment: %q", got)
30 }
31}
32
33// walkHost is a host of scratch repositories a walk reads through
34// discovery: the instance repository valley, whose main carries
35// policy/instance and whose projects ref lists app, site and valley, and
36// app and site beside it, whose mains name it at policy/valley. The walk
37// runs from a checkout of app, as alice, and reads site and valley through
38// cache clones.
39type walkHost struct {
40 t *testing.T
41 dir, tmp, server string
42 instance string // the instance repository's URL, as app names it
43 work map[string]string
44}
45
46func newWalkHost(t *testing.T) *walkHost {
47 dir := t.TempDir()
48 h := &walkHost{t: t, dir: dir, tmp: filepath.Join(dir, "tmp"), server: filepath.Join(dir, "srv"), work: map[string]string{}}
49 for k, v := range map[string]string{"HOME": dir, "XDG_CONFIG_HOME": filepath.Join(dir, "config"),
50 "XDG_STATE_HOME": filepath.Join(dir, "state"), "XDG_CACHE_HOME": filepath.Join(dir, "cache"),
51 "GIT_CONFIG_NOSYSTEM": "1", "VALLEY_KNOWN_SIGNERS": "", "VALLEY_INTEGRATOR_SIGNER": "", "TMPDIR": h.tmp} {
52 t.Setenv(k, v)
53 }
54 if err := os.MkdirAll(h.tmp, 0o755); err != nil {
55 t.Fatal(err)
56 }
57 h.instance = h.url("valley")
58 h.project("valley", "policy/instance/readme", "the instance\n")
59 h.project("app", "policy/valley", h.instance+"\n")
60 h.project("site", "policy/valley", h.instance+"\n")
61 return h
62}
63
64// url is the URL of the project name on the host.
65func (h *walkHost) url(name string) string { return filepath.Join(h.server, name+".git") }
66
67// project makes the project name on the host, with a checkout whose main
68// holds one file, and lists it in the instance's projects ref.
69func (h *walkHost) project(name, file, content string) {
70 origin, work := h.url(name), filepath.Join(h.dir, name)
71 h.git(h.dir, "init", "--quiet", "--bare", "--initial-branch=main", origin)
72 h.git(h.dir, "clone", "--quiet", origin, work)
73 h.work[name] = work
74 for _, kv := range [][2]string{{"user.name", "alice"}, {"user.email", "alice@example.org"}, {"valley.principal", "alice"}} {
75 h.git(work, "config", kv[0], kv[1])
76 }
77 h.git(work, "checkout", "--quiet", "-b", "main")
78 h.write(name, file, content)
79 h.git(work, "add", ".")
80 h.git(work, "commit", "--quiet", "-m", "base")
81 h.git(work, "push", "--quiet", "origin", "main")
82 listed := h.git(h.url("valley"), "for-each-ref", "--format=%(objectname)", projectsRef)
83 names := ""
84 if listed != "" {
85 names = h.git(h.url("valley"), "cat-file", "blob", listed) + "\n"
86 }
87 blob := h.gitIn(h.url("valley"), names+name+"\n", "hash-object", "-w", "--stdin")
88 h.git(h.url("valley"), "update-ref", projectsRef, blob)
89}
90
91// write writes a file in a project's checkout.
92func (h *walkHost) write(name, file, content string) {
93 path := filepath.Join(h.work[name], file)
94 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
95 h.t.Fatal(err)
96 }
97 if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
98 h.t.Fatal(err)
99 }
100}
101
102// ready readies a change in the project name: a branch with one commit,
103// pushed, then readied as the change id.
104func (h *walkHost) ready(name, id, branch string) {
105 work := h.work[name]
106 h.git(work, "checkout", "--quiet", "-b", branch, "main")
107 h.write(name, branch+".txt", branch+"\n")
108 h.git(work, "add", ".")
109 h.git(work, "commit", "--quiet", "-m", branch)
110 h.git(work, "push", "--quiet", "origin", branch)
111 h.git(work, "checkout", "--quiet", "main")
112 h.t.Chdir(work)
113 var stdout, stderr bytes.Buffer
114 if code := run([]string{"ready", "--change", id, branch}, &stdout, &stderr, os.Exit); code != 0 {
115 h.t.Fatalf("valley ready in %s: %s", name, stderr.String())
116 }
117}
118
119// point has the project name's main name the valley at url.
120func (h *walkHost) point(name, url string) {
121 h.write(name, "policy/valley", url+"\n")
122 h.git(h.work[name], "commit", "--quiet", "-am", "another valley")
123 h.git(h.work[name], "push", "--quiet", "origin", "main")
124}
125
126func (h *walkHost) git(dir string, args ...string) string {
127 h.t.Helper()
128 return h.gitIn(dir, "", args...)
129}
130
131func (h *walkHost) gitIn(dir, stdin string, args ...string) string {
132 h.t.Helper()
133 cmd := exec.Command("git", args...)
134 cmd.Dir = dir
135 cmd.Stdin = strings.NewReader(stdin)
136 out, err := cmd.CombinedOutput()
137 if err != nil {
138 h.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
139 }
140 return strings.TrimSpace(string(out))
141}
142
143// ran is how a run of valley ended: its status and output.
144type ran struct {
145 status int
146 stdout, stderr string
147}
148
149// run runs valley with args in app's checkout, its answers read from
150// stdin. h.t.Chdir must have been called from the test's goroutine.
151func (h *walkHost) run(stdin *os.File, args ...string) ran { return <-h.start(stdin, args...) }
152
153// start runs valley as run does, in a goroutine, and says how it ended. A
154// signal the review takes ends it through the end path, which would end
155// the process: it fails the test, says how it ended and leaves its
156// goroutine, so a test that waits is not left waiting.
157func (h *walkHost) start(stdin *os.File, args ...string) <-chan ran {
158 ended := make(chan ran, 2)
159 go func() {
160 old := os.Stdin
161 os.Stdin = stdin
162 defer func() { os.Stdin = old }()
163 var stdout, stderr bytes.Buffer
164 status := run(args, &stdout, &stderr, func(status int) {
165 h.t.Errorf("a signal the review took ended it with %d", status)
166 ended <- ran{status, stdout.String(), stderr.String()}
167 runtime.Goexit()
168 })
169 ended <- ran{status, stdout.String(), stderr.String()}
170 }()
171 return ended
172}
173
174// fromApp has the test run valley from app's checkout. The walk and
175// valley review <change> catch SIGINT and SIGTERM until the process
176// exits, so the test gives them back once it has ended.
177func (h *walkHost) fromApp() {
178 h.t.Chdir(h.work["app"])
179 h.t.Cleanup(func() { signal.Reset(os.Interrupt, syscall.SIGTERM) })
180}
181
182// leftBehind fails the test when the run left anything in its TMPDIR.
183func (h *walkHost) leftBehind() {
184 h.t.Helper()
185 if left, _ := os.ReadDir(h.tmp); len(left) > 0 {
186 h.t.Errorf("the run left %s in its TMPDIR", left[0].Name())
187 }
188}
189
190// answers is a file holding the answers given.
191func (h *walkHost) answers(text string) *os.File {
192 path := filepath.Join(h.dir, "answers")
193 if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
194 h.t.Fatal(err)
195 }
196 f, err := os.Open(path)
197 if err != nil {
198 h.t.Fatal(err)
199 }
200 h.t.Cleanup(func() { f.Close() })
201 return f
202}
203
204// heldChecks makes the checks read every review starts hold through
205// SIGTERM, which a review's cleanup sends it, until the test releases it
206// (fakeCheckline). It returns once the read is running, and the review has
207// shown its page; it is given the answers that end the review.
208type heldChecks struct {
209 t *testing.T
210 dir string
211}
212
213func holdChecks(t *testing.T) heldChecks {
214 dir := t.TempDir()
215 for _, f := range []string{"ready", "termed", "release"} {
216 if err := syscall.Mkfifo(filepath.Join(dir, f), 0o600); err != nil {
217 t.Fatal(err)
218 }
219 }
220 t.Setenv("VALLEY_TEST_HELD_CHECKS", dir)
221 return heldChecks{t, dir}
222}
223
224// await returns once the held read says it has reached the stage named.
225func (c heldChecks) await(stage string) {
226 if _, err := os.ReadFile(filepath.Join(c.dir, stage)); err != nil {
227 c.t.Fatal(err)
228 }
229}
230
231// release lets the held read end.
232func (c heldChecks) release() {
233 if err := os.WriteFile(filepath.Join(c.dir, "release"), nil, 0o600); err != nil {
234 c.t.Fatal(err)
235 }
236}
237
238// fakeCheckline is the review's checks read when the test binary is run as
239// checkline: it reads no checks and prints no line. Under
240// VALLEY_TEST_HELD_CHECKS, the first read says it is running on the fifo
241// ready there, and once sent SIGTERM says so on termed and waits for
242// release, which holds the review's cleanup open. Any later read ends at
243// once, so a walk that goes on does not wait on it.
244func fakeCheckline() int {
245 dir := os.Getenv("VALLEY_TEST_HELD_CHECKS")
246 if dir == "" {
247 return 0
248 }
249 if f, err := os.OpenFile(filepath.Join(dir, "claimed"), os.O_CREATE|os.O_EXCL, 0o600); err != nil {
250 return 0
251 } else {
252 f.Close()
253 }
254 c := make(chan os.Signal, 1)
255 signal.Notify(c, syscall.SIGTERM)
256 _ = os.WriteFile(filepath.Join(dir, "ready"), nil, 0o600)
257 <-c
258 _ = os.WriteFile(filepath.Join(dir, "termed"), nil, 0o600)
259 _, _ = os.ReadFile(filepath.Join(dir, "release"))
260 return 0
261}
262
263// signalSelf sends sig to the test's process, and returns once every
264// channel notified of it has been sent it: os/signal sends to all of them
265// under one lock, which Stop takes.
266func signalSelf(t *testing.T, sig syscall.Signal) {
267 seen := make(chan os.Signal, 1)
268 signal.Notify(seen, sig)
269 if err := syscall.Kill(os.Getpid(), sig); err != nil {
270 t.Fatal(err)
271 }
272 <-seen
273 signal.Stop(seen)
274}
275
276// interruptCleanup runs valley with args from app's checkout, answers s
277// once the first review's checks read is running, and sends SIGTERM once
278// that review has stopped listening and its cleanup waits on the read.
279// The input then ends, so a review that goes on ends rather than waits.
280func (h *walkHost) interruptCleanup(args ...string) ran {
281 held := holdChecks(h.t)
282 h.fromApp()
283 in, out, err := os.Pipe()
284 if err != nil {
285 h.t.Fatal(err)
286 }
287 defer in.Close()
288 ended := h.start(in, args...)
289 held.await("ready")
290 if _, err := out.Write([]byte("s\n")); err != nil {
291 h.t.Fatal(err)
292 }
293 held.await("termed")
294 signalSelf(h.t, syscall.SIGTERM)
295 held.release()
296 out.Close()
297 return <-ended
298}
299
300// A signal that arrives once a step's review has stopped listening, while
301// it cleans up, ends the walk before the next step: the step ends as it
302// would, the summary so far is printed, nothing is left in TMPDIR, and the
303// walk exits 130.
304func TestWalkEndsOnASignalWhileAStepCleansUp(t *testing.T) {
305 h := newWalkHost(t)
306 h.ready("app", strings.Repeat("m", 32), "a-one")
307 h.ready("app", strings.Repeat("n", 32), "a-two")
308 r := h.interruptCleanup("review", "--repo", "app")
309 if r.status != interruptedStatus {
310 t.Fatalf("the walk exited %d, not 130\n%s%s", r.status, r.stdout, r.stderr)
311 }
312 for _, want := range []string{"walked (1 of 2)\n", " ◇ app mmmm v1 skipped\n"} {
313 if !strings.Contains(r.stdout, want) {
314 t.Errorf("the walk did not print %q:\n%s", want, r.stdout)
315 }
316 }
317 if strings.Contains(r.stdout, "[2/2]") || strings.Contains(r.stdout, "needs you (") && strings.Contains(r.stdout, "still needs you") {
318 t.Errorf("the walk went on after the signal:\n%s", r.stdout)
319 }
320 h.leftBehind()
321}
322
323// valley review <change> given a signal while it cleans up exits 130.
324func TestReviewEndsOnASignalWhileItCleansUp(t *testing.T) {
325 h := newWalkHost(t)
326 h.ready("app", strings.Repeat("m", 32), "a-one")
327 r := h.interruptCleanup("review", strings.Repeat("m", 32))
328 if r.status != interruptedStatus {
329 t.Fatalf("the review exited %d, not 130\n%s%s", r.status, r.stdout, r.stderr)
330 }
331 if !strings.Contains(r.stdout, "skipped a-one; nothing done") {
332 t.Errorf("the review did not end as it would:\n%s", r.stdout)
333 }
334 h.leftBehind()
335}
336
337// A step in a project whose main names another valley is not reviewed with
338// the walk's signer source: it ends in error, saying which valley each
339// names, and the walk goes on. Given what to trust, the walk reviews it.
340func TestWalkRefusesAStepWhoseProjectNamesAnotherValley(t *testing.T) {
341 h := newWalkHost(t)
342 other := filepath.Join(h.dir, "other.git")
343 h.git(h.dir, "init", "--quiet", "--bare", other)
344 h.publish(other, "other-host/attestations")
345 h.point("site", other)
346 h.ready("site", strings.Repeat("s", 32), "s-one")
347 h.ready("app", strings.Repeat("m", 32), "a-one")
348 h.fromApp()
349 r := h.run(h.answers("s\n"), "review")
350 if r.status != 1 {
351 t.Fatalf("the walk exited %d, not 1\n%s%s", r.status, r.stdout, r.stderr)
352 }
353 why := "its main names the valley " + other + ", not this checkout's " + h.instance +
354 " · review it from a checkout of its own valley"
355 if !strings.Contains(r.stderr, "valley: site: "+why+"\n") {
356 t.Errorf("the refused step did not say %q:\n%s", why, r.stderr)
357 }
358 for _, want := range []string{"walked (2 of 2)\n", " ✗ site ssss v1 error · its main names the valley ", " ◇ app mmmm v1 skipped\n"} {
359 if !strings.Contains(r.stdout, want) {
360 t.Errorf("the walk did not print %q:\n%s", want, r.stdout)
361 }
362 }
363 if strings.Contains(r.stdout, "s-one; nothing done") {
364 t.Errorf("the refused step was reviewed:\n%s", r.stdout)
365 }
366 t.Setenv("VALLEY_INTEGRATOR_SIGNER", "operator")
367 r = h.run(h.answers("s\ns\n"), "review")
368 if r.status != 0 || !strings.Contains(r.stdout, " ◇ site ssss v1 skipped\n") {
369 t.Errorf("the walk given an integrator name did not review site (%d):\n%s%s", r.status, r.stdout, r.stderr)
370 }
371 h.leftBehind()
372}
373
374// The instance repository names itself by its origin, which its cache
375// clone spells as the listing does, and another project names it at
376// policy/valley as written there. A checkout that spells it otherwise
377// still walks both: each reads the same publication.
378func TestWalkReviewsTheInstanceAndProjectsNamingItAnotherWay(t *testing.T) {
379 h := newWalkHost(t)
380 h.publish(h.url("valley"), "valley-host/attestations")
381 h.point("app", h.instance+"/")
382 h.ready("valley", strings.Repeat("v", 32), "v-one")
383 h.ready("site", strings.Repeat("s", 32), "s-one")
384 h.fromApp()
385 r := h.run(h.answers("s\ns\n"), "review")
386 if r.status != 0 {
387 t.Fatalf("the walk exited %d, not 0\n%s%s", r.status, r.stdout, r.stderr)
388 }
389 for _, want := range []string{" ◇ valley vvvv v1 skipped\n", " ◇ site ssss v1 skipped\n"} {
390 if !strings.Contains(r.stdout, want) {
391 t.Errorf("the walk did not print %q:\n%s%s", want, r.stdout, r.stderr)
392 }
393 }
394 h.leftBehind()
395}
396
397// publish has the bare repository at dir publish signers under name.
398func (h *walkHost) publish(dir, name string) {
399 keys := h.gitIn(dir, name+" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKf0k8m5mJ8T0pQ1o4n3wWvZ0f0r6C5g1Y8p0rJpY1sQ\n", "hash-object", "-w", "--stdin")
400 named := h.gitIn(dir, name+"\n", "hash-object", "-w", "--stdin")
401 tree := h.gitIn(dir, "100644 blob "+named+"\t"+signersName+"\n100644 blob "+keys+"\t"+signersKeys+"\n", "mktree")
402 h.git(dir, "update-ref", signersRef, tree)
403}