| 1 | //go:build darwin || testbuild |
| 2 | |
| 3 | package runner |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "errors" |
| 10 | "net" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 19 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 20 | ) |
| 21 | |
| 22 | // macSocketDir is a private directory with a path short enough for a |
| 23 | // Mac's sun_path, without symbolic links (a Mac's TMPDIR is under /var, |
| 24 | // a link to /private/var). |
| 25 | func macSocketDir(t *testing.T) string { |
| 26 | t.Helper() |
| 27 | root, err := filepath.EvalSymlinks(os.TempDir()) |
| 28 | if err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | dir, err := os.MkdirTemp(root, "t") |
| 32 | if err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | t.Cleanup(func() { os.RemoveAll(dir) }) |
| 36 | if err := os.Chmod(dir, 0700); err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | if len(dir)+len("/equipo.sock") > provider.MaxDarwinSocketPath { |
| 40 | t.Fatalf("TMPDIR %s is too long for a Mac socket path; set a shorter TMPDIR", root) |
| 41 | } |
| 42 | return dir |
| 43 | } |
| 44 | |
| 45 | // lockedBuffer is what a test server was sent, read while it runs. |
| 46 | type lockedBuffer struct { |
| 47 | mu sync.Mutex |
| 48 | buf bytes.Buffer |
| 49 | } |
| 50 | |
| 51 | func (b *lockedBuffer) Write(p []byte) (int, error) { |
| 52 | b.mu.Lock() |
| 53 | defer b.mu.Unlock() |
| 54 | return b.buf.Write(p) |
| 55 | } |
| 56 | |
| 57 | func (b *lockedBuffer) Len() int { |
| 58 | b.mu.Lock() |
| 59 | defer b.mu.Unlock() |
| 60 | return b.buf.Len() |
| 61 | } |
| 62 | |
| 63 | func (b *lockedBuffer) String() string { |
| 64 | b.mu.Lock() |
| 65 | defer b.mu.Unlock() |
| 66 | return b.buf.String() |
| 67 | } |
| 68 | |
| 69 | // echoServer listens at dir/equipo.sock and answers each line with |
| 70 | // reply, recording what it was sent. |
| 71 | func echoServer(t *testing.T, dir, reply string) (string, *lockedBuffer) { |
| 72 | t.Helper() |
| 73 | path := filepath.Join(dir, "equipo.sock") |
| 74 | l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) |
| 75 | if err != nil { |
| 76 | t.Fatal(err) |
| 77 | } |
| 78 | if err := os.Chmod(path, 0600); err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | got := &lockedBuffer{} |
| 82 | done := make(chan struct{}) |
| 83 | go func() { |
| 84 | defer close(done) |
| 85 | for { |
| 86 | c, err := l.AcceptUnix() |
| 87 | if err != nil { |
| 88 | return |
| 89 | } |
| 90 | r := bufio.NewReader(c) |
| 91 | for { |
| 92 | line, err := r.ReadBytes('\n') |
| 93 | got.Write(line) |
| 94 | if err != nil { |
| 95 | break |
| 96 | } |
| 97 | if bytes.Contains(line, []byte(`"id"`)) { |
| 98 | c.Write([]byte(reply + "\n")) |
| 99 | } |
| 100 | } |
| 101 | c.Close() |
| 102 | } |
| 103 | }() |
| 104 | t.Cleanup(func() { l.Close(); <-done }) |
| 105 | return path, got |
| 106 | } |
| 107 | |
| 108 | // internal/toolproxy's bounds (maxToolFrame, maxReplyFrame), which the |
| 109 | // Mac endpoint keeps. |
| 110 | const ( |
| 111 | linuxToolFrame = 64 << 10 |
| 112 | linuxReplyFrame = 4 << 20 |
| 113 | ) |
| 114 | |
| 115 | // The Mac endpoint relays as the Linux tool proxy does: a request up to |
| 116 | // 64 KiB, a reply up to 4 MiB (an image a tool returned), a notification |
| 117 | // with no reply; anything over a bound or not JSON-RPC 2.0 ends it, and |
| 118 | // nothing over a bound is passed on. |
| 119 | func TestDarwinToolProxyFrameBounds(t *testing.T) { |
| 120 | image := `{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"header"},{"type":"image","data":"` + strings.Repeat("A", 2_100_000) + `","mimeType":"image/png"}]}}` |
| 121 | runner, proxy := net.Pipe() |
| 122 | go func() { |
| 123 | r := bufio.NewReader(runner) |
| 124 | if _, err := r.ReadBytes('\n'); err == nil { |
| 125 | runner.Write([]byte(image + "\n")) |
| 126 | } |
| 127 | runner.Close() |
| 128 | }() |
| 129 | var out bytes.Buffer |
| 130 | in := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_attachment"}}` + "\n") |
| 131 | if err := macRelay(in, &out, proxy); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | if out.String() != image+"\n" { |
| 135 | t.Fatalf("reply of %d bytes", out.Len()) |
| 136 | } |
| 137 | |
| 138 | runner, proxy = net.Pipe() |
| 139 | go func() { |
| 140 | r := bufio.NewReader(runner) |
| 141 | if _, err := r.ReadBytes('\n'); err == nil { |
| 142 | runner.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"` + strings.Repeat("A", linuxReplyFrame) + `"}]}}` + "\n")) |
| 143 | } |
| 144 | runner.Close() |
| 145 | }() |
| 146 | out.Reset() |
| 147 | in = strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_attachment"}}` + "\n") |
| 148 | if err := macRelay(in, &out, proxy); !errors.Is(err, runnerproto.ErrInvalid) || out.Len() != 0 { |
| 149 | t.Fatalf("a reply over the bound: %v, %d bytes out", err, out.Len()) |
| 150 | } |
| 151 | |
| 152 | for name, line := range map[string]string{ |
| 153 | "over the bound": `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + strings.Repeat("x", linuxToolFrame) + `"}}`, |
| 154 | "not 2.0": `{"jsonrpc":"1.0","id":1,"method":"ping"}`, |
| 155 | "unknown field": `{"jsonrpc":"2.0","id":1,"method":"ping","extra":1}`, |
| 156 | "two values": `{"jsonrpc":"2.0","id":1,"method":"ping"}{"jsonrpc":"2.0","id":2,"method":"ping"}`, |
| 157 | "no newline": `{"jsonrpc":"2.0","id":1,"method":"ping"}`, |
| 158 | } { |
| 159 | runner, proxy = net.Pipe() |
| 160 | sent := make(chan int, 1) |
| 161 | go func() { |
| 162 | n, _ := bufio.NewReader(runner).ReadBytes('\n') |
| 163 | sent <- len(n) |
| 164 | runner.Close() |
| 165 | }() |
| 166 | input := line + "\n" |
| 167 | if name == "no newline" { |
| 168 | input = line |
| 169 | } |
| 170 | out.Reset() |
| 171 | if err := macRelay(strings.NewReader(input), &out, proxy); !errors.Is(err, runnerproto.ErrInvalid) || out.Len() != 0 { |
| 172 | t.Fatalf("%s: %v, %d bytes out", name, err, out.Len()) |
| 173 | } |
| 174 | proxy.Close() |
| 175 | if n := <-sent; n != 0 { |
| 176 | t.Fatalf("%s: %d bytes reached the runner", name, n) |
| 177 | } |
| 178 | runner.Close() |
| 179 | } |
| 180 | |
| 181 | // A notification goes up and waits for no reply. |
| 182 | runner, proxy = net.Pipe() |
| 183 | got := make(chan string, 1) |
| 184 | go func() { |
| 185 | line, _ := bufio.NewReader(runner).ReadString('\n') |
| 186 | got <- line |
| 187 | runner.Close() |
| 188 | }() |
| 189 | out.Reset() |
| 190 | note := `{"jsonrpc":"2.0","method":"notifications/initialized"}` |
| 191 | if err := macRelay(strings.NewReader(note+"\n"), &out, proxy); err != nil || out.Len() != 0 || <-got != note+"\n" { |
| 192 | t.Fatalf("notification: %v, %q out", err, out.String()) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // ServeDarwinToolProxy dials only a socket at a clean absolute path that |
| 197 | // fits a Mac's sun_path, in a private directory of this user's reached |
| 198 | // without a symbolic link, and refuses anything else before a byte is |
| 199 | // sent or written. |
| 200 | func TestDarwinToolProxyRefusesPaths(t *testing.T) { |
| 201 | dir := macSocketDir(t) |
| 202 | path, got := echoServer(t, dir, `{"jsonrpc":"2.0","id":1,"result":{}}`) |
| 203 | ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n" |
| 204 | var out bytes.Buffer |
| 205 | if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, path); err != nil || out.String() != `{"jsonrpc":"2.0","id":1,"result":{}}`+"\n" { |
| 206 | t.Fatalf("a private socket: %v %q", err, out.String()) |
| 207 | } |
| 208 | link := dir + "-link" |
| 209 | if err := os.Symlink(dir, link); err != nil { |
| 210 | t.Fatal(err) |
| 211 | } |
| 212 | t.Cleanup(func() { os.Remove(link) }) |
| 213 | open := filepath.Join(filepath.Dir(dir), filepath.Base(dir)+"-open") |
| 214 | if err := os.Mkdir(open, 0755); err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | t.Cleanup(func() { os.RemoveAll(open) }) |
| 218 | openPath, openGot := echoServer(t, open, `{"jsonrpc":"2.0","id":1,"result":{}}`) |
| 219 | plain := filepath.Join(dir, "plain") |
| 220 | if err := os.WriteFile(plain, nil, 0600); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | looseDir := filepath.Join(dir, "l") |
| 224 | if err := os.Mkdir(looseDir, 0700); err != nil { |
| 225 | t.Fatal(err) |
| 226 | } |
| 227 | loose, looseGot := echoServer(t, looseDir, `{"jsonrpc":"2.0","id":1,"result":{}}`) |
| 228 | if err := os.Chmod(loose, 0666); err != nil { |
| 229 | t.Fatal(err) |
| 230 | } |
| 231 | // The longest path a Mac takes: a socket at exactly 103 bytes serves. |
| 232 | edgeDir := dir + "/" + strings.Repeat("d", provider.MaxDarwinSocketPath-len(dir)-1-len("/equipo.sock")) |
| 233 | if err := os.Mkdir(edgeDir, 0700); err != nil { |
| 234 | t.Fatal(err) |
| 235 | } |
| 236 | edge, _ := echoServer(t, edgeDir, `{"jsonrpc":"2.0","id":1,"result":{}}`) |
| 237 | if len(edge) != provider.MaxDarwinSocketPath { |
| 238 | t.Fatalf("the edge socket is %d bytes", len(edge)) |
| 239 | } |
| 240 | out.Reset() |
| 241 | if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, edge); err != nil || out.Len() == 0 { |
| 242 | t.Fatalf("a socket of %d bytes: %v %q", len(edge), err, out.String()) |
| 243 | } |
| 244 | // A real socket one byte longer. A Mac cannot bind that path by |
| 245 | // name, so it is bound by a relative name from inside its directory |
| 246 | // (either system takes that); the endpoint must refuse it by length. |
| 247 | longDir := dir + "/" + strings.Repeat("e", provider.MaxDarwinSocketPath-len(dir)-len("/equipo.sock")) |
| 248 | if err := os.Mkdir(longDir, 0700); err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | t.Chdir(longDir) |
| 252 | ll, err := net.ListenUnix("unix", &net.UnixAddr{Name: "equipo.sock", Net: "unix"}) |
| 253 | if err != nil { |
| 254 | t.Fatal(err) |
| 255 | } |
| 256 | defer ll.Close() |
| 257 | long := filepath.Join(longDir, "equipo.sock") |
| 258 | if err := os.Chmod(long, 0600); err != nil || len(long) != provider.MaxDarwinSocketPath+1 { |
| 259 | t.Fatalf("the long socket %s (%d bytes): %v", long, len(long), err) |
| 260 | } |
| 261 | // Every refusal comes before a dial. |
| 262 | dials := 0 |
| 263 | defer func(f func(context.Context, string, string) (net.Conn, error)) { macDial = f }(macDial) |
| 264 | macDial = func(ctx context.Context, network, address string) (net.Conn, error) { |
| 265 | dials++ |
| 266 | return (&net.Dialer{}).DialContext(ctx, network, address) |
| 267 | } |
| 268 | for name, p := range map[string]string{ |
| 269 | "relative": "t/equipo.sock", |
| 270 | "unclean": dir + "/./equipo.sock", |
| 271 | "too long": long, |
| 272 | "linked": filepath.Join(link, "equipo.sock"), |
| 273 | "open parent": openPath, |
| 274 | "not a socket": plain, |
| 275 | "loose socket": loose, |
| 276 | "missing": filepath.Join(dir, "gone.sock"), |
| 277 | } { |
| 278 | out.Reset() |
| 279 | before := got.Len() |
| 280 | // A refusal is immediate; a dial that should not have happened |
| 281 | // is cut off rather than left waiting. |
| 282 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 283 | err := ServeDarwinToolProxy(ctx, strings.NewReader(ping), &out, p) |
| 284 | cancel() |
| 285 | if err == nil || out.Len() != 0 || got.Len() != before || openGot.Len() != 0 || looseGot.Len() != 0 || dials != 0 { |
| 286 | t.Fatalf("%s %s: %v, %q out, %d dials", name, p, err, out.String(), dials) |
| 287 | } |
| 288 | } |
| 289 | // The seam is the endpoint's dial: the private socket goes through it. |
| 290 | if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, path); err != nil || dials != 1 { |
| 291 | t.Fatalf("the private socket: %v, %d dials", err, dials) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // The endpoint checks who listens before it sends anything: a step |
| 296 | // socket bound by another user is refused (LOCAL_PEERCRED on a Mac, |
| 297 | // through its seam here). |
| 298 | func TestDarwinToolProxyChecksTheListener(t *testing.T) { |
| 299 | dir := macSocketDir(t) |
| 300 | path, got := echoServer(t, dir, `{"jsonrpc":"2.0","id":1,"result":{}}`) |
| 301 | ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n" |
| 302 | defer func(f func(*net.UnixConn) (uint32, error)) { macListenerUID = f }(macListenerUID) |
| 303 | for name, seam := range map[string]func(*net.UnixConn) (uint32, error){ |
| 304 | "another user": func(*net.UnixConn) (uint32, error) { return uint32(os.Getuid()) + 1, nil }, |
| 305 | "root": func(*net.UnixConn) (uint32, error) { return 0, nil }, |
| 306 | "unknown": func(*net.UnixConn) (uint32, error) { return uint32(os.Getuid()), errors.New("no credential") }, |
| 307 | } { |
| 308 | if os.Getuid() == 0 && name == "root" { |
| 309 | continue |
| 310 | } |
| 311 | macListenerUID = seam |
| 312 | var out bytes.Buffer |
| 313 | if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, path); !errors.Is(err, runnerproto.ErrInvalid) || out.Len() != 0 { |
| 314 | t.Fatalf("%s: %v %q", name, err, out.String()) |
| 315 | } |
| 316 | } |
| 317 | // Give the server a moment to have read anything it was sent. |
| 318 | time.Sleep(20 * time.Millisecond) |
| 319 | if got.Len() != 0 { |
| 320 | t.Fatalf("a refused listener was sent %q", got.String()) |
| 321 | } |
| 322 | } |
| 323 | |