diff --git a/internal/gui/plugins.go b/internal/gui/plugins.go index a4d448f7b..e4fd4acf1 100644 --- a/internal/gui/plugins.go +++ b/internal/gui/plugins.go @@ -524,7 +524,9 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { Provider string Method int Inputs map[string]string - Key string // an "api" method's key + Key string // an "api" method's key + Proxy *string // the one picked to sign in through (#1663) + User string // the account signed in to again } if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&in); err != nil { fail(rw, err) @@ -546,7 +548,7 @@ func pluginRoutes(mux *http.ServeMux, w Windows) { writeJSON(rw, provider.SignInState{Agent: id, State: "done", User: pp.Name}) return } - st, err := provider.StartPluginSignIn(in.Provider, in.Method, in.Inputs) + st, err := provider.StartPluginSignInWith(in.Provider, in.Method, in.Inputs, provider.SignInOptions{Proxy: in.Proxy, User: in.User}) if err != nil { fail(rw, err) return diff --git a/internal/gui/providers.go b/internal/gui/providers.go index b44a90d8c..c291dfa0a 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -1863,12 +1863,18 @@ func providerRoutes(mux *http.ServeMux, w Windows) { // Adding a subscription: magpie opens the vendor's sign-in in the // browser and the window follows it until the account is in. mux.HandleFunc("POST /api/signin", func(rw http.ResponseWriter, r *http.Request) { - var in struct{ Agent, Site string } // Site: ZCode's "zai" or "bigmodel" + var in struct { + Agent, Site string // Site: ZCode's "zai" or "bigmodel" + // Proxy is the one picked to sign in through, kept as the + // account's (#1663); none picked, the one its requests go through + Proxy *string + User string // the account signed in to again + } if err := json.NewDecoder(r.Body).Decode(&in); err != nil { fail(rw, err) return } - st, err := provider.StartSignInAt(in.Agent, in.Site) + st, err := provider.StartSignInWith(in.Agent, provider.SignInOptions{Site: in.Site, Proxy: in.Proxy, User: in.User}) if err != nil { fail(rw, err) return diff --git a/internal/plugin/host.js b/internal/plugin/host.js index f9e973692..d5df5f7a5 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -1565,7 +1565,11 @@ function signInKey(provider, account) { let nextSession = 1 -async function authorize({ provider, method, inputs, account }) { +// A sign-in goes through the proxy its subscription's requests will (proxy, +// as fetch's: "", "direct" or its URL), so the vendor sees the account +// come from one place from its first request on (#1663): authorize and the +// callback that trades the code are both run under it. +async function authorize({ provider, method, inputs, account, proxy }) { const m = authOf(provider).methods[method] if (!m) throw new Error(`no sign-in method ${method} for ${provider}`) if (m.type !== "oauth") throw new Error("not an oauth method") @@ -1575,9 +1579,9 @@ async function authorize({ provider, method, inputs, account }) { // auth login) calls, and a plugin told so asks its questions on the // terminal, magpie's stdin here (opencode-antigravity-auth waited on its // "Project ID" prompt, the sign-in never starting) - const a = await inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined)) + const a = await via.run(proxy ?? "", () => inScope(provider, key, () => m.authorize(m.prompts?.length ? inputs ?? {} : undefined))) const session = String(nextSession++) - sessions.set(session, { provider, key, a, inputs }) + sessions.set(session, { provider, key, a, inputs, proxy: proxy ?? "" }) return { session, url: a.url ?? "", instructions: a.instructions ?? "", method: a.method } } @@ -1592,12 +1596,12 @@ async function callback({ session, code }) { const s = sessions.get(session) if (!s) throw new Error("no such sign-in") sessions.delete(session) - const r = await inScope(s.provider, s.key, () => (s.a.method === "code" ? s.a.callback(code ?? "") : s.a.callback())) + const r = await via.run(s.proxy, () => inScope(s.provider, s.key, () => (s.a.method === "code" ? s.a.callback(code ?? "") : s.a.callback()))) if (!r || r.type !== "success") return failed(r) return { ok: true, ...save(s.provider, s.key, r, undefined) } } -async function apiKey({ provider, method, inputs, key, account }) { +async function apiKey({ provider, method, inputs, key, account, proxy }) { const m = authOf(provider).methods[method] if (!m || m.type !== "api") throw new Error("not an API key method") const at = signInKey(provider, account) @@ -1606,7 +1610,7 @@ async function apiKey({ provider, method, inputs, key, account }) { setAuth(at, { type: "api", key, ...md }) return { ok: true, provider, account: settle(provider, at) } } - const r = await inScope(provider, at, () => m.authorize(inputs ?? {})) + const r = await via.run(proxy ?? "", () => inScope(provider, at, () => m.authorize(inputs ?? {}))) if (!r || r.type !== "success") return failed(r) return { ok: true, ...save(provider, at, r, inputs, key) } } diff --git a/internal/plugin/plugin_test.go b/internal/plugin/plugin_test.go index 33b579b4f..d9b21ed5a 100644 --- a/internal/plugin/plugin_test.go +++ b/internal/plugin/plugin_test.go @@ -414,6 +414,51 @@ func TestPluginProxy(t *testing.T) { } } +// A sign-in goes through the proxy it was begun with (#1663): the +// plugin's requests while it authorizes, and the ones its callback makes +// to trade the code, which Finish is asked for with no proxy named; the +// global one is asked for neither. +func TestPluginSignInProxy(t *testing.T) { + sandbox(t) + var mu sync.Mutex + var own, global []string + proxy := func(seen *[]string) *httptest.Server { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + *seen = append(*seen, r.URL.String()) + mu.Unlock() + fmt.Fprint(w, "ok") + })) + t.Cleanup(srv.Close) + return srv + } + ownSrv, globalSrv := proxy(&own), proxy(&global) + t.Setenv("HTTP_PROXY", globalSrv.URL) + t.Setenv("http_proxy", globalSrv.URL) + t.Setenv("FAKE_SIGNIN", "http://vendor.invalid/signin") + ctx, cancel := context.WithTimeout(context.Background(), 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) + } + a, err := Authorize(netproxy.With(ctx, ownSrv.URL), "fakeco", 1, map[string]string{"where": "home"}, NewAccount) + if err != nil { + t.Fatal(err) + } + if _, err := Finish(ctx, a.Session, "good"); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if !slices.Equal(own, []string{"http://vendor.invalid/signin/device", "http://vendor.invalid/signin/token"}) || len(global) != 0 { + t.Fatalf("the sign-in's own proxy saw %q, the global one %q", own, global) + } +} + // Plugins changed by another magpie (magpie plugin add or move in a // terminal while the app runs) reach the one running: its host starts // again with them, and meanwhile it knows the providers the other magpie diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index d746ab947..8cbb3605c 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -633,10 +633,12 @@ type Authorization struct { // already signed in replaces that one's instead. const NewAccount = "new" -// Authorize begins an OAuth sign-in to account (a key, or NewAccount). +// Authorize begins an OAuth sign-in to account (a key, or NewAccount), +// through the proxy ctx names (netproxy.With): the plugin's requests for +// it, there and in Finish, go through that one (#1663). func Authorize(ctx context.Context, provider string, method int, inputs map[string]string, account string) (Authorization, error) { var a Authorization - err := Call(ctx, "authorize", map[string]any{"provider": provider, "method": method, "inputs": inputs, "account": account}, &a) + err := Call(ctx, "authorize", map[string]any{"provider": provider, "method": method, "inputs": inputs, "account": account, "proxy": proxyOf(ctx)}, &a) return a, err } @@ -659,8 +661,8 @@ func failure(why string) error { } // Finish waits for an OAuth sign-in to finish: an "auto" one on its own, -// a "code" one with the code pasted back. It gives where the sign-in was -// saved. +// a "code" one with the code pasted back, through the proxy Authorize was +// given. It gives where the sign-in was saved. func Finish(ctx context.Context, session, code string) (Saved, error) { var r struct { OK bool `json:"ok"` @@ -677,14 +679,14 @@ func Finish(ctx context.Context, session, code string) (Saved, error) { } // APIKey signs in to account (a key, or NewAccount) with a key, as an -// "api" method does. +// "api" method does, through the proxy ctx names. func APIKey(ctx context.Context, provider string, method int, inputs map[string]string, key, account string) (Saved, error) { var r struct { OK bool `json:"ok"` Error string `json:"error"` Saved } - if err := Call(ctx, "apiKey", map[string]any{"provider": provider, "method": method, "inputs": inputs, "key": key, "account": account}, &r); err != nil { + if err := Call(ctx, "apiKey", map[string]any{"provider": provider, "method": method, "inputs": inputs, "key": key, "account": account, "proxy": proxyOf(ctx)}, &r); err != nil { return Saved{}, err } if !r.OK { diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index c18c1ce97..4fc1a3ede 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -123,12 +123,14 @@ export const FakePlugin = async ({ client }) => ({ ], // $FAKE_LOOPBACK: the page comes back to a port here, as Devin's // and Kiro's plugins sign in - authorize: async (inputs) => process.env.FAKE_LOOPBACK ? loopbackSignIn(inputs) : ({ + // $FAKE_SIGNIN: the sign-in asks the vendor there, as a device + // sign-in asks for its code and trades it for the tokens (#1663) + authorize: async (inputs) => process.env.FAKE_LOOPBACK ? loopbackSignIn(inputs) : (process.env.FAKE_SIGNIN && (await fetch(process.env.FAKE_SIGNIN + "/device").catch(() => {})), { url: "https://fake.invalid/auth?where=" + inputs.where, instructions: "Paste the code", method: "code", callback: async (code) => - code === "good" + (process.env.FAKE_SIGNIN && (await fetch(process.env.FAKE_SIGNIN + "/token").catch(() => {})), code === "good") ? { type: "success", refresh: "r-" + (inputs.team ?? "none"), access: "stale", expires: 0, ...fakeWho(inputs.team) } : code === "expired" ? { type: "failed", error: "the sign-in page expired" } diff --git a/internal/provider/claude_signin.go b/internal/provider/claude_signin.go index 18d09437d..29aa524db 100644 --- a/internal/provider/claude_signin.go +++ b/internal/provider/claude_signin.go @@ -160,7 +160,8 @@ func startClaudeSignIn(s *signInFlow) error { ctx, cancel := context.WithCancel(context.Background()) cmd := cli.command(ctx, "auth", "login", "--claudeai") cmd.Dir = dir - cmd.Env = cli.env(netproxy.Env(env)) + // through the proxy the account's requests will go through (#1663) + cmd.Env = cli.env(netproxy.EnvWith(s.proxy, env)) in, err := cmd.StdinPipe() if err != nil { cancel() @@ -210,7 +211,7 @@ func startClaudeSignIn(s *signInFlow) error { msg = tail[n-1] } if err == nil { - l, lerr := claudeSignedIn(cli, dir) + l, lerr := claudeSignedIn(cli, dir, s.proxy) if lerr == nil { var using bool if using, lerr = addLogin(l); lerr == nil { @@ -286,8 +287,8 @@ func isLoopback(host string) bool { // claudeSignedIn is the account `claude auth login` signed in to in config // directory dir, as magpie keeps it: the sign-in Claude Code kept, and who -// it says that is. -func claudeSignedIn(cli claudeCLI, dir string) (savedLogin, error) { +// it says that is, asked through the sign-in's proxy. +func claudeSignedIn(cli claudeCLI, dir, proxy string) (savedLogin, error) { c, ok := readClaudeDir(dir) if !ok { return savedLogin{}, errors.New("Claude Code signed in, but kept no sign-in magpie can read") @@ -296,7 +297,7 @@ func claudeSignedIn(cli claudeCLI, dir string) (savedLogin, error) { defer cancel() cmd := cli.probe(ctx, "auth", "status", "--json") cmd.Dir = dir - cmd.Env = cli.env(claudeSignInEnv(os.Environ(), dir)) + cmd.Env = cli.env(netproxy.EnvWith(proxy, claudeSignInEnv(os.Environ(), dir))) b, _ := cmd.Output() var status struct { Email string `json:"email"` diff --git a/internal/provider/commandcode_plan.go b/internal/provider/commandcode_plan.go index cecffd392..6e92b5439 100644 --- a/internal/provider/commandcode_plan.go +++ b/internal/provider/commandcode_plan.go @@ -780,7 +780,7 @@ func (s *signInFlow) commandCodeCallback(w http.ResponseWriter, r *http.Request) answer(false, "this sign-in is already finishing") return } - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + ctx, cancel := context.WithTimeout(s.via(r.Context()), 30*time.Second) defer cancel() // the browser comes back for its page after this: the server stays up // a while for it, where finish would close it within a second @@ -848,7 +848,7 @@ func (s *signInFlow) commandCodeKey(raw string) error { if !s.claim() { return errors.New("this sign-in is already finishing") } - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cancel := context.WithTimeout(s.via(context.Background()), 30*time.Second) defer cancel() return s.commandCodeKeep(ctx, cmdAuth{APIKey: key}, false) } diff --git a/internal/provider/copilot_signin.go b/internal/provider/copilot_signin.go index dd38600d3..7695cb87a 100644 --- a/internal/provider/copilot_signin.go +++ b/internal/provider/copilot_signin.go @@ -63,7 +63,7 @@ func startCopilotSignIn(s *signInFlow) error { if err != nil { return err } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(s.via(context.Background())) var dc struct { DeviceCode string `json:"device_code"` UserCode string `json:"user_code"` diff --git a/internal/provider/factory_signin.go b/internal/provider/factory_signin.go index 3043ed265..d15a61fca 100644 --- a/internal/provider/factory_signin.go +++ b/internal/provider/factory_signin.go @@ -26,7 +26,7 @@ import ( ) func startFactorySignIn(s *signInFlow) error { - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(s.via(context.Background())) dctx, dcancel := context.WithTimeout(ctx, 30*time.Second) var dc struct { DeviceCode string `json:"device_code"` diff --git a/internal/provider/grok.go b/internal/provider/grok.go index c52a8a41b..b3c2b78fd 100644 --- a/internal/provider/grok.go +++ b/internal/provider/grok.go @@ -879,7 +879,7 @@ func runCLISignIn(s *signInFlow, what string, env []string, using bool, failed f ctx, cancel := context.WithCancel(context.Background()) cmd := proc.CommandContext(ctx, path, args...) cmd.Dir, _ = os.UserHomeDir() - cmd.Env = netproxy.Env(env) + cmd.Env = netproxy.EnvWith(s.proxy, env) out, err := cmd.StdoutPipe() if err != nil { cancel() diff --git a/internal/provider/kiro_signin.go b/internal/provider/kiro_signin.go index 31a46f1c7..8b42500ac 100644 --- a/internal/provider/kiro_signin.go +++ b/internal/provider/kiro_signin.go @@ -157,7 +157,7 @@ func (s *signInFlow) kiroCallback(w http.ResponseWriter, r *http.Request) { return } k := s.kiro - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + ctx, cancel := context.WithTimeout(s.via(r.Context()), 30*time.Second) defer cancel() var saved kiroSaved switch { diff --git a/internal/provider/mimo_signin.go b/internal/provider/mimo_signin.go index 35d770ddf..3044d88c3 100644 --- a/internal/provider/mimo_signin.go +++ b/internal/provider/mimo_signin.go @@ -110,7 +110,7 @@ func mimoAccountGet(ctx context.Context, client *http.Client, u, deviceID string func startMiMoSignIn(s *signInFlow) error { base := mimoBaseOf(mimoDefaultRegion) deviceID := mimoDeviceID() - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(s.via(context.Background())) start, stop := context.WithTimeout(ctx, 20*time.Second) defer stop() sid, callback := mimoServiceOf(start, base) diff --git a/internal/provider/pluginsignin.go b/internal/provider/pluginsignin.go index e3cdf5617..345f3cc31 100644 --- a/internal/provider/pluginsignin.go +++ b/internal/provider/pluginsignin.go @@ -20,11 +20,20 @@ import ( // is. A built-in moved onto its plugin installs the CLI it runs through // first, as the built-in's sign-in did. func StartPluginSignIn(id string, method int, inputs map[string]string) (SignInState, error) { + return StartPluginSignInWith(id, method, inputs, SignInOptions{}) +} + +// StartPluginSignInWith is StartPluginSignIn through the proxy o picks, +// else the one the provider's requests go through (#1663). +func StartPluginSignInWith(id string, method int, inputs map[string]string, o SignInOptions) (SignInState, error) { if settings.AccountDiscoveryOff() { return SignInState{}, errAccountDiscoveryOff } s := &signInFlow{done: make(chan struct{})} - s.st = SignInState{ID: randomToken(9), Agent: PluginID(id), State: "waiting"} + if err := s.pickProxy(PluginID(id), o); err != nil { + return SignInState{}, err + } + s.st = SignInState{ID: randomToken(9), Agent: PluginID(id), State: "waiting", Proxy: s.proxy} var cli agentCLI install := false if Moved(s.st.Agent) { @@ -73,7 +82,7 @@ var pluginRunsCLI = map[string]bool{"grok": true} // pluginBegin asks the plugin for the page to open and waits for the // sign-in to finish there, or for the code the page shows. func (s *signInFlow) pluginBegin(id string, method int, inputs map[string]string) error { - ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + ctx, cancel := context.WithTimeout(s.via(context.Background()), time.Minute) a, err := plugin.Authorize(ctx, id, method, inputs, plugin.NewAccount) cancel() if err != nil { @@ -169,7 +178,8 @@ func PluginAPIKey(ctx context.Context, id string, method int, inputs map[string] if strings.TrimSpace(key) == "" { return "", errors.New("enter the key") } - saved, err := plugin.APIKey(ctx, id, method, inputs, strings.TrimSpace(key), plugin.NewAccount) + // through the proxy the provider's requests go through (#1663) + saved, err := plugin.APIKey(Via(ctx, PluginID(id)), id, method, inputs, strings.TrimSpace(key), plugin.NewAccount) if err != nil { return "", err } diff --git a/internal/provider/proxy.go b/internal/provider/proxy.go index 4c0236f8b..ad305962c 100644 --- a/internal/provider/proxy.go +++ b/internal/provider/proxy.go @@ -2,7 +2,10 @@ package provider import ( "context" + "errors" "fmt" + "maps" + "slices" "strings" "github.com/yetone/magpie/internal/netproxy" @@ -132,6 +135,57 @@ func keyProxies(p Provider) map[string]string { return out } +// keepSignInProxy keeps the proxy an account of the subscription id was +// signed in through, picked for that sign-in, as the one its requests go +// through (#1663): the subscription's when the account is its only one, +// as the editor shows one account's proxy, else the account's own. +func keepSignInProxy(id, user, proxy string) error { + proxy = strings.TrimSpace(proxy) + if err := settings.CheckProxy(proxy); err != nil { + return err + } + if ProxyOfLogin(id, user) == proxy { + return nil + } + alone := true + for _, l := range Logins(id) { + if user == "" || accountKey(l.User) != accountKey(user) { + alone = false + } + } + f, err := read() + if err != nil { + return err + } + i := slices.IndexFunc(f.Providers, func(p Provider) bool { return p.ID == id }) + if i < 0 { + f.Providers = append(f.Providers, Provider{ID: id}) + i = len(f.Providers) - 1 + } + p := &f.Providers[i] + own := maps.Clone(p.AccountProxies) + if own == nil { + own = map[string]string{} + } + switch { + case alone: + p.Proxy = proxy + delete(own, accountKey(user)) + case user == "": + return errors.New("the account it signed in to isn't known") + case proxy == p.Proxy: + delete(own, accountKey(user)) + case proxy == "": + // an account's own can't say "the global one": "" follows the + // subscription's + return errors.New("an account can't follow the global proxy while its subscription has a proxy of its own") + default: + own[accountKey(user)] = proxy + } + p.AccountProxies = normalAccountProxies(own) + return store(f) +} + // checkAccountProxies refuses an account's proxy Settings would refuse. func checkAccountProxies(m map[string]string) error { for u, v := range m { diff --git a/internal/provider/qoder.go b/internal/provider/qoder.go index ad374a291..fc1032a72 100644 --- a/internal/provider/qoder.go +++ b/internal/provider/qoder.go @@ -535,7 +535,7 @@ func startQoderSignIn(s *signInFlow, site *qoder.Site) error { if err != nil { return fmt.Errorf("%s sign-in: %w", site.Name, err) } - ctx, cancel := context.WithDeadline(context.Background(), fl.deadline) + ctx, cancel := context.WithDeadline(s.via(context.Background()), fl.deadline) s.mu.Lock() s.st.URL, s.stop = authURL, cancel s.mu.Unlock() diff --git a/internal/provider/signin.go b/internal/provider/signin.go index af18b39b8..9a9646334 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -27,6 +27,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/settings" ) @@ -69,6 +70,9 @@ type SignInState struct { // than a new account added (#413) Again bool `json:"again,omitempty"` Error string `json:"error,omitempty"` + // Proxy is the one the sign-in goes through ("" the global one, + // "direct" none): the one the account's requests will (#1663) + Proxy string `json:"proxy,omitempty"` } type signInFlow struct { @@ -97,6 +101,49 @@ type signInFlow struct { // sign-in done reads as done once the account is shown again finished bool done chan struct{} + + // proxy is the one the sign-in's requests go through, as netproxy.With + // takes it: the one the account's will go through once it is signed in + // (ProxyOfLogin), or the one picked for it (chosen), which is kept as + // the account's once it is done (#1663) + proxy string + chosen bool + // user is the account signed in to again, "" for a new one + user string +} + +// SignInOptions are a sign-in's choices beyond its subscription. +type SignInOptions struct { + Site string // where to sign in, for one with more than one (StartSignInAt) + // Proxy is the one to sign in through, as netproxy.With takes it ("" the + // global one, "direct" none, or its address); nil for the one the + // account's requests would go through. Picked, it is kept as the + // account's own once the sign-in is done. + Proxy *string + // User is the account signed in to again, for the proxy it goes through + User string +} + +// via is ctx for the sign-in's requests: through its proxy, so the vendor +// sees an account signed in from where its requests will come from, not +// signed in through the global proxy and used through its own (#1663). +func (s *signInFlow) via(ctx context.Context) context.Context { + return netproxy.With(ctx, s.proxy) +} + +// pickProxy sets the proxy a sign-in to agent goes through. +func (s *signInFlow) pickProxy(agent string, o SignInOptions) error { + s.user = strings.TrimSpace(o.User) + s.proxy = ProxyOfLogin(agent, s.user) + if o.Proxy == nil { + return nil + } + p := strings.TrimSpace(*o.Proxy) + if err := settings.CheckProxy(p); err != nil { + return err + } + s.proxy, s.chosen = p, true + return nil } var signIns = struct { @@ -124,6 +171,13 @@ func StartSignIn(agent string) (SignInState, error) { // StartSignInAt is StartSignIn on one of the sites an agent signs in on: // ZCode's "zai" (the default) or "bigmodel". func StartSignInAt(agent, site string) (SignInState, error) { + return StartSignInWith(agent, SignInOptions{Site: site}) +} + +// StartSignInWith is StartSignIn with the sign-in's choices: its site and +// the proxy it goes through. +func StartSignInWith(agent string, o SignInOptions) (SignInState, error) { + site := o.Site if settings.AccountDiscoveryOff() { return SignInState{}, errAccountDiscoveryOff } @@ -133,7 +187,10 @@ func StartSignInAt(agent, site string) (SignInState, error) { return SignInState{}, fmt.Errorf("%s runs on its plugin: sign in through the plugin (magpie plugin login %s)", agent, agent) } s := &signInFlow{verifier: randomToken(48), state: randomToken(24), done: make(chan struct{}), site: site} - s.st = SignInState{ID: randomToken(9), Agent: agent, State: "waiting"} + if err := s.pickProxy(agent, o); err != nil { + return SignInState{}, err + } + s.st = SignInState{ID: randomToken(9), Agent: agent, State: "waiting", Proxy: s.proxy} cli, install := missingCLI(agent) var installing context.Context if install { @@ -569,13 +626,19 @@ func (s *signInFlow) finish(out SignInState) bool { } s.finished = true if out.State == "done" { - agent := s.st.Agent + agent, proxy, chosen := s.st.Agent, s.proxy, s.chosen s.mu.Unlock() // signing in again brings back an account removed from magpie _ = ShowAccount(agent) + if chosen { + // the proxy picked for it is the account's from now on + if err := keepSignInProxy(agent, out.User, proxy); err != nil { + out.Error = "signed in, but its proxy wasn't kept: " + err.Error() + } + } s.mu.Lock() } - out.ID, out.Agent, out.URL, out.Code = s.st.ID, s.st.Agent, s.st.URL, s.st.Code + out.ID, out.Agent, out.URL, out.Code, out.Proxy = s.st.ID, s.st.Agent, s.st.URL, s.st.Code, s.st.Proxy s.st = out stop, srv := s.stop, s.srv s.mu.Unlock() @@ -635,7 +698,7 @@ func (s *signInFlow) callback(w http.ResponseWriter, r *http.Request) { signInPage(w, false, "This sign-in is already finishing", "magpie shows the account when it's done.") return } - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + ctx, cancel := context.WithTimeout(s.via(r.Context()), 30*time.Second) defer cancel() if app, ok := googleAppOf(s.st.Agent); ok { s.googleDone(ctx, w, app, q.Get("code")) diff --git a/internal/provider/signin_claude_test.go b/internal/provider/signin_claude_test.go index f7cf7bba8..8594da6f4 100644 --- a/internal/provider/signin_claude_test.go +++ b/internal/provider/signin_claude_test.go @@ -55,6 +55,8 @@ if [ "$1 $2" = "auth status" ]; then %s fi [ "$1 $2" = "auth login" ] || exit 2 +# the proxy it was run with, beside it (#1663) +printf '%%s' "$HTTPS_PROXY" > "${0%%/*}/login-proxy" echo "Opening browser to sign in…" "$BROWSER" '%s' echo "If the browser didn't open, visit: %s" diff --git a/internal/provider/signin_proxy_test.go b/internal/provider/signin_proxy_test.go new file mode 100644 index 000000000..a2623285e --- /dev/null +++ b/internal/provider/signin_proxy_test.go @@ -0,0 +1,267 @@ +package provider + +import ( + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/testenv" +) + +// setProxies gives subscription id a proxy of its own, and its accounts +// theirs, as the editor saves them. +func setProxies(t *testing.T, id, proxy string, own map[string]string) { + t.Helper() + f, err := read() + if err != nil { + t.Fatal(err) + } + f.Providers = slices.DeleteFunc(f.Providers, func(p Provider) bool { return p.ID == id }) + f.Providers = append(f.Providers, Provider{ID: id, Proxy: proxy, AccountProxies: own}) + if err := store(f); err != nil { + t.Fatal(err) + } +} + +// codexVendorProxy is a proxy that answers Codex's token exchange itself, +// as OpenAI would, the code naming the account; it tells what it was +// asked. +func codexVendorProxy(t *testing.T) (*httptest.Server, func() []string) { + t.Helper() + var mu sync.Mutex + var seen []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + seen = append(seen, r.URL.String()) + mu.Unlock() + r.ParseForm() + user := r.Form.Get("code") + "@example.com" + json.NewEncoder(w).Encode(map[string]any{ + "id_token": fakeJWT(map[string]any{"email": user, + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "plus", "chatgpt_account_id": "acct-" + user}}), + "access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}), + "refresh_token": "r-" + user, + }) + })) + t.Cleanup(srv.Close) + return srv, func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(seen) + } +} + +// #1663 (demystify0137): an account is signed in through the proxy its +// requests will go through, the subscription's, not the global one, so the +// vendor sees it come from one place. A proxy picked for the sign-in is +// kept as the account's: the subscription's for its only account, else +// that account's own. +func TestSignInGoesThroughItsProxy(t *testing.T) { + claudeHome(t) + dialed := dialsOut(t) + sub, subSaw := codexVendorProxy(t) + other, otherSaw := codexVendorProxy(t) + oldTok, oldAddr := codexTokenURL, codexCallbackAddr + t.Cleanup(func() { codexTokenURL, codexCallbackAddr = oldTok, oldAddr }) + codexTokenURL = "http://auth.openai.invalid/oauth/token" + ln, _ := net.Listen("tcp", "127.0.0.1:0") + codexCallbackAddr = ln.Addr().String() + ln.Close() + const token = "http://auth.openai.invalid/oauth/token" + + signIn := func(o SignInOptions, code string) SignInState { + t.Helper() + st, err := StartSignInWith("codex", o) + if err != nil { + t.Fatal(err) + } + finishInBrowser(t, st, code) + if st = waitDone(t, st.ID); st.State != "done" || st.User != code+"@example.com" || st.Error != "" { + t.Fatalf("state %+v", st) + } + time.Sleep(1200 * time.Millisecond) // the callback port is let go + return st + } + stored := func() Provider { + t.Helper() + p, _ := storedPicks("codex") + return p + } + + // the first account, through a proxy picked for it: the subscription's + // from now on, as its only account's proxy is + pick := sub.URL + if st := signIn(SignInOptions{Proxy: &pick}, "a"); st.Proxy != sub.URL { + t.Fatalf("the sign-in says it goes through %q", st.Proxy) + } + if got := subSaw(); !slices.Equal(got, []string{token}) { + t.Fatalf("the picked proxy saw %q", got) + } + if p := stored(); p.Proxy != sub.URL || len(p.AccountProxies) != 0 { + t.Fatalf("kept as proxy %q, accounts' %v", p.Proxy, p.AccountProxies) + } + + // the next, picked nothing: through the subscription's, where it went + // through the global one + if st := signIn(SignInOptions{}, "b"); st.Proxy != sub.URL { + t.Fatalf("the sign-in says it goes through %q", st.Proxy) + } + if got := subSaw(); !slices.Equal(got, []string{token, token}) { + t.Fatalf("the subscription's proxy saw %q", got) + } + + // one more, through another: that account's own, the others' left + pick = other.URL + signIn(SignInOptions{Proxy: &pick}, "c") + if got := otherSaw(); !slices.Equal(got, []string{token}) { + t.Fatalf("the picked proxy saw %q", got) + } + if p := stored(); p.Proxy != sub.URL || len(p.AccountProxies) != 1 || p.AccountProxies["c@example.com"] != other.URL { + t.Fatalf("kept as proxy %q, accounts' %v", p.Proxy, p.AccountProxies) + } + if got := ProxyOfLogin("codex", "C@example.com"); got != other.URL { + t.Fatalf("c's requests go through %q", got) + } + + // signing in to it again goes through its own + st, err := StartSignInWith("codex", SignInOptions{User: "c@example.com"}) + if err != nil { + t.Fatal(err) + } + CancelSignIn(st.ID) + if st.Proxy != other.URL { + t.Fatalf("signing c in again goes through %q", st.Proxy) + } + if d := dialed(); len(d) != 0 { + t.Fatalf("dialed %v past the proxies", d) + } + + // a proxy that isn't one is refused before anything starts + bad := "ftp://x" + if _, err := StartSignInWith("codex", SignInOptions{Proxy: &bad}); err == nil { + t.Fatal("ftp://x was taken as a proxy") + } +} + +// A device sign-in run by magpie (Copilot's: the code asked for, then +// polled for the token, then whose account it is) goes through the +// subscription's proxy from its first request (#1663). +func TestDeviceSignInGoesThroughItsProxy(t *testing.T) { + signIn(t) + dialed := dialsOut(t) + var mu sync.Mutex + var seen []string + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + seen = append(seen, r.URL.Path) + mu.Unlock() + switch r.URL.Path { + case "/login/device/code": + json.NewEncoder(w).Encode(map[string]any{"device_code": "dc", "user_code": "ABCD-1234", "verification_uri": "https://github.com/login/device", "interval": 0}) + case "/login/oauth/access_token": + json.NewEncoder(w).Encode(map[string]any{"access_token": "gho_p"}) + case "/user": + json.NewEncoder(w).Encode(map[string]any{"login": "proxied"}) + case "/copilot_internal/user": + json.NewEncoder(w).Encode(map[string]any{"copilot_plan": "individual"}) + default: + w.WriteHeader(404) + } + })) + t.Cleanup(proxy.Close) + const gh = "http://github.invalid" + oldDev, oldTok, oldCU, oldGU := gitHubDeviceURL, gitHubTokenURL, CopilotUserURL, GitHubUserURL + gitHubDeviceURL, gitHubTokenURL = gh+"/login/device/code", gh+"/login/oauth/access_token" + CopilotUserURL, GitHubUserURL = gh+"/copilot_internal/user", gh+"/user" + t.Cleanup(func() { gitHubDeviceURL, gitHubTokenURL, CopilotUserURL, GitHubUserURL = oldDev, oldTok, oldCU, oldGU }) + setProxies(t, "copilot", proxy.URL, nil) + + st, err := StartSignIn("copilot") + if err != nil { + t.Fatal(err) + } + if st = waitDone(t, st.ID); st.State != "done" || st.User != "proxied" { + t.Fatalf("state %+v", st) + } + mu.Lock() + got := slices.Clone(seen) + mu.Unlock() + if len(got) < 3 || got[0] != "/login/device/code" || !slices.Contains(got, "/login/oauth/access_token") || !slices.Contains(got, "/user") { + t.Fatalf("the subscription's proxy saw %q", got) + } + if d := dialed(); len(d) != 0 { + t.Fatalf("dialed %v past the proxy", d) + } +} + +// A plugin's sign-in goes through its provider's proxy too: the plugin's +// requests while it authorizes, and when it trades the code pasted back +// (#1663). +func TestPluginSignInGoesThroughItsProxy(t *testing.T) { + bun := testenv.Bun(t) + claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("FAKE_SIGNIN", "http://vendor.invalid/signin") + t.Cleanup(plugin.Settle) + var mu sync.Mutex + var seen []string + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + seen = append(seen, r.URL.String()) + mu.Unlock() + })) + t.Cleanup(proxy.Close) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + setProxies(t, "fakeco", proxy.URL, nil) + st, err := StartPluginSignIn("fakeco", 1, map[string]string{"where": "home"}) + if err != nil || st.Proxy != proxy.URL { + t.Fatalf("StartPluginSignIn = %+v, %v", st, err) + } + if err := SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if !slices.Equal(seen, []string{"http://vendor.invalid/signin/device", "http://vendor.invalid/signin/token"}) { + t.Fatalf("the provider's proxy saw %q", seen) + } +} + +// Claude Code's own sign-in is run with the subscription's proxy, where it +// was run with the global one (#1663). +func TestClaudeSignInGoesThroughItsProxy(t *testing.T) { + claudeHome(t) + noAnthropic(t) + exe := fakeClaudeLogin(t, fakeClaudeAccount{email: "p@example.com", name: "P", plan: "max", refresh: "sk-ant-ort01-p"}, "", true) + setProxies(t, "claude", "http://127.0.0.1:9", 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) + } + b, _ := os.ReadFile(filepath.Join(filepath.Dir(exe), "login-proxy")) + if strings.TrimRight(string(b), "/") != "http://127.0.0.1:9" { + t.Fatalf("claude auth login ran with HTTPS_PROXY=%q", b) + } +} diff --git a/internal/provider/workbuddy.go b/internal/provider/workbuddy.go index 1c92158a7..c7274e7ab 100644 --- a/internal/provider/workbuddy.go +++ b/internal/provider/workbuddy.go @@ -773,7 +773,7 @@ func wbCallVia(ctx context.Context, do func(*http.Request) (*http.Response, erro // app asks for a state and a page, opens the page for the user to sign in, // then polls for the token and the account. func startWorkBuddySignIn(s *signInFlow, w *wbSite) error { - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(s.via(context.Background())) var state struct { State string `json:"state"` AuthURL string `json:"authUrl"` diff --git a/internal/provider/zcode.go b/internal/provider/zcode.go index af622e1f6..815b456ec 100644 --- a/internal/provider/zcode.go +++ b/internal/provider/zcode.go @@ -713,7 +713,7 @@ func startZCodeSignIn(s *signInFlow, site string) error { if site != "bigmodel" { site = "zai" } - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(s.via(context.Background())) b := make([]byte, 32) _, _ = rand.Read(b) poll := "Bearer " + hex.EncodeToString(b) diff --git a/internal/provider/zed_signin.go b/internal/provider/zed_signin.go index 86440fc2b..e3527efc4 100644 --- a/internal/provider/zed_signin.go +++ b/internal/provider/zed_signin.go @@ -63,7 +63,7 @@ func startZedSignIn(s *signInFlow) error { http.Redirect(w, r, zedSite+"/native_app_signin_succeeded", http.StatusFound) }) srv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(s.via(context.Background())) s.mu.Lock() s.st.URL = zed.SignInURL(zedSite, port, pub, systemID) s.srv, s.stop = srv, cancel diff --git a/plugins_cli.go b/plugins_cli.go index 7bb58e04c..aea0f91ce 100644 --- a/plugins_cli.go +++ b/plugins_cli.go @@ -410,6 +410,8 @@ func pluginLogin(ctx context.Context, name, method string) error { fmt.Println(msg) } } + // signed in through the proxy its requests will go through (#1663) + ctx = provider.Via(ctx, provider.PluginID(pp.ID)) var saved plugin.Saved if pp.Methods[m].Type == "api" { key, err := secret("key", keyPrompt(pp.Name, pp.Methods[m]), false)