Files
magpie/internal/netproxy/netproxy_test.go
T
appointatandClaude Opus 5.5 abdc4b113d netproxy, provider, gateway: every request to the ChatGPT backend goes over HTTP/1.1, magpie's own too, not only the gateway's turns (#1700)
f6e1e98e put the gateway's turns to chatgpt.com on HTTP/1.1 through a
wrapper on the gateway's client. magpie's own requests there go through
http.DefaultClient and still spoke HTTP/2: the models list
(codexModels), the warm-up's POST to /backend-api/codex/responses
(warmCodex), the allowance (codexWindows via accountJSON), the reset
credits (codexResets) and spending one (consumeCodexReset). #1700's
reporter, on 0.1.1164, had Codex's /responses fail with PROTOCOL_ERROR
through a local proxy until GODEBUG=http2client=0, set by editing the
app bundle.

The rule now lives where every magpie Go client goes through.
netproxy.Dispatch sends a request netproxy.HTTP1 names through a clone
of its transport kept for HTTP/1.1, beside a provider's own proxy if
any, and the provider package sets HTTP1 to codexBackend (CodexBase's
host). The clone's TLS hello offers no ALPN, as codex-cli's: a transport
that has spoken HTTP/2 carries h2 in its TLS config, which a clone
copies, and a server that took it would be sent HTTP/1.1 on an HTTP/2
connection. The gateway's codexHTTP1 wrapper is folded into this; its
transport file is now upstream_transport.go. Every other vendor is still
offered HTTP/2, and GODEBUG=http2client=0 still turns HTTP/2 off for all.

What was run (Go 1.26.8, darwin/arm64, a sandbox HOME):
- TestCodexBackendOwnRequestsOverHTTP1 (provider): http.DefaultClient
  as netproxy.Install leaves it, a TLS server offering HTTP/2, the five
  requests directly, through Settings' proxy and through an account's
  own CONNECT proxy. On origin/main 6c1c0a74 it fails: all five
  "HTTP/2.0 (h2 offered)" each way. Another vendor's accountJSON read
  stays HTTP/2.0.
- TestDispatchHTTP1 (netproxy): after the transport has spoken HTTP/2
  to the server, a named request arrives HTTP/1.1 with no h2 offered,
  with a proxy choice too. Without the NextProtos reset it fails with
  "malformed HTTP response"; with HTTP1 ignored, with "HTTP/2.0".
- With the provider's hook off, the gateway's TestCodexBackendOverHTTP1
  fails too ("asked over HTTP/2.0, not HTTP/1.1"). TestAccountProxy,
  which stubs http.DefaultClient with a Dispatch of its own, passes; a
  separate Codex client in provider, tried first, failed it.
- go test -race -count=20: ./internal/netproxy TestDispatchHTTP1 and
  TestWith, ./internal/provider TestCodex* (this one included),
  ./internal/gateway TestCodexBackendOverHTTP1 and TestAccountProxy.
  gofmt -l; go vet (darwin, GOOS=linux -tags nogui, GOOS=windows); go
  build (the same three); go test -tags nogui ./... (49 packages) pass.
- Real use, behind Clash on a Mac: Codex's own sign-in copied into a
  sandbox HOME (days left on the token, nothing refreshed), and a
  CONNECT proxy in front of Clash logging each TLS hello's ALPN.
  origin/main: `magpie provider models codex` and one request at the
  gateway's start offered h2 to chatgpt.com, the turn none. This
  branch: no hello to chatgpt.com offered any, models.dev still h2.
  #1700's minimal request on codex/gpt-6-astra answered 200 with
  MAGPIE_CODEX_OK on both.

Not reproduced: PROTOCOL_ERROR itself; chatgpt.com answered HTTP/2 on
this Mac, so whether HTTP/1.1 is what the reporter's path needs is for
their use to say. The warm-up and spending a reset weren't sent for
real.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XSjhwVsPdGd6QUTrq4KvE4
2026-10-13 06:18:27 +08:00

275 lines
9.9 KiB
Go

package netproxy
import (
"context"
"crypto/tls"
"crypto/x509"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
func TestParseScutil(t *testing.T) {
out := `<dictionary> {
ExceptionsList : <array> {
0 : 127.0.0.1
1 : *.local
}
HTTPEnable : 1
HTTPPort : 7890
HTTPProxy : 127.0.0.1
HTTPSEnable : 1
HTTPSPort : 7891
HTTPSProxy : 127.0.0.1
SOCKSEnable : 1
SOCKSPort : 7892
SOCKSProxy : 127.0.0.1
}`
p := parseScutil(out)
if p.URL != "http://127.0.0.1:7891" || len(p.Bypass) != 2 || p.Bypass[1] != "*.local" {
t.Fatalf("%+v", p)
}
// each entry alone, for Codex's reqwest, which takes the HTTP one for
// an http:// URL and never the HTTPS or SOCKS one
if p.HTTP != "http://127.0.0.1:7890" || p.SOCKS != "socks5://127.0.0.1:7892" {
t.Fatalf("entries: %+v", p)
}
if p := parseScutil("<dictionary> {\n SOCKSEnable : 1\n SOCKSPort : 1080\n SOCKSProxy : 10.0.0.2\n}"); p.URL != "socks5://10.0.0.2:1080" || p.HTTP != "" || p.SOCKS != p.URL {
t.Fatalf("socks: %+v", p)
}
if p := parseScutil("<dictionary> {\n HTTPSEnable : 1\n HTTPSPort : 7890\n HTTPSProxy : 127.0.0.1\n}"); p.URL != "http://127.0.0.1:7890" || p.HTTP != "" {
t.Fatalf("https only: %+v", p)
}
if p := parseScutil("<dictionary> {\n HTTPEnable : 0\n HTTPProxy : x\n}"); p.URL != "" {
t.Fatalf("off: %+v", p)
}
}
func TestParseWindows(t *testing.T) {
for server, want := range map[string]string{
"127.0.0.1:7890": "http://127.0.0.1:7890",
"http=127.0.0.1:1;https=127.0.0.1:2": "http://127.0.0.1:2",
"socks=127.0.0.1:1080": "socks5://127.0.0.1:1080",
"": "",
} {
if got := parseWindows(server, "").URL; got != want {
t.Errorf("%q: %q, want %q", server, got, want)
}
}
// reqwest reads ProxyServer as one address: a list per protocol isn't one
if p := parseWindows("127.0.0.1:7890", ""); p.HTTP != "http://127.0.0.1:7890" {
t.Fatalf("one for all: %+v", p)
}
if p := parseWindows("http=127.0.0.1:1;https=127.0.0.1:2;socks=127.0.0.1:3", ""); p.HTTP != "" || p.SOCKS != "socks5://127.0.0.1:3" {
t.Fatalf("per protocol: %+v", p)
}
p := parseWindows("127.0.0.1:7890", "*.corp;<local>")
if !bypassed("git.corp", p.Bypass) || !bypassed("intranet", p.Bypass) || bypassed("chatgpt.com", p.Bypass) {
t.Fatalf("bypass: %+v", p.Bypass)
}
}
func TestFor(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} {
t.Setenv(k, "")
}
sysCache.at, sysCache.p = farFuture, Proxy{URL: "http://127.0.0.1:7890", Bypass: []string{"*.corp"}}
t.Cleanup(func() { sysCache.at = zero })
u, _ := url.Parse("https://chatgpt.com/backend-api/codex/responses")
if p, _ := For(u); p == nil || p.String() != "http://127.0.0.1:7890" {
t.Fatalf("system: %v", p)
}
corp, _ := url.Parse("https://git.corp/x")
if p, _ := For(corp); p != nil {
t.Fatalf("bypass: %v", p)
}
local := &http.Request{URL: &url.URL{Scheme: "http", Host: "127.0.0.1:3425"}}
if p, _ := Func(local); p != nil {
t.Fatalf("loopback: %v", p)
}
// magpie's own setting wins; "direct" turns it off
settings.Save(settings.Settings{Proxy: "socks5://127.0.0.1:1080"})
if p, _ := For(u); p == nil || p.String() != "socks5://127.0.0.1:1080" {
t.Fatalf("setting: %v", p)
}
settings.Save(settings.Settings{Proxy: "direct"})
if p, _ := For(u); p != nil {
t.Fatalf("direct: %v", p)
}
if err := settings.Save(settings.Settings{Proxy: "ftp://x"}); err == nil {
t.Fatal("ftp proxy accepted")
}
if settings.Save(settings.Settings{Proxy: "127.0.0.1:7890"}) != nil || filepath.Dir(settings.Path()) != filepath.Join(dir, "magpie") {
t.Fatal("host:port proxy refused")
}
}
func TestEnv(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
sysCache.at, sysCache.p = farFuture, Proxy{URL: "http://127.0.0.1:7890", Bypass: []string{"*.corp", "<local>"}}
t.Cleanup(func() { sysCache.at = zero })
get := func(env []string, k string) string {
v := ""
for _, e := range env {
if key, val, _ := strings.Cut(e, "="); key == k {
v = val
}
}
return v
}
// the system's proxy, where the environment names none
env := Env([]string{"PATH=/bin", "HOME=/h"})
if get(env, "HTTPS_PROXY") != "http://127.0.0.1:7890" || get(env, "all_proxy") != "http://127.0.0.1:7890" ||
get(env, "NO_PROXY") != "localhost,127.0.0.1,::1,.corp" || get(env, "PATH") != "/bin" {
t.Fatalf("system: %v", env)
}
// one the environment names is kept
env = Env([]string{"https_proxy=http://10.0.0.1:1", "NO_PROXY=x"})
if len(env) != 2 || get(env, "https_proxy") != "http://10.0.0.1:1" {
t.Fatalf("environment: %v", env)
}
// magpie's own replaces the environment's
settings.Save(settings.Settings{Proxy: "127.0.0.1:6152"})
env = Env([]string{"HTTPS_PROXY=http://10.0.0.1:1", "PATH=/bin"})
if get(env, "HTTPS_PROXY") != "http://127.0.0.1:6152" || get(env, "http_proxy") != "http://127.0.0.1:6152" ||
get(env, "NO_PROXY") != "localhost,127.0.0.1,::1" || len(env) != 9 {
t.Fatalf("setting: %v", env)
}
// and "direct" leaves none
settings.Save(settings.Settings{Proxy: "direct"})
if env = Env([]string{"HTTPS_PROXY=http://10.0.0.1:1", "PATH=/bin"}); len(env) != 1 {
t.Fatalf("direct: %v", env)
}
}
var farFuture = time.Now().Add(time.Hour)
var zero time.Time
// A provider's own proxy (#237) wins over the global one, "direct" over
// both, and each proxy is given one transport of its own, kept.
func TestWith(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
settings.Save(settings.Settings{Proxy: "127.0.0.1:6152"})
u := &url.URL{Scheme: "https", Host: "api.openai.com"}
req := func(choice string) *http.Request {
return (&http.Request{URL: u}).WithContext(With(context.Background(), choice))
}
if p, _ := Func(req("")); p == nil || p.String() != "http://127.0.0.1:6152" {
t.Fatalf("follow: %v", p)
}
if p, _ := Func(req("socks5://127.0.0.1:1080")); p == nil || p.String() != "socks5://127.0.0.1:1080" {
t.Fatalf("own: %v", p)
}
if p, _ := Func(req("direct")); p != nil {
t.Fatalf("direct: %v", p)
}
// a request for a provider that follows the global proxy, made while
// serving one set to its own or to none, follows the global one
// (#1522: Codex's search inside a turn of a provider set to direct)
for _, outer := range []string{"direct", "socks5://127.0.0.1:1080"} {
inner := (&http.Request{URL: u}).WithContext(With(With(context.Background(), outer), ""))
if p, _ := Func(inner); p == nil || p.String() != "http://127.0.0.1:6152" {
t.Fatalf("follow inside %s: %v", outer, p)
}
if c := Choice(inner.Context()); c != "" {
t.Fatalf("follow inside %s: choice %q", outer, c)
}
}
local := (&http.Request{URL: &url.URL{Scheme: "http", Host: "127.0.0.1:3425"}}).WithContext(With(context.Background(), "127.0.0.1:1"))
if p, _ := Func(local); p != nil {
t.Fatalf("loopback: %v", p)
}
d := Dispatch(&http.Transport{Proxy: Func}).(*dispatch)
a, b := d.transport(route{choice: "127.0.0.1:1"}), d.transport(route{choice: "direct"})
if a == b || d.transport(route{choice: "127.0.0.1:1"}) != a || len(d.own) != 2 {
t.Fatalf("transports: %d kept", len(d.own))
}
if p, _ := a.Proxy(req("")); p == nil || p.Host != "127.0.0.1:1" {
t.Fatalf("own transport: %v", p)
}
if p, _ := b.Proxy(req("")); p != nil {
t.Fatalf("direct transport: %v", p)
}
get := func(env []string, k string) string {
for _, e := range env {
if key, val, _ := strings.Cut(e, "="); key == k {
return val
}
}
return ""
}
if env := EnvWith("socks5://127.0.0.1:1080", []string{"PATH=/bin"}); get(env, "HTTPS_PROXY") != "socks5://127.0.0.1:1080" {
t.Fatalf("own env: %v", env)
}
if env := EnvWith("direct", []string{"HTTPS_PROXY=http://x:1", "PATH=/bin"}); len(env) != 1 {
t.Fatalf("direct env: %v", env)
}
if env := EnvWith("", []string{"PATH=/bin"}); get(env, "HTTPS_PROXY") != "http://127.0.0.1:6152" {
t.Fatalf("follow env: %v", env)
}
}
// A request HTTP1 names goes over HTTP/1.1, its TLS hello offering no h2,
// though its transport has already spoken HTTP/2 to that server (which
// leaves h2 in the TLS config a clone copies: a server that took it would
// be sent HTTP/1.1 on an HTTP/2 connection), and with a provider's own
// proxy too. Every other request still gets HTTP/2.
func TestDispatchHTTP1(t *testing.T) {
var mu sync.Mutex
offered := map[string]bool{} // the client's address → its hello offered h2
var got []string
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
got = append(got, r.URL.Path+" "+r.Proto+map[bool]string{true: " (h2 offered)"}[offered[r.RemoteAddr]])
}))
srv.EnableHTTP2 = true
srv.TLS = &tls.Config{GetConfigForClient: func(h *tls.ClientHelloInfo) (*tls.Config, error) {
mu.Lock()
defer mu.Unlock()
offered[h.Conn.RemoteAddr().String()] = slices.Contains(h.SupportedProtos, "h2")
return nil, nil
}}
srv.StartTLS()
t.Cleanup(srv.Close)
pool := x509.NewCertPool()
pool.AddCert(srv.Certificate())
d := Dispatch(&http.Transport{Proxy: Func, ForceAttemptHTTP2: true, TLSClientConfig: &tls.Config{RootCAs: pool}}).(*dispatch)
t.Cleanup(d.CloseIdleConnections)
was := HTTP1
HTTP1 = func(u *url.URL) bool { return strings.HasPrefix(u.Path, "/h1") }
t.Cleanup(func() { HTTP1 = was })
for _, c := range []struct {
path string
choice string
}{{"/h2", ""}, {"/h1", ""}, {"/h1/own", "direct"}, {"/h2/own", "direct"}} {
req, _ := http.NewRequestWithContext(With(context.Background(), c.choice), http.MethodGet, srv.URL+c.path, nil)
res, err := d.RoundTrip(req)
if err != nil {
t.Fatalf("%s: %v", c.path, err)
}
io.Copy(io.Discard, res.Body)
res.Body.Close()
}
want := []string{"/h2 HTTP/2.0 (h2 offered)", "/h1 HTTP/1.1", "/h1/own HTTP/1.1", "/h2/own HTTP/2.0 (h2 offered)"}
if !slices.Equal(got, want) {
t.Fatalf("asked\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}