gunk-dev/the-valley

pending_linux_test.go

sourceb40fcdedd01cmain's published tip history
8.6 KiB
1package main
2
3import (
4 "bytes"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "syscall"
13 "testing"
14 "time"
15)
16
17// However valley pending ends while its read of the worker's telemetry
18// runs, the read's ssh ends with it, and the signal ends pending as it
19// would end any process: SIGTERM and SIGKILL while pending waits on a
20// stalled host for main's line, and SIGPIPE when the reader of its output
21// has gone by the time it writes, with nothing waiting on the read. Each
22// time the ssh is killed by the system as pending dies (dieWithParent),
23// and this process, the reaper of what pending leaves, waits for it.
24func TestPendingsSSHEndsWithIt(t *testing.T) {
25 self, err := os.Executable()
26 if err != nil {
27 t.Fatal(err)
28 }
29 for _, c := range []struct {
30 name string
31 signal syscall.Signal // sent to pending, or SIGPIPE from its write
32 }{
33 {"SIGTERM", syscall.SIGTERM},
34 {"SIGKILL", syscall.SIGKILL},
35 {"SIGPIPE", syscall.SIGPIPE},
36 } {
37 t.Run(c.name, func(t *testing.T) {
38 reapOrphans(t)
39 dir := t.TempDir()
40 real, err := exec.LookPath("git")
41 if err != nil {
42 t.Skip("no git to run")
43 }
44 toolsOnPath(t, dir, "git", "cue")
45 pid, gate := filepath.Join(dir, "ssh.pid"), filepath.Join(dir, "ssh.gate")
46 if err := syscall.Mkfifo(pid, 0o600); err != nil {
47 t.Fatal(err)
48 }
49 // ssh is the host: it says its process ID, lets a git the
50 // gate holds go on, says the answer's first line, and stalls.
51 header := `{"kind":"header","host":"valley-host","format":"valley-telemetry/v1"}`
52 ssh := fmt.Sprintf("#!/bin/sh\necho $$ > '%s'\n[ -p '%s' ] && echo go > '%s'\necho '%s'\nexec sleep 86398\n", pid, gate, gate, header)
53 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil {
54 t.Fatal(err)
55 }
56 cmd := exec.Command(self, "pending")
57 cmd.Stdin = strings.NewReader("x")
58 var out bytes.Buffer
59 cmd.Stdout, cmd.Stderr = &out, &out
60 if c.signal == syscall.SIGPIPE {
61 // Nothing waits on the read, and pending's first write,
62 // which finds no reader, comes once origin is listed. The
63 // listing waits for ssh, so the read is running by then.
64 sh, _ := policyProject(t, filepath.Join(dir, "origin"), 1)
65 sh("config", "valley.telemetry.remote", "ssh://git@valley-host/origin.git")
66 if err := syscall.Mkfifo(gate, 0o600); err != nil {
67 t.Fatal(err)
68 }
69 held := fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = ls-remote ] && [ ! -e '%s.passed' ]; then : > '%s.passed'; read go < '%s'; fi\nexec '%s' \"$@\"\n", gate, gate, gate, real)
70 if err := os.WriteFile(filepath.Join(dir, "bin", "git"), []byte(held), 0o755); err != nil {
71 t.Fatal(err)
72 }
73 r, w, err := os.Pipe()
74 if err != nil {
75 t.Fatal(err)
76 }
77 r.Close()
78 defer w.Close()
79 cmd.Stdout = w
80 } else {
81 followProject(t, filepath.Join(dir, "origin"))
82 }
83 cmd.Env = append(os.Environ(), "VALLEY_TEST_AS_MAIN=1")
84 if err := cmd.Start(); err != nil {
85 t.Fatal(err)
86 }
87 exited := make(chan error, 1)
88 go func() { exited <- cmd.Wait() }()
89 said := make(chan int, 1)
90 go func() {
91 data, _ := os.ReadFile(pid)
92 n, _ := strconv.Atoi(strings.TrimSpace(string(data)))
93 said <- n
94 }()
95 var read int
96 select {
97 case read = <-said:
98 case err := <-exited:
99 unheard(pid)
100 t.Fatalf("pending ended before its read reached the host: %v\n%s", err, out.String())
101 case <-time.After(time.Minute):
102 cmd.Process.Kill()
103 <-exited
104 unheard(pid)
105 t.Fatalf("pending's read did not reach the host in a minute\n%s", out.String())
106 }
107 if c.signal != syscall.SIGPIPE {
108 cmd.Process.Signal(c.signal)
109 }
110 err = <-exited
111 var ee *exec.ExitError
112 if !errors.As(err, &ee) || !ee.Sys().(syscall.WaitStatus).Signaled() || ee.Sys().(syscall.WaitStatus).Signal() != c.signal {
113 t.Errorf("pending ended with %v, not by %s\n%s", err, c.name, out.String())
114 }
115 if ws, ok := waitOrphan(t, read); ok && (!ws.Signaled() || ws.Signal() != syscall.SIGKILL) {
116 t.Errorf("the read's ssh ended with %v, not killed as pending died", ws)
117 }
118 })
119 }
120}
121
122// However valley pending ends while attest verifies the evidence origin
123// holds, the verify ends with it: SIGTERM and SIGKILL while main's walk
124// judges the two notes stored for main's tree. The system kills the
125// attest as pending dies (dieWithParent), and this process, the reaper of
126// what pending leaves, waits for it.
127func TestPendingsAttestEndsWithIt(t *testing.T) {
128 self, err := os.Executable()
129 if err != nil {
130 t.Fatal(err)
131 }
132 for _, signal := range []syscall.Signal{syscall.SIGTERM, syscall.SIGKILL} {
133 t.Run(signal.String(), func(t *testing.T) {
134 reapOrphans(t)
135 dir := t.TempDir()
136 toolsOnPath(t, dir, "git", "cue")
137 pid := filepath.Join(dir, "attest.pid")
138 if err := syscall.Mkfifo(pid, 0o600); err != nil {
139 t.Fatal(err)
140 }
141 // attest says its process ID and stalls.
142 stall := fmt.Sprintf("#!/bin/sh\necho $$ > '%s'\nexec sleep 86397\n", pid)
143 if err := os.WriteFile(filepath.Join(dir, "bin", "attest"), []byte(stall), 0o755); err != nil {
144 t.Fatal(err)
145 }
146 followProject(t, filepath.Join(dir, "origin"))
147 storeMainEvidence(t, filepath.Join(dir, "origin", "origin.git"))
148 cmd := exec.Command(self, "pending")
149 cmd.Stdin = strings.NewReader("x")
150 var out bytes.Buffer
151 cmd.Stdout, cmd.Stderr = &out, &out
152 cmd.Env = append(os.Environ(), "VALLEY_TEST_AS_MAIN=1")
153 if err := cmd.Start(); err != nil {
154 t.Fatal(err)
155 }
156 exited := make(chan error, 1)
157 go func() { exited <- cmd.Wait() }()
158 said := make(chan int, 1)
159 go func() {
160 data, _ := os.ReadFile(pid)
161 n, _ := strconv.Atoi(strings.TrimSpace(string(data)))
162 said <- n
163 }()
164 var verifying int
165 select {
166 case verifying = <-said:
167 case err := <-exited:
168 unheard(pid)
169 t.Fatalf("pending ended before it verified main's evidence: %v\n%s", err, out.String())
170 case <-time.After(time.Minute):
171 cmd.Process.Kill()
172 <-exited
173 unheard(pid)
174 t.Fatalf("pending did not verify main's evidence in a minute\n%s", out.String())
175 }
176 cmd.Process.Signal(signal)
177 err := <-exited
178 var ee *exec.ExitError
179 if !errors.As(err, &ee) || !ee.Sys().(syscall.WaitStatus).Signaled() || ee.Sys().(syscall.WaitStatus).Signal() != signal {
180 t.Errorf("pending ended with %v, not by %s\n%s", err, signal, out.String())
181 }
182 if ws, ok := waitOrphan(t, verifying); ok && (!ws.Signaled() || ws.Signal() != syscall.SIGKILL) {
183 t.Errorf("the attest verify ended with %v, not killed as pending died", ws)
184 }
185 })
186 }
187}
188
189// storeMainEvidence stores in origin, the bare repository of a project
190// followProject made, two notes about f-1 for the tree of main's tip, one
191// signer's each, and publishes the host's signers, so main's walk verifies
192// both in one attest run. The project reads no worker telemetry.
193func storeMainEvidence(t *testing.T, origin string) {
194 t.Helper()
195 if out, err := exec.Command("git", "config", "--unset", "valley.telemetry.remote").CombinedOutput(); err != nil {
196 t.Fatalf("git config --unset: %v\n%s", err, out)
197 }
198 in := bareGit(t, origin)
199 tip := in("", "rev-parse", "main")
200 digest, err := rememberedDigest(git{env: gitEnvironment(os.Environ()), dir: origin}, tip)
201 if err != nil {
202 t.Fatal(err)
203 }
204 publishSigners(t, origin, "integrator", "worker")
205 stored := in("predicate.check.name f-1\n\n— worker signature\n", "hash-object", "-w", "--stdin")
206 check := in(fmt.Sprintf("100644 blob %s\tstatement.note\n", stored), "mktree")
207 tree := in(fmt.Sprintf("040000 tree %s\tf-1\n", check), "mktree")
208 for _, hash := range []string{"00000001", "00000002"} {
209 in("", "update-ref", attestationRefs+digest+"/"+hash, tree)
210 }
211}
212
213// reapOrphans makes this process the reaper of the processes its children
214// leave when they die (PR_SET_CHILD_SUBREAPER), until the test ends, so a
215// test can wait for them.
216func reapOrphans(t *testing.T) {
217 t.Helper()
218 const setChildSubreaper = 36
219 if _, _, e := syscall.RawSyscall(syscall.SYS_PRCTL, setChildSubreaper, 1, 0); e != 0 {
220 t.Fatalf("could not reap orphans: %v", e)
221 }
222 t.Cleanup(func() { syscall.RawSyscall(syscall.SYS_PRCTL, setChildSubreaper, 0, 0) })
223}
224
225// waitOrphan waits for pid, a process reapOrphans makes this one's, to
226// end, and says how it ended. One still running after a minute has
227// outlived what started it: it is killed, and ok is false.
228func waitOrphan(t *testing.T, pid int) (ws syscall.WaitStatus, ok bool) {
229 t.Helper()
230 ended := make(chan syscall.WaitStatus, 1)
231 go func() {
232 var ws syscall.WaitStatus
233 syscall.Wait4(pid, &ws, 0, nil)
234 ended <- ws
235 }()
236 select {
237 case ws := <-ended:
238 return ws, true
239 case <-time.After(time.Minute):
240 syscall.Kill(pid, syscall.SIGKILL)
241 <-ended
242 t.Errorf("process %d outlived what started it", pid)
243 return 0, false
244 }
245}