provider, plugin: a subscription's sign-in goes through the proxy its account's requests use, not always the global one (#1663, demystify0137)

What changed: every sign-in started in magpie now leaves through the
account's own proxy (ProxyOfLogin: the account's, else the
subscription's, else the global one). Before, the sign-in's token
exchange and checks went through the global proxy while the account's
later refresh and usage calls went through its own (ViaLogin), so the
vendor saw one account come from two exits.

- signin.go: SignInOptions{Site, Proxy, User}, StartSignInWith; the flow
  picks its proxy (pickProxy, validated with settings.CheckProxy) and
  every request goes through s.via. Each built-in sign-in (Claude,
  Codex/ChatGPT, Grok, Zed, WorkBuddy, Copilot, ZCode, Factory, MiMo,
  Qoder, Command Code, Kiro) uses s.via; Claude Code's own login gets the
  proxy as *_PROXY (netproxy.EnvWith).
- proxy.go keepSignInProxy: a proxy picked for the sign-in is kept as
  the subscription's when the account is its only one, else as that
  account's own entry. "" (global) is refused while the subscription has
  a proxy and other accounts, since nothing could keep it.
- plugin host: authorize and callback run under via.run(proxy), so a
  plugin's sign-in fetches go through the same proxy; plugins_cli.go
  does the same for `magpie plugins login`. PluginAPIKey goes through Via.
- gui: POST /api/signin and /api/plugin-signin take proxy and user.

What was run:
- go test -tags nogui ./... (sandbox HOME), all packages ok.
- gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui on the
  touched packages.
- Red without the change (each broken by hand, then restored):
  TestSignInGoesThroughItsProxy, TestDeviceSignInGoesThroughItsProxy,
  TestPluginSignInGoesThroughItsProxy, TestClaudeSignInGoesThroughItsProxy
  (internal/provider) and TestPluginSignInProxy (internal/plugin) each
  fail with the s.via / EnvWith / via.run / keepSignInProxy removed.

Not tried: a real vendor account through a real proxy. The browser's own
leg of an OAuth sign-in goes through the browser's network, not magpie's.
Devin's CLI probes still use the global proxy.
This commit is contained in:
yetone
2026-10-12 02:47:08 +08:00
parent f38f65030c
commit 3a53d06d99
23 changed files with 501 additions and 41 deletions
+4 -2
View File
@@ -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
+8 -2
View File
@@ -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
+10 -6
View File
@@ -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) }
}
+45
View File
@@ -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
+8 -6
View File
@@ -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 {
+4 -2
View File
@@ -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" }
+6 -5
View File
@@ -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"`
+2 -2
View File
@@ -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)
}
+1 -1
View File
@@ -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"`
+1 -1
View File
@@ -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"`
+1 -1
View File
@@ -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()
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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)
+13 -3
View File
@@ -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
}
+54
View File
@@ -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 {
+1 -1
View File
@@ -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()
+67 -4
View File
@@ -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"))
+2
View File
@@ -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"
+267
View File
@@ -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)
}
}
+1 -1
View File
@@ -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"`
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
+2
View File
@@ -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)