diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 10a03d54b..49e0de9fa 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -35,6 +35,24 @@ FrierenF on Discord). A run as anyone else has its env as before. Only the bridge's run gets it; the warm-up and `/usage` runs don't skip permissions. +Every Claude Code magpie starts for the subscription (a turn's run, the +warm-up and model test `askClaude`, `/usage`, and the sign-in's +`auth login` and `auth status`) is given its proxy through one helper, +`claudeCLI.proxied` in each package, which is +`netproxy.EnvForBunWith`: the account's own proxy, else the +subscription's, else the global one (`netproxy.EnvWith`), with a SOCKS5 +proxy replaced by magpie's loopback HTTP bridge to it (`netproxy.Bridge`, +as for every bun magpie starts, #1409). Claude Code is built with Bun, +which takes only http:// and https:// proxies: given `socks5://`, every +request failed as `UnsupportedProxyProtocol`, after about three minutes of +Claude Code's own retries, as a 502 (#2651). A Claude Code in a WSL +distro that doesn't share Windows' loopback (`wslrun.Tool.Host` set) +can't reach the bridge, so there, and where the bridge can't start, a +SOCKS proxy is refused before Claude Code starts, with an error that says +to use an http:// proxy. The `settings.json` env that magpie writes for the +user's own Claude Code sessions leaves a SOCKS proxy out (see +[Providers and accounts](providers-accounts.md)). + The run's MCP server is magpie itself (`magpie claude-mcp-helper`, `internal/claudebridge`), which hands each tool call back to the gateway at `POST /_magpie/claude-mcp/` (`mcpCall`), where the call is @@ -514,6 +532,9 @@ carries none. go test -tags nogui ./internal/gateway/ -run '^TestClaudeClientCache' -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeLeanPrompt' -count=1 go test -tags nogui ./internal/claudecode/ -count=1 +go test -tags nogui ./internal/gateway/ -run '^TestClaudeCodeGivenTheBridgeForASOCKSProxy$' -count=1 +go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProxy$' -count=1 +go test -tags nogui ./internal/netproxy/ -run '^TestEnvForBunWith' -count=1 go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn' -count=1 ``` diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index e4c12dab3..8043601a4 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -168,7 +168,7 @@ The host gets magpie's proxy only as `MAGPIE_*_PROXY` and applies it to each fet magpie downloads the Bun build for this machine (`bunTarget` in [`bun.go`](../../internal/plugin/bun.go)): the baseline build on x64 Linux and Windows, the native `bun-windows-aarch64` on Windows on ARM (it was turned away as having no build until #2183), and on a musl Linux such as Alpine (`libc.Musl`, the check Claude Code's download uses too) the musl one, `bun-linux-x64-musl-baseline` or `bun-linux-aarch64-musl`. A glibc build names glibc's loader, which Alpine lacks, so it couldn't start there and exec said "no such file or directory" (#1877). A musl Linux keeps its Buns and their `state.json` under `bun/musl`, so a machine whose C library changed never runs the other one's build or takes its set-aside versions; everywhere else they stay in `bun`, where a Bun downloaded before is. A bun that is on disk but can't be started says it is a build for another C library and names `MAGPIE_BUN` (`cantStart`), and it isn't fallen back from or set aside: the version before is the same build. Bun's musl build needs libstdc++ and libgcc; on an Alpine without them, `bun add` and the host's start say which library is missing and `apk add libstdc++ libgcc` (`missingLibs`). `TestBunTargetForMusl`, `TestMuslBunKeptApartFromGlibc`, `TestCantStartSaysCLibrary`, `TestHostOnUnstartableBunSaysCLibrary`, `TestMissingLibsNamesThem` and `TestHostOnBunLackingLibsSaysWhich` in [`bunmusl_test.go`](../../internal/plugin/bunmusl_test.go) cover these. -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`). +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`). Claude Code, built with Bun, gets it for the Claude subscription's runs and sign-ins (`netproxy.EnvForBunWith`, #2651; see [Claude subscription bridge](claude-subscription-bridge.md)). The host reads its proxy once, when it starts. When the proxy magpie would give a new host differs from the one the running host got (the system proxy set after magpie started, as at login before Clash is up, or Settings changed), the next call to the host replaces it (`proxyMoved` in [`host.go`](../../internal/plugin/host.go), looked at no more than every 15s, or every 2s while the host has no proxy: `proxyLookNone`, #1518). A call made for a read nobody asked for, while allowances are read only when asked (`netproxy.Held`), never reaches the host. Before this, a host started without a proxy kept none, so the Grok plugin's `grok models` couldn't renew its token and the account read as signed out after each restart (#1363). diff --git a/internal/gateway/claude_socks_test.go b/internal/gateway/claude_socks_test.go new file mode 100644 index 000000000..d5d98548f --- /dev/null +++ b/internal/gateway/claude_socks_test.go @@ -0,0 +1,95 @@ +package gateway + +import ( + "context" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/netproxy" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// #2651 (demystify0137): a Claude account behind a socks5:// proxy was +// answered 502 after minutes, Claude Code failing every try as +// UnsupportedProxyProtocol, since Bun, which Claude Code is built with, +// takes only http:// and https:// proxies. Every Claude Code magpie runs +// for the subscription — a turn, a model test, /usage — is given magpie's +// HTTP bridge to the SOCKS proxy instead, never socks5:// itself. +func TestClaudeCodeGivenTheBridgeForASOCKSProxy(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + const socks = "socks5://127.0.0.1:1" + dir := t.TempDir() + log := filepath.Join(dir, "log") + // a turn's run answers with its proxy; a test's or /usage's writes it + // to log + script := `#!/bin/sh +proxies="https=$HTTPS_PROXY http=$HTTP_PROXY all=$ALL_PROXY lower=$https_proxy" +case " $* " in +*" stream-json "*) + while read -r line; do + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'"$proxies"'"}}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":""}' + done ;; +*) + echo "$proxies" > ` + log + ` + echo '{"type":"result","is_error":false,"result":"Hi!"}' ;; +esac +` + testenv.Program(t, filepath.Join(dir, "claude"), script) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + runsEndWithTest(t, dir) + + bridged := func(what, got string) { + t.Helper() + if strings.Contains(got, "socks5") { + t.Fatalf("%s: Claude Code was given the SOCKS proxy: %s", what, got) + } + for _, k := range []string{"https", "http", "all", "lower"} { + if !strings.Contains(got, k+"=http://127.0.0.1:") { + t.Fatalf("%s: no bridge in %s: %s", what, k, got) + } + } + } + + s := New() + t.Cleanup(s.subscription.abortAll) + p := provider.Provider{ID: "claude", Proxy: socks, Account: &provider.Account{Agent: "claude", User: "u"}} + body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + var u Usage + if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u); code != 200 { + t.Fatalf("%d %s", code, msg) + } + var res struct { + Content []struct{ Text string } `json:"content"` + } + json.Unmarshal(rec.Body.Bytes(), &res) + if len(res.Content) == 0 { + t.Fatalf("no answer: %s", rec.Body) + } + bridged("a turn", res.Content[0].Text) + + ctx := netproxy.With(context.Background(), socks) + if err := askClaude(ctx, "", "haiku"); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(log) + bridged("a model test", string(b)) + os.Remove(log) + if _, err := claudeUsage(ctx, ""); err != nil { + t.Fatal(err) + } + b, _ = os.ReadFile(log) + bridged("/usage", string(b)) +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index b5e2edaf3..448dc0e52 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -537,6 +537,14 @@ func (c claudeCLI) env(env []string, configDir string) []string { return c.wsl.Env(env, names...) } +// proxied is env told the proxy a run for ctx goes through (claudeProxy), +// a SOCKS one bridged: Claude Code is built with Bun, which takes only +// http:// and https:// proxies (#2651). One in a WSL distro reaches the +// bridge only when the distro shares Windows' loopback. +func (c claudeCLI) proxied(ctx context.Context, env []string) ([]string, error) { + return netproxy.EnvForBunWith(claudeProxy(ctx), env, c.wsl == nil || c.wsl.Host == "") +} + // file is where this Claude Code reads a file of magpie's at path: one in // WSL under the distro's mount of the drive. func (c claudeCLI) file(path string) string { @@ -696,7 +704,11 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, } cmd := binary.command(context.Background(), args...) cmd.Dir = work - env := netproxy.EnvWith(claudeProxy(ctx), cleanClaudeEnv(os.Environ())) + env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ())) + if err != nil { + cleanup() + return nil, nil, err + } if req.clientCache != nil { env = append(env, "DISABLE_PROMPT_CACHING=1") } diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go index 330791aff..007c63051 100644 --- a/internal/gateway/claude_warmup.go +++ b/internal/gateway/claude_warmup.go @@ -50,7 +50,11 @@ func askClaude(ctx context.Context, configDir, model string) error { cmd := binary.command(ctx, claudeWarmArgs(model)...) cmd.Dir = tmp cmd.Stdin = strings.NewReader("hi") - cmd.Env = binary.env(netproxy.EnvWith(claudeProxy(ctx), cleanClaudeEnv(os.Environ())), configDir) + env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ())) + if err != nil { + return err + } + cmd.Env = binary.env(env, configDir) var out, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &stderr runErr := runClaudeTree(cmd) @@ -101,7 +105,11 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) { }) } env = append(env, "DISABLE_TELEMETRY=1", "DISABLE_ERROR_REPORTING=1", "DISABLE_AUTOUPDATER=1") - cmd.Env = binary.env(netproxy.EnvWith(claudeProxy(ctx), env), configDir) + env, err = binary.proxied(ctx, env) + if err != nil { + return "", err + } + cmd.Env = binary.env(env, configDir) var out, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &out, &stderr runErr := runClaudeTree(cmd) diff --git a/internal/netproxy/bridge.go b/internal/netproxy/bridge.go index 5b6ed1900..d407ba394 100644 --- a/internal/netproxy/bridge.go +++ b/internal/netproxy/bridge.go @@ -319,3 +319,38 @@ func EnvForBun(env []string) []string { } return out } + +// EnvForBunWith is EnvWith's env (the proxy choice names, see With) for a +// Bun-built CLI magpie runs on a provider's behalf — Claude Code, for its +// subscription's requests, warm-ups, usage and sign-ins — with a SOCKS5 +// proxy bridged as EnvForBun bridges it. Given socks5:// as it was, Claude +// Code failed every request as UnsupportedProxyProtocol, after minutes of +// its own retries (#2651). loopback says the CLI reaches this computer's +// loopback, where a bridge listens; one that doesn't (Claude Code in a +// WSL distro under NAT) can't be bridged. A SOCKS proxy left in env, there +// or where the bridge can't start, is an error, at once: the CLI would +// fail with it every time. +func EnvForBunWith(choice string, env []string, loopback bool) ([]string, error) { + env = EnvWith(choice, env) + out := make([]string, 0, len(env)) + for _, e := range env { + k, v, _ := strings.Cut(e, "=") + switch strings.ToUpper(k) { + case "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY": + u, err := Parse(v) + if strings.TrimSpace(v) == "" || err != nil || !IsSOCKS(u) { + break + } + if !loopback { + return nil, fmt.Errorf("the proxy %s is SOCKS, which Claude Code can't use (UnsupportedProxyProtocol), and magpie's HTTP bridge to it is on this computer's loopback, which Claude Code in WSL doesn't reach: set an http:// proxy for it instead", Redact(v)) + } + a, err := Bridge(u) + if err != nil { + return nil, fmt.Errorf("the proxy %s is SOCKS, which Claude Code can't use (UnsupportedProxyProtocol), and magpie's HTTP bridge to it didn't start (%v): set an http:// proxy for it instead", Redact(v), err) + } + e = k + "=" + a + } + out = append(out, e) + } + return out, nil +} diff --git a/internal/netproxy/bridge_test.go b/internal/netproxy/bridge_test.go index ccc215b4d..e1fa2b4ab 100644 --- a/internal/netproxy/bridge_test.go +++ b/internal/netproxy/bridge_test.go @@ -280,3 +280,62 @@ func TestEnvForBunBridgesSystemSOCKS(t *testing.T) { t.Fatalf("an http proxy: %q", got) } } + +// #2651: a Bun-built CLI run on a provider's behalf (Claude Code) is given +// the bridge in front of the provider's SOCKS proxy, the bridge carrying +// to it. Where the CLI can't reach the bridge (WSL under NAT), or the +// bridge can't start, it is an error at once, never socks5:// handed on +// for the CLI to fail with on every try. +func TestEnvForBunWithBridgesTheProvidersSOCKS(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + socks, n := fakeSOCKS(t, "", "") + env, err := EnvForBunWith(socks.String(), []string{"PATH=/bin", "HTTPS_PROXY=http://old:1"}, true) + if err != nil { + t.Fatal(err) + } + var bridge string + for _, kv := range env { + k, v, _ := strings.Cut(kv, "=") + switch strings.ToUpper(k) { + case "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY": + if !strings.HasPrefix(v, "http://127.0.0.1:") { + t.Fatalf("the CLI is given %s", kv) + } + bridge = v + } + } + if bridge == "" || !slices.Contains(env, "PATH=/bin") { + t.Fatalf("env: %q", env) + } + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") })) + defer plain.Close() + pu, _ := url.Parse(bridge) + res, err := (&http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}).Get(plain.URL) + if err != nil { + t.Fatal(err) + } + b, _ := io.ReadAll(res.Body) + res.Body.Close() + if string(b) != "ok" || n.Load() != 1 { + t.Fatalf("through the bridge: %q, the SOCKS proxy carried %d", b, n.Load()) + } + + // an http:// proxy, and "direct", are EnvWith's as they are + for _, c := range []string{"http://127.0.0.1:7890", "direct"} { + got, err := EnvForBunWith(c, []string{"PATH=/bin"}, false) + if want := EnvWith(c, []string{"PATH=/bin"}); err != nil || strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("%s: %q %v, want %q", c, got, err, want) + } + } + + if _, err := EnvForBunWith("socks5://u:secret@10.0.0.2:1080", []string{"PATH=/bin"}, false); err == nil || + !strings.Contains(err.Error(), "UnsupportedProxyProtocol") || strings.Contains(err.Error(), "secret") { + t.Fatalf("out of the bridge's reach: %v", err) + } + old := listenLoopback + listenLoopback = func() (net.Listener, error) { return nil, io.ErrClosedPipe } + t.Cleanup(func() { listenLoopback = old }) + if _, err := EnvForBunWith("socks5://10.0.0.3:1080", []string{"PATH=/bin"}, true); err == nil || !strings.Contains(err.Error(), "didn't start") { + t.Fatalf("no bridge: %v", err) + } +} diff --git a/internal/provider/claude_signin.go b/internal/provider/claude_signin.go index 980febc00..34bc61a58 100644 --- a/internal/provider/claude_signin.go +++ b/internal/provider/claude_signin.go @@ -136,6 +136,14 @@ func (c claudeCLI) env(env []string) []string { return c.wsl.Env(env, "CLAUDE_CONFIG_DIR/p", "BROWSER/p", openedURLEnv+"/p") } +// proxied is env told the proxy choice names (netproxy.With), a SOCKS +// one bridged: Claude Code is built with Bun, which takes only http:// and +// https:// proxies (#2651). One in a WSL distro reaches the bridge only +// when the distro shares Windows' loopback. +func (c claudeCLI) proxied(choice string, env []string) ([]string, error) { + return netproxy.EnvForBunWith(choice, env, c.wsl == nil || c.wsl.Host == "") +} + // startClaudeSignIn runs `claude auth login` and gives the window the page // to open: the one Claude Code would have opened, which comes back to it on // this machine, or, when it opened none, the one it prints, whose page @@ -162,7 +170,13 @@ func startClaudeSignIn(s *signInFlow) error { cmd := cli.command(ctx, "auth", "login", "--claudeai") cmd.Dir = dir // through the proxy the account's requests will go through (#1663) - cmd.Env = cli.env(netproxy.EnvWith(s.proxy, env)) + env, err = cli.proxied(s.proxy, env) + if err != nil { + cancel() + cleanup() + return err + } + cmd.Env = cli.env(env) in, err := cmd.StdinPipe() if err != nil { cancel() @@ -334,7 +348,11 @@ func claudeSignedIn(cli claudeCLI, dir, proxy string) (savedLogin, error) { defer cancel() cmd := cli.probe(ctx, "auth", "status", "--json") cmd.Dir = dir - cmd.Env = cli.env(netproxy.EnvWith(proxy, claudeSignInEnv(os.Environ(), dir))) + env, err := cli.proxied(proxy, claudeSignInEnv(os.Environ(), dir)) + if err != nil { + return savedLogin{}, err + } + cmd.Env = cli.env(env) b, _ := cmd.Output() var status struct { Email string `json:"email"` diff --git a/internal/provider/signin_claude_test.go b/internal/provider/signin_claude_test.go index 72e5ce4b7..0952c9c28 100644 --- a/internal/provider/signin_claude_test.go +++ b/internal/provider/signin_claude_test.go @@ -51,7 +51,7 @@ func fakeClaudeLogin(t *testing.T, a fakeClaudeAccount, own string, opens bool) exe := filepath.Join(dir, "claude") script := fmt.Sprintf(`#!/bin/sh if [ "$1 $2" = "auth status" ]; then - if [ -n "$CLAUDE_CONFIG_DIR" ]; then cat "$CLAUDE_CONFIG_DIR/status.json"; exit 0; fi + if [ -n "$CLAUDE_CONFIG_DIR" ]; then printf '%%s' "$HTTPS_PROXY" > "${0%%/*}/status-proxy"; cat "$CLAUDE_CONFIG_DIR/status.json"; exit 0; fi %s fi [ "$1 $2" = "auth login" ] || exit 2 diff --git a/internal/provider/signin_proxy_test.go b/internal/provider/signin_proxy_test.go index d763d8c1b..8dbc765f9 100644 --- a/internal/provider/signin_proxy_test.go +++ b/internal/provider/signin_proxy_test.go @@ -266,6 +266,31 @@ func TestClaudeSignInGoesThroughItsProxy(t *testing.T) { } } +// A Claude subscription behind a socks5:// proxy (#2651): Claude Code is +// built with Bun, which takes only http:// and https:// proxies and failed +// as UnsupportedProxyProtocol, so its sign-in, and the auth status read +// after it, are given magpie's HTTP bridge to the SOCKS proxy. +func TestClaudeSignInBridgesASOCKSProxy(t *testing.T) { + claudeHome(t) + noAnthropic(t) + exe := fakeClaudeLogin(t, fakeClaudeAccount{email: "s@example.com", name: "S", plan: "max", refresh: "sk-ant-ort01-s"}, "", true) + setProxies(t, "claude", "socks5://127.0.0.1:1", nil) + st, err := StartSignIn("claude") + if err != nil { + t.Fatal(err) + } + finishInBrowser(t, st, "the-code") + if st = waitDone(t, st.ID); st.State != "done" { + t.Fatalf("state %+v", st) + } + for _, f := range []string{"login-proxy", "status-proxy"} { + b, _ := os.ReadFile(filepath.Join(filepath.Dir(exe), f)) + if !strings.HasPrefix(string(b), "http://127.0.0.1:") { + t.Fatalf("%s: Claude Code ran with HTTPS_PROXY=%q", f, b) + } + } +} + // Signing out of a ChatGPT account, OpenAI revokes its refresh token // through the account's own proxy, the exit its sign-in and requests left // through, not the global one (#1663).