diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 355a2c5fe..93364e5b0 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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 diff --git a/internal/gateway/codex_relay.go b/internal/gateway/codex_relay.go index 99dc03e77..202883eef 100644 --- a/internal/gateway/codex_relay.go +++ b/internal/gateway/codex_relay.go @@ -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 diff --git a/internal/gateway/codex_socket.go b/internal/gateway/codex_socket.go index 74b27f863..0411a8cbc 100644 --- a/internal/gateway/codex_socket.go +++ b/internal/gateway/codex_socket.go @@ -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, }) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 550fb26e7..be57d55f1 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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") != "", diff --git a/internal/gateway/redirect_key_test.go b/internal/gateway/redirect_key_test.go new file mode 100644 index 000000000..99080254d --- /dev/null +++ b/internal/gateway/redirect_key_test.go @@ -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]) + } +} diff --git a/internal/provider/account.go b/internal/provider/account.go index c7e034c02..75a64d736 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -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 } diff --git a/internal/provider/balance.go b/internal/provider/balance.go index 6e0adc735..30c90643b 100644 --- a/internal/provider/balance.go +++ b/internal/provider/balance.go @@ -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 diff --git a/internal/provider/balance_probe.go b/internal/provider/balance_probe.go index 0fecab503..15d91bff5 100644 --- a/internal/provider/balance_probe.go +++ b/internal/provider/balance_probe.go @@ -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 } diff --git a/internal/provider/chatgpt_api.go b/internal/provider/chatgpt_api.go index 7343a4fc5..4546e3536 100644 --- a/internal/provider/chatgpt_api.go +++ b/internal/provider/chatgpt_api.go @@ -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 diff --git a/internal/provider/cline_usage.go b/internal/provider/cline_usage.go index c5855ca77..0d309e8da 100644 --- a/internal/provider/cline_usage.go +++ b/internal/provider/cline_usage.go @@ -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 } diff --git a/internal/provider/codex_device_signin.go b/internal/provider/codex_device_signin.go index d703439f7..bb6a757d8 100644 --- a/internal/provider/codex_device_signin.go +++ b/internal/provider/codex_device_signin.go @@ -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 } diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 0dadf32db..13346ad9f 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -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 } diff --git a/internal/provider/codex_resets.go b/internal/provider/codex_resets.go index ce1ce2e83..78025eb5b 100644 --- a/internal/provider/codex_resets.go +++ b/internal/provider/codex_resets.go @@ -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 } diff --git a/internal/provider/codex_warmup.go b/internal/provider/codex_warmup.go index 1f25491e4..026788666 100644 --- a/internal/provider/codex_warmup.go +++ b/internal/provider/codex_warmup.go @@ -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 } diff --git a/internal/provider/copilot_accounts.go b/internal/provider/copilot_accounts.go index 8514bdfc2..10914a182 100644 --- a/internal/provider/copilot_accounts.go +++ b/internal/provider/copilot_accounts.go @@ -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 } diff --git a/internal/provider/copilot_auto.go b/internal/provider/copilot_auto.go index bb76ec58a..f33cc960d 100644 --- a/internal/provider/copilot_auto.go +++ b/internal/provider/copilot_auto.go @@ -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 } diff --git a/internal/provider/copilot_cli.go b/internal/provider/copilot_cli.go index 4818cd288..cb4de01c9 100644 --- a/internal/provider/copilot_cli.go +++ b/internal/provider/copilot_cli.go @@ -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()) } diff --git a/internal/provider/copilot_signin.go b/internal/provider/copilot_signin.go index 46db46182..31786e7eb 100644 --- a/internal/provider/copilot_signin.go +++ b/internal/provider/copilot_signin.go @@ -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 } diff --git a/internal/provider/decide.go b/internal/provider/decide.go index 1f90eb7d8..d465209df 100644 --- a/internal/provider/decide.go +++ b/internal/provider/decide.go @@ -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) } diff --git a/internal/provider/google.go b/internal/provider/google.go index d74419271..732cf326d 100644 --- a/internal/provider/google.go +++ b/internal/provider/google.go @@ -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 } diff --git a/internal/provider/kilo.go b/internal/provider/kilo.go index 4f43eb79d..1c572fa48 100644 --- a/internal/provider/kilo.go +++ b/internal/provider/kilo.go @@ -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 } diff --git a/internal/provider/kiro.go b/internal/provider/kiro.go index 50fe83f80..38b53424a 100644 --- a/internal/provider/kiro.go +++ b/internal/provider/kiro.go @@ -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 } diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index 42d68161d..c6606042b 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -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 } diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index 2a347eada..f96a0159c 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -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 diff --git a/internal/provider/redirect.go b/internal/provider/redirect.go new file mode 100644 index 000000000..5e43187ca --- /dev/null +++ b/internal/provider/redirect.go @@ -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 +} diff --git a/internal/provider/redirect_test.go b/internal/provider/redirect_test.go new file mode 100644 index 000000000..a19df1e4e --- /dev/null +++ b/internal/provider/redirect_test.go @@ -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) + } +} diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 78f5b2606..08fb27ac3 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -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 } diff --git a/internal/provider/stepfun_plan.go b/internal/provider/stepfun_plan.go index 84af89f28..d1aeedd59 100644 --- a/internal/provider/stepfun_plan.go +++ b/internal/provider/stepfun_plan.go @@ -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 } diff --git a/internal/provider/subscription_usage.go b/internal/provider/subscription_usage.go index a8d9c6cee..79078efc7 100644 --- a/internal/provider/subscription_usage.go +++ b/internal/provider/subscription_usage.go @@ -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)) diff --git a/internal/provider/tencent_usage.go b/internal/provider/tencent_usage.go index 61a4667e9..f7fb7e89a 100644 --- a/internal/provider/tencent_usage.go +++ b/internal/provider/tencent_usage.go @@ -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 } diff --git a/internal/provider/volcengine_usage.go b/internal/provider/volcengine_usage.go index 1a1037766..96fae947d 100644 --- a/internal/provider/volcengine_usage.go +++ b/internal/provider/volcengine_usage.go @@ -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 } diff --git a/internal/provider/zcode.go b/internal/provider/zcode.go index eec3d6752..346b3077d 100644 --- a/internal/provider/zcode.go +++ b/internal/provider/zcode.go @@ -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 }