//go:build darwin || testbuild package runner import ( "bufio" "bytes" "context" "errors" "net" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) // macSocketDir is a private directory with a path short enough for a // Mac's sun_path, without symbolic links (a Mac's TMPDIR is under /var, // a link to /private/var). func macSocketDir(t *testing.T) string { t.Helper() root, err := filepath.EvalSymlinks(os.TempDir()) if err != nil { t.Fatal(err) } dir, err := os.MkdirTemp(root, "t") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(dir) }) if err := os.Chmod(dir, 0700); err != nil { t.Fatal(err) } if len(dir)+len("/equipo.sock") > provider.MaxDarwinSocketPath { t.Fatalf("TMPDIR %s is too long for a Mac socket path; set a shorter TMPDIR", root) } return dir } // lockedBuffer is what a test server was sent, read while it runs. type lockedBuffer struct { mu sync.Mutex buf bytes.Buffer } func (b *lockedBuffer) Write(p []byte) (int, error) { b.mu.Lock() defer b.mu.Unlock() return b.buf.Write(p) } func (b *lockedBuffer) Len() int { b.mu.Lock() defer b.mu.Unlock() return b.buf.Len() } func (b *lockedBuffer) String() string { b.mu.Lock() defer b.mu.Unlock() return b.buf.String() } // echoServer listens at dir/equipo.sock and answers each line with // reply, recording what it was sent. func echoServer(t *testing.T, dir, reply string) (string, *lockedBuffer) { t.Helper() path := filepath.Join(dir, "equipo.sock") l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) if err != nil { t.Fatal(err) } if err := os.Chmod(path, 0600); err != nil { t.Fatal(err) } got := &lockedBuffer{} done := make(chan struct{}) go func() { defer close(done) for { c, err := l.AcceptUnix() if err != nil { return } r := bufio.NewReader(c) for { line, err := r.ReadBytes('\n') got.Write(line) if err != nil { break } if bytes.Contains(line, []byte(`"id"`)) { c.Write([]byte(reply + "\n")) } } c.Close() } }() t.Cleanup(func() { l.Close(); <-done }) return path, got } // internal/toolproxy's bounds (maxToolFrame, maxReplyFrame), which the // Mac endpoint keeps. const ( linuxToolFrame = 64 << 10 linuxReplyFrame = 4 << 20 ) // The Mac endpoint relays as the Linux tool proxy does: a request up to // 64 KiB, a reply up to 4 MiB (an image a tool returned), a notification // with no reply; anything over a bound or not JSON-RPC 2.0 ends it, and // nothing over a bound is passed on. func TestDarwinToolProxyFrameBounds(t *testing.T) { image := `{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"header"},{"type":"image","data":"` + strings.Repeat("A", 2_100_000) + `","mimeType":"image/png"}]}}` runner, proxy := net.Pipe() go func() { r := bufio.NewReader(runner) if _, err := r.ReadBytes('\n'); err == nil { runner.Write([]byte(image + "\n")) } runner.Close() }() var out bytes.Buffer in := strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_attachment"}}` + "\n") if err := macRelay(in, &out, proxy); err != nil { t.Fatal(err) } if out.String() != image+"\n" { t.Fatalf("reply of %d bytes", out.Len()) } runner, proxy = net.Pipe() go func() { r := bufio.NewReader(runner) if _, err := r.ReadBytes('\n'); err == nil { runner.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"` + strings.Repeat("A", linuxReplyFrame) + `"}]}}` + "\n")) } runner.Close() }() out.Reset() in = strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_attachment"}}` + "\n") if err := macRelay(in, &out, proxy); !errors.Is(err, runnerproto.ErrInvalid) || out.Len() != 0 { t.Fatalf("a reply over the bound: %v, %d bytes out", err, out.Len()) } for name, line := range map[string]string{ "over the bound": `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + strings.Repeat("x", linuxToolFrame) + `"}}`, "not 2.0": `{"jsonrpc":"1.0","id":1,"method":"ping"}`, "unknown field": `{"jsonrpc":"2.0","id":1,"method":"ping","extra":1}`, "two values": `{"jsonrpc":"2.0","id":1,"method":"ping"}{"jsonrpc":"2.0","id":2,"method":"ping"}`, "no newline": `{"jsonrpc":"2.0","id":1,"method":"ping"}`, } { runner, proxy = net.Pipe() sent := make(chan int, 1) go func() { n, _ := bufio.NewReader(runner).ReadBytes('\n') sent <- len(n) runner.Close() }() input := line + "\n" if name == "no newline" { input = line } out.Reset() if err := macRelay(strings.NewReader(input), &out, proxy); !errors.Is(err, runnerproto.ErrInvalid) || out.Len() != 0 { t.Fatalf("%s: %v, %d bytes out", name, err, out.Len()) } proxy.Close() if n := <-sent; n != 0 { t.Fatalf("%s: %d bytes reached the runner", name, n) } runner.Close() } // A notification goes up and waits for no reply. runner, proxy = net.Pipe() got := make(chan string, 1) go func() { line, _ := bufio.NewReader(runner).ReadString('\n') got <- line runner.Close() }() out.Reset() note := `{"jsonrpc":"2.0","method":"notifications/initialized"}` if err := macRelay(strings.NewReader(note+"\n"), &out, proxy); err != nil || out.Len() != 0 || <-got != note+"\n" { t.Fatalf("notification: %v, %q out", err, out.String()) } } // ServeDarwinToolProxy dials only a socket at a clean absolute path that // fits a Mac's sun_path, in a private directory of this user's reached // without a symbolic link, and refuses anything else before a byte is // sent or written. func TestDarwinToolProxyRefusesPaths(t *testing.T) { dir := macSocketDir(t) path, got := echoServer(t, dir, `{"jsonrpc":"2.0","id":1,"result":{}}`) ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n" var out bytes.Buffer if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, path); err != nil || out.String() != `{"jsonrpc":"2.0","id":1,"result":{}}`+"\n" { t.Fatalf("a private socket: %v %q", err, out.String()) } link := dir + "-link" if err := os.Symlink(dir, link); err != nil { t.Fatal(err) } t.Cleanup(func() { os.Remove(link) }) open := filepath.Join(filepath.Dir(dir), filepath.Base(dir)+"-open") if err := os.Mkdir(open, 0755); err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(open) }) openPath, openGot := echoServer(t, open, `{"jsonrpc":"2.0","id":1,"result":{}}`) plain := filepath.Join(dir, "plain") if err := os.WriteFile(plain, nil, 0600); err != nil { t.Fatal(err) } looseDir := filepath.Join(dir, "l") if err := os.Mkdir(looseDir, 0700); err != nil { t.Fatal(err) } loose, looseGot := echoServer(t, looseDir, `{"jsonrpc":"2.0","id":1,"result":{}}`) if err := os.Chmod(loose, 0666); err != nil { t.Fatal(err) } // The longest path a Mac takes: a socket at exactly 103 bytes serves. edgeDir := dir + "/" + strings.Repeat("d", provider.MaxDarwinSocketPath-len(dir)-1-len("/equipo.sock")) if err := os.Mkdir(edgeDir, 0700); err != nil { t.Fatal(err) } edge, _ := echoServer(t, edgeDir, `{"jsonrpc":"2.0","id":1,"result":{}}`) if len(edge) != provider.MaxDarwinSocketPath { t.Fatalf("the edge socket is %d bytes", len(edge)) } out.Reset() if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, edge); err != nil || out.Len() == 0 { t.Fatalf("a socket of %d bytes: %v %q", len(edge), err, out.String()) } // A real socket one byte longer. A Mac cannot bind that path by // name, so it is bound by a relative name from inside its directory // (either system takes that); the endpoint must refuse it by length. longDir := dir + "/" + strings.Repeat("e", provider.MaxDarwinSocketPath-len(dir)-len("/equipo.sock")) if err := os.Mkdir(longDir, 0700); err != nil { t.Fatal(err) } t.Chdir(longDir) ll, err := net.ListenUnix("unix", &net.UnixAddr{Name: "equipo.sock", Net: "unix"}) if err != nil { t.Fatal(err) } defer ll.Close() long := filepath.Join(longDir, "equipo.sock") if err := os.Chmod(long, 0600); err != nil || len(long) != provider.MaxDarwinSocketPath+1 { t.Fatalf("the long socket %s (%d bytes): %v", long, len(long), err) } // Every refusal comes before a dial. dials := 0 defer func(f func(context.Context, string, string) (net.Conn, error)) { macDial = f }(macDial) macDial = func(ctx context.Context, network, address string) (net.Conn, error) { dials++ return (&net.Dialer{}).DialContext(ctx, network, address) } for name, p := range map[string]string{ "relative": "t/equipo.sock", "unclean": dir + "/./equipo.sock", "too long": long, "linked": filepath.Join(link, "equipo.sock"), "open parent": openPath, "not a socket": plain, "loose socket": loose, "missing": filepath.Join(dir, "gone.sock"), } { out.Reset() before := got.Len() // A refusal is immediate; a dial that should not have happened // is cut off rather than left waiting. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) err := ServeDarwinToolProxy(ctx, strings.NewReader(ping), &out, p) cancel() if err == nil || out.Len() != 0 || got.Len() != before || openGot.Len() != 0 || looseGot.Len() != 0 || dials != 0 { t.Fatalf("%s %s: %v, %q out, %d dials", name, p, err, out.String(), dials) } } // The seam is the endpoint's dial: the private socket goes through it. if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, path); err != nil || dials != 1 { t.Fatalf("the private socket: %v, %d dials", err, dials) } } // The endpoint checks who listens before it sends anything: a step // socket bound by another user is refused (LOCAL_PEERCRED on a Mac, // through its seam here). func TestDarwinToolProxyChecksTheListener(t *testing.T) { dir := macSocketDir(t) path, got := echoServer(t, dir, `{"jsonrpc":"2.0","id":1,"result":{}}`) ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n" defer func(f func(*net.UnixConn) (uint32, error)) { macListenerUID = f }(macListenerUID) for name, seam := range map[string]func(*net.UnixConn) (uint32, error){ "another user": func(*net.UnixConn) (uint32, error) { return uint32(os.Getuid()) + 1, nil }, "root": func(*net.UnixConn) (uint32, error) { return 0, nil }, "unknown": func(*net.UnixConn) (uint32, error) { return uint32(os.Getuid()), errors.New("no credential") }, } { if os.Getuid() == 0 && name == "root" { continue } macListenerUID = seam var out bytes.Buffer if err := ServeDarwinToolProxy(context.Background(), strings.NewReader(ping), &out, path); !errors.Is(err, runnerproto.ErrInvalid) || out.Len() != 0 { t.Fatalf("%s: %v %q", name, err, out.String()) } } // Give the server a moment to have read anything it was sent. time.Sleep(20 * time.Millisecond) if got.Len() != 0 { t.Fatalf("a refused listener was sent %q", got.String()) } }