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.
200 lines
6.7 KiB
Go
200 lines
6.7 KiB
Go
package provider
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
)
|
|
|
|
// KiloVersion is the Kilo CLI release magpie says it is to the Kilo
|
|
// Gateway.
|
|
const KiloVersion = "7.8.3"
|
|
|
|
// KiloClient makes a request to the Kilo Gateway carry what the Kilo CLI
|
|
// sends it (Kilo-Org/kilocode packages/opencode/src/session/llm/request.ts
|
|
// and kilocode/const.ts, packages/kilo-gateway/src/headers.ts): Kilo
|
|
// Code's attribution and User-Agent, the editor it runs in, its mode, and
|
|
// the session as the task, which the gateway keys its prompt cache on.
|
|
// session names the conversation, made into one of the CLI's ids (ses_…)
|
|
// as for OpenCode; none leaves the session headers out. A provider with no
|
|
// key sends no Authorization at all: the gateway answers a free model to a
|
|
// caller with no credential as anonymous (by IP, 200 requests an hour), and
|
|
// refuses a bearer it can't verify with 401 (Kilo-Org/cloud
|
|
// web-shared/src/lib/tokens.ts, ai-gateway/handlers/llm-proxy.ts). Kilo's
|
|
// clients still send "Bearer anonymous", which the gateway reads as none
|
|
// only until no released client sends it, so it is not copied here.
|
|
func KiloClient(h http.Header, key, session string) {
|
|
h.Set("HTTP-Referer", "https://kilocode.ai")
|
|
h.Set("X-Title", "Kilo Code")
|
|
h.Set("User-Agent", "Kilo-Code/"+KiloVersion)
|
|
h.Set("X-KILOCODE-EDITORNAME", "Kilo CLI "+KiloVersion)
|
|
if session != "" {
|
|
id := openCodeSession(session)
|
|
h.Set("x-kilocode-mode", "code")
|
|
h.Set("X-KILOCODE-TASKID", id)
|
|
h.Set("x-session-affinity", id)
|
|
h.Set("X-Session-Id", id)
|
|
}
|
|
if key == "" {
|
|
h.Del("Authorization")
|
|
}
|
|
}
|
|
|
|
// IsKilo reports whether the provider is the Kilo Gateway: made from its
|
|
// preset, or at Kilo's API host.
|
|
func (p Provider) IsKilo() bool {
|
|
if p.Preset == "kilo" {
|
|
return true
|
|
}
|
|
h := p.Host()
|
|
return h == "api.kilo.ai" || h == "api.kilocode.ai"
|
|
}
|
|
|
|
// kiloModels is the gateway's list as Kilo's clients ask it (GET
|
|
// {base}/models, kilo-gateway src/api/models.ts): OpenRouter's shape, with
|
|
// isFree on the models it serves at no cost. Without a key only those are
|
|
// listed, the rest wanting a Kilo account; with one, all of them, the free
|
|
// ones marked. A model that says it takes no tools is left out, as Kilo
|
|
// leaves it out.
|
|
func (p Provider) kiloModels(ctx context.Context) ([]catalog.Model, string, error) {
|
|
base := strings.TrimRight(strings.TrimSpace(p.Chat), "/")
|
|
u := base + "/models"
|
|
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
var ms []catalog.Model
|
|
err := catalog.Paged(u, func(at string) (bool, string, error) {
|
|
page, more, last, err := p.kiloModelsPage(ctx, at)
|
|
if err != nil {
|
|
return false, "", err
|
|
}
|
|
ms = append(ms, page...)
|
|
return more, last, nil
|
|
})
|
|
if err != nil {
|
|
return nil, base, err
|
|
}
|
|
if len(ms) == 0 {
|
|
return nil, base, errors.New(u + ": no models listed")
|
|
}
|
|
return ms, base, nil
|
|
}
|
|
|
|
// kiloModelsPage asks the gateway's list at at, one page of it, and says
|
|
// whether another page follows, and the id it starts after. The reply's
|
|
// shape is OpenRouter's, which pages with has_more and last_id, so the
|
|
// pages are followed to the end of the list (catalog.Paged) rather than
|
|
// refused: a page read as the whole list drops every model of the pages
|
|
// after from the user's picks (#904). As far as was measured on 2026-10-06
|
|
// the gateway answers with the whole list either way — 400 models and no
|
|
// has_more at api.kilo.ai/api/openrouter/models, 466 and links.next: null
|
|
// at OpenRouter's own /api/v1/models — so this is the shape's rule kept in
|
|
// one place, for the day either of them does answer with a page.
|
|
func (p Provider) kiloModelsPage(ctx context.Context, at string) ([]catalog.Model, bool, string, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, at, nil)
|
|
if err != nil {
|
|
return nil, false, "", err
|
|
}
|
|
req.Header.Set("Accept", "application/json")
|
|
KiloClient(req.Header, p.Key, "")
|
|
if p.Key != "" {
|
|
req.Header.Set("Authorization", "Bearer "+p.Key)
|
|
}
|
|
for k, v := range p.SentHeaders(ctx) {
|
|
catalog.PutUserHeader(req.Header, k, v)
|
|
}
|
|
res, err := Keyed(http.DefaultClient).Do(req)
|
|
if err != nil {
|
|
return nil, false, "", err
|
|
}
|
|
defer res.Body.Close()
|
|
b, _ := io.ReadAll(io.LimitReader(res.Body, 8<<20))
|
|
if res.StatusCode != http.StatusOK {
|
|
return nil, false, "", errorf("%s: HTTP %d", at, res.StatusCode)
|
|
}
|
|
var list struct {
|
|
Data []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
ContextLength any `json:"context_length"`
|
|
MaxOutput any `json:"max_completion_tokens"`
|
|
Params []string `json:"supported_parameters"`
|
|
IsFree bool `json:"isFree"`
|
|
TopProvider struct {
|
|
MaxOutput any `json:"max_completion_tokens"`
|
|
} `json:"top_provider"`
|
|
Architecture struct {
|
|
Input []string `json:"input_modalities"`
|
|
Output []string `json:"output_modalities"`
|
|
} `json:"architecture"`
|
|
} `json:"data"`
|
|
HasMore bool `json:"has_more"`
|
|
LastID string `json:"last_id"`
|
|
}
|
|
if err := json.Unmarshal(b, &list); err != nil {
|
|
return nil, false, "", errorf("%s: not a model list", at)
|
|
}
|
|
num := func(v any) int {
|
|
if n, ok := v.(float64); ok && n > 0 {
|
|
return int(n)
|
|
}
|
|
return 0
|
|
}
|
|
var ms []catalog.Model
|
|
for _, r := range list.Data {
|
|
if r.ID == "" || len(r.Params) > 0 && !slices.Contains(r.Params, "tools") {
|
|
continue
|
|
}
|
|
if out := r.Architecture.Output; len(out) > 0 && !slices.Contains(out, "text") {
|
|
continue // one that only draws or makes sound
|
|
}
|
|
free := r.IsFree || isKiloFree(r.ID)
|
|
if p.Key == "" && !free {
|
|
continue
|
|
}
|
|
name := r.Name
|
|
if name == "" {
|
|
name = r.ID
|
|
}
|
|
m := catalog.Model{ID: r.ID, Name: name, Free: free, Context: num(r.ContextLength),
|
|
Reasoning: slices.Contains(r.Params, "reasoning")}
|
|
if m.Output = num(r.TopProvider.MaxOutput); m.Output == 0 {
|
|
m.Output = num(r.MaxOutput)
|
|
}
|
|
if in := r.Architecture.Input; in != nil {
|
|
yes := slices.Contains(in, "image")
|
|
m.ImageInput, m.Images = &yes, yes
|
|
}
|
|
if free {
|
|
m.Price = &catalog.Price{}
|
|
}
|
|
ms = append(ms, m)
|
|
}
|
|
return ms, list.HasMore, list.LastID, nil
|
|
}
|
|
|
|
// isKiloFree reports whether id is one of the gateway's free models by its
|
|
// id alone: a ":free" one, which its docs say anyone may ask, or Kilo's
|
|
// own free router.
|
|
func isKiloFree(id string) bool {
|
|
return strings.HasSuffix(id, ":free") || id == "kilo-auto/free"
|
|
}
|
|
|
|
// kiloFreeModel reports whether model is one of the Kilo Gateway's free
|
|
// models on p: one the fetched list marks free, else one free by its id.
|
|
func (p Provider) kiloFreeModel(model string) bool {
|
|
if !p.IsKilo() {
|
|
return false
|
|
}
|
|
if ms := p.liveByID(model); len(ms) > 0 {
|
|
return ms[0].Free
|
|
}
|
|
return isKiloFree(model)
|
|
}
|