| 1 | package toolproxy |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "golang.org/x/sys/unix" |
| 11 | "io" |
| 12 | "net" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "strings" |
| 16 | ) |
| 17 | |
| 18 | // maxToolFrame bounds a request from the CLI; maxReplyFrame a reply from |
| 19 | // the runner, which may carry one image a tool returned |
| 20 | // (read_attachment: at most attach.ModelBytes, base64 in JSON). |
| 21 | const ( |
| 22 | maxToolFrame = 64 << 10 |
| 23 | maxReplyFrame = 4 << 20 |
| 24 | ) |
| 25 | |
| 26 | var errInvalid = errors.New("invalid_tool_proxy_frame") |
| 27 | |
| 28 | type mcpRequest struct { |
| 29 | JSONRPC string `json:"jsonrpc"` |
| 30 | ID json.RawMessage `json:"id,omitempty"` |
| 31 | Method string `json:"method"` |
| 32 | Params json.RawMessage `json:"params,omitempty"` |
| 33 | } |
| 34 | |
| 35 | func decode(raw []byte, v any) error { |
| 36 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 37 | d.DisallowUnknownFields() |
| 38 | if err := d.Decode(v); err != nil { |
| 39 | return err |
| 40 | } |
| 41 | var extra any |
| 42 | if d.Decode(&extra) != io.EOF { |
| 43 | return errInvalid |
| 44 | } |
| 45 | return nil |
| 46 | } |
| 47 | |
| 48 | // Serve is the fixed binary's stdio mode. It knows only an endpoint. |
| 49 | func Serve(ctx context.Context, input io.Reader, output io.Writer, path string) error { |
| 50 | if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| 51 | return errInvalid |
| 52 | } |
| 53 | // Inside the namespace /tool is an immutable mount. On the host, verify its |
| 54 | // private parent and use the open fd so long paths never need truncation. |
| 55 | dialPath := path |
| 56 | var parent *os.File |
| 57 | if path != "/tool/equipo.sock" { |
| 58 | var err error |
| 59 | parent, err = openPrivateDir(filepath.Dir(path)) |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | defer parent.Close() |
| 64 | dialPath = fmt.Sprintf("/proc/self/fd/%d/%s", parent.Fd(), filepath.Base(path)) |
| 65 | } |
| 66 | conn, err := (&net.Dialer{}).DialContext(ctx, "unix", dialPath) |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | defer conn.Close() |
| 71 | stop := context.AfterFunc(ctx, func() { conn.Close() }) |
| 72 | defer stop() |
| 73 | return relay(input, output, conn) |
| 74 | } |
| 75 | |
| 76 | // relay carries the CLI's JSON-RPC lines to the runner's socket and each |
| 77 | // reply back, one request at a time. |
| 78 | func relay(input io.Reader, output io.Writer, conn io.ReadWriter) error { |
| 79 | reader := bufio.NewReaderSize(input, maxToolFrame+1) |
| 80 | replies := bufio.NewReaderSize(conn, maxReplyFrame+1) |
| 81 | for { |
| 82 | if _, err := reader.Peek(1); err == io.EOF { |
| 83 | return nil |
| 84 | } else if err != nil { |
| 85 | return err |
| 86 | } |
| 87 | raw, err := readToolFrame(reader, maxToolFrame) |
| 88 | if err != nil { |
| 89 | return err |
| 90 | } |
| 91 | var q mcpRequest |
| 92 | if decode(raw, &q) != nil || q.JSONRPC != "2.0" { |
| 93 | return errInvalid |
| 94 | } |
| 95 | if _, err := conn.Write(append(raw, '\n')); err != nil { |
| 96 | return err |
| 97 | } |
| 98 | if len(q.ID) == 0 { |
| 99 | continue |
| 100 | } |
| 101 | reply, err := readToolFrame(replies, maxReplyFrame) |
| 102 | if err != nil { |
| 103 | return err |
| 104 | } |
| 105 | if _, err := output.Write(append(reply, '\n')); err != nil { |
| 106 | return err |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | func readToolFrame(r *bufio.Reader, limit int) ([]byte, error) { |
| 112 | raw, err := r.ReadSlice('\n') |
| 113 | if err != nil || len(raw) > limit { |
| 114 | return nil, errInvalid |
| 115 | } |
| 116 | return bytes.TrimSuffix(raw, []byte{'\n'}), nil |
| 117 | } |
| 118 | |
| 119 | // openNoLinks walks every component using directory-relative no-follow opens. |
| 120 | func openNoLinks(path string, flags int) (*os.File, error) { |
| 121 | if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| 122 | return nil, errInvalid |
| 123 | } |
| 124 | fd, err := unix.Open("/", unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| 125 | if err != nil { |
| 126 | return nil, errInvalid |
| 127 | } |
| 128 | parts := strings.Split(strings.TrimPrefix(path, "/"), "/") |
| 129 | for i, p := range parts { |
| 130 | f := unix.O_PATH | unix.O_DIRECTORY |
| 131 | if i == len(parts)-1 { |
| 132 | f = flags |
| 133 | } |
| 134 | next, e := unix.Openat(fd, p, f|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 135 | unix.Close(fd) |
| 136 | if e != nil { |
| 137 | return nil, errInvalid |
| 138 | } |
| 139 | fd = next |
| 140 | } |
| 141 | return os.NewFile(uintptr(fd), path), nil |
| 142 | } |
| 143 | func privateInfo(f *os.File, mode os.FileMode, dir bool) bool { |
| 144 | var st unix.Stat_t |
| 145 | if unix.Fstat(int(f.Fd()), &st) != nil || st.Uid != uint32(os.Getuid()) { |
| 146 | return false |
| 147 | } |
| 148 | info, err := f.Stat() |
| 149 | return err == nil && info.Mode().Perm() == mode && ((dir && info.IsDir()) || (!dir && info.Mode().IsRegular())) |
| 150 | } |
| 151 | func openPrivateDir(path string) (*os.File, error) { |
| 152 | f, err := openNoLinks(path, unix.O_RDONLY|unix.O_DIRECTORY) |
| 153 | if err != nil { |
| 154 | return nil, err |
| 155 | } |
| 156 | if !privateInfo(f, 0700, true) { |
| 157 | f.Close() |
| 158 | return nil, errInvalid |
| 159 | } |
| 160 | return f, nil |
| 161 | } |
| 162 | |