Merge task 6 (darwin MCP tool endpoint) into mac-slice-f
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+1,641
−19
cmd/equipo-runner/main.go+8 −0cmd/equipo-runner/release_guard_test.go+42 −1cmd/equipo-runner/tool_proxy_isolation_test.go+184 −0cmd/equipo-runner/tool_proxy_mac.go+83 −0cmd/equipo-runner/tool_proxy_mac_test.go+77 −0cmd/equipo-runner/tool_proxy_other.go+12 −0internal/runner/peer_darwin_test.go+30 −0internal/runner/provider/darwin_tool.go+49 −0internal/runner/provider/darwin_tool_test.go+41 −0internal/runner/thin/contract_test.go+1 −1internal/runner/thin/engineer.go+5 −1internal/runner/thin/mcp.go+12 −6internal/runner/thin/run.go+1 −0internal/runner/thin/testdata/toolproxy-transcript.txt+82 −0internal/runner/thin/toolproxy_mac_test.go+23 −0internal/runner/thin/toolproxy_transcript_linux_test.go+40 −0internal/runner/thin/toolproxy_transcript_test.go+275 −0internal/runner/thin/toolsocket_layout.go+34 −0internal/runner/thin/toolsocket_layout_test.go+42 −0internal/runner/thin/toolsocket_linux.go+11 −0internal/runner/thin/toolsocket_other.go+40 −4internal/runner/thin/toolsocket_peer_test.go+65 −0internal/runner/tool_proxy_mac.go+158 −0internal/runner/tool_proxy_mac_test.go+322 −0internal/runner/tool_proxy_serve_darwin.go+4 −6
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index 6f714040..5cb57670 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -16,6 +16,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| "amadan.net/oficina/equipo/internal/runner/thin" |
| "amadan.net/oficina/equipo/internal/runner/webread" |
| @@ -34,6 +35,13 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| if len(args) > 0 && args[0] == "webread" { |
| return webread.Main(args[1:], input, errorOutput) |
| } |
| + // A Mac's MCP tool endpoint, started by the CLI: before anything |
| + // reads the environment or a configuration. |
| + if len(args) > 0 && args[0] == provider.DarwinToolProxyCommand { |
| + if code, ok := toolProxy(ctx, args[1:], input, output); ok { |
| + return code |
| + } |
| + } |
| if len(args) > 0 && args[0] == "account" { |
| return accountLogin(ctx, args[1:], input, output, errorOutput, getenv) |
| } |
diff --git a/cmd/equipo-runner/release_guard_test.go b/cmd/equipo-runner/release_guard_test.go| index 5ea8f19a..e92a9e4e 100644 |
| --- a/cmd/equipo-runner/release_guard_test.go |
| +++ b/cmd/equipo-runner/release_guard_test.go |
| @@ -35,8 +35,9 @@ func TestReleaseRunnerHasNoFakeWorker(t *testing.T) { |
| } |
| dir := t.TempDir() |
| bin := filepath.Join(dir, "equipo-runner") |
| + // The Linux release, on whatever machine runs this. |
| build := exec.Command("go", "build", "-trimpath", "-ldflags", "-s -w", "-o", bin, ".") |
| - build.Env = append(os.Environ(), "CGO_ENABLED=0") |
| + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH=amd64") |
| testci.GoCommand(t, build) |
| testci.Files(t, "../../scripts/no-fake-worker.sh") |
| if out, err := build.CombinedOutput(); err != nil { |
| @@ -52,9 +53,33 @@ func TestReleaseRunnerHasNoFakeWorker(t *testing.T) { |
| if bytes.Contains(raw, []byte(egressMarker)) { |
| t.Fatal("the release runner contains the test build's egress route") |
| } |
| + // A Mac's MCP endpoint is built for darwin and the test build: a |
| + // Linux release runs the certified equipo-tool-proxy instead. |
| + if bytes.Contains(raw, []byte(darwinProxyMarker)) { |
| + t.Fatal("the Linux release runner contains the Mac's tool endpoint") |
| + } |
| if out, err := exec.Command("../../scripts/no-fake-worker.sh", bin).CombinedOutput(); err != nil { |
| t.Fatalf("the release check refused a clean binary: %s", out) |
| } |
| + // The Mac release (darwin/arm64, as make release-runner builds it) |
| + // has the Mac's endpoint and nothing of the test build. |
| + mac := filepath.Join(dir, "equipo-runner-darwin") |
| + build = exec.Command("go", "build", "-trimpath", "-ldflags", "-s -w", "-o", mac, ".") |
| + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=darwin", "GOARCH=arm64") |
| + testci.GoCommand(t, build) |
| + if out, err := build.CombinedOutput(); err != nil { |
| + t.Fatalf("Mac release build: %v %s", err, out) |
| + } |
| + raw, err = os.ReadFile(mac) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Contains(raw, []byte(darwinProxyMarker)) || bytes.Contains(raw, []byte(marker)) || bytes.Contains(raw, []byte(egressMarker)) { |
| + t.Fatal("the Mac release runner lacks its tool endpoint or holds the test build's code") |
| + } |
| + if out, err := exec.Command("../../scripts/no-fake-worker.sh", mac).CombinedOutput(); err != nil { |
| + t.Fatalf("the release check refused the Mac runner: %s", out) |
| + } |
| archive := filepath.Join(dir, "thin.a") |
| test := exec.Command("go", "build", "-tags", "testbuild", "-o", archive, "../../internal/runner/thin") |
| test.Env = append(os.Environ(), "CGO_ENABLED=0") |
| @@ -83,8 +108,24 @@ func TestReleaseRunnerHasNoFakeWorker(t *testing.T) { |
| if out, err := exec.Command("../../scripts/no-fake-worker.sh", egress).CombinedOutput(); err == nil { |
| t.Fatalf("the release check accepted the egress route: %s", out) |
| } |
| + // The test build does have the Mac's endpoint, so the check above |
| + // can see it. |
| + proxy := filepath.Join(dir, "runner.a") |
| + test = exec.Command("go", "build", "-tags", "testbuild", "-o", proxy, "../../internal/runner") |
| + test.Env = append(os.Environ(), "CGO_ENABLED=0") |
| + testci.GoCommand(t, test) |
| + if out, err := test.CombinedOutput(); err != nil { |
| + t.Fatalf("test build: %v %s", err, out) |
| + } |
| + if raw, _ := os.ReadFile(proxy); !bytes.Contains(raw, []byte(darwinProxyMarker)) { |
| + t.Fatal("the test build has no Mac tool endpoint: this guard sees nothing") |
| + } |
| } |
| +// darwinProxyMarker names a Mac's MCP tool endpoint (internal/runner |
| +// tool_proxy_mac.go). |
| +const darwinProxyMarker = "ServeDarwinToolProxy" |
| + |
| // egressMarker names the test build's egress route (internal/runner/egress |
| // proxy_testbuild.go). |
| const egressMarker = "EQUIPO_TEST_EGRESS_UPSTREAM" |
diff --git a/cmd/equipo-runner/tool_proxy_isolation_test.go b/cmd/equipo-runner/tool_proxy_isolation_test.go| new file mode 100644 |
| index 00000000..27374d9c |
| --- /dev/null |
| +++ b/cmd/equipo-runner/tool_proxy_isolation_test.go |
| @@ -0,0 +1,184 @@ |
| +//go:build darwin || testbuild |
| + |
| +package main |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "net" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// childArgs starts this test binary as equipo-runner with those |
| +// arguments (a JSON array, toolProxyChild) instead of running its tests; |
| +// childReport names the file it reports to. |
| +const ( |
| + childArgs = "EQUIPO_TEST_TOOL_PROXY_ARGS" |
| + childReport = "EQUIPO_TEST_TOOL_PROXY_REPORT" |
| +) |
| + |
| +func init() { |
| + if raw := os.Getenv(childArgs); raw != "" { |
| + var args []string |
| + if json.Unmarshal([]byte(raw), &args) != nil { |
| + os.Exit(93) |
| + } |
| + os.Exit(toolProxyChild(args, os.Getenv(childReport))) |
| + } |
| +} |
| + |
| +// toolProxyReport is what the endpoint process holds once it has |
| +// served: its environment, the descriptors above 2 without |
| +// close-on-exec, the identity of every descriptor above 2, and any |
| +// variable run read through getenv. |
| +type toolProxyReport struct { |
| + Getenv []string `json:"getenv"` |
| + Env []string `json:"env"` |
| + Inherited []int `json:"inherited"` |
| + Open [][2]uint64 `json:"open"` |
| + Pipe bool `json:"pipe"` |
| +} |
| + |
| +// toolProxyChild runs equipo-runner as the CLI starts it, then reports |
| +// to the file at report. The Go runtime's poller is in use before the |
| +// endpoint starts (a pipe, as signal handling and the runner's own files |
| +// are): its descriptors must survive, which the pipe shows afterwards. |
| +func toolProxyChild(args []string, reportPath string) int { |
| + r, w, err := os.Pipe() |
| + if err != nil { |
| + return 90 |
| + } |
| + var read []string |
| + code := run(context.Background(), args, os.Stdin, os.Stdout, os.Stderr, func(k string) string { read = append(read, k); return "" }) |
| + report := toolProxyReport{Getenv: read, Env: os.Environ()} |
| + _ = r.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| + if _, err := w.Write([]byte("x")); err == nil { |
| + b := make([]byte, 1) |
| + n, err := r.Read(b) |
| + report.Pipe = err == nil && n == 1 |
| + } |
| + entries, err := os.ReadDir("/dev/fd") |
| + if err != nil { |
| + return 91 |
| + } |
| + for _, e := range entries { |
| + fd, err := strconv.Atoi(e.Name()) |
| + if err != nil || fd <= 2 { |
| + continue |
| + } |
| + flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0) |
| + if err != nil { |
| + continue // the directory's own descriptor, closed by now |
| + } |
| + if flags&unix.FD_CLOEXEC == 0 { |
| + report.Inherited = append(report.Inherited, fd) |
| + } |
| + var st unix.Stat_t |
| + if unix.Fstat(fd, &st) == nil { |
| + report.Open = append(report.Open, [2]uint64{uint64(st.Dev), uint64(st.Ino)}) |
| + } |
| + } |
| + raw, err := json.Marshal(report) |
| + if err != nil || os.WriteFile(reportPath, raw, 0600) != nil { |
| + return 92 |
| + } |
| + return code |
| +} |
| + |
| +// The endpoint starts as the CLI's child, so it inherits whatever the CLI |
| +// leaves open and its whole environment: a token's descriptor |
| +// (CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) and any token variable. It |
| +// keeps neither while it serves: every inherited descriptor above 2 is |
| +// closed and the environment is emptied, while the runtime's own |
| +// descriptors (its poller) keep working. |
| +func TestToolProxyDropsInheritedCredentials(t *testing.T) { |
| + socket := echoSocket(t) |
| + tokenR, tokenW, err := os.Pipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer tokenR.Close() |
| + defer tokenW.Close() |
| + if _, err := tokenW.WriteString("sk-ant-oat01-SENTINEL\n"); err != nil { |
| + t.Fatal(err) |
| + } |
| + var tokenID [2]uint64 |
| + var st unix.Stat_t |
| + if err := unix.Fstat(int(tokenR.Fd()), &st); err != nil { |
| + t.Fatal(err) |
| + } |
| + tokenID = [2]uint64{uint64(st.Dev), uint64(st.Ino)} |
| + // The token's read end as fd 3, its write end as fd 6. |
| + code, out, stderr, report := runToolProxy(t, []string{"tool-proxy", "--socket", socket}, `{"jsonrpc":"2.0","id":1,"method":"ping"}`+"\n", []*os.File{tokenR, nil, nil, tokenW}, |
| + "CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-SENTINEL", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3", "ANTHROPIC_API_KEY=sk-ant-api-SENTINEL", "HOME=/Users/sentinel", "PATH=/usr/bin:/bin") |
| + if code != 0 || stderr != "" || out != `{"jsonrpc":"2.0","id":1,"result":{}}`+"\n" { |
| + t.Fatalf("the endpoint did not serve: exit %d, out %q, stderr %q", code, out, stderr) |
| + } |
| + if len(report.Env) != 0 { |
| + t.Fatalf("the endpoint kept its environment: %q", report.Env) |
| + } |
| + if len(report.Inherited) != 0 { |
| + t.Fatalf("the endpoint kept inherited descriptors %v", report.Inherited) |
| + } |
| + for _, id := range report.Open { |
| + if tokenID[1] != 0 && id == tokenID { |
| + t.Fatalf("the endpoint still holds the token's pipe (%v)", id) |
| + } |
| + } |
| + if !report.Pipe { |
| + t.Fatal("the runtime's poller no longer works after the endpoint started") |
| + } |
| +} |
| + |
| +// echoSocket is a 0600 socket in a 0700 directory, without links, that |
| +// answers each request with an empty result. |
| +func echoSocket(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) |
| + } |
| + path := filepath.Join(dir, "s") |
| + l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { l.Close() }) |
| + if err := os.Chmod(path, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + go func() { |
| + for { |
| + c, err := l.AcceptUnix() |
| + if err != nil { |
| + return |
| + } |
| + go func() { |
| + defer c.Close() |
| + r := bufio.NewReader(c) |
| + for { |
| + if _, err := r.ReadBytes('\n'); err != nil { |
| + return |
| + } |
| + c.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{}}` + "\n")) |
| + } |
| + }() |
| + } |
| + }() |
| + return path |
| +} |
diff --git a/cmd/equipo-runner/tool_proxy_mac.go b/cmd/equipo-runner/tool_proxy_mac.go| new file mode 100644 |
| index 00000000..af191e2b |
| --- /dev/null |
| +++ b/cmd/equipo-runner/tool_proxy_mac.go |
| @@ -0,0 +1,83 @@ |
| +//go:build darwin || testbuild |
| + |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "os" |
| + "strconv" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| +) |
| + |
| +// toolProxy is a Mac runner's MCP tool endpoint, the CLI's only MCP |
| +// server there (provider.DarwinToolMCP): equipo-runner tool-proxy |
| +// --socket <path>. Like the Linux tool proxy it reads no environment and |
| +// no configuration and writes nothing to stderr: 2 for other arguments, |
| +// 1 when it cannot serve. A Linux release does not have it; Linux runs |
| +// the certified equipo-tool-proxy instead. |
| +func toolProxy(ctx context.Context, args []string, input io.Reader, output io.Writer) (int, bool) { |
| + if len(args) != 2 || args[0] != "--socket" { |
| + return 2, true |
| + } |
| + if dropInherited() != nil { |
| + return 1, true |
| + } |
| + if runner.ServeDarwinToolProxy(ctx, input, output, args[1]) != nil { |
| + return 1, true |
| + } |
| + return 0, true |
| +} |
| + |
| +// errInherited: the endpoint could not list or close what it inherited. |
| +var errInherited = errors.New("tool endpoint: inherited descriptors") |
| + |
| +// dropInherited lets go of what the endpoint inherited from the CLI that |
| +// started it: a token's descriptor (CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) |
| +// and the CLI's whole environment. It serves with neither. |
| +// |
| +// A descriptor above 2 is inherited exactly when close-on-exec is clear: |
| +// one that had it set did not survive exec, and every descriptor the Go |
| +// runtime and standard library open carries it (the poller's kqueue or |
| +// epoll and eventfd, pipes, files, sockets; this binary has no cgo). So |
| +// the runtime's own descriptors are kept by what they are, not guessed |
| +// by number, whenever they were opened. The list comes from /dev/fd (on |
| +// Linux a link to /proc/self/fd). |
| +// |
| +// The environment is emptied: the endpoint needs none of it. That clears |
| +// the process's own copy; the original strings exec placed in memory |
| +// remain, which is why a token never travels in the environment (task 8 |
| +// passes it by descriptor). |
| +func dropInherited() error { |
| + entries, err := os.ReadDir("/dev/fd") |
| + if err != nil { |
| + return errInherited |
| + } |
| + for _, e := range entries { |
| + fd, err := strconv.Atoi(e.Name()) |
| + if err != nil { |
| + return errInherited |
| + } |
| + if fd <= 2 { |
| + continue |
| + } |
| + flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0) |
| + if errors.Is(err, unix.EBADF) { |
| + continue // the listing's own descriptor, closed already |
| + } |
| + if err != nil { |
| + return errInherited |
| + } |
| + if flags&unix.FD_CLOEXEC == 0 { |
| + if err := unix.Close(fd); err != nil { |
| + return errInherited |
| + } |
| + } |
| + } |
| + os.Clearenv() |
| + return nil |
| +} |
diff --git a/cmd/equipo-runner/tool_proxy_mac_test.go b/cmd/equipo-runner/tool_proxy_mac_test.go| new file mode 100644 |
| index 00000000..d2d8f853 |
| --- /dev/null |
| +++ b/cmd/equipo-runner/tool_proxy_mac_test.go |
| @@ -0,0 +1,77 @@ |
| +//go:build darwin || testbuild |
| + |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// runToolProxy runs equipo-runner tool-proxy with args as the CLI starts |
| +// it, in a child process (toolProxyChild): the endpoint lets go of its |
| +// inherited descriptors and environment, which must not happen to the |
| +// test process. extra are descriptors from 3 on, env the child's |
| +// environment besides what starts it. |
| +func runToolProxy(t *testing.T, args []string, input string, extra []*os.File, env ...string) (code int, out, stderr string, report toolProxyReport) { |
| + t.Helper() |
| + rawArgs, err := json.Marshal(args) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reportPath := filepath.Join(t.TempDir(), "report.json") |
| + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^$") |
| + cmd.Env = append([]string{childArgs + "=" + string(rawArgs), childReport + "=" + reportPath}, env...) |
| + cmd.ExtraFiles = extra |
| + cmd.Stdin = strings.NewReader(input) |
| + var o, e bytes.Buffer |
| + cmd.Stdout, cmd.Stderr = &o, &e |
| + err = cmd.Run() |
| + if exit, ok := err.(*exec.ExitError); ok { |
| + code = exit.ExitCode() |
| + } else if err != nil { |
| + t.Fatalf("%q: %v", args, err) |
| + } |
| + raw, err := os.ReadFile(reportPath) |
| + if err != nil || json.Unmarshal(raw, &report) != nil { |
| + t.Fatalf("%q: no report (exit %d, stderr %q): %v", args, code, e.String(), err) |
| + } |
| + return code, o.String(), e.String(), report |
| +} |
| + |
| +// equipo-runner tool-proxy --socket <path> is a Mac's MCP tool endpoint. |
| +// Like the Linux tool proxy it takes exactly that, reads no environment |
| +// and no configuration, says nothing on stderr, and exits 2 for any other |
| +// arguments and 1 when it cannot serve. |
| +func TestToolProxyCommand(t *testing.T) { |
| + path := echoSocket(t) |
| + dir := filepath.Dir(path) |
| + ping := `{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n" |
| + for _, tc := range []struct { |
| + args []string |
| + code int |
| + out string |
| + }{ |
| + {[]string{"tool-proxy", "--socket", path}, 0, `{"jsonrpc":"2.0","id":1,"result":{}}` + "\n"}, |
| + {[]string{"tool-proxy"}, 2, ""}, |
| + {[]string{"tool-proxy", "--socket"}, 2, ""}, |
| + {[]string{"tool-proxy", "--sock", path}, 2, ""}, |
| + {[]string{"tool-proxy", "--socket", path, "extra"}, 2, ""}, |
| + {[]string{"tool-proxy", "--env-file", "/nonexistent", "--socket", path}, 2, ""}, |
| + {[]string{"tool-proxy", "--socket", "s"}, 1, ""}, |
| + {[]string{"tool-proxy", "--socket", filepath.Join(dir, "missing")}, 1, ""}, |
| + } { |
| + code, out, stderr, report := runToolProxy(t, tc.args, ping, nil, "EQUIPO_ORIGIN=https://equipo.example.com") |
| + if code != tc.code || out != tc.out || stderr != "" || len(report.Getenv) != 0 { |
| + t.Fatalf("%q: exit %d, out %q, stderr %q, read %q", tc.args, code, out, stderr, report.Getenv) |
| + } |
| + } |
| +} |
diff --git a/cmd/equipo-runner/tool_proxy_other.go b/cmd/equipo-runner/tool_proxy_other.go| new file mode 100644 |
| index 00000000..df66882a |
| --- /dev/null |
| +++ b/cmd/equipo-runner/tool_proxy_other.go |
| @@ -0,0 +1,12 @@ |
| +//go:build !darwin && !testbuild |
| + |
| +package main |
| + |
| +import ( |
| + "context" |
| + "io" |
| +) |
| + |
| +// toolProxy: a Linux runner has no tool-proxy mode; the certified |
| +// equipo-tool-proxy serves its CLI. |
| +func toolProxy(context.Context, []string, io.Reader, io.Writer) (int, bool) { return 0, false } |
diff --git a/internal/runner/peer_darwin_test.go b/internal/runner/peer_darwin_test.go| new file mode 100644 |
| index 00000000..6c31089e |
| --- /dev/null |
| +++ b/internal/runner/peer_darwin_test.go |
| @@ -0,0 +1,30 @@ |
| +package runner |
| + |
| +import ( |
| + "os" |
| + "testing" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// On a Mac the tool socket's peer is read with LOCAL_PEERCRED: both ends |
| +// of a socket pair this process made are its own user. Runs only on a |
| +// Mac; the seam tests (TestToolSocketPeerUID, TestDarwinToolProxyChecksTheListener) |
| +// cover the decision everywhere. |
| +func TestPeerUIDIsThisUser(t *testing.T) { |
| + fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_STREAM, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer unix.Close(fds[0]) |
| + defer unix.Close(fds[1]) |
| + for _, fd := range fds { |
| + uid, err := peerUID(fd) |
| + if err != nil || uid != uint32(os.Getuid()) { |
| + t.Fatalf("peer of %d: %d %v, want %d", fd, uid, err, os.Getuid()) |
| + } |
| + } |
| + if _, err := peerUID(-1); err == nil { |
| + t.Fatal("a closed descriptor has a peer") |
| + } |
| +} |
diff --git a/internal/runner/provider/darwin_tool.go b/internal/runner/provider/darwin_tool.go| new file mode 100644 |
| index 00000000..6a23ae5b |
| --- /dev/null |
| +++ b/internal/runner/provider/darwin_tool.go |
| @@ -0,0 +1,49 @@ |
| +package provider |
| + |
| +import ( |
| + "encoding/json" |
| + "path/filepath" |
| + "strings" |
| +) |
| + |
| +// A Mac's MCP tool endpoint (Mac runners spec §8.1, §8.2). Linux mounts |
| +// the certified tool proxy at /opt/equipo-tool-proxy and the step's |
| +// socket at /tool/equipo.sock inside the namespace. A Mac has neither: |
| +// the runner binary itself serves the same stdio MCP protocol in its |
| +// tool-proxy mode, dialling the step's tool socket at its real path. |
| +const ( |
| + // DarwinToolProxyCommand is the runner's subcommand for it: |
| + // equipo-runner tool-proxy --socket <path>. |
| + DarwinToolProxyCommand = "tool-proxy" |
| + // MaxDarwinSocketPath is the longest Unix socket path a Mac takes: |
| + // sun_path holds 104 bytes there, the NUL included, and with no |
| + // /proc/self/fd a socket is reached by its path alone. |
| + MaxDarwinSocketPath = 103 |
| +) |
| + |
| +// DarwinToolMCP is the CLI's --mcp-config on a Mac: runner (the runner |
| +// binary's absolute path) in its tool-proxy mode as the only MCP server, |
| +// on socket, the step's tool socket. Both must be clean absolute paths, |
| +// and socket must fit a Mac's sun_path. |
| +func DarwinToolMCP(runner, socket string) (json.RawMessage, error) { |
| + for _, p := range []string{runner, socket} { |
| + if !filepath.IsAbs(p) || filepath.Clean(p) != p || strings.ContainsAny(p, "\x00\n\r") { |
| + return nil, ErrPolicy |
| + } |
| + } |
| + if len(socket) > MaxDarwinSocketPath { |
| + return nil, ErrPolicy |
| + } |
| + type server struct { |
| + Type string `json:"type"` |
| + Command string `json:"command"` |
| + Args []string `json:"args"` |
| + } |
| + raw, err := json.Marshal(struct { |
| + MCPServers map[string]server `json:"mcpServers"` |
| + }{map[string]server{"equipo": {Type: "stdio", Command: runner, Args: []string{DarwinToolProxyCommand, "--socket", socket}}}}) |
| + if err != nil { |
| + return nil, ErrPolicy |
| + } |
| + return raw, nil |
| +} |
diff --git a/internal/runner/provider/darwin_tool_test.go b/internal/runner/provider/darwin_tool_test.go| new file mode 100644 |
| index 00000000..42ab6222 |
| --- /dev/null |
| +++ b/internal/runner/provider/darwin_tool_test.go |
| @@ -0,0 +1,41 @@ |
| +package provider |
| + |
| +import ( |
| + "errors" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// A Mac's CLI reaches Equipo's tools through the runner binary itself, |
| +// in its tool-proxy mode, as the only MCP server: the same shape as the |
| +// Linux configuration, with real paths where Linux has its mounts. |
| +func TestDarwinToolMCP(t *testing.T) { |
| + runner := "/Users/paulequipo/.local/lib/equipo-runner/equipo-runner" |
| + socket := "/Users/paulequipo/.local/share/equipo-runner/scratch/t/123456/s" |
| + got, err := DarwinToolMCP(runner, socket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := `{"mcpServers":{"equipo":{"type":"stdio","command":"` + runner + `","args":["tool-proxy","--socket","` + socket + `"]}}}` |
| + if string(got) != want { |
| + t.Fatalf("MCP config\n got %s\nwant %s", got, want) |
| + } |
| + long := "/Users/" + strings.Repeat("n", MaxDarwinSocketPath) |
| + for _, bad := range [][2]string{ |
| + {"equipo-runner", socket}, |
| + {runner + "/../equipo-runner", socket}, |
| + {runner, "t/123456/s"}, |
| + {runner, socket + "/"}, |
| + {runner, long[:MaxDarwinSocketPath+1]}, |
| + {runner, socket + "\x00"}, |
| + {runner, socket + "\n"}, |
| + } { |
| + if out, err := DarwinToolMCP(bad[0], bad[1]); !errors.Is(err, ErrPolicy) || out != nil { |
| + t.Fatalf("%q accepted: %s %v", bad, out, err) |
| + } |
| + } |
| + // The longest socket path that fits a Mac's sun_path is accepted. |
| + if _, err := DarwinToolMCP(runner, long[:MaxDarwinSocketPath]); err != nil { |
| + t.Fatalf("a socket path of %d bytes: %v", MaxDarwinSocketPath, err) |
| + } |
| +} |
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go| index 25e107f9..c5fef010 100644 |
| --- a/internal/runner/thin/contract_test.go |
| +++ b/internal/runner/thin/contract_test.go |
| @@ -499,7 +499,7 @@ func TestSweepOrphans(t *testing.T) { |
| root := t.TempDir() |
| c := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state")} |
| keep := []string{filepath.Join(c.ScratchRoot, "homes", "unrelated"), filepath.Join(c.StateDir, "private")} |
| - gone := []string{filepath.Join(c.ScratchRoot, "homes", "account-1"), filepath.Join(c.ScratchRoot, "homes", "config-1"), filepath.Join(c.ScratchRoot, "policy-1"), filepath.Join(c.WorkspaceRoot, "converse-1"), filepath.Join(c.StateDir, "coord-tool-1")} |
| + gone := []string{filepath.Join(c.ScratchRoot, "homes", "account-1"), filepath.Join(c.ScratchRoot, "homes", "config-1"), filepath.Join(c.ScratchRoot, "policy-1"), filepath.Join(c.WorkspaceRoot, "converse-1"), filepath.Join(c.StateDir, "coord-tool-1"), filepath.Join(c.ScratchRoot, "t", "123456")} |
| for _, d := range append(append([]string{}, keep...), gone...) { |
| os.MkdirAll(d, 0700) |
| } |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index 14e49d9d..aa77f87b 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -1038,7 +1038,11 @@ func (e *Engineer) run(ctx context.Context, r stepRow, tree workspace.TaskTree, |
| var refused atomic.Int64 |
| permission := countRefusals(spec.permission, &refused) |
| set := toolSet{list: spec.tools, names: spec.names, permission: func(raw json.RawMessage) string { return string(permission(raw, policy)) }} |
| - tool, err := openToolSet(context.Background(), o.Runner.StateDir, set, spec.call) |
| + root, err := toolRoot(o.Runner) |
| + if err != nil { |
| + return stepResult{reason: "provider_failed", terminated: true} |
| + } |
| + tool, err := openToolSet(context.Background(), root, set, spec.call) |
| if err != nil { |
| return stepResult{reason: "provider_failed", terminated: true} |
| } |
diff --git a/internal/runner/thin/mcp.go b/internal/runner/thin/mcp.go| index 512661db..21f6d2ad 100644 |
| --- a/internal/runner/thin/mcp.go |
| +++ b/internal/runner/thin/mcp.go |
| @@ -63,10 +63,16 @@ type toolSocket struct { |
| listener *net.UnixListener |
| cancel context.CancelFunc |
| wg sync.WaitGroup |
| + peerUID func(fd int) (uint32, error) |
| } |
| -// openToolSocket creates <root>/coord-tool-*/equipo.sock, 0700 and 0600. |
| -// root must be a private directory the model cannot read. |
| +// toolPeerUID reads a tool socket peer's user: SO_PEERCRED on Linux, |
| +// LOCAL_PEERCRED on a Mac (runner peer_*.go). Tests stand in. |
| +var toolPeerUID = runner.PeerUID |
| + |
| +// openToolSocket creates <root>/coord-tool-*/equipo.sock, 0700 and 0600 |
| +// (on a Mac <root>/<random>/s, toolsocket_layout.go). root must be a |
| +// private directory the model cannot read (toolRoot). |
| func openToolSocket(ctx context.Context, root string, call ToolFunc) (*toolSocket, error) { |
| return openToolSet(ctx, root, converseSet(call != nil), call) |
| } |
| @@ -101,7 +107,7 @@ func openToolSet(ctx context.Context, root string, set toolSet, call ToolFunc) ( |
| // openReplySet is openToolSet for tools whose answers may carry an image. |
| func openReplySet(ctx context.Context, root string, set toolSet, call ToolReplyFunc) (*toolSocket, error) { |
| - dir, err := os.MkdirTemp(root, "coord-tool-") |
| + dir, err := os.MkdirTemp(root, toolDirPrefix) |
| if err != nil { |
| return nil, err |
| } |
| @@ -109,7 +115,7 @@ func openReplySet(ctx context.Context, root string, set toolSet, call ToolReplyF |
| if err = os.Chmod(dir, 0700); err != nil { |
| return fail(err) |
| } |
| - path := filepath.Join(dir, "equipo.sock") |
| + path := filepath.Join(dir, toolSocketName) |
| l, err := listenToolSocket(dir, path) |
| if err != nil { |
| return fail(err) |
| @@ -120,7 +126,7 @@ func openReplySet(ctx context.Context, root string, set toolSet, call ToolReplyF |
| return fail(err) |
| } |
| ctx, cancel := context.WithCancel(ctx) |
| - s := &toolSocket{Path: path, dir: dir, listener: l, cancel: cancel, call: call, set: set} |
| + s := &toolSocket{Path: path, dir: dir, listener: l, cancel: cancel, call: call, set: set, peerUID: toolPeerUID} |
| context.AfterFunc(ctx, func() { l.Close() }) |
| s.wg.Add(1) |
| go s.accept(ctx) |
| @@ -145,7 +151,7 @@ func (s *toolSocket) accept(ctx context.Context) { |
| raw, err := c.SyscallConn() |
| uid, known := uint32(0), false |
| if err == nil { |
| - _ = raw.Control(func(fd uintptr) { uid, err = runner.PeerUID(int(fd)); known = err == nil }) |
| + _ = raw.Control(func(fd uintptr) { uid, err = s.peerUID(int(fd)); known = err == nil }) |
| } |
| if err != nil || !known || uid != uint32(os.Getuid()) { |
| c.Close() |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index a11ebfb6..c412719f 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -646,6 +646,7 @@ func sweepOrphans(c runner.Config) error { |
| c.ScratchRoot: {"policy-"}, |
| c.WorkspaceRoot: {"converse-", "step-"}, |
| c.StateDir: {"coord-tool-"}, |
| + macToolRoot(c): {macToolDirPrefix}, |
| } { |
| entries, err := os.ReadDir(dir) |
| if errors.Is(err, os.ErrNotExist) { |
diff --git a/internal/runner/thin/testdata/toolproxy-transcript.txt b/internal/runner/thin/testdata/toolproxy-transcript.txt| new file mode 100644 |
| index 00000000..37c3b269 |
| --- /dev/null |
| +++ b/internal/runner/thin/testdata/toolproxy-transcript.txt |
| @@ -0,0 +1,82 @@ |
| +# The tool proxy transcript: what a CLI sends through a tool proxy to a |
| +# step's tool socket (>) and each reply (<), one tool socket per session. |
| +# Recorded 2026-11-28 on docs-t1 (linux/amd64) from the Linux tool proxy |
| +# (internal/toolproxy.Serve) by TestLinuxToolProxyTranscript, and the |
| +# oracle for TestDarwinToolProxySpeaksTheProtocol. Record it again with |
| +# EQUIPO_RECORD_TOOL_TRANSCRIPT=1 go test ./internal/runner/thin -run TestLinuxToolProxyTranscript |
| +== implement |
| +> {"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"claude-code","version":"2.1.312"}}} |
| +< {"id":0,"jsonrpc":"2.0","result":{"capabilities":{"tools":{}},"protocolVersion":"2025-06-18","serverInfo":{"name":"equipo-runner","version":"2"}}} |
| +> {"jsonrpc":"2.0","method":"notifications/initialized"} |
| +> {"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}} |
| +< {"id":1,"jsonrpc":"2.0","result":{"tools":[{"inputSchema":{"additionalProperties":false,"properties":{"input":{"type":"object"},"tool_name":{"type":"string"},"tool_use_id":{"type":"string"}},"required":["tool_name","input"],"type":"object"},"name":"permission"},{"description":"Not needed: when you finish, Equipo commits your changes in /workspace and pushes them. End with a short summary instead.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"submit_candidate"},{"description":"Nobody can answer during this step. Make the most reasonable choice and say so in your summary.","inputSchema":{"additionalProperties":false,"properties":{"question":{"type":"string"}},"required":["question"],"type":"object"},"name":"ask_person"},{"description":"Not available in this step.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"submit_render"}]}} |
| +> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Read","tool_use_id":"toolu_2","input":{"file_path":"/workspace/main.go"}}}} |
| +< {"id":2,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"allow\",\"updatedInput\":{\"file_path\":\"/workspace/main.go\"}}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Edit","tool_use_id":"toolu_3","input":{"file_path":"/workspace/main.go","old_string":"hello","new_string":"hola"}}}} |
| +< {"id":3,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"allow\",\"updatedInput\":{\"file_path\":\"/workspace/main.go\",\"new_string\":\"hola\",\"old_string\":\"hello\"}}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Read","tool_use_id":"toolu_4","input":{"file_path":"/etc/passwd"}}}} |
| +< {"id":4,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: this step can use files only under /workspace (and read /research)\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Read","tool_use_id":"toolu_5","input":{"file_path":"/workspace/../etc/passwd"}}}} |
| +< {"id":5,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: this step can use files only under /workspace (and read /research)\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":5.5,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Read","tool_use_id":"toolu_5.5","input":{"file_path":"/workspace/.git/config"}}}} |
| +< {"id":5.5,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: that path is protected: credentials, runtime files and links are never available\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"WebFetch","tool_use_id":"toolu_6","input":{"url":"https://example.com/","prompt":"read it"}}}} |
| +< {"id":6,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: this tool is not available to this step\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Bash","tool_use_id":"toolu_7","input":{"command":"go test ./..."}}}} |
| +< {"id":7,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"allow\",\"updatedInput\":{\"command\":\"go test ./...\"}}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Bash","tool_use_id":"toolu_8","input":{"command":"ls","dangerouslyDisableSandbox":true}}}} |
| +< {"id":8,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: commands run only inside the sandbox; dangerouslyDisableSandbox is not available\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"mcp__equipo__submit_candidate","tool_use_id":"toolu_9","input":{}}}} |
| +< {"id":9,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: this tool is not available to this step\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"submit_candidate","arguments":{},"_meta":{"claudecode/toolUseId":"toolu_10"}}} |
| +< {"id":10,"jsonrpc":"2.0","result":{"content":[{"text":"Not needed in this step: Equipo commits and pushes your changes in /workspace when you finish. Carry on, and end with a short summary of what you changed and why.","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"ask_person","arguments":{"question":"Which colour?"},"_meta":{"claudecode/toolUseId":"toolu_11"}}} |
| +< {"id":11,"jsonrpc":"2.0","result":{"content":[{"text":"Not needed in this step: Equipo commits and pushes your changes in /workspace when you finish. Carry on, and end with a short summary of what you changed and why.","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"submit_render","arguments":null,"_meta":{"claudecode/toolUseId":"toolu_12"}}} |
| +< {"id":12,"jsonrpc":"2.0","result":{"content":[{"text":"Not needed in this step: Equipo commits and pushes your changes in /workspace when you finish. Carry on, and end with a short summary of what you changed and why.","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"submit_answer","arguments":{"answer":"yes"},"_meta":{"claudecode/toolUseId":"toolu_13"}}} |
| +< {"error":{"code":-32602,"message":"unavailable"},"id":13,"jsonrpc":"2.0"} |
| +> {"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"read_file","arguments":{"repo":"oficina/equipo","path":"/etc/passwd"},"_meta":{"claudecode/toolUseId":"toolu_14"}}} |
| +< {"error":{"code":-32602,"message":"unavailable"},"id":14,"jsonrpc":"2.0"} |
| +> {"jsonrpc":"2.0","id":15,"method":"ping"} |
| +< {"id":15,"jsonrpc":"2.0","result":{}} |
| +> {"jsonrpc":"2.0","id":16,"method":"resources/list","params":{}} |
| +< {"error":{"code":-32601,"message":"unavailable"},"id":16,"jsonrpc":"2.0"} |
| +> {"jsonrpc":"2.0","id":"seventeen","method":"tools/call","params":{"name":"submit_candidate"}} |
| +< {"id":"seventeen","jsonrpc":"2.0","result":{"content":[{"text":"Not needed in this step: Equipo commits and pushes your changes in /workspace when you finish. Carry on, and end with a short summary of what you changed and why.","type":"text"}],"isError":false}} |
| +== answer |
| +> {"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"claude-code","version":"2.1.312"}}} |
| +< {"id":0,"jsonrpc":"2.0","result":{"capabilities":{"tools":{}},"protocolVersion":"2025-03-26","serverInfo":{"name":"equipo-runner","version":"2"}}} |
| +> {"jsonrpc":"2.0","method":"notifications/initialized"} |
| +> {"jsonrpc":"2.0","id":1,"method":"tools/list"} |
| +< {"id":1,"jsonrpc":"2.0","result":{"tools":[{"inputSchema":{"additionalProperties":false,"properties":{"input":{"type":"object"},"tool_name":{"type":"string"},"tool_use_id":{"type":"string"}},"required":["tool_name","input"],"type":"object"},"name":"permission"},{"description":"Read-only: the commits of this task's change, from the commit it started from to the one in /workspace, newest first, one line each.","inputSchema":{"additionalProperties":false,"properties":{},"required":[],"type":"object"},"name":"git_log"},{"description":"Read-only: the change itself, from the commit the task started from to the one in /workspace, as a patch. path limits it to one file or directory.","inputSchema":{"additionalProperties":false,"properties":{"path":{"type":"string"}},"required":[],"type":"object"},"name":"git_diff"},{"description":"Read-only: one commit from git_log, by its hash, with its message and patch.","inputSchema":{"additionalProperties":false,"properties":{"commit":{"type":"string"}},"required":["commit"],"type":"object"},"name":"git_show"}]}} |
| +> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Read","tool_use_id":"toolu_2","input":{"file_path":"/workspace/README.md"}}}} |
| +< {"id":2,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"allow\",\"updatedInput\":{\"file_path\":\"/workspace/README.md\"}}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Grep","tool_use_id":"toolu_3","input":{"pattern":"TODO","path":"/workspace"}}}} |
| +< {"id":3,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"allow\",\"updatedInput\":{\"path\":\"/workspace\",\"pattern\":\"TODO\"}}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Write","tool_use_id":"toolu_4","input":{"file_path":"/workspace/README.md","content":"x"}}}} |
| +< {"id":4,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: this step only reads: use Read, Glob and Grep under /workspace\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Bash","tool_use_id":"toolu_5","input":{"command":"git log"}}}} |
| +< {"id":5,"jsonrpc":"2.0","result":{"content":[{"text":"{\"behavior\":\"deny\",\"message\":\"provider_policy_rejected: this step only reads: use Read, Glob and Grep under /workspace\"}","type":"text"}]}} |
| +> {"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"git_log","arguments":{},"_meta":{"claudecode/toolUseId":"toolu_6"}}} |
| +< {"id":6,"jsonrpc":"2.0","result":{"content":[{"text":"git_log toolu_6 {}","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"git_diff","arguments":{"path":"main.go"},"_meta":{"claudecode/toolUseId":"toolu_7"}}} |
| +< {"id":7,"jsonrpc":"2.0","result":{"content":[{"text":"git_diff toolu_7 {\"path\":\"main.go\"}","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"git_show","arguments":{"commit":"abc1234"},"_meta":{"claudecode/toolUseId":"toolu_8"}}} |
| +< {"id":8,"jsonrpc":"2.0","result":{"content":[{"text":"git_show toolu_8 {\"commit\":\"abc1234\"}","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"submit_candidate","arguments":{},"_meta":{"claudecode/toolUseId":"toolu_9"}}} |
| +< {"error":{"code":-32602,"message":"unavailable"},"id":9,"jsonrpc":"2.0"} |
| +== submit |
| +> {"jsonrpc":"2.0","id":1,"method":"tools/list"} |
| +< {"error":{"code":-32600,"message":"not initialized"},"id":1,"jsonrpc":"2.0"} |
| +> {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"submit_answer","arguments":{"answer":"before"}}} |
| +< {"error":{"code":-32602,"message":"unavailable"},"id":2,"jsonrpc":"2.0"} |
| +> {"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"claude-code","version":"2.1.312"}}} |
| +< {"id":0,"jsonrpc":"2.0","result":{"capabilities":{"tools":{}},"protocolVersion":"2024-11-05","serverInfo":{"name":"equipo-runner","version":"2"}}} |
| +> {"jsonrpc":"2.0","method":"notifications/initialized"} |
| +> {"jsonrpc":"2.0","id":3,"method":"tools/list"} |
| +< {"id":3,"jsonrpc":"2.0","result":{"tools":[{"description":"Submit the answer.","inputSchema":{"additionalProperties":false,"properties":{"answer":{"type":"string"}},"required":["answer"],"type":"object"},"name":"submit_answer"}]}} |
| +> {"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"submit_answer","arguments":{"answer":"The greeting is in main.go, line 12."},"_meta":{"claudecode/toolUseId":"toolu_4"}}} |
| +< {"id":4,"jsonrpc":"2.0","result":{"content":[{"text":"submit_answer toolu_4 {\"answer\":\"The greeting is in main.go, line 12.\"}","type":"text"}],"isError":false}} |
| +> {"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"Read","tool_use_id":"toolu_5","input":{"file_path":"/workspace/main.go"}}}} |
| +< {"error":{"code":-32602,"message":"unavailable"},"id":5,"jsonrpc":"2.0"} |
diff --git a/internal/runner/thin/toolproxy_mac_test.go b/internal/runner/thin/toolproxy_mac_test.go| new file mode 100644 |
| index 00000000..0f0ffebb |
| --- /dev/null |
| +++ b/internal/runner/thin/toolproxy_mac_test.go |
| @@ -0,0 +1,23 @@ |
| +//go:build darwin || testbuild |
| + |
| +package thin |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| +) |
| + |
| +// A Mac's MCP endpoint (equipo-runner tool-proxy) speaks to the CLI and |
| +// to the step's tool socket exactly as the Linux tool proxy does: every |
| +// reply in the transcript recorded from the Linux proxy, byte for byte. |
| +// The shared code is built for darwin or the test build, so this runs on |
| +// Linux CI too. |
| +func TestDarwinToolProxySpeaksTheProtocol(t *testing.T) { |
| + header, want := readTranscript(t) |
| + if !strings.Contains(header, "# Recorded ") || !strings.Contains(header, " on ") { |
| + t.Fatalf("the transcript does not say when and where it was recorded:\n%s", header) |
| + } |
| + sameTranscript(t, playTranscript(t, runner.ServeDarwinToolProxy), want) |
| +} |
diff --git a/internal/runner/thin/toolproxy_transcript_linux_test.go b/internal/runner/thin/toolproxy_transcript_linux_test.go| new file mode 100644 |
| index 00000000..e48acf21 |
| --- /dev/null |
| +++ b/internal/runner/thin/toolproxy_transcript_linux_test.go |
| @@ -0,0 +1,40 @@ |
| +package thin |
| + |
| +import ( |
| + "os" |
| + "runtime" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/toolproxy" |
| +) |
| + |
| +// The Linux tool proxy still speaks the recorded transcript, so the |
| +// oracle the Mac endpoint is held to is what Linux does today. With |
| +// EQUIPO_RECORD_TOOL_TRANSCRIPT=1 it records the transcript again, with |
| +// today's date and this machine in its header. |
| +func TestLinuxToolProxyTranscript(t *testing.T) { |
| + got := playTranscript(t, toolproxy.Serve) |
| + if os.Getenv("EQUIPO_RECORD_TOOL_TRANSCRIPT") == "1" { |
| + host, err := os.Hostname() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + header := "# The tool proxy transcript: what a CLI sends through a tool proxy to a\n" + |
| + "# step's tool socket (>) and each reply (<), one tool socket per session.\n" + |
| + "# Recorded " + time.Now().UTC().Format("2006-01-02") + " on " + strings.ToLower(host) + " (" + runtime.GOOS + "/" + runtime.GOARCH + ") from the Linux tool proxy\n" + |
| + "# (internal/toolproxy.Serve) by TestLinuxToolProxyTranscript, and the\n" + |
| + "# oracle for TestDarwinToolProxySpeaksTheProtocol. Record it again with\n" + |
| + "# EQUIPO_RECORD_TOOL_TRANSCRIPT=1 go test ./internal/runner/thin -run TestLinuxToolProxyTranscript\n" |
| + if err := os.WriteFile(transcriptFile, []byte(header+got), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + _, want := readTranscript(t) |
| + sameTranscript(t, got, want) |
| + // The oracle holds both answers: a permission allowed and one denied. |
| + if !strings.Contains(want, `\"behavior\":\"allow\"`) || !strings.Contains(want, `\"behavior\":\"deny\"`) { |
| + t.Fatal("the transcript records no allowed and denied permission") |
| + } |
| +} |
diff --git a/internal/runner/thin/toolproxy_transcript_test.go b/internal/runner/thin/toolproxy_transcript_test.go| new file mode 100644 |
| index 00000000..bfebd968 |
| --- /dev/null |
| +++ b/internal/runner/thin/toolproxy_transcript_test.go |
| @@ -0,0 +1,275 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| +) |
| + |
| +// The tool proxy transcript is the oracle for a Mac's MCP endpoint: the |
| +// requests a CLI sends through a tool proxy to a step's tool socket and |
| +// the replies it gets back, recorded from the Linux tool proxy |
| +// (TestLinuxToolProxyTranscript) and replayed through the Mac's |
| +// (TestDarwinToolProxySpeaksTheProtocol). Its header says when and where |
| +// it was recorded. |
| +const transcriptFile = "testdata/toolproxy-transcript.txt" |
| + |
| +// transcriptSession is one tool socket's conversation: the set it |
| +// serves, its tool caller and what the CLI sends. A request without an |
| +// id is a notification and gets no reply. |
| +type transcriptSession struct { |
| + name string |
| + set toolSet |
| + call ToolFunc |
| + requests []string |
| +} |
| + |
| +// transcriptSessions are Engineering's step (its permission callback, |
| +// submit_candidate, ask_person), the answer action's read-only git tools |
| +// with the read-only callback, and a set naming submit_answer. |
| +func transcriptSessions() []transcriptSession { |
| + initialize := func(version string) string { |
| + return `{"jsonrpc":"2.0","id":0,"method":"initialize","params":{"protocolVersion":"` + version + `","capabilities":{},"clientInfo":{"name":"claude-code","version":"2.1.312"}}}` |
| + } |
| + initialized := `{"jsonrpc":"2.0","method":"notifications/initialized"}` |
| + permission := func(id, tool, input string) string { |
| + return `{"jsonrpc":"2.0","id":` + id + `,"method":"tools/call","params":{"name":"permission","arguments":{"tool_name":"` + tool + `","tool_use_id":"toolu_` + id + `","input":` + input + `}}}` |
| + } |
| + call := func(id, name, args string) string { |
| + return `{"jsonrpc":"2.0","id":` + id + `,"method":"tools/call","params":{"name":"` + name + `","arguments":` + args + `,"_meta":{"claudecode/toolUseId":"toolu_` + id + `"}}}` |
| + } |
| + // An Engineering step's policy as far as its permission callback |
| + // reads it: the workspace on the host (absent, so nothing in it is a |
| + // link), a denied path, its native tools, and every command kept in |
| + // the CLI's sandbox. |
| + policy := provider.Policy{Manifest: json.RawMessage(`{"Workspace":"/nonexistent/equipo-transcript/workspace","DeniedPaths":["/workspace/.git"],"Tools":["Bash","Read","Write","Edit","Glob","Grep"],"Settings":{"sandbox":{"enabled":true,"failIfUnavailable":true,"allowUnsandboxedCommands":false,"excludedCommands":[]}}}`)} |
| + echo := func(_ context.Context, name, useID string, args json.RawMessage) (string, bool) { |
| + return name + " " + useID + " " + string(args), false |
| + } |
| + return []transcriptSession{ |
| + { |
| + name: "implement", |
| + set: toolSet{list: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: func(raw json.RawMessage) string { |
| + return string(claude.StepPermission(raw, policy)) |
| + }}, |
| + call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, |
| + requests: []string{ |
| + initialize("2025-06-18"), |
| + initialized, |
| + `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}`, |
| + permission("2", "Read", `{"file_path":"/workspace/main.go"}`), |
| + permission("3", "Edit", `{"file_path":"/workspace/main.go","old_string":"hello","new_string":"hola"}`), |
| + permission("4", "Read", `{"file_path":"/etc/passwd"}`), |
| + permission("5", "Read", `{"file_path":"/workspace/../etc/passwd"}`), |
| + permission("5.5", "Read", `{"file_path":"/workspace/.git/config"}`), |
| + permission("6", "WebFetch", `{"url":"https://example.com/","prompt":"read it"}`), |
| + permission("7", "Bash", `{"command":"go test ./..."}`), |
| + permission("8", "Bash", `{"command":"ls","dangerouslyDisableSandbox":true}`), |
| + permission("9", "mcp__equipo__submit_candidate", `{}`), |
| + call("10", "submit_candidate", `{}`), |
| + call("11", "ask_person", `{"question":"Which colour?"}`), |
| + call("12", "submit_render", `null`), |
| + call("13", "submit_answer", `{"answer":"yes"}`), |
| + call("14", "read_file", `{"repo":"oficina/equipo","path":"/etc/passwd"}`), |
| + `{"jsonrpc":"2.0","id":15,"method":"ping"}`, |
| + `{"jsonrpc":"2.0","id":16,"method":"resources/list","params":{}}`, |
| + `{"jsonrpc":"2.0","id":"seventeen","method":"tools/call","params":{"name":"submit_candidate"}}`, |
| + }, |
| + }, |
| + { |
| + name: "answer", |
| + set: toolSet{list: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: func(raw json.RawMessage) string { |
| + return string(claude.ReadPermission(raw, policy)) |
| + }}, |
| + call: echo, |
| + requests: []string{ |
| + initialize("2025-03-26"), |
| + initialized, |
| + `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, |
| + permission("2", "Read", `{"file_path":"/workspace/README.md"}`), |
| + permission("3", "Grep", `{"pattern":"TODO","path":"/workspace"}`), |
| + permission("4", "Write", `{"file_path":"/workspace/README.md","content":"x"}`), |
| + permission("5", "Bash", `{"command":"git log"}`), |
| + call("6", "git_log", `{}`), |
| + call("7", "git_diff", `{"path":"main.go"}`), |
| + call("8", "git_show", `{"commit":"abc1234"}`), |
| + call("9", "submit_candidate", `{}`), |
| + }, |
| + }, |
| + { |
| + name: "submit", |
| + set: toolSet{list: []any{map[string]any{"name": "submit_answer", "description": "Submit the answer.", "inputSchema": toolSchema(map[string]any{"answer": str}, "answer")}}, names: []string{"submit_answer"}}, |
| + call: echo, |
| + requests: []string{ |
| + `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, |
| + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"submit_answer","arguments":{"answer":"before"}}}`, |
| + initialize("2024-11-05"), |
| + initialized, |
| + `{"jsonrpc":"2.0","id":3,"method":"tools/list"}`, |
| + call("4", "submit_answer", `{"answer":"The greeting is in main.go, line 12."}`), |
| + permission("5", "Read", `{"file_path":"/workspace/main.go"}`), |
| + }, |
| + }, |
| + } |
| +} |
| + |
| +// shortToolRoot is a private directory for tool sockets whose paths fit |
| +// a Mac's sun_path, without symbolic links (a Mac's TMPDIR is under /var). |
| +func shortToolRoot(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) |
| + } |
| + // The longest socket either layout makes under dir. |
| + if len(dir)+len("/coord-tool-4294967295/equipo.sock") > provider.MaxDarwinSocketPath { |
| + t.Fatalf("TMPDIR %s is too long for a Mac socket path; set a shorter TMPDIR", root) |
| + } |
| + return dir |
| +} |
| + |
| +// toolProxyServe is a tool proxy's stdio mode: the Linux tool proxy's |
| +// toolproxy.Serve or the Mac runner's runner.ServeDarwinToolProxy. |
| +type toolProxyServe func(ctx context.Context, input io.Reader, output io.Writer, path string) error |
| + |
| +// playTranscript plays every session through serve against a fresh tool |
| +// socket and returns the transcript body: per session a "== name" line, |
| +// then each request (">") followed by its reply ("<"), if it has one. |
| +func playTranscript(t *testing.T, serve toolProxyServe) string { |
| + t.Helper() |
| + root := shortToolRoot(t) |
| + var b strings.Builder |
| + for _, s := range transcriptSessions() { |
| + sock, err := openToolSet(context.Background(), root, s.set, s.call) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out strings.Builder |
| + err = serve(context.Background(), strings.NewReader(strings.Join(s.requests, "\n")+"\n"), &out, sock.Path) |
| + sock.Close() |
| + if err != nil { |
| + t.Fatalf("%s: %v", s.name, err) |
| + } |
| + replies := strings.SplitAfter(out.String(), "\n") |
| + if replies[len(replies)-1] == "" { |
| + replies = replies[:len(replies)-1] |
| + } |
| + b.WriteString("== " + s.name + "\n") |
| + for _, q := range s.requests { |
| + b.WriteString("> " + q + "\n") |
| + var id struct { |
| + ID json.RawMessage `json:"id"` |
| + } |
| + if json.Unmarshal([]byte(q), &id) != nil { |
| + t.Fatalf("%s: a request that is not JSON: %s", s.name, q) |
| + } |
| + if len(id.ID) == 0 { |
| + continue |
| + } |
| + if len(replies) == 0 { |
| + t.Fatalf("%s: no reply to %s", s.name, q) |
| + } |
| + b.WriteString("< " + replies[0]) |
| + replies = replies[1:] |
| + } |
| + if len(replies) != 0 { |
| + t.Fatalf("%s: replies nobody asked for: %q", s.name, replies) |
| + } |
| + } |
| + return b.String() |
| +} |
| + |
| +// readTranscript is the recorded transcript's header (its "#" lines) and |
| +// body. |
| +func readTranscript(t *testing.T) (header, body string) { |
| + t.Helper() |
| + raw, err := os.ReadFile(transcriptFile) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + text := string(raw) |
| + for strings.HasPrefix(text, "#") { |
| + line, rest, _ := strings.Cut(text, "\n") |
| + header += line + "\n" |
| + text = rest |
| + } |
| + return header, text |
| +} |
| + |
| +// fataler is what sameTranscript needs of a test, so its own test can |
| +// watch it fail. |
| +type fataler interface { |
| + Helper() |
| + Fatalf(format string, args ...any) |
| +} |
| + |
| +// sameTranscript fails t unless got is want byte for byte, naming the |
| +// first line that differs. |
| +func sameTranscript(t fataler, got, want string) { |
| + t.Helper() |
| + if got == want { |
| + return |
| + } |
| + g, w := strings.Split(got, "\n"), strings.Split(want, "\n") |
| + for i := 0; i < len(g) || i < len(w); i++ { |
| + var gl, wl string |
| + if i < len(g) { |
| + gl = g[i] |
| + } |
| + if i < len(w) { |
| + wl = w[i] |
| + } |
| + if gl != wl || i >= len(g) || i >= len(w) { |
| + t.Fatalf("transcript line %d differs\n got %q\nwant %q", i+1, gl, wl) |
| + return |
| + } |
| + } |
| + t.Fatalf("transcript differs (%d bytes, want %d)", len(got), len(want)) |
| +} |
| + |
| +// fatalRecorder records sameTranscript's verdict. |
| +type fatalRecorder struct{ failed []string } |
| + |
| +func (r *fatalRecorder) Helper() {} |
| +func (r *fatalRecorder) Fatalf(format string, args ...any) { |
| + r.failed = append(r.failed, fmt.Sprintf(format, args...)) |
| +} |
| + |
| +// A line-based MCP client reads a reply only at its newline, so a |
| +// transcript differing only in a final newline, or in an empty last |
| +// line, differs. |
| +func TestSameTranscriptIsExact(t *testing.T) { |
| + want := "== s\n> {\"id\":1}\n< {\"id\":1}\n" |
| + for name, got := range map[string]string{ |
| + "missing final newline": strings.TrimSuffix(want, "\n"), |
| + "extra empty line": want + "\n", |
| + "changed reply": strings.Replace(want, "< {\"id\":1}", "< {\"id\":2}", 1), |
| + "missing reply": "== s\n> {\"id\":1}\n", |
| + } { |
| + r := &fatalRecorder{} |
| + sameTranscript(r, got, want) |
| + if len(r.failed) == 0 { |
| + t.Fatalf("%s: %q passed as %q", name, got, want) |
| + } |
| + } |
| + r := &fatalRecorder{} |
| + if sameTranscript(r, want, want); len(r.failed) != 0 { |
| + t.Fatalf("an equal transcript failed: %v", r.failed) |
| + } |
| +} |
diff --git a/internal/runner/thin/toolsocket_layout.go b/internal/runner/thin/toolsocket_layout.go| new file mode 100644 |
| index 00000000..33a2da73 |
| --- /dev/null |
| +++ b/internal/runner/thin/toolsocket_layout.go |
| @@ -0,0 +1,34 @@ |
| +package thin |
| + |
| +import ( |
| + "path/filepath" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| +) |
| + |
| +// A Mac's tool sockets (Mac runners spec §8.2). Linux binds a step's tool |
| +// socket through its directory's descriptor, so the path's length never |
| +// matters there. A Mac has no /proc/self/fd: the CLI's tool endpoint |
| +// dials the socket by its path, which must fit sun_path |
| +// (provider.MaxDarwinSocketPath). The state directory with Linux's names |
| +// does not fit a long home, so a Mac's go under the scratch root's short |
| +// t/, each in a directory named only by MkdirTemp's random number (at |
| +// most 10 digits), as s. |
| +const ( |
| + macToolDirPrefix = "" |
| + macToolSocketName = "s" |
| + // macToolHomeName is the longest runner user name whose sockets fit, |
| + // for install_mac.go's roots (~/.local/share/equipo-runner/scratch): |
| + // /Users/<name>/.local/share/equipo-runner/scratch/t/<10 digits>/s. |
| + macToolHomeName = 46 |
| +) |
| + |
| +// macToolRoot is the directory a Mac's tool sockets go under. |
| +func macToolRoot(c runner.Config) string { return filepath.Join(c.ScratchRoot, "t") } |
| + |
| +// macToolSocketLongest is the longest tool socket path a Mac makes under |
| +// root. |
| +func macToolSocketLongest(root string) string { |
| + return filepath.Join(root, macToolDirPrefix+strings.Repeat("9", 10), macToolSocketName) |
| +} |
diff --git a/internal/runner/thin/toolsocket_layout_test.go b/internal/runner/thin/toolsocket_layout_test.go| new file mode 100644 |
| index 00000000..bfe02f9b |
| --- /dev/null |
| +++ b/internal/runner/thin/toolsocket_layout_test.go |
| @@ -0,0 +1,42 @@ |
| +package thin |
| + |
| +import ( |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +// A Mac has no /proc/self/fd to bind a socket through, so a step's tool |
| +// socket path itself must fit sun_path (104 bytes with its NUL). It goes |
| +// under the scratch root's short t/, in a directory named only by |
| +// MkdirTemp's random number, as s: for a runner user whose home is as |
| +// long as macToolHomeName allows, the longest path still fits. The roots |
| +// are install_mac.go's (~/.local/share/equipo-runner). |
| +func TestToolSocketPathFits(t *testing.T) { |
| + cfg := func(name string) runner.Config { |
| + share := filepath.Join("/Users", name, ".local", "share", "equipo-runner") |
| + return runner.Config{StateDir: filepath.Join(share, "state"), ScratchRoot: filepath.Join(share, "scratch"), WorkspaceRoot: filepath.Join(share, "work")} |
| + } |
| + for _, name := range []string{"paulequipo", strings.Repeat("n", 32), strings.Repeat("n", macToolHomeName)} { |
| + c := cfg(name) |
| + root := macToolRoot(c) |
| + if root != filepath.Join(c.ScratchRoot, "t") { |
| + t.Fatalf("a Mac's tool sockets are under %s, not the scratch root's t/", root) |
| + } |
| + if got := macToolSocketLongest(root); len(got) > provider.MaxDarwinSocketPath { |
| + t.Fatalf("home of %d bytes: %s is %d bytes", len(name), got, len(got)) |
| + } |
| + } |
| + // One byte more no longer fits, and is refused, never cut short. |
| + if got := macToolSocketLongest(macToolRoot(cfg(strings.Repeat("n", macToolHomeName+1)))); len(got) <= provider.MaxDarwinSocketPath { |
| + t.Fatalf("macToolHomeName is not the longest name that fits: %s", got) |
| + } |
| + // The state directory, where Linux puts them, would not fit a long |
| + // name with the Linux names. |
| + if long := filepath.Join(cfg(strings.Repeat("n", 32)).StateDir, "coord-tool-4294967295", "equipo.sock"); len(long) <= provider.MaxDarwinSocketPath { |
| + t.Fatalf("the Linux layout fits after all: %s", long) |
| + } |
| +} |
diff --git a/internal/runner/thin/toolsocket_linux.go b/internal/runner/thin/toolsocket_linux.go| index cb619714..2125335c 100644 |
| --- a/internal/runner/thin/toolsocket_linux.go |
| +++ b/internal/runner/thin/toolsocket_linux.go |
| @@ -7,8 +7,19 @@ import ( |
| "strconv" |
| "golang.org/x/sys/unix" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| +) |
| + |
| +// A step's tool socket on Linux: <state dir>/coord-tool-*/equipo.sock. |
| +const ( |
| + toolDirPrefix = "coord-tool-" |
| + toolSocketName = "equipo.sock" |
| ) |
| +// toolRoot is the private directory a runner's tool sockets go under. |
| +func toolRoot(c runner.Config) (string, error) { return c.StateDir, nil } |
| + |
| // listenToolSocket binds the socket through its directory's descriptor, |
| // as the egress proxy does: a Unix socket's path holds 107 bytes, and a |
| // runner's state directory can leave less room than that (2026-11-22, |
diff --git a/internal/runner/thin/toolsocket_other.go b/internal/runner/thin/toolsocket_other.go| index 4418d832..322d376f 100644 |
| --- a/internal/runner/thin/toolsocket_other.go |
| +++ b/internal/runner/thin/toolsocket_other.go |
| @@ -5,14 +5,50 @@ package thin |
| import ( |
| "errors" |
| "net" |
| + "os" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +var ( |
| + errToolSocketPath = errors.New("tool socket path too long") |
| + errToolRoot = errors.New("tool socket root is not a directory") |
| +) |
| + |
| +// A step's tool socket on a Mac: <scratch root>/t/<random>/s |
| +// (toolsocket_layout.go), dialled by its path. |
| +const ( |
| + toolDirPrefix = macToolDirPrefix |
| + toolSocketName = macToolSocketName |
| ) |
| -var errToolSocketPath = errors.New("tool socket path too long") |
| +// toolRoot is the private directory a runner's tool sockets go under, |
| +// created 0700 if it is missing: never a link, always this user's. |
| +func toolRoot(c runner.Config) (string, error) { |
| + root := macToolRoot(c) |
| + if err := os.MkdirAll(root, 0700); err != nil { |
| + return "", err |
| + } |
| + info, err := os.Lstat(root) |
| + if err != nil { |
| + return "", err |
| + } |
| + if !info.IsDir() { |
| + return "", errToolRoot |
| + } |
| + if info.Mode().Perm() != 0700 { |
| + if err := os.Chmod(root, 0700); err != nil { |
| + return "", err |
| + } |
| + } |
| + return root, nil |
| +} |
| -// listenToolSocket binds the socket at path, which must fit a Unix |
| -// socket's path. |
| +// listenToolSocket binds the socket at path, which must fit a Mac's |
| +// sun_path: it is refused, never cut short. |
| func listenToolSocket(_, path string) (*net.UnixListener, error) { |
| - if len(path) > 103 { |
| + if len(path) > provider.MaxDarwinSocketPath { |
| return nil, errToolSocketPath |
| } |
| return net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"}) |
diff --git a/internal/runner/thin/toolsocket_peer_test.go b/internal/runner/thin/toolsocket_peer_test.go| new file mode 100644 |
| index 00000000..81216596 |
| --- /dev/null |
| +++ b/internal/runner/thin/toolsocket_peer_test.go |
| @@ -0,0 +1,65 @@ |
| +package thin |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "errors" |
| + "net" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// Only the runner's own user may talk to a step's tool socket. On a Mac |
| +// the peer is read with LOCAL_PEERCRED (runner peer_darwin.go), on Linux |
| +// with SO_PEERCRED; the decision is exercised through its seam, so a |
| +// peer of another user, root, or one whose credential cannot be read is |
| +// shut out on either. |
| +func TestToolSocketPeerUID(t *testing.T) { |
| + root := shortToolRoot(t) |
| + ping := func(path string) (string, error) { |
| + c, err := net.Dial("unix", path) |
| + if err != nil { |
| + return "", err |
| + } |
| + defer c.Close() |
| + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) |
| + if _, err := c.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"ping"}` + "\n")); err != nil { |
| + return "", err |
| + } |
| + return bufio.NewReader(c).ReadString('\n') |
| + } |
| + open := func() *toolSocket { |
| + t.Helper() |
| + s, err := openToolSet(context.Background(), root, converseSet(false), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(s.Close) |
| + return s |
| + } |
| + // The real credential: this process is its own peer. |
| + if reply, err := ping(open().Path); err != nil || !strings.Contains(reply, `"result"`) { |
| + t.Fatalf("the runner's own user was refused: %q %v", reply, err) |
| + } |
| + defer func(f func(int) (uint32, error)) { toolPeerUID = f }(toolPeerUID) |
| + own := uint32(os.Getuid()) |
| + for name, seam := range map[string]func(int) (uint32, error){ |
| + "another user": func(int) (uint32, error) { return own + 1, nil }, |
| + "root": func(int) (uint32, error) { return 0, nil }, |
| + "unknown": func(int) (uint32, error) { return own, errors.New("no credential") }, |
| + } { |
| + if own == 0 && name == "root" { |
| + continue |
| + } |
| + toolPeerUID = seam |
| + if reply, err := ping(open().Path); err == nil || reply != "" { |
| + t.Fatalf("%s was answered: %q %v", name, reply, err) |
| + } |
| + } |
| + toolPeerUID = func(int) (uint32, error) { return own, nil } |
| + if reply, err := ping(open().Path); err != nil || !strings.Contains(reply, `"result"`) { |
| + t.Fatalf("the seam's own user was refused: %q %v", reply, err) |
| + } |
| +} |
diff --git a/internal/runner/tool_proxy_mac.go b/internal/runner/tool_proxy_mac.go| new file mode 100644 |
| index 00000000..551598f2 |
| --- /dev/null |
| +++ b/internal/runner/tool_proxy_mac.go |
| @@ -0,0 +1,158 @@ |
| +//go:build darwin || testbuild |
| + |
| +package runner |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net" |
| + "path/filepath" |
| + "strings" |
| + |
| + "golang.org/x/sys/unix" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +// A Mac runner's MCP tool endpoint, equipo-runner tool-proxy --socket |
| +// <path> (Mac runners spec §8.1, §8.2). Linux keeps its certified tool |
| +// proxy (internal/toolproxy, byte for byte); a Mac release has none, so |
| +// the runner binary relays the CLI's stdio MCP to the step's tool socket |
| +// itself, with the same bounds and the same framing. It is built for |
| +// darwin, and for the test build so Linux CI runs it; a Linux release |
| +// does not contain it. |
| + |
| +// macToolFrame bounds a request from the CLI and macReplyFrame a reply |
| +// from the runner, as internal/toolproxy's maxToolFrame and |
| +// maxReplyFrame do. |
| +const ( |
| + macToolFrame = 64 << 10 |
| + macReplyFrame = 4 << 20 |
| +) |
| + |
| +// macDial dials the step socket once every check has passed. Tests |
| +// stand in to see that a refusal never reaches it. |
| +var macDial = (&net.Dialer{}).DialContext |
| + |
| +// macListenerUID is the user that holds the step socket's other end |
| +// (LOCAL_PEERCRED on a Mac). Tests stand in. |
| +var macListenerUID = func(c *net.UnixConn) (uint32, error) { |
| + raw, err := c.SyscallConn() |
| + if err != nil { |
| + return 0, err |
| + } |
| + var uid uint32 |
| + var perr error |
| + if err := raw.Control(func(fd uintptr) { uid, perr = peerUID(int(fd)) }); err != nil { |
| + return 0, err |
| + } |
| + return uid, perr |
| +} |
| + |
| +// ServeDarwinToolProxy is the Mac endpoint's stdio mode. path is the |
| +// step's tool socket: a clean absolute path that fits a Mac's sun_path, |
| +// reached without a symbolic link, in a 0700 directory of this user's, |
| +// a 0600 socket of this user's, held open by this user. Anything else is |
| +// refused before a byte is sent or written. |
| +func ServeDarwinToolProxy(ctx context.Context, input io.Reader, output io.Writer, path string) error { |
| + if !filepath.IsAbs(path) || filepath.Clean(path) != path || len(path) > provider.MaxDarwinSocketPath || strings.ContainsRune(path, 0) { |
| + return runnerproto.ErrInvalid |
| + } |
| + parent, err := openPrivateDir(filepath.Dir(path)) |
| + if err != nil { |
| + return err |
| + } |
| + var st unix.Stat_t |
| + err = unix.Fstatat(int(parent.Fd()), filepath.Base(path), &st, unix.AT_SYMLINK_NOFOLLOW) |
| + parent.Close() |
| + if err != nil || st.Mode&unix.S_IFMT != unix.S_IFSOCK || st.Mode&0777 != 0600 || !toolOwner(st.Uid) { |
| + return runnerproto.ErrInvalid |
| + } |
| + // No /proc/self/fd here: the path is dialled as checked. Only this |
| + // user can change what lies under a directory it alone may enter, |
| + // and the listener's credential is checked before anything is sent. |
| + conn, err := macDial(ctx, "unix", path) |
| + if err != nil { |
| + return err |
| + } |
| + defer conn.Close() |
| + unixConn, ok := conn.(*net.UnixConn) |
| + if !ok { |
| + return runnerproto.ErrInvalid |
| + } |
| + if uid, err := macListenerUID(unixConn); err != nil || !toolOwner(uid) { |
| + return runnerproto.ErrInvalid |
| + } |
| + stop := context.AfterFunc(ctx, func() { conn.Close() }) |
| + defer stop() |
| + return macRelay(input, output, conn) |
| +} |
| + |
| +// macMCPRequest is the JSON-RPC envelope the endpoint checks, as |
| +// internal/toolproxy's mcpRequest. |
| +type macMCPRequest struct { |
| + JSONRPC string `json:"jsonrpc"` |
| + ID json.RawMessage `json:"id,omitempty"` |
| + Method string `json:"method"` |
| + Params json.RawMessage `json:"params,omitempty"` |
| +} |
| + |
| +// macRelay carries the CLI's JSON-RPC lines to the runner's socket and |
| +// each reply back, one request at a time, as internal/toolproxy's relay. |
| +func macRelay(input io.Reader, output io.Writer, conn io.ReadWriter) error { |
| + reader := bufio.NewReaderSize(input, macToolFrame+1) |
| + replies := bufio.NewReaderSize(conn, macReplyFrame+1) |
| + for { |
| + if _, err := reader.Peek(1); err == io.EOF { |
| + return nil |
| + } else if err != nil { |
| + return err |
| + } |
| + raw, err := macFrame(reader, macToolFrame) |
| + if err != nil { |
| + return err |
| + } |
| + var q macMCPRequest |
| + if macDecode(raw, &q) != nil || q.JSONRPC != "2.0" { |
| + return runnerproto.ErrInvalid |
| + } |
| + if _, err := conn.Write(append(raw, '\n')); err != nil { |
| + return err |
| + } |
| + if len(q.ID) == 0 { |
| + continue |
| + } |
| + reply, err := macFrame(replies, macReplyFrame) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := output.Write(append(reply, '\n')); err != nil { |
| + return err |
| + } |
| + } |
| +} |
| + |
| +func macFrame(r *bufio.Reader, limit int) ([]byte, error) { |
| + raw, err := r.ReadSlice('\n') |
| + if err != nil || len(raw) > limit { |
| + return nil, runnerproto.ErrInvalid |
| + } |
| + return bytes.TrimSuffix(raw, []byte{'\n'}), nil |
| +} |
| + |
| +func macDecode(raw []byte, v any) error { |
| + d := json.NewDecoder(bytes.NewReader(raw)) |
| + d.DisallowUnknownFields() |
| + if err := d.Decode(v); err != nil { |
| + return err |
| + } |
| + var extra any |
| + if d.Decode(&extra) != io.EOF { |
| + return runnerproto.ErrInvalid |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/tool_proxy_mac_test.go b/internal/runner/tool_proxy_mac_test.go| new file mode 100644 |
| index 00000000..db155d8e |
| --- /dev/null |
| +++ b/internal/runner/tool_proxy_mac_test.go |
| @@ -0,0 +1,322 @@ |
| +//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()) |
| + } |
| +} |
diff --git a/internal/runner/tool_proxy_serve_darwin.go b/internal/runner/tool_proxy_serve_darwin.go| index 9c0c4aba..ccadc58e 100644 |
| --- a/internal/runner/tool_proxy_serve_darwin.go |
| +++ b/internal/runner/tool_proxy_serve_darwin.go |
| @@ -2,13 +2,11 @@ package runner |
| import ( |
| "context" |
| - "errors" |
| "io" |
| ) |
| -// ServeToolProxy: the tool proxy serves a Linux coordinator in its |
| -// namespace. A Mac worker runs checks only and has none; the tool proxy |
| -// itself is built for Linux alone. |
| -func ServeToolProxy(context.Context, io.Reader, io.Writer, string) error { |
| - return errors.New("the tool proxy is not on a Mac runner") |
| +// ServeToolProxy on a Mac is the runner's own MCP tool endpoint |
| +// (ServeDarwinToolProxy): a Mac release has no separate tool proxy. |
| +func ServeToolProxy(ctx context.Context, input io.Reader, output io.Writer, path string) error { |
| + return ServeDarwinToolProxy(ctx, input, output, path) |
| } |