gateway: a vendor's redirect to another origin is sent no provider key
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.
This commit is contained in:
@@ -840,6 +840,10 @@ OpenAI shape can't carry. GET, POST, PUT, PATCH and DELETE
|
||||
`Sign` puts in the provider's key as it takes one, and magpie's
|
||||
User-Agent goes in (`stampUA`). The answer's hop headers, `Set-Cookie`,
|
||||
`Alt-Svc` and HSTS don't come back (`nativeAnswerDropped`).
|
||||
- **Redirects.** A redirect on the vendor's own origin (scheme, host and
|
||||
port, or http to https on the same host) is followed, signed; any other
|
||||
comes back to the caller as it came, `Location` included, and the host
|
||||
it names is sent nothing (`provider.KeepsCredentials`, below).
|
||||
- **Keys.** It is behind the gateway's guards as every route is (a key
|
||||
beyond loopback, lanGuard's Host check against a rebound page,
|
||||
corsGuard: a foreign Origin, `null` and `*.localhost` without a key,
|
||||
@@ -1503,7 +1507,21 @@ magpie's proxy settings as the vendor's own address does
|
||||
The key is sent only to that URL. Go keeps Brave's `X-Subscription-Token`
|
||||
and Exa's `x-api-key` across a redirect to another host, so `askSearchAPI`
|
||||
doesn't follow one. The 3xx is the error, and it names where the search
|
||||
was sent. magpie ships and lists no third-party search endpoint; the URL
|
||||
was sent. Every request sent with a provider's credential has the
|
||||
same rule: the gateway's client, `Provider.Do` through whichever client
|
||||
it is given (`provider.Keyed`), the provider package's own reads (usage,
|
||||
balance, models, sign-in refreshes) and the Codex relay follow a redirect
|
||||
only to the request's origin, or from http to https on its host
|
||||
(`provider.KeepsCredentials` in
|
||||
[`redirect.go`](../../internal/provider/redirect.go)). Go would follow one
|
||||
anywhere, https to http included, and keep `x-api-key`, `x-goog-api-key`,
|
||||
`api-key` and a provider's own headers on it, and `Authorization` too
|
||||
when only the port differs. A redirect elsewhere is the answer, a 3xx
|
||||
the route reports as the vendor's failure. No vendor magpie speaks to
|
||||
redirects its API to another origin; a file a vendor answers by URL is
|
||||
fetched unsigned, by `vendorClient`. `TestRedirectKeepsTheKeyAtItsOrigin`,
|
||||
`TestRedirectNeverDowngrades`, `TestNativeRedirectKeepsTheKey`,
|
||||
`TestChatRedirectKeepsTheKey`. magpie ships and lists no third-party search endpoint; the URL
|
||||
is only ever the user's.
|
||||
|
||||
A value the user set is never replaced by the vendor's default. In
|
||||
|
||||
@@ -25,7 +25,8 @@ import (
|
||||
// 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 {
|
||||
client := &http.Client{Transport: upstreamTransport()}
|
||||
// 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
|
||||
|
||||
@@ -275,7 +275,7 @@ func (t codexSocket) socket(req *http.Request, msg []byte) (*http.Response, erro
|
||||
timer := time.AfterFunc(codexSocketDial, cancel)
|
||||
u := *req.URL
|
||||
c, hs, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{
|
||||
HTTPClient: &http.Client{Transport: t.next},
|
||||
HTTPClient: &http.Client{Transport: t.next, CheckRedirect: provider.KeepsCredentials},
|
||||
HTTPHeader: codexSocketHeaders(req),
|
||||
CompressionMode: websocket.CompressionNoContextTakeover,
|
||||
})
|
||||
|
||||
@@ -580,8 +580,10 @@ func New() *Server {
|
||||
s := &Server{
|
||||
// a request counted against a MaxRPM waits for room in its minute
|
||||
// first (rpm.go); the ChatGPT backend is spoken to over HTTP/1.1
|
||||
// (netproxy.HTTP1, which provider/codex_http1.go sets)
|
||||
client: &http.Client{Transport: rpmTransport{upstreamTransport()}},
|
||||
// (netproxy.HTTP1, which provider/codex_http1.go sets); a vendor's
|
||||
// redirect is followed to its own origin only, so its key goes
|
||||
// nowhere else (provider.KeepsCredentials)
|
||||
client: &http.Client{Transport: rpmTransport{upstreamTransport()}, CheckRedirect: provider.KeepsCredentials},
|
||||
unfit: make(map[string]bool),
|
||||
subscription: newSubscriptionBridge(),
|
||||
debug: os.Getenv("MAGPIE_DEBUG") != "",
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// stealHost is a host a vendor's redirect names: it records every request
|
||||
// that reaches it.
|
||||
type stealHost struct {
|
||||
*httptest.Server
|
||||
mu sync.Mutex
|
||||
seen []http.Header
|
||||
}
|
||||
|
||||
func newStealHost(t *testing.T) *stealHost {
|
||||
t.Helper()
|
||||
s := &stealHost{}
|
||||
s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
s.mu.Lock()
|
||||
s.seen = append(s.seen, r.Header.Clone())
|
||||
s.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"stolen":true}`)
|
||||
}))
|
||||
t.Cleanup(s.Close)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *stealHost) reached() []http.Header {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]http.Header(nil), s.seen...)
|
||||
}
|
||||
|
||||
// A vendor answering the native route with a redirect to another host
|
||||
// has its 3xx passed back to the caller as it came, and the host it names
|
||||
// gets nothing: not the x-api-key and Authorization of an Anthropic
|
||||
// provider, the x-goog-api-key of a Gemini one, nor a provider's own
|
||||
// header. A redirect on the vendor's own origin is followed, signed.
|
||||
func TestNativeRedirectKeepsTheKey(t *testing.T) {
|
||||
fresh(t)
|
||||
steal := newStealHost(t)
|
||||
up := newVendorAPI(t)
|
||||
up.answer = func(w http.ResponseWriter, r *http.Request, _ []byte) bool {
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/away"):
|
||||
w.Header().Set("Location", steal.URL+"/steal")
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
return true
|
||||
case strings.HasSuffix(r.URL.Path, "/here"):
|
||||
w.Header().Set("Location", strings.TrimSuffix(r.URL.Path, "/here")+"/landed")
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
hdr := map[string]string{"X-Relay-Secret": "relay-secret"}
|
||||
saveVendor(t, provider.Provider{ID: "claudeish", Name: "Claudeish", Anthropic: up.URL + "/anthropic", Key: "ak-secret", Models: []string{"c"}, Headers: hdr})
|
||||
saveVendor(t, provider.Provider{ID: "gem", Name: "Gem", Gemini: up.URL + "/v1beta", Key: "AIza-secret", Models: []string{"gemini-2.5-pro"}, Headers: hdr})
|
||||
h := nativeServe(t)
|
||||
for _, id := range []string{"claudeish", "gem"} {
|
||||
rec := nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+id+"/v1/away", "127.0.0.1:50000", `{"model":"m"}`, "Content-Type", "application/json")
|
||||
if rec.Code != http.StatusTemporaryRedirect || rec.Header().Get("Location") != steal.URL+"/steal" {
|
||||
t.Errorf("%s: %d %q %s, want the vendor's 307 as it came", id, rec.Code, rec.Header().Get("Location"), rec.Body)
|
||||
}
|
||||
before := len(up.asked())
|
||||
rec = nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+id+"/v1/here", "127.0.0.1:50000", `{"model":"m"}`, "Content-Type", "application/json")
|
||||
if rec.Code != 201 {
|
||||
t.Fatalf("%s: a same-origin redirect: %d %s", id, rec.Code, rec.Body)
|
||||
}
|
||||
got := up.asked()[before:]
|
||||
if len(got) != 2 || !strings.HasSuffix(got[1].uri, "/v1/landed") || got[1].body != `{"model":"m"}` || got[1].header.Get("X-Relay-Secret") != "relay-secret" {
|
||||
t.Fatalf("%s: a same-origin redirect reached %+v", id, got)
|
||||
}
|
||||
if id == "gem" && got[1].header.Get("X-Goog-Api-Key") != "AIza-secret" || id == "claudeish" && got[1].header.Get("X-Api-Key") != "ak-secret" {
|
||||
t.Errorf("%s: a same-origin redirect lost the key: %v", id, got[1].header)
|
||||
}
|
||||
}
|
||||
if seen := steal.reached(); len(seen) != 0 {
|
||||
t.Fatalf("the redirect's host was sent %d requests, the first with %v", len(seen), seen[0])
|
||||
}
|
||||
}
|
||||
|
||||
// The same on a translated route: a vendor's redirect to another host
|
||||
// is not followed, so a provider's own header and its key stay with it.
|
||||
func TestChatRedirectKeepsTheKey(t *testing.T) {
|
||||
fresh(t)
|
||||
steal := newStealHost(t)
|
||||
up := newVendorAPI(t)
|
||||
up.answer = func(w http.ResponseWriter, r *http.Request, _ []byte) bool {
|
||||
w.Header().Set("Location", steal.URL+"/v1/chat/completions")
|
||||
w.WriteHeader(http.StatusTemporaryRedirect)
|
||||
return true
|
||||
}
|
||||
saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk-secret", Models: []string{"m"}, Headers: map[string]string{"X-Relay-Secret": "relay-secret", "Api-Key": "vk-secret"}})
|
||||
h := nativeServe(t)
|
||||
rec := nativeDo(h, "POST", "http://127.0.0.1:3425/v1/chat/completions", "127.0.0.1:50000", `{"model":"vendor/m","messages":[{"role":"user","content":"hi"}]}`, "Content-Type", "application/json")
|
||||
if rec.Code == 200 {
|
||||
t.Errorf("the redirect's host answered: %s", rec.Body)
|
||||
}
|
||||
if len(up.asked()) == 0 {
|
||||
t.Fatal("the vendor was never asked")
|
||||
}
|
||||
if seen := steal.reached(); len(seen) != 0 {
|
||||
t.Fatalf("the redirect's host was sent %d requests, the first with %v", len(seen), seen[0])
|
||||
}
|
||||
}
|
||||
@@ -1247,7 +1247,7 @@ func codexRefresh(ctx context.Context, raw map[string]any, reason string) (strin
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
codexClientHeaders(req.Header, codexVersion())
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return "", errors.New("Codex token refresh: " + err.Error())
|
||||
}
|
||||
@@ -1635,7 +1635,7 @@ func copilotToken(ctx context.Context, app copilotApp) (copilotSession, error) {
|
||||
for k, v := range copilotHeaders {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return copilotSession{}, errors.New("Copilot sign-in: " + err.Error())
|
||||
}
|
||||
@@ -1713,7 +1713,7 @@ func copilotAccept(ctx context.Context, app copilotApp, s copilotSession, model
|
||||
for k, v := range s.headers() {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -1744,7 +1744,7 @@ func copilotModels(ctx context.Context, app copilotApp) ([]catalog.Model, error)
|
||||
for k, v := range s.headers() {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1434,7 +1434,7 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [
|
||||
}
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
if k := url.QueryEscape(p.Key); k != "" && strings.Contains(err.Error(), k) {
|
||||
// the URL in the error has the key in it: not shown on a card
|
||||
|
||||
@@ -239,7 +239,7 @@ func askProbe(ctx context.Context, p Provider, raw string) (ok bool, code int) {
|
||||
req.Header.Set(k, withBalanceKey(v, p.Key, false))
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return false, 0
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ const (
|
||||
SIWCUsageURL = "https://chatgpt.com/settings/usage"
|
||||
)
|
||||
|
||||
var siwcClient = &http.Client{Timeout: 30 * time.Second}
|
||||
var siwcClient = &http.Client{Timeout: 30 * time.Second, CheckRedirect: KeepsCredentials}
|
||||
|
||||
// siwcNoUsage is what a ChatGPT API account's usage line says: OpenAI's
|
||||
// API tells no plan usage, and the account added as ChatGPT (Codex's
|
||||
|
||||
@@ -153,7 +153,7 @@ func clineGet(ctx context.Context, key, path string, out any) error {
|
||||
ClineClient(req.Header)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ func codexDevicePost(ctx context.Context, u string, body any) (int, []byte, erro
|
||||
}
|
||||
codexClientHeaders(req.Header, codexVersion())
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func codexModels(ctx context.Context, sign func(context.Context, *http.Request,
|
||||
if err := sign(ctx, req, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func CodexLiveList(ctx context.Context) ([]byte, error) {
|
||||
if err := p.Account.sign(ctx, req, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -374,7 +374,7 @@ func consumeCodexReset(ctx context.Context, base, token, accountID, credit, id s
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
|
||||
@@ -512,7 +512,7 @@ func warmCodex(ctx context.Context, sign func(context.Context, *http.Request, []
|
||||
return err
|
||||
}
|
||||
CodexCompressed(req, body) // as Codex sends a turn
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -357,7 +357,7 @@ func copilotUser(ctx context.Context, token, host string) (user, plan string, er
|
||||
}
|
||||
req.Header.Set("Authorization", "token "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -205,7 +205,7 @@ func copilotAutoResolve(ctx context.Context, app copilotApp, fresh bool) (copilo
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
req.Header.Set("X-GitHub-Api-Version", copilotAutoVersion)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return copilotAutoSession{}, errors.New("Copilot Auto: " + err.Error())
|
||||
}
|
||||
@@ -287,7 +287,7 @@ func copilotAutoRoute(ctx context.Context, app copilotApp, s copilotSession, bas
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
req.Header.Set("X-GitHub-Api-Version", copilotAutoV2Version)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return copilotAutoSession{}, err.Error(), false
|
||||
}
|
||||
|
||||
@@ -226,7 +226,7 @@ func copilotDirect(ctx context.Context, app copilotApp) (copilotSession, error)
|
||||
}
|
||||
req.Header.Set("Authorization", "token "+github)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return copilotSession{}, errors.New("Copilot sign-in: " + err.Error())
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func gitHubForm(ctx context.Context, u string, form url.Values, v any) error {
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -601,7 +601,7 @@ func (p Provider) cloudflareAccount(ctx context.Context) (string, error) {
|
||||
if err := p.Sign(ctx, req, Chat, nil); err != nil {
|
||||
return "", err
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s: %v", p.Name, err)
|
||||
}
|
||||
@@ -919,7 +919,7 @@ func (p Provider) fetchDecide(ctx context.Context) ([]catalog.Model, error) {
|
||||
if err := p.Sign(ctx, req, Chat, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1131,7 +1131,7 @@ func (p Provider) checkKey(ctx context.Context, u string) error {
|
||||
if err := p.Sign(ctx, req, Chat, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %v", p.Name, err)
|
||||
}
|
||||
|
||||
@@ -517,7 +517,7 @@ func (g googleAccount) call(ctx context.Context, base, method string, body, out
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1716,7 +1716,7 @@ func googleWho(ctx context.Context, access string) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+access)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ func (p Provider) kiloModelsPage(ctx context.Context, at string) ([]catalog.Mode
|
||||
for k, v := range p.SentHeaders(ctx) {
|
||||
catalog.PutUserHeader(req.Header, k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, false, "", err
|
||||
}
|
||||
|
||||
@@ -480,7 +480,7 @@ func kiroPost(ctx context.Context, u, contentType string, body []byte, headers m
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("refreshing Kiro's sign-in: %w", err)
|
||||
}
|
||||
@@ -521,7 +521,7 @@ func kiroManagement(ctx context.Context, region, token, tokenType, method string
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -569,7 +569,7 @@ func kiroProfile(ctx context.Context, c kiroCred) (string, error) {
|
||||
KiroAuth{Token: c.access, TokenType: "API_KEY"}.Header(req.Header)
|
||||
req.Header.Set("Content-Type", "application/x-amz-json-1.0")
|
||||
req.Header.Set("X-Amz-Target", "AmazonCodeWhispererService.GetProfile")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -610,7 +610,7 @@ func planBody(ctx context.Context, src planQuotaSource, key string) ([]byte, err
|
||||
// Go's usage is asked at its gateway, which routes nothing that names
|
||||
// no session
|
||||
OpenCodeSession(req.Header, src.url)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -938,7 +938,7 @@ func zhipuKeyTeamAt(ctx context.Context, root, quotaURL, key string, team *Zhipu
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
@@ -932,7 +932,8 @@ func firstOf(ss ...string) string {
|
||||
|
||||
// Do sends req, through the account's own transport when it has one (a
|
||||
// plugin's), the client the account asks for this request when it asks
|
||||
// for one (ZCode's Start Plan: zcodeStartClient), and client otherwise.
|
||||
// for one (ZCode's Start Plan: zcodeStartClient), and client otherwise,
|
||||
// following a redirect only to the request's own origin (Keyed).
|
||||
//
|
||||
// A request sent for magpie's own test (probelog.With) is written into the
|
||||
// request log here, whichever way it goes: a plugin's fetch and a client
|
||||
@@ -974,7 +975,8 @@ func (p Provider) do(client *http.Client, req *http.Request) (*http.Response, er
|
||||
}
|
||||
}
|
||||
req.Header.Del(ConversationHeader)
|
||||
return client.Do(req)
|
||||
// the account's credential goes to its own origin only (redirect.go)
|
||||
return Keyed(client).Do(req)
|
||||
}
|
||||
|
||||
// pluginsOff is the plugins' own ids of the plugin providers switched off
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A request that carries a vendor's credential is followed through a
|
||||
// redirect only to its own origin (the scheme, host and port it was sent
|
||||
// to), or from http to https on the same host. Go follows any redirect to
|
||||
// any host, https to http included, and on a hop to another host drops
|
||||
// only Authorization, Cookie and WWW-Authenticate: x-api-key,
|
||||
// x-goog-api-key, api-key and a provider's own headers went to wherever
|
||||
// the vendor's Location named. A redirect elsewhere is not followed, and
|
||||
// its 3xx is the answer, as it came, so the caller sees where the vendor
|
||||
// sent it and no credential goes there. No vendor magpie speaks to was
|
||||
// found to redirect its API to another origin (a download that does is
|
||||
// fetched by its own URL, unsigned), and the search APIs had this rule
|
||||
// already (search_api.go, #1580).
|
||||
|
||||
// KeepsCredentials is the CheckRedirect of a client that sends a vendor's
|
||||
// credential: same-origin redirects are followed, at most 10 as Go's
|
||||
// default, and any other is given back as the answer
|
||||
// (http.ErrUseLastResponse).
|
||||
func KeepsCredentials(next *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return errors.New("stopped after 10 redirects")
|
||||
}
|
||||
if !SameOrigin(via[0].URL.Scheme, via[0].URL.Host, next.URL.Scheme, next.URL.Host) {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SameOrigin says whether a redirect from scheme://host to
|
||||
// toScheme://toHost may carry a credential: the same scheme, host and
|
||||
// port (a port left out is the scheme's own), or http to https on the
|
||||
// same host and default ports.
|
||||
func SameOrigin(scheme, host, toScheme, toHost string) bool {
|
||||
scheme, toScheme = strings.ToLower(scheme), strings.ToLower(toScheme)
|
||||
h, port := splitOrigin(scheme, host)
|
||||
th, tport := splitOrigin(toScheme, toHost)
|
||||
if h == "" || h != th {
|
||||
return false
|
||||
}
|
||||
if scheme == toScheme {
|
||||
return port == tport
|
||||
}
|
||||
// an upgrade: the key went over http already, to this same host
|
||||
return scheme == "http" && toScheme == "https" && port == "80" && tport == "443"
|
||||
}
|
||||
|
||||
func splitOrigin(scheme, host string) (string, string) {
|
||||
h, port, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
h, port = host, ""
|
||||
}
|
||||
if port == "" {
|
||||
switch scheme {
|
||||
case "http":
|
||||
port = "80"
|
||||
case "https":
|
||||
port = "443"
|
||||
}
|
||||
}
|
||||
return strings.ToLower(strings.Trim(h, "[]")), port
|
||||
}
|
||||
|
||||
// Keyed is c with KeepsCredentials after c's own CheckRedirect, for a
|
||||
// request that carries a vendor's credential. c is left as it is.
|
||||
func Keyed(c *http.Client) *http.Client {
|
||||
if c == nil {
|
||||
c = http.DefaultClient
|
||||
}
|
||||
k := *c
|
||||
own := c.CheckRedirect
|
||||
k.CheckRedirect = func(next *http.Request, via []*http.Request) error {
|
||||
if own != nil {
|
||||
if err := own(next, via); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return KeepsCredentials(next, via)
|
||||
}
|
||||
return &k
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// keyHeaders are the credentials a vendor's request may carry, a
|
||||
// provider's own header among them: none of them may reach a host the
|
||||
// vendor redirects to.
|
||||
var keyHeaders = []string{"Authorization", "X-Api-Key", "X-Goog-Api-Key", "Api-Key", "X-Custom-Secret"}
|
||||
|
||||
// thief is a host a vendor's redirect names, which records what reached it.
|
||||
type thief struct {
|
||||
*httptest.Server
|
||||
mu sync.Mutex
|
||||
seen []http.Header
|
||||
}
|
||||
|
||||
func newThief(t *testing.T) *thief {
|
||||
th := &thief{}
|
||||
th.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
th.mu.Lock()
|
||||
th.seen = append(th.seen, r.Header.Clone())
|
||||
th.mu.Unlock()
|
||||
}))
|
||||
t.Cleanup(th.Close)
|
||||
return th
|
||||
}
|
||||
|
||||
func (th *thief) reached() int {
|
||||
th.mu.Lock()
|
||||
defer th.mu.Unlock()
|
||||
return len(th.seen)
|
||||
}
|
||||
|
||||
func keyedRequest(t *testing.T, method, u string) *http.Request {
|
||||
req, err := http.NewRequest(method, u, strings.NewReader(`{"model":"m"}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range keyHeaders {
|
||||
req.Header.Set(k, "secret-"+k)
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
// A vendor's redirect to another origin is never followed by a request
|
||||
// sent for a provider (Provider.Do, through any client it is given): its
|
||||
// 3xx comes back as it came, and the host it names gets no request, so no
|
||||
// key. One to the vendor's own origin is followed, with every key.
|
||||
func TestRedirectKeepsTheKeyAtItsOrigin(t *testing.T) {
|
||||
th := newThief(t)
|
||||
var mu sync.Mutex
|
||||
var landed http.Header
|
||||
vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/away":
|
||||
http.Redirect(w, r, th.URL+"/steal", http.StatusTemporaryRedirect)
|
||||
case "/away302":
|
||||
http.Redirect(w, r, th.URL+"/steal", http.StatusFound)
|
||||
case "/here":
|
||||
http.Redirect(w, r, "/landed", http.StatusTemporaryRedirect)
|
||||
case "/landed":
|
||||
mu.Lock()
|
||||
landed = r.Header.Clone()
|
||||
mu.Unlock()
|
||||
w.WriteHeader(200)
|
||||
}
|
||||
}))
|
||||
defer vendor.Close()
|
||||
p := Provider{ID: "v", Chat: vendor.URL}
|
||||
for _, c := range []*http.Client{http.DefaultClient, {}, {Transport: http.DefaultTransport}} {
|
||||
for _, path := range []string{"/away", "/away302"} {
|
||||
res, err := p.Do(c, keyedRequest(t, "POST", vendor.URL+path))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode/100 != 3 || res.Header.Get("Location") != th.URL+"/steal" {
|
||||
t.Errorf("%s: %d %q, want the vendor's 3xx as it came", path, res.StatusCode, res.Header.Get("Location"))
|
||||
}
|
||||
}
|
||||
res, err := p.Do(c, keyedRequest(t, "POST", vendor.URL+"/here"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode != 200 {
|
||||
t.Errorf("a same-origin redirect wasn't followed: %d", res.StatusCode)
|
||||
}
|
||||
mu.Lock()
|
||||
for _, k := range keyHeaders {
|
||||
if landed.Get(k) != "secret-"+k {
|
||||
t.Errorf("a same-origin redirect lost %s: %v", k, landed)
|
||||
}
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
if n := th.reached(); n != 0 {
|
||||
t.Fatalf("the redirect's host was sent %d requests: %v", n, th.seen)
|
||||
}
|
||||
}
|
||||
|
||||
// An https vendor's redirect to http is not followed, its own host and
|
||||
// port included, so its key never goes in the clear.
|
||||
func TestRedirectNeverDowngrades(t *testing.T) {
|
||||
th := newThief(t)
|
||||
vendor := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/plain":
|
||||
// its own host and port, over http
|
||||
http.Redirect(w, r, "http://"+r.Host+"/x", http.StatusTemporaryRedirect)
|
||||
case "/elsewhere":
|
||||
http.Redirect(w, r, th.URL+"/steal", http.StatusPermanentRedirect)
|
||||
}
|
||||
}))
|
||||
defer vendor.Close()
|
||||
p := Provider{ID: "v", Chat: vendor.URL}
|
||||
for _, path := range []string{"/plain", "/elsewhere"} {
|
||||
res, err := p.Do(vendor.Client(), keyedRequest(t, "POST", vendor.URL+path))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", path, err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if res.StatusCode/100 != 3 {
|
||||
t.Errorf("%s: %d, want the vendor's 3xx as it came", path, res.StatusCode)
|
||||
}
|
||||
}
|
||||
if n := th.reached(); n != 0 {
|
||||
t.Fatalf("an https vendor's redirect to http was followed %d times", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameOrigin(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
from, host, to, toHost string
|
||||
want bool
|
||||
}{
|
||||
{"https", "api.example", "https", "api.example", true},
|
||||
{"https", "api.example", "https", "API.example:443", true},
|
||||
{"https", "api.example:8443", "https", "api.example:8443", true},
|
||||
{"http", "api.example", "https", "api.example", true}, // an upgrade
|
||||
{"https", "api.example", "http", "api.example", false},
|
||||
{"https", "api.example:443", "http", "api.example:443", false},
|
||||
{"https", "api.example", "https", "api.example:8443", false},
|
||||
{"https", "api.example", "https", "evil.example", false},
|
||||
{"https", "api.example", "https", "x.api.example", false},
|
||||
{"http", "127.0.0.1:1", "http", "127.0.0.1:2", false},
|
||||
{"http", "[::1]:1", "http", "[::1]:1", true},
|
||||
{"https", "", "https", "", false},
|
||||
} {
|
||||
if got := SameOrigin(c.from, c.host, c.to, c.toHost); got != c.want {
|
||||
t.Errorf("SameOrigin(%s://%s → %s://%s) = %v", c.from, c.host, c.to, c.toHost, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keyed keeps a client's own redirect rule, and adds its own after it.
|
||||
func TestKeyedKeepsTheClientsRule(t *testing.T) {
|
||||
asked := 0
|
||||
own := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { asked++; return http.ErrUseLastResponse }}
|
||||
vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/here" {
|
||||
http.Redirect(w, r, "/landed", http.StatusFound)
|
||||
}
|
||||
}))
|
||||
defer vendor.Close()
|
||||
res, err := Keyed(own).Get(vendor.URL + "/here")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res.Body.Close()
|
||||
if asked != 1 || res.StatusCode != http.StatusFound || own.CheckRedirect == nil {
|
||||
t.Fatalf("asked %d, %d", asked, res.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -776,7 +776,7 @@ func postTokenWith(ctx context.Context, tokenURL, ctype, bearer string, h http.H
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -384,7 +384,7 @@ func stepfunCall(ctx context.Context, site string, s stepfunSession, path string
|
||||
req.Header.Set("Oasis-Appid", st.app)
|
||||
req.Header.Set("Oasis-Platform", "web")
|
||||
req.Header.Set("Oasis-Webid", s.WebID)
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -616,7 +616,7 @@ func accountJSON(ctx context.Context, url, token string, headers map[string]stri
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1301,7 +1301,7 @@ func copilotSubscriptionUsage(ctx context.Context, githubToken, host string) Sub
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
var res *http.Response
|
||||
res, err = http.DefaultClient.Do(req)
|
||||
res, err = Keyed(http.DefaultClient).Do(req)
|
||||
if err == nil {
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
|
||||
@@ -395,7 +395,7 @@ func tencentAPICall(ctx context.Context, secretID, secretKey, region, action str
|
||||
req.Header.Set("X-TC-Region", region)
|
||||
req.Header.Set("X-TC-Timestamp", strconv.FormatInt(now.Unix(), 10))
|
||||
req.Header.Set("Authorization", tc3Sign(secretID, secretKey, tcAPIService, tcAPIHost, action, body, now))
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -252,7 +252,7 @@ func volcOpenAPICall(ctx context.Context, ak, sk, region, action string, now tim
|
||||
req.Header.Set("X-Content-Sha256", contentSHA)
|
||||
req.Header.Set("Authorization", auth)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -379,7 +379,7 @@ func zcodeCallH(ctx context.Context, method, u, auth string, hdr map[string]stri
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user