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