//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 }