package toolproxy import ( "bufio" "bytes" "context" "encoding/json" "errors" "fmt" "golang.org/x/sys/unix" "io" "net" "os" "path/filepath" "strings" ) // maxToolFrame bounds a request from the CLI; maxReplyFrame a reply from // the runner, which may carry one image a tool returned // (read_attachment: at most attach.ModelBytes, base64 in JSON). const ( maxToolFrame = 64 << 10 maxReplyFrame = 4 << 20 ) var errInvalid = errors.New("invalid_tool_proxy_frame") type mcpRequest struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Method string `json:"method"` Params json.RawMessage `json:"params,omitempty"` } func decode(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 errInvalid } return nil } // Serve is the fixed binary's stdio mode. It knows only an endpoint. func Serve(ctx context.Context, input io.Reader, output io.Writer, path string) error { if !filepath.IsAbs(path) || filepath.Clean(path) != path { return errInvalid } // Inside the namespace /tool is an immutable mount. On the host, verify its // private parent and use the open fd so long paths never need truncation. dialPath := path var parent *os.File if path != "/tool/equipo.sock" { var err error parent, err = openPrivateDir(filepath.Dir(path)) if err != nil { return err } defer parent.Close() dialPath = fmt.Sprintf("/proc/self/fd/%d/%s", parent.Fd(), filepath.Base(path)) } conn, err := (&net.Dialer{}).DialContext(ctx, "unix", dialPath) if err != nil { return err } defer conn.Close() stop := context.AfterFunc(ctx, func() { conn.Close() }) defer stop() return relay(input, output, conn) } // relay carries the CLI's JSON-RPC lines to the runner's socket and each // reply back, one request at a time. func relay(input io.Reader, output io.Writer, conn io.ReadWriter) error { reader := bufio.NewReaderSize(input, maxToolFrame+1) replies := bufio.NewReaderSize(conn, maxReplyFrame+1) for { if _, err := reader.Peek(1); err == io.EOF { return nil } else if err != nil { return err } raw, err := readToolFrame(reader, maxToolFrame) if err != nil { return err } var q mcpRequest if decode(raw, &q) != nil || q.JSONRPC != "2.0" { return errInvalid } if _, err := conn.Write(append(raw, '\n')); err != nil { return err } if len(q.ID) == 0 { continue } reply, err := readToolFrame(replies, maxReplyFrame) if err != nil { return err } if _, err := output.Write(append(reply, '\n')); err != nil { return err } } } func readToolFrame(r *bufio.Reader, limit int) ([]byte, error) { raw, err := r.ReadSlice('\n') if err != nil || len(raw) > limit { return nil, errInvalid } return bytes.TrimSuffix(raw, []byte{'\n'}), nil } // openNoLinks walks every component using directory-relative no-follow opens. func openNoLinks(path string, flags int) (*os.File, error) { if !filepath.IsAbs(path) || filepath.Clean(path) != path { return nil, errInvalid } fd, err := unix.Open("/", unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { return nil, errInvalid } parts := strings.Split(strings.TrimPrefix(path, "/"), "/") for i, p := range parts { f := unix.O_PATH | unix.O_DIRECTORY if i == len(parts)-1 { f = flags } next, e := unix.Openat(fd, p, f|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) unix.Close(fd) if e != nil { return nil, errInvalid } fd = next } return os.NewFile(uintptr(fd), path), nil } func privateInfo(f *os.File, mode os.FileMode, dir bool) bool { var st unix.Stat_t if unix.Fstat(int(f.Fd()), &st) != nil || st.Uid != uint32(os.Getuid()) { return false } info, err := f.Stat() return err == nil && info.Mode().Perm() == mode && ((dir && info.IsDir()) || (!dir && info.Mode().IsRegular())) } func openPrivateDir(path string) (*os.File, error) { f, err := openNoLinks(path, unix.O_RDONLY|unix.O_DIRECTORY) if err != nil { return nil, err } if !privateInfo(f, 0700, true) { f.Close() return nil, errInvalid } return f, nil }