From 51d2cf88ea92ee57d237572d2c7b3675b2f4c429 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 6 Oct 2026 22:16:09 +0800 Subject: [PATCH] =?UTF-8?q?plugin=20host:=20a=20plugin's=20node:http2=20co?= =?UTF-8?q?nnection=20goes=20through=20magpie's=20proxy=20like=20its=20fet?= =?UTF-8?q?ch=20does=20(#1035,=20cataglyphis:=20Cursor=20opus-5-5=20high?= =?UTF-8?q?=20ends=20after=20~148s=20with=20"Cursor:=20502=20Bad=20Gateway?= =?UTF-8?q?"=20cursor=5Ferror)=20=E2=80=94=20the=20Cursor=20plugin=20runs?= =?UTF-8?q?=20agent.v1.AgentService/Run=20over=20node:http2,=20which=20Bun?= =?UTF-8?q?=20connects=20directly=20and=20ignores=20the=20proxy=20that=20h?= =?UTF-8?q?ost.js=20gives=20every=20fetch;=20the=20built-in=20sent=20the?= =?UTF-8?q?=20same=20request=20through=20s.client,=20so=20a=20user=20who?= =?UTF-8?q?=20needs=20magpie's=20proxy=20(setting,=20env=20or=20the=20syst?= =?UTF-8?q?em's)=20to=20reach=20Cursor=20had=20their=20sign-in,=20models?= =?UTF-8?q?=20and=20usage=20proxied=20but=20every=20Run=20went=20out=20dir?= =?UTF-8?q?ectly.=20host.js=20now=20wraps=20http2.connect:=20for=20a=20URL?= =?UTF-8?q?=20proxyFor=20gives=20a=20proxy=20to=20(provider/account=20via,?= =?UTF-8?q?=20global,=20SOCKS=20bridged),=20it=20opens=20an=20HTTP=20CONNE?= =?UTF-8?q?CT=20tunnel=20(Proxy-Authorization=20from=20the=20URL)=20and=20?= =?UTF-8?q?runs=20TLS=20with=20ALPN=20h2=20over=20it;=20"direct",=20a=20ca?= =?UTF-8?q?ller's=20own=20createConnection=20and=20unproxied=20URLs=20keep?= =?UTF-8?q?=20Bun's=20connect;=20a=20tunnel=20that=20fails=20ends=20the=20?= =?UTF-8?q?session=20with=20"proxyconnect=20tcp:=20=E2=80=A6".=20TestPlugi?= =?UTF-8?q?nHTTP2TakesTheProxy=20(an=20HTTP/2=20vendor=20at=20an=20unresol?= =?UTF-8?q?vable=20host=20reached=20only=20through=20a=20CONNECT=20proxy;?= =?UTF-8?q?=20direct=20and=20a=20dead=20proxy=20fail=20with=20the=20reason?= =?UTF-8?q?)=20fails=20without=20the=20change=20("h2:=20getaddrinfo=20ENOT?= =?UTF-8?q?FOUND=20h2vendor.invalid";=20it=20carried=200)=20and=20passes?= =?UTF-8?q?=20-race=20-count=3D10.=20With=20the=20owner's=20Cursor=20accou?= =?UTF-8?q?nt=20in=20a=20sandbox=20HOME=20and=20a=20logging=20proxy=20set,?= =?UTF-8?q?=20Claude=20Code's=20captured=20request=20on=20cursor/claude-op?= =?UTF-8?q?us-5-5=20high:=20before,=20the=20proxy=20saw=20api2.cursor.sh?= =?UTF-8?q?=20only;=20after,=20it=20also=20sees=20agentn.global.api5.curso?= =?UTF-8?q?r.sh=20and=20the=20reply=20streams.=20The=20reporter's=20502=20?= =?UTF-8?q?wasn't=20reproduced=20here=20(direct=20runs=20answer=20in=204?= =?UTF-8?q?=E2=80=9320s).=20go=20test=20-race=20./internal/plugin,=20the?= =?UTF-8?q?=20gateway/provider=20Plugin|Proxy|Cursor=20tests,=20gofmt=20an?= =?UTF-8?q?d=20vet=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/plugin/host.js | 92 +++++++++++++++++++ internal/plugin/plugin_h2proxy_test.go | 121 +++++++++++++++++++++++++ internal/plugin/testdata/fake/index.js | 23 +++++ 3 files changed, 236 insertions(+) create mode 100644 internal/plugin/plugin_h2proxy_test.go diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 4fe304df2..ad1a0bd06 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -27,9 +27,11 @@ import { AsyncLocalStorage } from "node:async_hooks" import fs from "node:fs" +import http2 from "node:http2" import net from "node:net" import path from "node:path" import readline from "node:readline" +import { Duplex } from "node:stream" import tls from "node:tls" import { pathToFileURL } from "node:url" @@ -422,6 +424,96 @@ globalThis.fetch = Object.assign(function fetch(input, init) { ) }, bunFetch) +// An HTTP/2 session a plugin opens itself goes through the proxy its +// fetches take, as a built-in's requests on Go's transport did. Cursor's +// plugin runs agent.v1.AgentService/Run on node:http2, which Bun connects +// directly, *_PROXY or not: where Cursor is reached only through magpie's +// proxy (the system's, or one set in magpie), its sign-in, models and +// usage came through and every chat went out without it (#1035). +const h2connect = http2.connect +http2.connect = function connect(authority, options, listener) { + if (typeof options === "function") [listener, options] = [options, undefined] + let u + try { + u = typeof authority === "string" ? new URL(authority) : authority instanceof URL ? authority : new URL(`${authority.protocol ?? "https:"}//${authority.host ?? authority.hostname}`) + } catch { + return h2connect.call(this, authority, options, listener) + } + const p = options?.createConnection ? "" : proxyFor(u.href) + if (!p) return h2connect.call(this, authority, options, listener) + const host = u.hostname.replace(/^\[|\]$/g, "") + const port = Number(u.port || (u.protocol === "http:" ? 80 : 443)) + const raw = tunnel(p, host, port) + const createConnection = () => + u.protocol === "http:" ? raw : tls.connect({ ...options, socket: raw, servername: options?.servername || (net.isIP(host) ? undefined : host), ALPNProtocols: ["h2"] }) + const session = h2connect.call(this, authority, { ...options, createConnection }, listener) + // the tunnel's failure is the session's: Bun's TLS over a stream leaves + // the stream's errors unheard (one unheard ends the host), and says a + // tunnel that never came as "h2 is not supported" + raw.on("error", (e) => session.destroy(e)) + return session +} + +// tunnel is a connection to host:port through the HTTP proxy p (a SOCKS +// one is handed to the host as an HTTP bridge to it, netproxy.ForBun): its +// CONNECT is asked first, and what is written waits for the tunnel. A proxy +// that turns it away fails it in Go's words ("proxyconnect …"). +function tunnel(p, host, port) { + const pu = new URL(p) + const ph = pu.hostname.replace(/^\[|\]$/g, "") + const pp = Number(pu.port || (pu.protocol === "https:" ? 443 : 80)) + const target = `${host.includes(":") ? `[${host}]` : host}:${port}` + let ready = false + const queued = [] + const sock = pu.protocol === "https:" ? tls.connect({ host: ph, port: pp, servername: net.isIP(ph) ? undefined : ph }) : net.connect({ host: ph, port: pp }) + const conn = new Duplex({ + read() {}, + write(chunk, enc, cb) { + if (ready) sock.write(chunk, cb) + else queued.push([chunk, cb]) + }, + final(cb) { + sock.end() + cb() + }, + destroy(err, cb) { + sock.destroy() + cb(err) + }, + }) + sock.once(pu.protocol === "https:" ? "secureConnect" : "connect", () => { + let req = `CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n` + if (pu.username) { + const cred = `${decodeURIComponent(pu.username)}:${decodeURIComponent(pu.password)}` + req += `Proxy-Authorization: Basic ${Buffer.from(cred).toString("base64")}\r\n` + } + sock.write(req + "\r\n") + }) + let got = Buffer.alloc(0) + const head = (chunk) => { + got = Buffer.concat([got, chunk]) + const end = got.indexOf("\r\n\r\n") + if (end < 0) { + if (got.length > 8192) conn.destroy(new Error(`proxyconnect tcp: ${ph}:${pp} answered CONNECT with no HTTP`)) + return + } + sock.off("data", head) + const status = got.subarray(0, got.indexOf("\r\n")).toString("latin1").replace(/^HTTP\/\d(\.\d)?\s+/, "") + if (!/^2\d\d/.test(status)) { + const body = got.subarray(end + 4, end + 304).toString("utf8").trim() + return conn.destroy(new Error(`proxyconnect tcp: ${body ? `${status}: ${body}` : status}`)) + } + ready = true + if (got.length > end + 4) conn.push(got.subarray(end + 4)) + sock.on("data", (d) => conn.push(d)) + for (const [c, cb] of queued.splice(0)) sock.write(c, cb) + } + sock.on("data", head) + sock.on("end", () => conn.push(null)) + sock.on("error", (e) => conn.destroy(ready ? e : new Error(`proxyconnect tcp: dial tcp ${ph}:${pp}: ${e?.message || e?.code || e}`))) + return conn +} + // ---- auth.json --------------------------------------------------------------- function readAuth() { diff --git a/internal/plugin/plugin_h2proxy_test.go b/internal/plugin/plugin_h2proxy_test.go new file mode 100644 index 000000000..0cd65afae --- /dev/null +++ b/internal/plugin/plugin_h2proxy_test.go @@ -0,0 +1,121 @@ +package plugin + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/netproxy" +) + +// connectTo is an HTTP proxy that tunnels every CONNECT to addr, whatever +// host it is asked for, counting them and keeping the last host asked. +func connectTo(t *testing.T, addr string) (string, *atomic.Int32, *atomic.Value) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + var n atomic.Int32 + var asked atomic.Value + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + var head []byte + b := make([]byte, 1) + for !strings.HasSuffix(string(head), "\r\n\r\n") { + if _, err := c.Read(b); err != nil { + return + } + head = append(head, b[0]) + } + f := strings.Fields(string(head)) + if len(f) < 2 || f[0] != "CONNECT" { + fmt.Fprint(c, "HTTP/1.1 405 Method Not Allowed\r\n\r\n") + return + } + asked.Store(f[1]) + up, err := net.Dial("tcp", addr) + if err != nil { + fmt.Fprint(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n") + return + } + defer up.Close() + n.Add(1) + fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n\r\n") + go io.Copy(up, c) + io.Copy(c, up) + }(c) + } + }() + return "http://" + ln.Addr().String(), &n, &asked +} + +// #1035: Cursor's plugin runs its chats on node:http2, which Bun connects +// directly whatever the proxy: where Cursor is reached only through +// magpie's proxy, the plugin's fetches (sign-in, models, usage) came +// through it and its chats didn't. A session a plugin opens goes through +// the proxy its fetches take, as the built-in's requests did; one for a +// provider set to "direct" goes through none. +func TestPluginHTTP2TakesTheProxy(t *testing.T) { + sandbox(t) + vendor := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "vendor %s %s", r.Proto, r.URL.Path) + })) + vendor.EnableHTTP2 = true + vendor.StartTLS() + defer vendor.Close() + proxy, carried, asked := connectTo(t, strings.TrimPrefix(vendor.URL, "https://")) + // a host that resolves nowhere: reached only through the proxy + t.Setenv("FAKE_H2", "https://h2vendor.invalid:8443") + t.Setenv("FAKE_BASE", "https://h2vendor.invalid:8443/v1") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil { + t.Fatal(err) + } + fetch := func(proxy string) (int, string) { + res, err := Fetch(netproxy.With(ctx, proxy), FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible", + URL: "https://h2vendor.invalid:8443/v1/chat/completions", Method: "POST", Body: []byte(`{}`)}) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + return res.StatusCode, string(b) + } + if code, b := fetch(proxy); code != 200 || b != "vendor HTTP/2.0 /v1/chat/completions" || carried.Load() != 1 { + t.Fatalf("an HTTP/2 session through the proxy: %d %q; it carried %d", code, b, carried.Load()) + } + if got := asked.Load(); got != "h2vendor.invalid:8443" { + t.Fatalf("the proxy was asked for %v, want h2vendor.invalid:8443", got) + } + if code, b := fetch("direct"); code != 502 || carried.Load() != 1 { + t.Fatalf("a provider set to direct: %d %q; the proxy carried %d, want it untouched", code, b, carried.Load()) + } + dead := "http://" + closedPort(t) + if code, b := fetch(dead); code != 502 || !strings.Contains(b, "proxyconnect tcp: dial tcp 127.0.0.1:") { + t.Fatalf("through a proxy that is down: %d %q, want it said as Go's transport says it", code, b) + } +} diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 39e35b46d..a04166cf4 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -10,6 +10,26 @@ function fakeWho(team) { return uid ? { accountId: name + "@fake", uid } : { accountId: name + "@fake" } } +// h2 POSTs path on an HTTP/2 session to origin, a test server's +// certificate taken, and answers with what it said; one that fails is a +// 502 saying why. +async function h2(origin, path) { + const http2 = (await import("node:http2")).default + return new Promise((resolve) => { + const s = http2.connect(origin, { rejectUnauthorized: false }) + const fail = (e) => (s.destroy(), resolve(new Response("h2: " + (e?.message || e?.code || e), { status: 502 }))) + s.on("error", fail) + const req = s.request({ ":method": "POST", ":path": path }) + req.on("error", fail) + let status = 0 + const body = [] + req.on("response", (h) => (status = h[":status"])) + req.on("data", (c) => body.push(c)) + req.on("end", () => (s.close(), resolve(new Response(Buffer.concat(body), { status })))) + req.end() + }) +} + export const FakePlugin = async ({ client }) => ({ config: async (cfg) => { cfg.provider = cfg.provider ?? {} @@ -76,6 +96,9 @@ export const FakePlugin = async ({ client }) => ({ h.set("authorization", "Bearer " + (a.type === "oauth" ? a.access : a.key)) h.set("x-models", Object.keys(provider.models).sort().join(",")) h.set("x-body-type", typeof init.body) + // $FAKE_H2: the request goes on node:http2 to that origin, as + // Cursor's plugin runs its chats + if (process.env.FAKE_H2) return h2(process.env.FAKE_H2, new URL(url).pathname) return fetch(url, { ...init, headers: h }) }, }),