plugin: a plugin's requests to a host on the user's own network go direct, as magpie's own do (#1572, ggbdpq)
What changed: with a proxy set (magpie's, the environment's or the system's), the plugin host sent a plugin's requests for a host on the user's own network - a Remote magpie, an LLM relay on the NAS - through that proxy, which can't reach it (502 Bad Gateway) or resolve its name. Go's netproxy.Func leaves such a host direct since #982 (lan.go onLAN); host.js's proxyFor and its node:http2 sessions (#1035) were that rule's siblings without it. - host.js ports lan.go's rule: onLAN takes a private (10/8, 172.16/12, 192.168/16, fc00::/7), link-local, loopback or CGNAT (100.64/10) address, a .local name, or a name every address of which is one of those; looked up for 400 ms at most, kept a minute (256 names), a failed or slow lookup is "not on the network". It is asked only when the global proxy would be taken (after loopback, a provider's own proxy or "direct", and NO_PROXY), as Func asks it, so a user without a proxy pays no lookup and a provider's own proxy is still taken as is. IPv6 is compared on its bytes, so a v4-mapped address in hex form (::ffff:a00:1, how URL writes it) is judged as its IPv4 address. - http2.connect returns its session at once, so tunnel() now takes a promise of the proxy and connects when onLAN has answered: straight to the host for one on the user's network, through the CONNECT otherwise. Unlike the issue's patch, a LAN name that needs a lookup is covered on this path too. - The issue's patch was reviewed, not applied: its lanIP missed loopback and hex v4-mapped IPv6, it didn't strip a trailing dot, it never cleared its lookup timer, and it left HTTP/2 to LAN names proxied. New TestPluginLeavesTheUserNetworkDirect (real Bun, a proxy that keeps every target it is asked): a fetch to this computer's private address over http:// (absolute form) and https:// (CONNECT; a certificate for that address via NODE_EXTRA_CA_CERTS), to "localhost." (a name decided by what it resolves to), and an HTTP/2 session to the private address all reach the server directly; a public address (203.0.113.5) and a name that resolves nowhere (vendor.invalid) still go through the proxy. Run: the new test against the old host.js fails on all three fetches (proxy asked for each); with only the HTTP/2 check removed it fails on the session ("h2: proxyconnect tcp: 502 Bad Gateway"); with every host taken as LAN it fails on the public address and the vendor name. A bun check of lanIP over 24 addresses (both sides of every range) matched lan.go. go test ./internal/plugin ./internal/netproxy ok; full go test -tags nogui ./... ok in every package (the five whose build hit another session's go-build cache prune were rerun, all ok: ., agent, gateway, gui, library); gofmt -l clean; go vet -tags nogui internal/plugin on darwin, GOOS=linux and GOOS=windows clean. Not tried with a real NAS or Remote magpie behind a real proxy.
This commit is contained in:
@@ -108,7 +108,7 @@ For a plugin fix, publish the corrected community package and raise the owning m
|
||||
|
||||
Keep the migration, host, and upstream behavior separate when investigating failures. A plugin bug can require a community change; a host, provider-card, sign-in orchestration, or migration bug can require a magpie change even for moved users.
|
||||
|
||||
The host gets magpie's proxy only as `MAGPIE_*_PROXY` and applies it to each fetch itself. A program a plugin starts, such as the Grok plugin's `grok login`, gets it back as `HTTPS_PROXY`/`HTTP_PROXY` from the spawn wrapper in `host.js`, unless the plugin set one. A sign-in that works in the built-in and fails through the plugin may be a host difference like this one, not a plugin bug.
|
||||
The host gets magpie's proxy only as `MAGPIE_*_PROXY` and applies it to each fetch itself (`proxyFor`), and to each HTTP/2 session a plugin opens (`http2.connect`, `tunnel`, #1035). A host on the user's own network goes around that proxy as it does for magpie's own requests (`onLAN` in `host.js`, a port of `internal/netproxy/lan.go`'s: a private, link-local, loopback or CGNAT address, a `.local` name, or a name every address of which is one of those, looked up for 400 ms at most and kept a minute; #1572). A provider's own proxy is still taken as it is. The two rules are kept the same: a change to one is made in the other. A program a plugin starts, such as the Grok plugin's `grok login`, gets it back as `HTTPS_PROXY`/`HTTP_PROXY` from the spawn wrapper in `host.js`, unless the plugin set one. A sign-in that works in the built-in and fails through the plugin may be a host difference like this one, not a plugin bug.
|
||||
|
||||
Bun takes only http:// and https:// proxies. A SOCKS5 one, such as a Mac's system SOCKS proxy, is given to every bun magpie starts as a loopback HTTP proxy in front of it (`netproxy.Bridge`): to the host through `hostEnv`, and to `bun add`, `bun update` and `bun remove` through `bunCommand` (`netproxy.EnvForBun`). Before, an install with only a SOCKS system proxy failed as `UnsupportedProxyProtocol` (#1409). An agent CLI that bun installed is updated through the bridge too (`updateEnv` in `internal/agent/cliupdate.go`).
|
||||
|
||||
@@ -128,7 +128,7 @@ Gateway parity tests in [`plugin_parity_test.go`](../../internal/gateway/plugin_
|
||||
|
||||
[`plugin_checkin_test.go`](../../internal/provider/plugin_checkin_test.go) runs the fake plugin's `auth.checkin` (`FAKE_CHECKIN`) through the schedule: off, each outcome, no second press the same day, failures only after the retry window, the next day, cards and Settings, and the vendor check-in stepping aside. `plugin-checkin.test.cjs` covers the card row and the Settings tab.
|
||||
|
||||
[`plugin_cliproxy_test.go`](../../internal/plugin/plugin_cliproxy_test.go)'s `TestPluginHostTakesANewProxy` starts a real host without a proxy, sets one, and checks that a program the plugin starts gets it. `plugin-signed-out-account.test.cjs` covers a moved Grok account signed out while in use and as the agent's own, in Chromium and WebKit, en and zh, 420 and 1100 wide.
|
||||
[`plugin_cliproxy_test.go`](../../internal/plugin/plugin_cliproxy_test.go)'s `TestPluginHostTakesANewProxy` starts a real host without a proxy, sets one, and checks that a program the plugin starts gets it. [`plugin_lan_test.go`](../../internal/plugin/plugin_lan_test.go)'s `TestPluginLeavesTheUserNetworkDirect` checks with a real host that fetches (http:// and https://) and an HTTP/2 session to this computer's private address reach it directly with a proxy set, and that a public address and an unresolvable name still go through the proxy. `plugin-signed-out-account.test.cjs` covers a moved Grok account signed out while in use and as the agent's own, in Chromium and WebKit, en and zh, 420 and 1100 wide.
|
||||
|
||||
These tests cover two plugins on one provider id:
|
||||
|
||||
|
||||
@@ -15,7 +15,9 @@ import (
|
||||
// Gateway, and its model list never came). A proxy is for reaching
|
||||
// vendors; one elsewhere can't reach the user's network, and one on this
|
||||
// computer would only go there directly itself. A provider's own proxy
|
||||
// (With) is still taken as it is: that one was set for it.
|
||||
// (With) is still taken as it is: that one was set for it. The plugin
|
||||
// host applies the same rule to plugins' requests (onLAN in
|
||||
// internal/plugin/host.js, #1572): a change here is made there too.
|
||||
|
||||
// lanLookup resolves a name to its addresses; tests replace it.
|
||||
var lanLookup = func(ctx context.Context, host string) ([]net.IPAddr, error) {
|
||||
|
||||
+151
-48
@@ -26,6 +26,7 @@
|
||||
// plugin's getAuth, client.auth.set and loader see that account alone.
|
||||
|
||||
import { AsyncLocalStorage } from "node:async_hooks"
|
||||
import dns from "node:dns"
|
||||
import fs from "node:fs"
|
||||
import http2 from "node:http2"
|
||||
import net from "node:net"
|
||||
@@ -323,24 +324,103 @@ function loopback(host) {
|
||||
return host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127\./.test(host)
|
||||
}
|
||||
|
||||
// proxyFor is the proxy a fetch of input goes through, "" for none.
|
||||
function proxyFor(input) {
|
||||
// A host on the user's own network — another computer's magpie, an LLM
|
||||
// relay on the NAS — is reached directly, whatever proxy the host was
|
||||
// started with, as magpie's own requests reach it (netproxy.onLAN, lan.go,
|
||||
// #982, #1572): a proxy is for reaching vendors; one elsewhere can't reach
|
||||
// the user's network, and one here only goes there directly itself. A
|
||||
// provider's own proxy (via) is still taken as it is. The rule is lan.go's:
|
||||
// keep the two the same.
|
||||
|
||||
// lanWait is how long a name is looked up for before it is taken as not on
|
||||
// the network; lanKeep is how long what it resolved to is kept.
|
||||
const lanWait = 400
|
||||
const lanKeep = 60_000
|
||||
const lanSeen = new Map() // host → {lan: Promise<boolean>, at}
|
||||
|
||||
// ipBytes is the 16 bytes of the IPv6 address s (an IPv4 one as
|
||||
// ::ffff:a.b.c.d), null when s is no address.
|
||||
function ipBytes(s) {
|
||||
if (net.isIPv4(s)) return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, ...s.split(".").map(Number)]
|
||||
if (!net.isIPv6(s)) return null
|
||||
s = s.replace(/%.*$/, "")
|
||||
const v4 = s.match(/(\d+\.\d+\.\d+\.\d+)$/)
|
||||
if (v4) {
|
||||
const [a, b, c, d] = v4[1].split(".").map(Number)
|
||||
s = s.slice(0, -v4[1].length) + ((a << 8) | b).toString(16) + ":" + ((c << 8) | d).toString(16)
|
||||
}
|
||||
const [head, tail] = s.includes("::") ? s.split("::") : [s, null]
|
||||
const words = (x) => (x ? x.split(":").map((w) => parseInt(w, 16)) : [])
|
||||
const h = words(head)
|
||||
const t = words(tail)
|
||||
const all = tail === null ? h : [...h, ...Array(8 - h.length - t.length).fill(0), ...t]
|
||||
return all.flatMap((w) => [w >> 8, w & 0xff])
|
||||
}
|
||||
|
||||
// lanIP is netproxy.lanIP: a private (10/8, 172.16/12, 192.168/16,
|
||||
// fc00::/7), link-local (169.254/16, fe80::/10), loopback or carrier-grade
|
||||
// NAT (Tailscale's 100.64/10) address.
|
||||
function lanIP(s) {
|
||||
const b = ipBytes(s)
|
||||
if (!b) return false
|
||||
if (b.slice(0, 10).every((x) => x === 0) && b[10] === 0xff && b[11] === 0xff) {
|
||||
const [p, q] = b.slice(12)
|
||||
return p === 10 || (p === 172 && (q & 0xf0) === 16) || (p === 192 && q === 168) || (p === 169 && q === 254) || p === 127 || (p === 100 && (q & 0xc0) === 64)
|
||||
}
|
||||
return (b[0] & 0xfe) === 0xfc || (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) || b.every((x, i) => x === (i === 15 ? 1 : 0))
|
||||
}
|
||||
|
||||
// onLAN is netproxy.onLAN: whether host is on the user's own network — an
|
||||
// address lanIP takes, a .local name, or a name every address of which is
|
||||
// one of those. A name that doesn't resolve here (in lanWait) is not: the
|
||||
// proxy is what reaches it.
|
||||
function onLAN(host) {
|
||||
host = host.toLowerCase().replace(/\.$/, "")
|
||||
if (!host) return Promise.resolve(false)
|
||||
if (net.isIP(host)) return Promise.resolve(lanIP(host))
|
||||
if (host.endsWith(".local")) return Promise.resolve(true)
|
||||
const seen = lanSeen.get(host)
|
||||
if (seen && Date.now() - seen.at < lanKeep) return seen.lan
|
||||
let timer
|
||||
const lan = Promise.race([
|
||||
dns.promises.lookup(host, { all: true, verbatim: true }).then(
|
||||
(as) => as.length > 0 && as.every((a) => lanIP(a.address)),
|
||||
() => false,
|
||||
),
|
||||
new Promise((r) => (timer = setTimeout(() => r(false), lanWait))),
|
||||
]).finally(() => clearTimeout(timer))
|
||||
if (lanSeen.size >= 256) lanSeen.clear()
|
||||
lanSeen.set(host, { lan, at: Date.now() })
|
||||
return lan
|
||||
}
|
||||
|
||||
// proxyOf is the proxy a request to input goes through, "" for none, and
|
||||
// whether it is the global one, which a host on the user's own network
|
||||
// goes around (proxyFor).
|
||||
function proxyOf(input) {
|
||||
const u = hostOf(input)
|
||||
if (!u || loopback(u.host)) return ""
|
||||
if (!u || loopback(u.host)) return { p: "" }
|
||||
const own = via.getStore()
|
||||
if (own === "direct") return ""
|
||||
if (own) return own
|
||||
if (globalProxy.no.some((n) => n === "*" || u.host === n || u.host.endsWith("." + n))) return ""
|
||||
return u.protocol === "https:" ? globalProxy.https : u.protocol === "http:" ? globalProxy.http : ""
|
||||
if (own === "direct") return { p: "" }
|
||||
if (own) return { p: own }
|
||||
if (globalProxy.no.some((n) => n === "*" || u.host === n || u.host.endsWith("." + n))) return { p: "" }
|
||||
const p = u.protocol === "https:" ? globalProxy.https : u.protocol === "http:" ? globalProxy.http : ""
|
||||
return { p, global: !!p, host: u.host }
|
||||
}
|
||||
|
||||
// proxyFor is the proxy a fetch of input goes through, "" for none.
|
||||
async function proxyFor(input) {
|
||||
const { p, global, host } = proxyOf(input)
|
||||
return global && (await onLAN(host)) ? "" : p
|
||||
}
|
||||
|
||||
// reach is what a check's fetches came to: whether one got an answer, and
|
||||
// the first that got none
|
||||
const reach = new AsyncLocalStorage()
|
||||
|
||||
function sent(input, init) {
|
||||
async function sent(input, init) {
|
||||
if (init && "proxy" in init) return bunFetch(input, init)
|
||||
const p = proxyFor(input)
|
||||
const p = await proxyFor(input)
|
||||
if (!p) return bunFetch(input, init)
|
||||
return bunFetch(input, { ...init, proxy: p }).catch(async (e) => {
|
||||
if (e?.name === "AbortError" || init?.signal?.aborted) throw e
|
||||
@@ -448,11 +528,13 @@ http2.connect = function connect(authority, options, listener) {
|
||||
} catch {
|
||||
return h2connect.call(this, authority, options, listener)
|
||||
}
|
||||
const p = options?.createConnection ? "" : proxyFor(u.href)
|
||||
const { p, global } = options?.createConnection ? { p: "" } : proxyOf(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)
|
||||
// the session is returned now, and its connection made once it is known
|
||||
// whether host is on the user's own network (direct) or not (the proxy)
|
||||
const raw = tunnel(global ? onLAN(host).then((lan) => (lan ? "" : p)) : 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)
|
||||
@@ -463,18 +545,19 @@ http2.connect = function connect(authority, options, listener) {
|
||||
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))
|
||||
// tunnel is a connection to host:port through the HTTP proxy which names
|
||||
// (a proxy, or a promise of one), or straight to it when that is "" (a host
|
||||
// on the user's own network, onLAN). A SOCKS proxy 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(which, host, port) {
|
||||
const target = `${host.includes(":") ? `[${host}]` : host}:${port}`
|
||||
let ready = false
|
||||
let sock = null
|
||||
let ended = false
|
||||
let gone = 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) {
|
||||
@@ -482,44 +565,64 @@ function tunnel(p, host, port) {
|
||||
else queued.push([chunk, cb])
|
||||
},
|
||||
final(cb) {
|
||||
sock.end()
|
||||
if (ready) sock.end()
|
||||
else ended = true
|
||||
cb()
|
||||
},
|
||||
destroy(err, cb) {
|
||||
sock.destroy()
|
||||
gone = true
|
||||
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}`))
|
||||
}
|
||||
const open = () => {
|
||||
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)
|
||||
if (ended) sock.end()
|
||||
}
|
||||
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}`)))
|
||||
Promise.resolve(which).then((p) => {
|
||||
if (gone) return
|
||||
if (!p) {
|
||||
sock = net.connect({ host, port })
|
||||
sock.once("connect", open)
|
||||
sock.on("end", () => conn.push(null))
|
||||
sock.on("error", (e) => conn.destroy(e))
|
||||
return
|
||||
}
|
||||
const pu = new URL(p)
|
||||
const ph = pu.hostname.replace(/^\[|\]$/g, "")
|
||||
const pp = Number(pu.port || (pu.protocol === "https:" ? 443 : 80))
|
||||
sock = pu.protocol === "https:" ? tls.connect({ host: ph, port: pp, servername: net.isIP(ph) ? undefined : ph }) : net.connect({ host: ph, port: pp })
|
||||
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}`))
|
||||
}
|
||||
if (got.length > end + 4) conn.push(got.subarray(end + 4))
|
||||
open()
|
||||
}
|
||||
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}`)))
|
||||
}).catch((e) => conn.destroy(e))
|
||||
return conn
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// lanAddr is a private IPv4 address of this computer: one on the user's
|
||||
// own network, as a Remote magpie or a NAS is.
|
||||
func lanAddr(t *testing.T) net.IP {
|
||||
t.Helper()
|
||||
addrs, _ := net.InterfaceAddrs()
|
||||
for _, a := range addrs {
|
||||
if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil && n.IP.IsPrivate() {
|
||||
return n.IP
|
||||
}
|
||||
}
|
||||
t.Skip("no private IPv4 address on this computer")
|
||||
return nil
|
||||
}
|
||||
|
||||
// askedProxy is an HTTP proxy that keeps the target of every request it
|
||||
// is asked: an absolute-form one (http://) is answered "proxy <target>",
|
||||
// a CONNECT (https://, HTTP/2) is turned away with 502.
|
||||
func askedProxy(t *testing.T) (string, func() []string) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { ln.Close() })
|
||||
var mu sync.Mutex
|
||||
var asked []string
|
||||
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 {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
asked = append(asked, f[1])
|
||||
mu.Unlock()
|
||||
if f[0] == "CONNECT" {
|
||||
fmt.Fprint(c, "HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")
|
||||
return
|
||||
}
|
||||
body := "proxy " + f[1]
|
||||
fmt.Fprintf(c, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(body), body)
|
||||
}(c)
|
||||
}
|
||||
}()
|
||||
return "http://" + ln.Addr().String(), func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return slices.Clone(asked)
|
||||
}
|
||||
}
|
||||
|
||||
// certFor is a certificate for ip, and the PEM of it a client trusts.
|
||||
func certFor(t *testing.T, ip net.IP) (tls.Certificate, []byte) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: ip.String()},
|
||||
IPAddresses: []net.IP{ip},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: true,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
|
||||
}
|
||||
|
||||
// #1572: a plugin's requests to a host on the user's own network — a
|
||||
// Remote magpie, an LLM relay on the NAS — went through the proxy magpie
|
||||
// gave the host, which can't reach it (502 Bad Gateway), while magpie's
|
||||
// own requests leave such a host direct (netproxy.onLAN, #982). The
|
||||
// plugin's fetches, http:// (sent to the proxy in absolute form) and
|
||||
// https:// (a CONNECT), and its HTTP/2 sessions now go direct too; a
|
||||
// vendor's still go through the proxy.
|
||||
func TestPluginLeavesTheUserNetworkDirect(t *testing.T) {
|
||||
ip := lanAddr(t)
|
||||
sandbox(t)
|
||||
for _, k := range []string{"NO_PROXY", "no_proxy", "ALL_PROXY", "all_proxy", "https_proxy", "http_proxy", "FAKE_H2"} {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
proxy, asked := askedProxy(t)
|
||||
t.Setenv("HTTPS_PROXY", proxy)
|
||||
t.Setenv("HTTP_PROXY", proxy)
|
||||
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "lan %s %s", r.Proto, r.URL.Path)
|
||||
})
|
||||
listen := func() net.Listener {
|
||||
ln, err := net.Listen("tcp", net.JoinHostPort(ip.String(), "0"))
|
||||
if err != nil {
|
||||
t.Skip("can't listen on", ip, err)
|
||||
}
|
||||
return ln
|
||||
}
|
||||
plain := httptest.NewUnstartedServer(handler)
|
||||
plain.Listener.Close()
|
||||
plain.Listener = listen()
|
||||
plain.Start()
|
||||
defer plain.Close()
|
||||
cert, caPEM := certFor(t, ip)
|
||||
secure := httptest.NewUnstartedServer(handler)
|
||||
secure.Listener.Close()
|
||||
secure.Listener = listen()
|
||||
secure.EnableHTTP2 = true
|
||||
secure.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||
secure.StartTLS()
|
||||
defer secure.Close()
|
||||
// a name the computer resolves to itself: what decides is what it
|
||||
// resolves to, as for a NAS's name on the router's DNS
|
||||
local := httptest.NewServer(handler)
|
||||
defer local.Close()
|
||||
ca := filepath.Join(t.TempDir(), "lan-ca.pem")
|
||||
if err := os.WriteFile(ca, caPEM, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("NODE_EXTRA_CA_CERTS", ca)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*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(url string) (int, string) {
|
||||
fctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
res, err := Fetch(fctx, FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
|
||||
URL: url, Method: "POST", Body: []byte(`{}`)})
|
||||
if err != nil {
|
||||
return 0, err.Error()
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res.StatusCode, string(b)
|
||||
}
|
||||
proxied := func(host string) bool {
|
||||
for _, a := range asked() {
|
||||
if strings.Contains(a, host) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
_, port, _ := net.SplitHostPort(local.Listener.Addr().String())
|
||||
for _, url := range []string{
|
||||
plain.URL + "/v1/chat/completions",
|
||||
secure.URL + "/v1/chat/completions",
|
||||
"http://localhost.:" + port + "/v1/chat/completions",
|
||||
} {
|
||||
code, b := fetch(url)
|
||||
if code != 200 || b != "lan HTTP/1.1 /v1/chat/completions" {
|
||||
t.Errorf("%s: %d %q, want it reached directly (the proxy was asked for %v)", url, code, b, asked())
|
||||
}
|
||||
}
|
||||
if proxied(ip.String()) || proxied("localhost.") {
|
||||
t.Fatalf("the proxy was asked for a host on the user's own network: %v", asked())
|
||||
}
|
||||
|
||||
// a vendor still goes through it: an address of the internet in
|
||||
// absolute form, and a name that resolves nowhere here as a CONNECT
|
||||
if code, b := fetch("http://203.0.113.5:9/v1/chat/completions"); code != 200 || b != "proxy http://203.0.113.5:9/v1/chat/completions" {
|
||||
t.Errorf("a public address: %d %q, want it through the proxy", code, b)
|
||||
}
|
||||
fetch("https://vendor.invalid/v1/chat/completions")
|
||||
if !slices.Contains(asked(), "vendor.invalid:443") {
|
||||
t.Errorf("a vendor's name: the proxy was asked for %v, want vendor.invalid:443", asked())
|
||||
}
|
||||
|
||||
// a plugin's own HTTP/2 session (Cursor's chats), as #1035 made it take
|
||||
// the proxy
|
||||
t.Setenv("FAKE_H2", secure.URL)
|
||||
Restart()
|
||||
if code, b := fetch(secure.URL + "/v1/chat/completions"); code != 200 || b != "lan HTTP/2.0 /v1/chat/completions" {
|
||||
t.Errorf("an HTTP/2 session to %s: %d %q, want it reached directly (the proxy was asked for %v)", secure.URL, code, b, asked())
|
||||
}
|
||||
if proxied(ip.String()) {
|
||||
t.Fatalf("the proxy was asked for a host on the user's own network: %v", asked())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user