Files
magpie/internal/gateway/account_proxy_test.go
T
yetone 3dc8f00f06 providers: each account of a subscription holding several can go through its own proxy — the provider's, none, or its own address (Discord, gakki: 是否可以为不同的codex账号设置不用的代理,现在是同一个供应商下使用相同的代理) — the per-provider proxy (#237) was one for all of Codex's signed-in accounts. A subscription's entry in providers.json now keeps accountProxies, by the account's name in lower case, each checked by settings.CheckProxy on save (ftp:// refused), addresses trimmed, accounts following the provider's proxy left out. Provider.ProxyChoice picks an account's own proxy, else the provider's, else the global one, so everything that already went through Provider.Via follows the account: gateway turns and fallback across accounts, usage and quota, token refresh, Codex's warm-up, reset and saved accounts' model lists, Claude's warm-up and the *_PROXY of Claude Code runs (ViaLogin / ProxyOfLogin), and Codex's own sign-in relayed as it came (ViaSignedIn). Extra accounts of Copilot, ZCode, Kiro and the like, made afresh without the provider's settings, now read them from providers.json, so they honour the provider's proxy too. A save without accountProxies keeps them; {} clears them. The provider editor, for a subscription with two or more accounts, lists each under the Proxy row: Provider's proxy | Direct | Custom, the address field's room kept so a pick moves nothing; Custom with no address is refused before anything is posted, its field focused without scrolling. en and zh together; no border stripes. Tested with internal/gateway/account_proxy_test.go in a sandbox HOME against fake proxies and a fake ChatGPT backend: three Codex accounts (own proxy, direct, following the provider) each reach the backend their own way in one turn and for usage; clearing an account's proxy sends it through the provider's, clearing the provider's through the global one, direct staying direct; ftp:// refused; TestClaudeAccountProxyEnv covers each Claude account's HTTPS_PROXY. Both fail with the per-account lookup off. account-proxy.test.cjs, Chromium and WebKit, en and zh (new), provider-proxy, click-scroll and old-webkit pass. go vet ./internal/..., go build -tags nogui (and GOOS=linux, GOOS=windows) and go test -tags nogui ./... pass. Not tried against a real proxy, real accounts or the real Wails window; Grok's per-account usage and Kiro's usage on a key still use the provider's proxy.
2026-09-30 04:52:03 +08:00

236 lines
8.6 KiB
Go

package gateway
import (
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// chatgptAt stands in for the ChatGPT backend, or for a proxy in front of
// it: it notes each request's path and account (chatgpt-account-id), and
// answers a turn for acct-1 and acct-2 with their allowance used up, so a
// turn moves on through every account, and acct-3's with "pong".
type chatgptAt struct {
mu sync.Mutex
name string
got []string // "<path> <account>"
}
func (c *chatgptAt) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
acct := r.Header.Get("chatgpt-account-id")
c.mu.Lock()
c.got = append(c.got, r.URL.Path+" "+acct)
c.mu.Unlock()
switch {
case strings.HasSuffix(r.URL.Path, "/responses"):
if acct != "acct-3" {
w.WriteHeader(429)
io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`)
return
}
io.WriteString(w, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`,
`data: {"type":"response.output_text.delta","delta":"pong via `+c.name+`"}`,
`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`))
case strings.HasSuffix(r.URL.Path, "/wham/usage"):
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"plan_type":"plus","rate_limit":{"primary_window":{"used_percent":10,"limit_window_seconds":18000,"reset_after_seconds":600}}}`)
default:
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"models":[]}`)
}
}
// saw is the accounts sent a request to a path ending in suffix.
func (c *chatgptAt) saw(suffix string) []string {
c.mu.Lock()
defer c.mu.Unlock()
var out []string
for _, g := range c.got {
if path, acct, _ := strings.Cut(g, " "); strings.HasSuffix(path, suffix) {
out = append(out, acct)
}
}
return out
}
func (c *chatgptAt) reset() {
c.mu.Lock()
c.got = nil
c.mu.Unlock()
}
// Each of a subscription's accounts goes through its own proxy (gakki:
// 是否可以为不同的codex账号设置不同的代理): of three Codex accounts, one
// through the proxy it names, one direct though Codex and Settings both
// name one, and one, following Codex's, through Codex's — a turn that
// moves over all three, and each account's usage, alike. An account set
// back to following goes through Codex's proxy, and with Codex's cleared,
// through the global one; ftp:// is refused.
func TestAccountProxy(t *testing.T) {
codexSignedIn(t, "spare@example.com", "third@example.com")
for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} {
t.Setenv(k, "")
}
own, codexs, global, vendor := &chatgptAt{name: "own"}, &chatgptAt{name: "codex's"}, &chatgptAt{name: "global"}, &chatgptAt{name: "vendor"}
var servers []*httptest.Server
for _, h := range []http.Handler{own, codexs, global, vendor} {
s := httptest.NewServer(h)
t.Cleanup(s.Close)
servers = append(servers, s)
}
ownProxy, codexProxy, globalProxy, backend := servers[0], servers[1], servers[2], servers[3]
all := []*chatgptAt{own, codexs, global, vendor}
resetAll := func() {
for _, x := range all {
x.reset()
}
}
// the backend at a name no proxy stands in front of (loopback never
// goes through one): dialled directly, chatgpt.test is the vendor
var d net.Dialer
dial := func(ctx context.Context, network, addr string) (net.Conn, error) {
if host, _, _ := net.SplitHostPort(addr); strings.HasSuffix(host, ".test") {
addr = backend.Listener.Addr().String()
}
return d.DialContext(ctx, network, addr)
}
transport := func() *http.Transport {
return &http.Transport{Proxy: netproxy.Func, DialContext: dial, ResponseHeaderTimeout: 10 * time.Second}
}
defaultTransport := http.DefaultClient.Transport
http.DefaultClient.Transport = netproxy.Dispatch(transport())
t.Cleanup(func() { http.DefaultClient.Transport = defaultTransport })
was := provider.CodexBase
provider.CodexBase = "http://chatgpt.test/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
st := settings.Load()
st.Proxy = globalProxy.URL
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
p, err := provider.Find("codex")
if err != nil {
t.Fatal(err)
}
bad := *p
bad.AccountProxies = map[string]string{"spare@example.com": "ftp://10.0.0.1:21"}
if err := provider.Save(bad); err == nil {
t.Fatal("an account's ftp:// proxy was taken")
}
p.Proxy = codexProxy.URL
p.AccountProxies = map[string]string{"Me@Example.com": " " + ownProxy.URL + " ", "spare@example.com": "direct", "third@example.com": ""}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
if p, _ = provider.Find("codex"); p.Proxy != codexProxy.URL || len(p.AccountProxies) != 2 ||
p.AccountProxies["me@example.com"] != ownProxy.URL || p.AccountProxies["spare@example.com"] != "direct" {
t.Fatalf("kept %q %v", p.Proxy, p.AccountProxies)
}
b, _ := os.ReadFile(provider.Path())
if !strings.Contains(string(b), `"accountProxies"`) || strings.Contains(string(b), "third@example.com") {
t.Fatalf("providers.json: %s", b)
}
// a turn over the three: acct-1 through its own proxy, acct-2 direct
// to the backend, acct-3 through Codex's
s := New()
s.client = &http.Client{Transport: netproxy.Dispatch(transport())}
turn := func() (int, string) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"ping"}`))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", "acct-1")
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
code, body := turn()
if code != 200 || !strings.Contains(body, "pong via codex's") {
t.Fatalf("turn: %d %s", code, body)
}
want := func(what, suffix string, by map[*chatgptAt][]string) {
t.Helper()
for _, x := range all {
if got := sorted(x.saw(suffix)...); !slices.Equal(got, by[x]) {
t.Fatalf("%s: %s was sent %v, want %v", what, x.name, got, by[x])
}
}
}
want("turn", "/responses", map[*chatgptAt][]string{own: {"acct-1"}, vendor: {"acct-2"}, codexs: {"acct-3"}})
// each account's usage goes the same ways
usage := func() {
t.Helper()
resetAll()
for _, u := range []string{"me@example.com", "spare@example.com", "third@example.com"} {
provider.StaleAllowance("codex", u)
}
for u, q := range provider.LoginUsage(context.Background(), "codex") {
if q.Error != "" {
t.Fatalf("%s's usage: %s", u, q.Error)
}
}
}
usage()
want("usage", "/wham/usage", map[*chatgptAt][]string{own: {"acct-1"}, vendor: {"acct-2"}, codexs: {"acct-3"}})
// acct-1 back to following Codex's proxy; then Codex's cleared, the
// accounts following it follow the global one
p, _ = provider.Find("codex")
delete(p.AccountProxies, "me@example.com")
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
usage()
want("acct-1 following Codex's", "/wham/usage", map[*chatgptAt][]string{vendor: {"acct-2"}, codexs: sorted("acct-1", "acct-3")})
p, _ = provider.Find("codex")
p.Proxy = ""
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
usage()
want("Codex following the global", "/wham/usage", map[*chatgptAt][]string{vendor: {"acct-2"}, global: sorted("acct-1", "acct-3")})
}
func sorted(s ...string) []string { slices.Sort(s); return s }
// A Claude Code run for one of its accounts (the bridge's, a warm-up's)
// gets that account's own proxy in its *_PROXY, or else Claude's.
func TestClaudeAccountProxyEnv(t *testing.T) {
fresh(t)
for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"} {
t.Setenv(k, "")
}
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
os.WriteFile(provider.Path(), []byte(`{"providers":[{"id":"claude","key":"","proxy":"http://10.0.0.9:7890","accountProxies":{"a@example.com":"socks5://10.0.0.8:1080","b@example.com":"direct"}}]}`), 0o600)
env := func(user string) string {
for _, kv := range netproxy.EnvWith(claudeProxy(provider.ViaLogin(context.Background(), "claude", user)), []string{"PATH=/bin"}) {
if v, ok := strings.CutPrefix(kv, "HTTPS_PROXY="); ok {
return v
}
}
return ""
}
for user, want := range map[string]string{"A@example.com": "socks5://10.0.0.8:1080", "b@example.com": "", "c@example.com": "http://10.0.0.9:7890"} {
if got := env(user); got != want {
t.Errorf("%s: HTTPS_PROXY %q, want %q", user, got, want)
}
}
}