A provider's fixed Headers can't say a value that changes from request
to request or from client to client. 3jRzfF52Qx on X asked for the
agent's own header values to reach the vendor. Each provider now has a
comma-separated list of request headers, saved as `passHeaders`. When the
agent's request carries one of them, its value goes to that provider as
the agent sent it.
- Where it is: the editor's "Request headers to pass" (zh 透传请求头),
under Advanced, right after Reply headers.
- The agent's value stands over a fixed Headers value of the same name.
When the agent sends none, the fixed one goes.
- Never passed on, listed or not (provider.RequestHeaderPassable):
- magpie's key: Authorization, X-Api-Key, X-Goog-Api-Key, Api-Key;
- cookies and sign-ins: Cookie, Set-Cookie(2), WWW-Authenticate,
Authentication-Info, Proxy-*;
- the connection's own fields: Host, Connection, Keep-Alive, TE,
Trailer, Transfer-Encoding, Upgrade, Expect;
- what magpie writes for the body: Content-*, Accept,
Accept-Encoding;
- Origin, Sec-* and X-Magpie-*.
Save refuses such a name with a reason (RequestHeadersOK), and so does
the editor, before the save. The editor's list is held to Go's by
TestReplyHeadersNeverAsTheProvidersAre. A name written into
providers.json by hand is dropped on read.
- Only that provider gets them. forwardOnce, which every chat,
responses, messages, count_tokens, group-member, fallback and plugin
try goes through, puts the agent's headers in the try's context under
the try's provider id (WithClientHeaders). Provider.Sign passes only
what that id lists, before an account signs, so a signed-in account's
own signing still wins. A plugin's fetch gets them in req.Header.
- Wire headers are still masked when read (5ec237568), so a passed
token header shows masked in a call's log.
Run on mote at the tree rebased on origin/main 06944e065:
- gofmt -l: clean.
- go vet: darwin (provider, gateway, gui), GOOS=linux -tags nogui
./..., and GOOS=windows ./...: ok.
- go test -timeout 45m ./internal/provider ./internal/gateway
./internal/gui: provider and gateway ok. In gui, TestCoreScriptBudget
and the i18n tests are ok and only TestMainWindowCorners/macOS_26_SDK
is red, as on main on macOS 27 (#3949).
- The core budget is not raised. This change's words, and the comments
on extra body and the never lists, were cut first. After the rebase
onto 63dc359fb it was 438 bytes over again, so three provider-editor
comments (User-Agent, balance token, plan access keys) were cut to a
line each. The core is 1,533,554 bytes, 248 under 1,533,802.
- At this head (rebased on origin/main 63dc359fb): go test -run
Budget|I18n|ReplyHeaders ./internal/gui is ok. The new provider and
gateway tests are ok. node --test pass-headers, reply-headers,
i18n-keys, header-session-hint, balance-fix and extra-body: 162 of
162 ok.
- node --test, Chromium and WebKit: pass-headers (en/zh/zh-TW/ja/de),
reply-headers, i18n-keys, provider-detect-models, header-session-hint
and extra-body: 46 of 46 ok.
- Before the budget cut, against the same base: every GUI file that
opens the provider editor and saves (45 files plus i18n-keys) had 739
of 758 ok. These were red, and red the same on a fresh origin/main
06944e065 copy: models-works-only (#4391), provider-picks-stay
(#4397) and remote-magpie (#4398). Also red: one WebKit sub-pixel
miss in provider-detect-models (#4964), which passed on main and at
this head.
New tests:
- TestRequestHeadersList: cleaning and refusals.
- TestSignPassesClientHeaders: the agent's value over the fixed one,
never magpie's key even when listed by hand, nothing for another id,
and the fixed value when nothing was sent.
- TestPassHeadersReachTheProvider: messages relayed and translated,
chat, a chat stream, responses and count_tokens.
- TestPassHeadersOnlyToTheirProvider: a fallback that lists nothing gets
nothing, the log shows the passed headers masked, and in a group the
member that lists them gets them while the one before it, which lists
nothing, doesn't.
Broken by hand, each red, then put back:
- forwardOnce without WithClientHeaders: both gateway tests red.
- RequestHeaderPassable ignoring the never list: TestRequestHeadersList
red, and TestSignPassesClientHeaders red on X-Api-Key=magpie-key
passed on.
- Sign not skipping a fixed header the agent sent: the provider test,
and the gateway test on every route, red on X-Route=route-fixed.
Not covered: embeddings, images, video and the Codex backend relay,
which don't go through forwardOnce.
Not tried:
- a real vendor or a real plugin provider with the setting;
- Windows and Linux test runs (vet only);
- a gateway test with Authorization listed by hand, which normalize
drops on read. Sign's own check is covered by
TestSignPassesClientHeaders.
Requested by 3jRzfF52Qx on X.
166 lines
6.5 KiB
Go
166 lines
6.5 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
// heardHeaders' sibling for a fake vendor: the headers of each request it
|
|
// was sent.
|
|
type sentTo struct {
|
|
mu sync.Mutex
|
|
seen []http.Header
|
|
}
|
|
|
|
func (s *sentTo) last() http.Header {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if len(s.seen) == 0 {
|
|
return nil
|
|
}
|
|
return s.seen[len(s.seen)-1]
|
|
}
|
|
|
|
func (s *sentTo) answer(vendor provider.Protocol, status int) http.HandlerFunc {
|
|
reply := vendorReply(vendor, status, "x")
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
s.mu.Lock()
|
|
s.seen = append(s.seen, r.Header.Clone())
|
|
s.mu.Unlock()
|
|
reply(w, r)
|
|
}
|
|
}
|
|
|
|
// the agent's request, carrying a header to pass, one to pass that also
|
|
// has a fixed value, magpie's key in every place an agent puts it, and a
|
|
// header nobody lists
|
|
func passRequest(path, body string) *http.Request {
|
|
r := httptest.NewRequest("POST", path, strings.NewReader(body))
|
|
r.Header.Set("X-Tenant", "tenant-from-client")
|
|
r.Header.Set("X-Route", "route-from-client")
|
|
r.Header.Set("X-Trace-Token", "trace-secret-0123456789")
|
|
r.Header.Set("X-Unlisted", "no")
|
|
r.Header.Set("Authorization", "Bearer magpie-gateway-key")
|
|
r.Header.Set("X-Api-Key", "magpie-gateway-key")
|
|
return r
|
|
}
|
|
|
|
// 3jRzfF52Qx on X: a header the provider lists goes to it as the agent
|
|
// sent it, on every API (relayed, translated, count_tokens), standing over
|
|
// the provider's fixed Header of the same name; the fixed one goes when
|
|
// the agent sends none; magpie's key never goes.
|
|
func TestPassHeadersReachTheProvider(t *testing.T) {
|
|
for _, c := range []struct {
|
|
name, path, body string
|
|
vendor provider.Protocol
|
|
}{
|
|
{"messages relayed", "/v1/messages", `{"model":"fake/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic},
|
|
{"messages to chat", "/v1/messages", `{"model":"fake/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat},
|
|
{"chat", "/v1/chat/completions", `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`, provider.Chat},
|
|
{"chat stream", "/v1/chat/completions", `{"model":"fake/sol","stream":true,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat},
|
|
{"responses to chat", "/v1/responses", `{"model":"fake/sol","input":"hi"}`, provider.Chat},
|
|
{"count_tokens", "/v1/messages/count_tokens", `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
fresh(t)
|
|
up := &sentTo{}
|
|
p := provider.Provider{ID: "fake", Name: "Fake", Key: "sk-upstream-0123456789", Models: []string{"sol"},
|
|
Headers: map[string]string{"X-Route": "route-fixed", "X-Fixed": "fixed"},
|
|
PassHeaders: []string{"x-tenant", "X-ROUTE", "x-trace-token", "x-missing"}}
|
|
rhVendor(t, p, c.vendor, up.answer(c.vendor, 200))
|
|
s := New()
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, passRequest(c.path, c.body))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%d %s", rec.Code, rec.Body)
|
|
}
|
|
h := up.last()
|
|
if h == nil {
|
|
t.Fatal("the vendor was sent nothing")
|
|
}
|
|
for k, want := range map[string]string{
|
|
"X-Tenant": "tenant-from-client",
|
|
"X-Route": "route-from-client", // the client's over the fixed one
|
|
"X-Trace-Token": "trace-secret-0123456789",
|
|
"X-Fixed": "fixed",
|
|
} {
|
|
if got := h.Values(k); len(got) != 1 || got[0] != want {
|
|
t.Errorf("%s = %q, want %q", k, got, want)
|
|
}
|
|
}
|
|
for _, k := range []string{"X-Unlisted", "X-Missing"} {
|
|
if got := h.Get(k); got != "" {
|
|
t.Errorf("%s = %q sent", k, got)
|
|
}
|
|
}
|
|
if a := h.Get("Authorization") + h.Get("X-Api-Key"); strings.Contains(a, "magpie-gateway-key") || !strings.Contains(a, "sk-upstream-0123456789") {
|
|
t.Errorf("the vendor's key headers %q, %q", h.Get("Authorization"), h.Get("X-Api-Key"))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A listed header, and its fixed value, go to the provider that lists it
|
|
// alone: a fallback that lists nothing is sent neither, and a group's
|
|
// member that lists it is sent it. What the call log shows of a passed
|
|
// header is masked as any header is.
|
|
func TestPassHeadersOnlyToTheirProvider(t *testing.T) {
|
|
fresh(t)
|
|
noRests()
|
|
t.Cleanup(noRests)
|
|
first, spare := &sentTo{}, &sentTo{}
|
|
rhVendor(t, provider.Provider{ID: "ag", Name: "AG", Key: "k", Models: []string{"sol"}, Fallback: []string{"spare/sol"},
|
|
PassHeaders: []string{"X-Tenant", "X-Trace-Token"}}, provider.Anthropic, first.answer(provider.Anthropic, 429))
|
|
rhVendor(t, provider.Provider{ID: "spare", Name: "Spare", Key: "k", Models: []string{"sol"}},
|
|
provider.Chat, spare.answer(provider.Chat, 200))
|
|
s := New()
|
|
rec := httptest.NewRecorder()
|
|
s.Handler().ServeHTTP(rec, passRequest("/v1/messages", `{"model":"ag/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("%d %s", rec.Code, rec.Body)
|
|
}
|
|
if got := first.last().Get("X-Tenant"); got != "tenant-from-client" {
|
|
t.Errorf("the listing provider was sent X-Tenant %q", got)
|
|
}
|
|
if h := spare.last(); h == nil || h.Get("X-Tenant") != "" || h.Get("X-Trace-Token") != "" {
|
|
t.Errorf("the fallback that lists nothing was sent %v", h)
|
|
}
|
|
data, _ := json.Marshal(s.Recent()[0].Headers())
|
|
if strings.Contains(string(data), "trace-secret-0123456789") {
|
|
t.Errorf("a passed token header shown unmasked:\n%s", data)
|
|
}
|
|
if !strings.Contains(string(data), "tenant-from-client") {
|
|
t.Errorf("the passed header isn't in the call's upstream headers:\n%s", data)
|
|
}
|
|
|
|
// a group: its first member lists nothing and is refused, the next
|
|
// lists it
|
|
fresh(t)
|
|
noRests()
|
|
other, member := &sentTo{}, &sentTo{}
|
|
rhVendor(t, provider.Provider{ID: "oth", Name: "Oth", Key: "k", Models: []string{"sol"}},
|
|
provider.Chat, other.answer(provider.Chat, 429))
|
|
rhVendor(t, provider.Provider{ID: "mem", Name: "Mem", Key: "k", Models: []string{"sol"}, PassHeaders: []string{"X-Tenant"}},
|
|
provider.Chat, member.answer(provider.Chat, 200))
|
|
if err := provider.SaveGroup(provider.Group{Name: "Grp", Members: []string{"oth/sol", "mem/sol"}, Routing: provider.Ordered}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rec = httptest.NewRecorder()
|
|
New().Handler().ServeHTTP(rec, passRequest("/v1/chat/completions", `{"model":"group/grp","messages":[{"role":"user","content":"hi"}]}`))
|
|
if rec.Code != 200 {
|
|
t.Fatalf("group: %d %s", rec.Code, rec.Body)
|
|
}
|
|
if h := other.last(); h == nil || h.Get("X-Tenant") != "" {
|
|
t.Errorf("the member that lists nothing was sent %v", h)
|
|
}
|
|
if h := member.last(); h == nil || h.Get("X-Tenant") != "tenant-from-client" {
|
|
t.Errorf("the member that lists it was sent %v", h)
|
|
}
|
|
}
|