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.
175 lines
5.2 KiB
Go
175 lines
5.2 KiB
Go
package provider
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// A ChatGPT sign-in by device code, as `codex login --device-auth` does it
|
|
// (codex-rs login/src/device_code_auth.rs): magpie asks for a code, the
|
|
// user enters it on ChatGPT's device page in any browser, and magpie asks
|
|
// until the page is done. Nothing comes back to localhost:1455, so magpie
|
|
// on a server or in Docker, its window in a browser elsewhere, signs in
|
|
// with no address to copy back (curtinp118 on Discord).
|
|
|
|
// codexIssuer is where Codex's device sign-in is; a var so tests can point
|
|
// it elsewhere.
|
|
var codexIssuer = "https://auth.openai.com"
|
|
|
|
// CodexDeviceSite is the "site" of a ChatGPT sign-in by device code
|
|
// (StartSignInWith): the window asks for it when it is opened from
|
|
// another computer.
|
|
const CodexDeviceSite = "device"
|
|
|
|
// codexDeviceWait is how long Codex keeps a device code: 15 minutes.
|
|
var codexDeviceWait = 15 * time.Minute
|
|
|
|
// codexDevicePollMisses is how many failed polls in a row end the sign-in.
|
|
var codexDevicePollMisses = 5
|
|
|
|
// errCodexDeviceOff is the vendor turning device codes away for Codex's client.
|
|
var errCodexDeviceOff = errors.New("ChatGPT doesn't take a device code for this sign-in now; use the browser sign-in")
|
|
|
|
// codexDevicePost posts body as JSON with Codex's own headers. It answers
|
|
// the status and the reply.
|
|
func codexDevicePost(ctx context.Context, u string, body any) (int, []byte, error) {
|
|
b, err := json.Marshal(body)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(b))
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
codexClientHeaders(req.Header, codexVersion())
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := Keyed(http.DefaultClient).Do(req)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
out, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
return resp.StatusCode, out, nil
|
|
}
|
|
|
|
// startCodexDeviceSignIn asks ChatGPT for a device code and waits, in the
|
|
// background, for the user to enter it.
|
|
func startCodexDeviceSignIn(s *signInFlow) error {
|
|
base := strings.TrimSuffix(codexIssuer, "/")
|
|
ctx, cancel := context.WithCancel(s.via(context.Background()))
|
|
code, b, err := codexDevicePost(ctx, base+"/api/accounts/deviceauth/usercode", map[string]string{"client_id": codexClientID})
|
|
if err != nil {
|
|
cancel()
|
|
return fmt.Errorf("couldn't reach ChatGPT for a sign-in code: %w", err)
|
|
}
|
|
if code == http.StatusNotFound {
|
|
cancel()
|
|
return errCodexDeviceOff
|
|
}
|
|
if code != http.StatusOK {
|
|
cancel()
|
|
return fmt.Errorf("ChatGPT gave no sign-in code (%d): %s", code, APIError(b, http.StatusText(code)))
|
|
}
|
|
var uc struct {
|
|
ID string `json:"device_auth_id"`
|
|
Code string `json:"user_code"`
|
|
Code2 string `json:"usercode"`
|
|
Interval any `json:"interval"` // a string of seconds, "5"
|
|
}
|
|
if err := json.Unmarshal(b, &uc); err != nil {
|
|
cancel()
|
|
return fmt.Errorf("ChatGPT's sign-in code didn't read: %w", err)
|
|
}
|
|
uc.Code = firstNonEmpty(uc.Code, uc.Code2)
|
|
if uc.ID == "" || uc.Code == "" {
|
|
cancel()
|
|
return errors.New("ChatGPT gave no sign-in code")
|
|
}
|
|
secs := 0
|
|
switch v := uc.Interval.(type) {
|
|
case string:
|
|
secs, _ = strconv.Atoi(strings.TrimSpace(v))
|
|
case float64:
|
|
secs = int(v)
|
|
}
|
|
s.mu.Lock()
|
|
s.st.URL, s.st.Code = base+"/codex/device", uc.Code
|
|
s.stop = cancel
|
|
s.mu.Unlock()
|
|
interval := devicePoll(secs)
|
|
go func() {
|
|
fail := func(msg string) {
|
|
log.Printf("codex device sign-in failed: %s", msg)
|
|
s.finish(SignInState{State: "failed", Error: msg})
|
|
}
|
|
deadline := time.Now().Add(codexDeviceWait)
|
|
misses := 0
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-time.After(interval):
|
|
}
|
|
if time.Now().After(deadline) {
|
|
fail("the code expired; start again")
|
|
return
|
|
}
|
|
code, b, err := codexDevicePost(ctx, base+"/api/accounts/deviceauth/token",
|
|
map[string]string{"device_auth_id": uc.ID, "user_code": uc.Code})
|
|
switch {
|
|
case ctx.Err() != nil:
|
|
return
|
|
case err != nil:
|
|
// a hiccup: ask again, unless it keeps failing
|
|
if misses++; misses >= codexDevicePollMisses {
|
|
fail("couldn't ask ChatGPT whether the code was entered: " + err.Error())
|
|
return
|
|
}
|
|
continue
|
|
case code == http.StatusForbidden || code == http.StatusNotFound:
|
|
// not entered yet
|
|
misses = 0
|
|
continue
|
|
case code != http.StatusOK:
|
|
fail(fmt.Sprintf("ChatGPT refused the sign-in (%d): %s", code, APIError(b, http.StatusText(code))))
|
|
return
|
|
}
|
|
var ok struct {
|
|
Code string `json:"authorization_code"`
|
|
Verifier string `json:"code_verifier"`
|
|
}
|
|
if json.Unmarshal(b, &ok) != nil || ok.Code == "" || ok.Verifier == "" {
|
|
fail("ChatGPT finished the sign-in but sent no code")
|
|
return
|
|
}
|
|
ectx, ecancel := context.WithTimeout(ctx, 30*time.Second)
|
|
l, err := codexExchange(ectx, ok.Code, ok.Verifier, base+"/deviceauth/callback")
|
|
if err == nil {
|
|
var using bool
|
|
err = keepLogin(ectx, func() (err error) { using, err = addLogin(l); return err })
|
|
if err == nil {
|
|
ecancel()
|
|
s.finish(SignInState{State: "done", User: l.User, Plan: l.Plan, Using: using})
|
|
return
|
|
}
|
|
}
|
|
ecancel()
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
fail(err.Error())
|
|
return
|
|
}
|
|
}()
|
|
return nil
|
|
}
|