Go's http.Client follows up to 10 redirects to any host, https to http included, and on a hop to another domain drops only Authorization, Cookie and WWW-Authenticate. So a vendor (or anything answering at its URL) that redirected elsewhere got x-api-key, x-goog-api-key, api-key and a provider's own headers sent there; Authorization too when only the port differed, and all of them in the clear on an https to http hop on the same host. The class is fixed where the requests leave: - provider.KeepsCredentials is a CheckRedirect that follows a redirect only to the request's own origin (scheme, host, port; or http to https on the same host and default ports), at most 10, and gives any other 3xx back as the answer (http.ErrUseLastResponse). - provider.Keyed(c) is a copy of c with c's own CheckRedirect, then KeepsCredentials. Provider.do, the choke point of every p.Do, sends through it, and every http.DefaultClient.Do in internal/provider that carries a credential is Keyed(http.DefaultClient).Do. A copy per call, since netproxy.Install sets the default client's transport at run time. Left alone: Grok's public download, Antigravity's version URL and cline.go's unsigned read. - the gateway's client (s.client, every vendor call), the Codex relay's and the Codex websocket's take KeepsCredentials, and so does chatgpt_api's siwcClient. The native route needs nothing more: the vendor's 3xx comes back to the caller as it came, Location included, and the caller decides. Translated routes don't follow either, rather than following with credentials stripped: it is the rule search_api.go had already (#1580), no vendor magpie speaks to was found redirecting its API to another origin, a stripped request elsewhere would only fail with a confusing 401, and the vendor-URL downloads (video, images) are fetched unsigned through vendorClient, so they are not affected. Tests: TestRedirectKeepsTheKeyAtItsOrigin (307 and 302 elsewhere with Authorization, x-api-key, x-goog-api-key, api-key and a custom header; a same-origin redirect followed with every key; three clients), TestRedirectNeverDowngrades (an https vendor's redirect to http on its own host and port), TestSameOrigin, TestKeyedKeepsTheClientsRule, TestNativeRedirectKeepsTheKey (Anthropic and Gemini providers with an own header) and TestChatRedirectKeepsTheKey. Broken by hand: with Provider.do back on client.Do and s.client without CheckRedirect, the thief got every key header, /away answered 200, the https vendor's /plain was followed (400 from the TLS port spoken to in http), the native route's claudeish and gem answered the thief's {"stolen":true} with Authorization, X-Api-Key and X-Relay-Secret sent there, and the chat route sent Api-Key, Authorization and X-Relay-Secret to it. TestSameOrigin and TestKeyedKeepsTheClientsRule don't depend on the wiring and passed. Run on mote at the pushed head 883690a0b (this commit and the next, on origin/main9a0aab32c): gofmt -l clean, go vet, GOOS=windows go vet and GOOS=linux -tags nogui go vet all clean. go test ./... -timeout 45m -count=1: 84 packages ok, including internal/gateway. 3 red, each filed and none in this change's path: - TestMainWindowCorners/macOS_26_SDK (gui, macOS 27, #3949) - TestRenewLoginsKeepsClaudeReading (provider, #5481). It is red 3 of 3 at the base49c9491b7without either commit. - TestHostEndedEndsWhatItsPluginStarted/own_end (plugin, a 30s wait in a full run; passes 3 of 3 alone at this head, #5515) This commit alone, at its first base49c9491b7, ran the same way with TestUnroutedHeldReportSaved (gateway, #4300) red besides. Rebased then onto origin/main303a31dd6(which fixed #5481) and run again at that tree: gofmt and the three vets clean, and internal/gateway, internal/provider, internal/plugin and internal/netproxy all ok. Rebased on19c45d5d4, which changes gateway.go (kept_error), Codex's usage_limit_reached, Cursor's mover min, sessions and the GUI; ran gofmt, go vet ./internal/..., GOOS=windows go vet of gateway and provider, and go test ./internal/gateway ./internal/provider: both ok. Rebased on94d4866b5, which changes only internal/sessions; ran gofmt, go vet of gateway, provider and sessions, and this change's own tests (-run Redirect|DropsProxyIdentity|SameOrigin|Keyed): ok. Rebased oncd77c725d, which changes only internal/provider's check-in; ran gofmt, go vet of gateway and provider, and this change's own tests again: ok. Not tried: a real vendor's redirect (none found that does), and the plugin host's fetch (host.js; Bun follows redirects by default), which is filed as #5508.
257 lines
8.0 KiB
Go
257 lines
8.0 KiB
Go
package provider
|
|
|
|
// The standalone Copilot CLI keeps its sign-in apart from the editors: who
|
|
// is signed in in ~/.copilot/config.json, the token in the system keychain
|
|
// (service copilot-cli), or in that file when the user chose plaintext. Its
|
|
// token is not traded for a session token the way an editor's is (that
|
|
// exchange answers 403): the CLI sends it as is, under its own integration.
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/tidwall/jsonc"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
"github.com/yetone/magpie/internal/proc"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// copilotCLIHeaders are what the CLI sends with its token.
|
|
var copilotCLIHeaders = map[string]string{
|
|
"Editor-Version": "copilot/1.0.88",
|
|
"Copilot-Integration-Id": "copilot-developer-cli",
|
|
"X-GitHub-Api-Version": "2026-07-01",
|
|
"User-Agent": "copilot/1.0.88",
|
|
}
|
|
|
|
// CopilotUserURL says where an account's Copilot API is; a var so tests can
|
|
// point it elsewhere.
|
|
var CopilotUserURL = "https://api.github.com/copilot_internal/user"
|
|
|
|
type copilotCLIUser struct {
|
|
Host string `json:"host"`
|
|
Login string `json:"login"`
|
|
}
|
|
|
|
// copilotCLIHome is where the CLI keeps its settings.
|
|
func copilotCLIHome() string {
|
|
if h := appdir.Getenv("COPILOT_HOME"); h != "" {
|
|
return h
|
|
}
|
|
home, _ := os.UserHomeDir()
|
|
return filepath.Join(home, ".copilot")
|
|
}
|
|
|
|
// CopilotWSLDirs, set by internal/agent, are the Copilot CLI's folders
|
|
// (~/.copilot), as magpie opens them, in the WSL distros that run now:
|
|
// magpie on Windows finds a Copilot CLI signed in inside one (#723,
|
|
// jia2). Where ~/.copilot is a link the folder is where it leads (#4502).
|
|
// nil, or none, off Windows. A stopped distro isn't in it: reading its
|
|
// files would start it.
|
|
var CopilotWSLDirs func() []string
|
|
|
|
// copilotWSLAge is how long a WSL distro's Copilot CLI sign-in is kept as
|
|
// read: its files are read over WSL's file share, slower than a disk's.
|
|
var copilotWSLAge = 20 * time.Second
|
|
|
|
var copilotWSL struct {
|
|
sync.Mutex
|
|
at time.Time
|
|
app copilotApp
|
|
ok bool
|
|
}
|
|
|
|
// copilotCLILogin is the account the Copilot CLI is signed in to, with its
|
|
// token: on this machine, or, for magpie on Windows, in a WSL distro that
|
|
// runs now. A distro's token is read only from its config.json, where the
|
|
// CLI keeps it when the distro has no keyring to put it in (WSL has none
|
|
// unless one is set up): magpie can't reach a distro's keyring.
|
|
func copilotCLILogin() (copilotApp, bool) {
|
|
if settings.AccountDiscoveryOff() {
|
|
return copilotApp{}, false
|
|
}
|
|
if app, ok := copilotCLILoginIn(copilotCLIHome(), copilotCLISecret); ok {
|
|
return app, true
|
|
}
|
|
if CopilotWSLDirs == nil {
|
|
return copilotApp{}, false
|
|
}
|
|
c := &copilotWSL
|
|
c.Lock()
|
|
defer c.Unlock()
|
|
if !c.at.IsZero() && time.Since(c.at) < copilotWSLAge {
|
|
return c.app, c.ok
|
|
}
|
|
c.app, c.ok = copilotApp{}, false
|
|
for _, dir := range CopilotWSLDirs() {
|
|
if app, ok := copilotCLILoginIn(dir, nil); ok {
|
|
c.app, c.ok = app, true
|
|
break
|
|
}
|
|
}
|
|
c.at = time.Now()
|
|
return c.app, c.ok
|
|
}
|
|
|
|
// copilotCLILoginIn is the account the Copilot CLI whose settings are in
|
|
// dir is signed in to, with its token: from its config.json, else from
|
|
// secret (the keychain), when given.
|
|
func copilotCLILoginIn(dir string, secret func(string) string) (copilotApp, bool) {
|
|
raw, err := readAccountFile(filepath.Join(dir, "config.json"))
|
|
if err != nil {
|
|
return copilotApp{}, false
|
|
}
|
|
var cfg struct {
|
|
Last *copilotCLIUser `json:"lastLoggedInUser"`
|
|
Users []copilotCLIUser `json:"loggedInUsers"`
|
|
Tokens map[string]string `json:"copilotTokens"`
|
|
}
|
|
if json.Unmarshal(jsonc.ToJSON(raw), &cfg) != nil {
|
|
return copilotApp{}, false
|
|
}
|
|
users := cfg.Users
|
|
if cfg.Last != nil {
|
|
users = append([]copilotCLIUser{*cfg.Last}, users...)
|
|
}
|
|
// a github.com account first, as before; then one an enterprise's
|
|
// `copilot login --host <name>.ghe.com` signed in (#723). A GitHub
|
|
// Enterprise Server's own host is left out: its API isn't GHE.com's.
|
|
for _, ghe := range []bool{false, true} {
|
|
for _, u := range users {
|
|
host, ok := copilotHostOf(u.Host)
|
|
if u.Login == "" || !ok || (host != "") != ghe {
|
|
continue
|
|
}
|
|
key := "https://github.com:" + u.Login
|
|
if ghe {
|
|
key = strings.TrimSuffix(u.Host, "/") + ":" + u.Login
|
|
}
|
|
tok := cfg.Tokens[key]
|
|
if tok == "" && secret != nil {
|
|
tok = secret(key)
|
|
}
|
|
if tok != "" {
|
|
return copilotApp{User: u.Login, Token: tok, Host: host, cli: true}, true
|
|
}
|
|
}
|
|
}
|
|
return copilotApp{}, false
|
|
}
|
|
|
|
var copilotSecrets struct {
|
|
sync.Mutex
|
|
at map[string]time.Time
|
|
tok map[string]string
|
|
}
|
|
|
|
// copilotCLISecret reads the CLI's token from the keychain, once in a
|
|
// while: each read may ask the user to allow it.
|
|
var copilotCLISecret = func(account string) string {
|
|
if settings.AccountDiscoveryOff() {
|
|
return ""
|
|
}
|
|
c := &copilotSecrets
|
|
c.Lock()
|
|
defer c.Unlock()
|
|
if c.at == nil {
|
|
c.at, c.tok = map[string]time.Time{}, map[string]string{}
|
|
}
|
|
ttl := time.Hour
|
|
if c.tok[account] == "" {
|
|
ttl = 10 * time.Minute // denied or absent; don't ask again at once
|
|
}
|
|
if at, ok := c.at[account]; ok && time.Since(at) < ttl {
|
|
return c.tok[account]
|
|
}
|
|
var out []byte
|
|
switch runtime.GOOS {
|
|
case "darwin":
|
|
out, _ = proc.Command("security", "find-generic-password", "-s", "copilot-cli", "-a", account, "-w").Output()
|
|
case "linux":
|
|
if p, err := exec.LookPath("secret-tool"); err == nil {
|
|
out = []byte(copilotSecretTool(p, account))
|
|
}
|
|
}
|
|
c.at[account], c.tok[account] = time.Now(), string(bytes.TrimSpace(out))
|
|
return c.tok[account]
|
|
}
|
|
|
|
// copilotSecretWait bounds one secret-tool lookup: a keyring that waits on
|
|
// a prompt nobody answers would hold the sign-in that asked (#723).
|
|
var copilotSecretWait = 5 * time.Second
|
|
|
|
// copilotSecretTool is the CLI's token in the Secret Service, as
|
|
// secret-tool (at path) finds it. The CLI before 1.0 (keytar, libsecret)
|
|
// keyed it by service and account; 1.0's own keyring store
|
|
// (zbus-secret-service-keyring-store) by service and username, so both
|
|
// are asked (#723).
|
|
func copilotSecretTool(path, account string) string {
|
|
for _, attr := range []string{"account", "username"} {
|
|
ctx, cancel := context.WithTimeout(context.Background(), copilotSecretWait)
|
|
cmd := proc.CommandContext(ctx, path, "lookup", "service", "copilot-cli", attr, account)
|
|
cmd.WaitDelay = time.Second
|
|
out, _ := cmd.Output()
|
|
cancel()
|
|
if tok := strings.TrimSpace(string(out)); tok != "" {
|
|
return tok
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// copilotDirect is the session a CLI token makes: the token itself, at the
|
|
// API its account is served from.
|
|
func copilotDirect(ctx context.Context, app copilotApp) (copilotSession, error) {
|
|
github := app.Token
|
|
copilotMu.Lock()
|
|
defer copilotMu.Unlock()
|
|
if s, ok := copilotSessions[github]; ok && time.Until(time.Unix(s.ExpiresAt, 0)) > 2*time.Minute {
|
|
return s, nil
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, copilotUserURL(app.Host), nil)
|
|
if err != nil {
|
|
return copilotSession{}, err
|
|
}
|
|
req.Header.Set("Authorization", "token "+github)
|
|
req.Header.Set("Accept", "application/json")
|
|
res, err := Keyed(http.DefaultClient).Do(req)
|
|
if err != nil {
|
|
return copilotSession{}, errors.New("Copilot sign-in: " + err.Error())
|
|
}
|
|
defer res.Body.Close()
|
|
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
|
var u struct {
|
|
Endpoints struct {
|
|
API string `json:"api"`
|
|
} `json:"endpoints"`
|
|
}
|
|
if res.StatusCode != 200 || json.Unmarshal(b, &u) != nil {
|
|
// 401 is GitHub refusing the token itself; a 403 here can be an
|
|
// account without Copilot, and a 5xx is GitHub's own trouble
|
|
if res.StatusCode == http.StatusUnauthorized {
|
|
copilotRefuse(github, res.StatusCode)
|
|
}
|
|
return copilotSession{}, errors.New("the Copilot CLI's sign-in was refused (" + APIError(b, res.Status) + "); run `copilot login` again")
|
|
}
|
|
copilotRefusals.Lock()
|
|
delete(copilotRefusals.at, github)
|
|
delete(copilotRefusals.status, github)
|
|
copilotRefusals.Unlock()
|
|
s := copilotSession{Token: github, ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), direct: true}
|
|
s.Endpoints.API = u.Endpoints.API
|
|
copilotSessions[github] = s
|
|
return s, nil
|
|
}
|