oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build darwin || testbuild
2
3package main
4
5import (
6 "bufio"
7 "context"
8 "encoding/json"
9 "net"
10 "os"
11 "path/filepath"
12 "strconv"
13 "testing"
14 "time"
15
16 "golang.org/x/sys/unix"
17)
18
19// childArgs starts this test binary as equipo-runner with those
20// arguments (a JSON array, toolProxyChild) instead of running its tests;
21// childReport names the file it reports to.
22const (
23 childArgs = "EQUIPO_TEST_TOOL_PROXY_ARGS"
24 childReport = "EQUIPO_TEST_TOOL_PROXY_REPORT"
25)
26
27func init() {
28 if raw := os.Getenv(childArgs); raw != "" {
29 var args []string
30 if json.Unmarshal([]byte(raw), &args) != nil {
31 os.Exit(93)
32 }
33 os.Exit(toolProxyChild(args, os.Getenv(childReport)))
34 }
35}
36
37// toolProxyReport is what the endpoint process holds once it has
38// served: its environment, the descriptors above 2 without
39// close-on-exec, the identity of every descriptor above 2, and any
40// variable run read through getenv.
41type toolProxyReport struct {
42 Getenv []string `json:"getenv"`
43 Env []string `json:"env"`
44 Inherited []int `json:"inherited"`
45 Open [][2]uint64 `json:"open"`
46 Pipe bool `json:"pipe"`
47}
48
49// toolProxyChild runs equipo-runner as the CLI starts it, then reports
50// to the file at report. The Go runtime's poller is in use before the
51// endpoint starts (a pipe, as signal handling and the runner's own files
52// are): its descriptors must survive, which the pipe shows afterwards.
53func toolProxyChild(args []string, reportPath string) int {
54 r, w, err := os.Pipe()
55 if err != nil {
56 return 90
57 }
58 var read []string
59 code := run(context.Background(), args, os.Stdin, os.Stdout, os.Stderr, func(k string) string { read = append(read, k); return "" })
60 report := toolProxyReport{Getenv: read, Env: os.Environ()}
61 _ = r.SetReadDeadline(time.Now().Add(5 * time.Second))
62 if _, err := w.Write([]byte("x")); err == nil {
63 b := make([]byte, 1)
64 n, err := r.Read(b)
65 report.Pipe = err == nil && n == 1
66 }
67 entries, err := os.ReadDir("/dev/fd")
68 if err != nil {
69 return 91
70 }
71 for _, e := range entries {
72 fd, err := strconv.Atoi(e.Name())
73 if err != nil || fd <= 2 {
74 continue
75 }
76 flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0)
77 if err != nil {
78 continue // the directory's own descriptor, closed by now
79 }
80 if flags&unix.FD_CLOEXEC == 0 {
81 report.Inherited = append(report.Inherited, fd)
82 }
83 var st unix.Stat_t
84 if unix.Fstat(fd, &st) == nil {
85 report.Open = append(report.Open, [2]uint64{uint64(st.Dev), uint64(st.Ino)})
86 }
87 }
88 raw, err := json.Marshal(report)
89 if err != nil || os.WriteFile(reportPath, raw, 0600) != nil {
90 return 92
91 }
92 return code
93}
94
95// The endpoint starts as the CLI's child, so it inherits whatever the CLI
96// leaves open and its whole environment: a token's descriptor
97// (CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR) and any token variable. It
98// keeps neither while it serves: every inherited descriptor above 2 is
99// closed and the environment is emptied, while the runtime's own
100// descriptors (its poller) keep working.
101func TestToolProxyDropsInheritedCredentials(t *testing.T) {
102 socket := echoSocket(t)
103 tokenR, tokenW, err := os.Pipe()
104 if err != nil {
105 t.Fatal(err)
106 }
107 defer tokenR.Close()
108 defer tokenW.Close()
109 if _, err := tokenW.WriteString("sk-ant-oat01-SENTINEL\n"); err != nil {
110 t.Fatal(err)
111 }
112 var tokenID [2]uint64
113 var st unix.Stat_t
114 if err := unix.Fstat(int(tokenR.Fd()), &st); err != nil {
115 t.Fatal(err)
116 }
117 tokenID = [2]uint64{uint64(st.Dev), uint64(st.Ino)}
118 // The token's read end as fd 3, its write end as fd 6.
119 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},
120 "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")
121 if code != 0 || stderr != "" || out != `{"jsonrpc":"2.0","id":1,"result":{}}`+"\n" {
122 t.Fatalf("the endpoint did not serve: exit %d, out %q, stderr %q", code, out, stderr)
123 }
124 if len(report.Env) != 0 {
125 t.Fatalf("the endpoint kept its environment: %q", report.Env)
126 }
127 if len(report.Inherited) != 0 {
128 t.Fatalf("the endpoint kept inherited descriptors %v", report.Inherited)
129 }
130 for _, id := range report.Open {
131 if tokenID[1] != 0 && id == tokenID {
132 t.Fatalf("the endpoint still holds the token's pipe (%v)", id)
133 }
134 }
135 if !report.Pipe {
136 t.Fatal("the runtime's poller no longer works after the endpoint started")
137 }
138}
139
140// echoSocket is a 0600 socket in a 0700 directory, without links, that
141// answers each request with an empty result.
142func echoSocket(t *testing.T) string {
143 t.Helper()
144 root, err := filepath.EvalSymlinks(os.TempDir())
145 if err != nil {
146 t.Fatal(err)
147 }
148 dir, err := os.MkdirTemp(root, "t")
149 if err != nil {
150 t.Fatal(err)
151 }
152 t.Cleanup(func() { os.RemoveAll(dir) })
153 if err := os.Chmod(dir, 0700); err != nil {
154 t.Fatal(err)
155 }
156 path := filepath.Join(dir, "s")
157 l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
158 if err != nil {
159 t.Fatal(err)
160 }
161 t.Cleanup(func() { l.Close() })
162 if err := os.Chmod(path, 0600); err != nil {
163 t.Fatal(err)
164 }
165 go func() {
166 for {
167 c, err := l.AcceptUnix()
168 if err != nil {
169 return
170 }
171 go func() {
172 defer c.Close()
173 r := bufio.NewReader(c)
174 for {
175 if _, err := r.ReadBytes('\n'); err != nil {
176 return
177 }
178 c.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{}}` + "\n"))
179 }
180 }()
181 }
182 }()
183 return path
184}
185