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.
137 lines
5.4 KiB
Go
137 lines
5.4 KiB
Go
package gateway
|
||
|
||
import (
|
||
"bytes"
|
||
"net/http"
|
||
"strings"
|
||
|
||
"github.com/yetone/magpie/internal/masking"
|
||
"github.com/yetone/magpie/internal/provider"
|
||
"github.com/yetone/magpie/internal/settings"
|
||
)
|
||
|
||
// CodexRelay is what serves Codex's own ChatGPT sign-in at the gateway's
|
||
// address once magpie has quit, for the Codex threads still open then
|
||
// (codexrelay). magpie takes the failover base URL out of Codex's config
|
||
// at quit (agent.EndCodexFailover), but a thread open in the Codex app,
|
||
// and the app-server holding it, keep the URL they started with: every
|
||
// turn after went to a port nobody listened on, and a system proxy in
|
||
// between answered 503 "Unknown error" until magpie was opened again
|
||
// (idkatbro on X). The relay passes those turns on to the ChatGPT backend
|
||
// as the gateway does a turn on one of Codex's own models, signed by the
|
||
// caller's own Authorization; it adds no credential of its own. What only
|
||
// the running magpie could do is refused with a reason Codex shows: a
|
||
// magpie model, a turn on one of magpie's accounts, masking (Settings ›
|
||
// Privacy) that would have masked it. Its answer at "/" never says it is
|
||
// magpie (ServedBy), so the next magpie starting asks it to leave.
|
||
func CodexRelay() http.Handler {
|
||
// the caller's sign-in goes to the ChatGPT backend's origin only
|
||
client := &http.Client{Transport: upstreamTransport(), CheckRedirect: provider.KeepsCredentials}
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
if !loopbackHost(r.Host) || r.Header.Get("Origin") != "" {
|
||
// as the gateway's corsGuard: a rebound or foreign page, or
|
||
// a frame's null, never reaches the sign-in Codex sends
|
||
relayError(w, http.StatusForbidden, "magpie's Codex relay serves Codex on this computer only")
|
||
return
|
||
}
|
||
if !strings.HasPrefix(r.URL.Path, CodexPath+"/") {
|
||
relayError(w, http.StatusServiceUnavailable, relayGone)
|
||
return
|
||
}
|
||
if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
|
||
http.Error(w, "magpie speaks HTTP", http.StatusUpgradeRequired)
|
||
return
|
||
}
|
||
rest := strings.TrimPrefix(r.URL.Path, CodexPath)
|
||
body, status, err := readBoundedRequestBody(w, r, requestLimits{body: codexBodyLimit()})
|
||
if err != nil {
|
||
relayError(w, status, err.Error())
|
||
return
|
||
}
|
||
if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") {
|
||
if msg := relayRefuses(r, body); msg != "" {
|
||
// 400, not 503: Codex retries a 5xx five times over for
|
||
// a refusal that a retry doesn't change (seen with codex
|
||
// 0.162.1), and shows a 4xx's message at once
|
||
relayError(w, http.StatusBadRequest, msg)
|
||
return
|
||
}
|
||
// as codexBackend sends a turn of Codex's own to its sign-in
|
||
body = plainItemIDs(boundCallIDs(callItemIDs(body)))
|
||
body, _ = codexInput(body, false)
|
||
}
|
||
body = withoutClaudeSeals(body)
|
||
base := provider.CodexBase
|
||
if apiKey(r.Header) && rest != "/models" {
|
||
base = codexAPIBase
|
||
}
|
||
if r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase {
|
||
body = provider.DeclareSearch(body, strings.EqualFold(r.Header.Get("X-OpenAI-Internal-Codex-Responses-Lite"), "true"))
|
||
}
|
||
u := base + rest
|
||
if r.URL.RawQuery != "" {
|
||
u += "?" + r.URL.RawQuery
|
||
}
|
||
req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), r.Method, u, bytes.NewReader(body))
|
||
if err != nil {
|
||
relayError(w, http.StatusBadGateway, err.Error())
|
||
return
|
||
}
|
||
copyHeaders(req.Header, r.Header)
|
||
req.Header.Del("Accept-Encoding")
|
||
provider.CodexCompressed(req, body)
|
||
res, err := client.Do(req)
|
||
if err != nil {
|
||
relayError(w, http.StatusBadGateway, "OpenAI can't be reached ("+err.Error()+"). magpie isn't running, so this thread goes to OpenAI on Codex's own sign-in.")
|
||
return
|
||
}
|
||
defer res.Body.Close()
|
||
for k, vs := range res.Header {
|
||
if !hopHeader(k) {
|
||
w.Header()[k] = vs
|
||
}
|
||
}
|
||
w.WriteHeader(res.StatusCode)
|
||
flush := http.NewResponseController(w)
|
||
buf := make([]byte, 32<<10)
|
||
for {
|
||
n, err := res.Body.Read(buf)
|
||
if n > 0 {
|
||
if _, werr := w.Write(buf[:n]); werr != nil {
|
||
return
|
||
}
|
||
flush.Flush()
|
||
}
|
||
if err != nil {
|
||
return
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
// relayGone is the relay's answer to anything but Codex's own turns.
|
||
const relayGone = "magpie isn't running: only Codex threads open when it quit are passed on, on Codex's own ChatGPT sign-in. Open magpie for everything else."
|
||
|
||
// relayRefuses says why a turn can't be passed on with magpie gone, ""
|
||
// when it can: what only the running gateway serves, and a turn masking
|
||
// would have masked, which never goes unmasked.
|
||
func relayRefuses(r *http.Request, body []byte) string {
|
||
model := modelOf(body)
|
||
if strings.Contains(model, "/") {
|
||
return model + " is one of magpie's models, and magpie isn't running. Open magpie to go on with this thread, or pick one of Codex's own models."
|
||
}
|
||
if r.Header.Get(AccountHeader) != "" {
|
||
return AccountHeader + " names one of magpie's Codex accounts, and magpie isn't running. Open magpie to go on with this thread."
|
||
}
|
||
if masking.Wanted(settings.Load()) {
|
||
return "magpie isn't running, and Settings › Privacy masks what is sent: this turn is not sent unmasked. Open magpie to go on with this thread."
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// relayError answers as the ChatGPT backend words an error, so Codex
|
||
// shows the message (an empty body reads "Unknown error").
|
||
func relayError(w http.ResponseWriter, status int, msg string) {
|
||
writeError(w, provider.Responses, status, msg)
|
||
}
|