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
This commit is contained in:
appointat
2026-10-13 06:18:27 +08:00
committed by yetone
co-authored by Claude Opus 5.5
parent d0e412e7a6
commit abdc4b113d
8 changed files with 390 additions and 72 deletions
+2
View File
@@ -119,6 +119,7 @@ A signed-in account's model list exists only at its vendor (Cursor's `cursor-age
- Claude Code's `/usage` prints a reset with no year when it falls this year ("Oct 9, 2:59pm (UTC)"), or, in older versions, as a time alone ("3pm"). `claudeResetTime` reads it as the end of its window, so never further ahead than the window's length (5 hours for the session, 7 days for a week) and `claudeResetSlack`: a date is in the first of last year, this year and next that is less than a day past and no further ahead, a time alone the next one no further ahead. Where none is, as for a reading days old, it is the latest one already past, so the window reads as renewed rather than full for a year. Where the clocks go back and show a time twice, the reading not yet past is taken. A week's time alone read just after its reset still reads as tomorrow's.
- A Copilot account is known by its GitHub login and host (`CopilotAccountName`, #1220): `mona` on github.com, `mona@acme.ghe.com` on an enterprise's GHE.com. That name is its `logins.json` user, its row in every list, its usage card and its per-account routing settings, and it is what `SwitchLogin`, `SetLoginOn` and `ForgetLogin` take, so one login on two hosts is two accounts, neither written over by the other nor dropped as the editors' own. One saved before on an enterprise's host under its login alone is read under its name with the host (`copilotSavedName`), keeping its id; the editors' own remembered so is renamed in place, still hidden if it was (`copilotRenamed`). Either rename takes the account's per-account settings in `providers.json` (proxy, models, cap, concurrency) from the bare login to the new name before the new name is written to `logins.json` (`renameSettled`): a setting the new name has already stays, and while `providers.json` can't be read or written the account stays saved under its old name, its settings with it. `magpie accounts switch|forget copilot` takes the full name, the login with `--host <name>.ghe.com`, or the login alone when it names one account.
- A Codex account is known by its email, with the plan for a workspace seat (`codexUser`), and a second seat of one email in another workspace by that name with its workspace after it (`codexName`): `me@example.com · Team · ws-two`. The account Codex is signed in to goes by the name it is saved under (`codexLiveName`) everywhere: its provider's `Account.User` (`codexAccount`), `liveLogin`, and its session identity (`SessionIdentities`). Its allowance, rests and sticks (`restKey`), cap, proxy, model list, a gateway key's account list (`LoginID`) and the Routing page all go by that name, so two seats of one email are never read as one (#1424).
- Every request to the ChatGPT backend (`CodexBase`'s host) goes over HTTP/1.1, as Codex itself speaks to it: each transport [`netproxy.Dispatch`](../../internal/netproxy/netproxy.go) makes (`http.DefaultClient`'s, the gateway's) sends a request `netproxy.HTTP1` names through an HTTP/1.1 copy of itself whose TLS hello offers no h2, and the provider package sets `HTTP1` to `codexBackend` ([codex_http1.go](../../internal/provider/codex_http1.go)). That covers the gateway's turns, the models list, the warm-up, the allowance, its resets and spending one, through the proxy in force, an account's own included. Every other vendor is still offered HTTP/2.
- The Copilot account the editors and CLI keep is read by `copilotLogin` ([account.go](../../internal/provider/account.go)): an editor's github.com sign-in in `~/.config/github-copilot/apps.json` or `hosts.json` first, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403, `copilotRefusals`, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (`copilotStandIn`); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (`copilotProbeEditor`, `addCopilotLogin`); while the editor token works, it is let go as the agent's own, as before.
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `lastgood.Keep` ([lastgood.go](../../internal/lastgood/lastgood.go)) keeps the file there now: as `logins.json.bak`, its last good generation, when it reads, or copied aside as `logins.json.bad-<time>` (`-2`, `-3`… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.
@@ -149,6 +150,7 @@ go test -tags nogui ./internal/plugin -run TestPluginSignInProxy
node --test internal/gui/tests/signin-proxy.test.cjs internal/gui/tests/signin-close.test.cjs
go test -tags nogui ./internal/provider -run 'TestAccount|TestImport|TestCodex|TestGroup|TestQuota|TestLogin|TestSignIn|TestSeveralKeys|TestKeyProtocol|TestSetKeyWeight|TestReadSub2APIKeyLimits|TestSub2APIKeyLimitsOnItsCard|TestKeyAllowance|TestPlanKeyAllowance|TestPayAsYouGoKeyAskedSeldom|TestClaudeAccountToldRenewed|TestPluginAccountToldRenewed|TestAllowancesReadOnlyWhenAsked|TestAllowancesReadByThemselvesByDefault|TestKeyReadsOnlyWhenAsked'
go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
go test -tags nogui ./internal/netproxy ./internal/provider ./internal/gateway -run 'TestDispatchHTTP1|OverHTTP1|TestAccountProxy'
go test -tags nogui ./internal/provider -run 'TestSeat|TestPlanOfASignedInAccountShownOnce|TestGLMPlanMatchesZCodePlugin|TestAccountName'
go test -tags nogui . -run TestAccountsAlias
node --test internal/gui/tests/account-alias.test.cjs
-53
View File
@@ -1,53 +0,0 @@
package gateway
import (
"crypto/tls"
"net/http"
"net/url"
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/provider"
)
// upstreamTLS is what the gateway's transports dial TLS with: nil, the
// system's roots, but for a test trusting its own server.
var upstreamTLS *tls.Config
// upstreamTransport is the gateway's transport to the vendors: a provider
// with a proxy of its own is sent through a transport kept for that proxy
// (#237). protocols nil speaks HTTP/2 wherever the server offers it.
func upstreamTransport(protocols *http.Protocols) http.RoundTripper {
return netproxy.Dispatch(&http.Transport{
Proxy: netproxy.Func,
ResponseHeaderTimeout: 10 * time.Minute,
MaxIdleConnsPerHost: 8,
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: protocols == nil,
Protocols: protocols,
TLSClientConfig: upstreamTLS,
})
}
// codexHTTP1 sends what goes to the ChatGPT backend (provider.CodexBase's
// host, chatgpt.com) over HTTP/1.1, and the rest over next. Codex itself
// offers no ALPN at all and so speaks HTTP/1.1 to it, and Pi's own Codex
// provider a WebSocket or Node's fetch, HTTP/1.1 both; the gateway's
// HTTP/2 put every Codex stream, every account's, on one connection,
// where Cloudflare in front reset one now and then mid-reply ("stream
// error: stream ID 21; INTERNAL_ERROR; received from peer", jasonz3g on
// X: Codex in Pi through magpie, never Codex or Pi alone).
type codexHTTP1 struct{ next, h1 http.RoundTripper }
func newCodexHTTP1(next http.RoundTripper) codexHTTP1 {
var h1 http.Protocols
h1.SetHTTP1(true)
return codexHTTP1{next: next, h1: upstreamTransport(&h1)}
}
func (t codexHTTP1) RoundTrip(r *http.Request) (*http.Response, error) {
if u, err := url.Parse(provider.CodexBase); err == nil && r.URL.Host == u.Host {
return t.h1.RoundTrip(r)
}
return t.next.RoundTrip(r)
}
+1 -1
View File
@@ -368,7 +368,7 @@ func New() *Server {
// a request counted against a MaxRPM waits for room in its minute
// first (rpm.go); the ChatGPT backend is spoken to over HTTP/1.1
// (codex_http1.go)
client: &http.Client{Transport: rpmTransport{newCodexHTTP1(upstreamTransport(nil))}},
client: &http.Client{Transport: rpmTransport{upstreamTransport()}},
unfit: make(map[string]bool),
subscription: newSubscriptionBridge(),
debug: os.Getenv("MAGPIE_DEBUG") != "",
+28
View File
@@ -0,0 +1,28 @@
package gateway
import (
"crypto/tls"
"net/http"
"time"
"github.com/yetone/magpie/internal/netproxy"
)
// upstreamTLS is what the gateway's transports dial TLS with: nil, the
// system's roots, but for a test trusting its own server.
var upstreamTLS *tls.Config
// upstreamTransport is the gateway's transport to the vendors: a provider
// with a proxy of its own is sent through a transport kept for that proxy
// (#237), and the ChatGPT backend over HTTP/1.1 (netproxy.HTTP1). Every
// other vendor is spoken HTTP/2 to wherever it offers it.
func upstreamTransport() http.RoundTripper {
return netproxy.Dispatch(&http.Transport{
Proxy: netproxy.Func,
ResponseHeaderTimeout: 10 * time.Minute,
MaxIdleConnsPerHost: 8,
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
TLSClientConfig: upstreamTLS,
})
}
+48 -16
View File
@@ -112,36 +112,50 @@ func forChoice(c string) (*url.URL, error) {
return Parse(c)
}
// HTTP1 says a request to u goes over HTTP/1.1 only, whatever its
// transport offers. internal/provider sets it to the ChatGPT backend's
// host, which Codex itself speaks HTTP/1.1 to; nil leaves every request to
// its transport.
var HTTP1 func(u *url.URL) bool
// Dispatch is a RoundTripper sending a request through base, unless its
// context names a provider's own proxy (With): then through a clone of
// base kept for that proxy alone. Connections are so reused among the
// requests going through one proxy and never carried to another — HTTP/2
// ones, which a transport shares by host whatever proxy they were dialled
// through, among them. A host whose IPv6 is taken but goes nowhere is
// through, among them. A request HTTP1 names goes through a clone kept
// for HTTP/1.1 (http1Only). A host whose IPv6 is taken but goes nowhere is
// dialed over IPv4 (v4Fallback).
func Dispatch(base *http.Transport) http.RoundTripper {
v4Fallback(base)
return &dispatch{base: base, own: map[string]*http.Transport{}}
return &dispatch{base: base, own: map[route]*http.Transport{}}
}
type dispatch struct {
base *http.Transport
mu sync.Mutex
own map[string]*http.Transport
own map[route]*http.Transport
}
// route is what a request needs of its transport other than base: a
// provider's own proxy, HTTP/1.1 only, or both.
type route struct {
choice string
h1 bool
}
func (d *dispatch) RoundTrip(req *http.Request) (*http.Response, error) {
c := choiceOf(req.Context())
if c == "" {
r := route{choice: choiceOf(req.Context()), h1: HTTP1 != nil && HTTP1(req.URL)}
if r == (route{}) {
return v4Retry(d.base, req)
}
return v4Retry(d.transport(c), req)
return v4Retry(d.transport(r), req)
}
func (d *dispatch) transport(c string) *http.Transport {
func (d *dispatch) transport(r route) *http.Transport {
d.mu.Lock()
defer d.mu.Unlock()
if t, ok := d.own[c]; ok {
if t, ok := d.own[r]; ok {
return t
}
if len(d.own) >= 32 { // choices come and go as they are edited
@@ -151,19 +165,37 @@ func (d *dispatch) transport(c string) *http.Transport {
}
}
t := d.base.Clone()
t.Proxy = func(req *http.Request) (*url.URL, error) {
if err := Held(req.Context()); err != nil {
return nil, err
if c := r.choice; c != "" {
t.Proxy = func(req *http.Request) (*url.URL, error) {
if err := Held(req.Context()); err != nil {
return nil, err
}
if loopback(req.URL.Hostname()) {
return nil, nil
}
return forChoice(c)
}
if loopback(req.URL.Hostname()) {
return nil, nil
}
return forChoice(c)
}
d.own[c] = t
if r.h1 {
http1Only(t)
}
d.own[r] = t
return t
}
// http1Only has t, a clone, speak HTTP/1.1 only, and its TLS hello offer
// no protocol (ALPN), as Codex's does. 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.
func http1Only(t *http.Transport) {
var h1 http.Protocols
h1.SetHTTP1(true)
t.Protocols, t.ForceAttemptHTTP2 = &h1, false
if t.TLSClientConfig != nil {
t.TLSClientConfig.NextProtos = nil
}
}
// CloseIdleConnections closes base's and every proxy's own.
func (d *dispatch) CloseIdleConnections() {
d.base.CloseIdleConnections()
+56 -2
View File
@@ -2,10 +2,16 @@ package netproxy
import (
"context"
"crypto/tls"
"crypto/x509"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
@@ -189,8 +195,8 @@ func TestWith(t *testing.T) {
}
d := Dispatch(&http.Transport{Proxy: Func}).(*dispatch)
a, b := d.transport("127.0.0.1:1"), d.transport("direct")
if a == b || d.transport("127.0.0.1:1") != a || len(d.own) != 2 {
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" {
@@ -218,3 +224,51 @@ func TestWith(t *testing.T) {
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"))
}
}
+23
View File
@@ -0,0 +1,23 @@
package provider
import (
"net/url"
"github.com/yetone/magpie/internal/netproxy"
)
func init() { netproxy.HTTP1 = codexBackend }
// codexBackend says u is on the ChatGPT backend (CodexBase's host), which
// every transport netproxy.Dispatch makes speaks HTTP/1.1 to: the
// gateway's turns, the models list, the warm-up, the allowance and its
// resets. Codex itself does: codex-cli offers no ALPN at all there, and
// Pi's Codex provider speaks HTTP/1.1 or a WebSocket. On one shared HTTP/2
// connection a Codex stream was reset now and then mid-reply (jasonz3g on
// X, "stream ID 21; INTERNAL_ERROR; received from peer"), and through a
// local proxy a request failed with PROTOCOL_ERROR until HTTP/2 was turned
// off.
func codexBackend(u *url.URL) bool {
b, err := url.Parse(CodexBase)
return err == nil && u.Host == b.Host
}
+232
View File
@@ -0,0 +1,232 @@
package provider
import (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"io"
"net"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/settings"
)
// h2Vendor is a TLS server offering HTTP/2 that notes, for each request,
// its path, the protocol it came over and whether the TLS hello offered h2.
type h2Vendor struct {
*httptest.Server
mu sync.Mutex
got []string
}
func newH2Vendor(t *testing.T, answer func(path string) string) *h2Vendor {
t.Helper()
v := &h2Vendor{}
offered := map[string]bool{} // the client's address → its hello offered h2
v.Server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v.mu.Lock()
h2 := offered[r.RemoteAddr]
v.got = append(v.got, r.URL.Path+" "+r.Proto+map[bool]string{true: " (h2 offered)"}[h2])
v.mu.Unlock()
io.WriteString(w, answer(r.URL.Path))
}))
v.EnableHTTP2 = true
v.TLS = &tls.Config{GetConfigForClient: func(h *tls.ClientHelloInfo) (*tls.Config, error) {
v.mu.Lock()
offered[h.Conn.RemoteAddr().String()] = slices.Contains(h.SupportedProtos, "h2")
v.mu.Unlock()
return nil, nil
}}
v.StartTLS()
t.Cleanup(v.Close)
return v
}
// asked is what the vendor was asked since the last call.
func (v *h2Vendor) asked() []string {
v.mu.Lock()
defer v.mu.Unlock()
got := v.got
v.got = nil
return got
}
// tunnel is an HTTP proxy that tunnels every CONNECT to addr and notes
// the host:port asked for.
type tunnel struct {
ln net.Listener
mu sync.Mutex
got []string
}
func newTunnel(t *testing.T, addr string) *tunnel {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
p := &tunnel{ln: ln}
t.Cleanup(func() { ln.Close() })
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go p.serve(c, addr)
}
}()
return p
}
func (p *tunnel) URL() string { return "http://" + p.ln.Addr().String() }
func (p *tunnel) connects() []string {
p.mu.Lock()
defer p.mu.Unlock()
return slices.Clone(p.got)
}
func (p *tunnel) serve(c net.Conn, addr string) {
defer c.Close()
br := bufio.NewReader(c)
req, err := http.ReadRequest(br)
if err != nil || req.Method != http.MethodConnect {
io.WriteString(c, "HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n")
return
}
p.mu.Lock()
p.got = append(p.got, req.Host)
p.mu.Unlock()
up, err := net.Dial("tcp", addr)
if err != nil {
io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")
return
}
defer up.Close()
io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n")
done := make(chan struct{}, 2)
go func() { io.Copy(up, br); done <- struct{}{} }()
go func() { io.Copy(c, up); done <- struct{}{} }()
<-done
}
// What magpie asks the ChatGPT backend on its own (the models list, the
// warm-up, the allowance, its resets and spending one) goes over HTTP/1.1,
// as the gateway's turns there do and Codex itself does, and its TLS hello
// offers no h2: directly, through Settings' proxy and through the
// account's own. Another vendor's allowance is still asked over HTTP/2.
// (reporter-provided: Codex's POST to /backend-api/codex/responses failed
// with PROTOCOL_ERROR through a local proxy until HTTP/2 was turned off.)
func TestCodexBackendOwnRequestsOverHTTP1(t *testing.T) {
chatgpt := newH2Vendor(t, func(path string) string {
switch {
case strings.HasSuffix(path, "/codex/models"):
return `{"models":[{"slug":"gpt-6.1-sol","visibility":"list"}]}`
case strings.HasSuffix(path, "/consume"):
return `{"code":"reset","windows_reset":1}`
}
return `{}`
})
other := newH2Vendor(t, func(string) string { return `{}` })
pool := x509.NewCertPool()
pool.AddCert(chatgpt.Certificate())
pool.AddCert(other.Certificate())
// http.DefaultClient as netproxy.Install leaves it: HTTP/2 wherever a
// server offers it
h2 := http.DefaultTransport.(*http.Transport).Clone()
h2.Proxy, h2.TLSClientConfig = netproxy.Func, &tls.Config{RootCAs: pool}
dispatch := netproxy.Dispatch(h2)
oldClient, oldBase := http.DefaultClient.Transport, CodexBase
http.DefaultClient.Transport = dispatch
t.Cleanup(func() {
dispatch.(interface{ CloseIdleConnections() }).CloseIdleConnections()
http.DefaultClient.Transport, CodexBase = oldClient, oldBase
})
sign := func(_ context.Context, r *http.Request, _ []byte) error {
r.Header.Set("Authorization", "Bearer t")
return nil
}
ask := func(ctx context.Context) {
t.Helper()
if _, err := codexModels(ctx, sign); err != nil {
t.Fatalf("models: %v", err)
}
if err := warmCodex(ctx, sign, "gpt-6.1-sol", "low"); err != nil {
t.Fatalf("warm-up: %v", err)
}
if _, _, _, _, _, err := codexWindows(ctx, "t", "acct"); err != nil {
t.Fatalf("allowance: %v", err)
}
base := strings.TrimSuffix(CodexBase, "/codex")
codexResets(ctx, base, "t", "acct", 1)
if _, err := consumeCodexReset(ctx, base, "t", "acct", "c1", "r1"); err != nil {
t.Fatalf("reset: %v", err)
}
}
want := []string{
"/backend-api/codex/models HTTP/1.1",
"/backend-api/codex/responses HTTP/1.1",
"/backend-api/wham/usage HTTP/1.1",
"/backend-api/wham/rate-limit-reset-credits HTTP/1.1",
"/backend-api/wham/rate-limit-reset-credits/consume HTTP/1.1",
}
check := func(what string) {
t.Helper()
if got := chatgpt.asked(); !slices.Equal(got, want) {
t.Errorf("%s: the ChatGPT backend was asked\n%s\nwant\n%s", what, strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}
CodexBase = chatgpt.URL + "/backend-api/codex"
ask(context.Background())
check("directly")
var bill struct{}
if err := accountJSON(context.Background(), other.URL+"/v1/billing", "k", nil, &bill); err != nil {
t.Fatal(err)
}
if got := other.asked(); !slices.Equal(got, []string{"/v1/billing HTTP/2.0 (h2 offered)"}) {
t.Errorf("another vendor was asked %v, not over HTTP/2", got)
}
// through a proxy the ChatGPT backend is a name, not this computer
// (loopback is never proxied): example.com is in the test certificate
CodexBase = "https://example.com/backend-api/codex"
global := newTunnel(t, chatgpt.Listener.Addr().String())
st := settings.Load()
st.Proxy = global.URL()
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
st := settings.Load()
st.Proxy = ""
settings.Save(st)
})
ask(context.Background())
check("through Settings' proxy")
if got := global.connects(); len(got) == 0 || slices.ContainsFunc(got, func(h string) bool { return h != "example.com:443" }) {
t.Errorf("Settings' proxy was asked to CONNECT %v", got)
}
own := newTunnel(t, chatgpt.Listener.Addr().String())
st = settings.Load()
st.Proxy = "direct"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
ask(netproxy.With(context.Background(), own.URL()))
check("through the account's own proxy")
if got := own.connects(); len(got) == 0 {
t.Errorf("the account's own proxy was never asked")
}
}