Files
magpie/internal/provider/replyheaders_test.go
T
yetone 3e31962225 provider: Request headers to pass, the agent's own values to its provider
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.
2026-11-03 14:16:20 +08:00

92 lines
4.0 KiB
Go

package provider
import (
"context"
"net/http"
"slices"
"testing"
)
// #4145: the list is kept canonical and once each, never with a header
// magpie doesn't pass on; matching ignores case.
func TestReplyHeadersList(t *testing.T) {
got := cleanReplyHeaders([]string{" x-oneapi-request-id ", "X-OneAPI-Request-ID", "set-cookie", "content-length", "access-control-allow-origin", "x-magpie-rest", "bad name", "", "x-trace"})
if want := []string{"X-Oneapi-Request-Id", "X-Trace"}; !slices.Equal(got, want) {
t.Errorf("cleaned %q, want %q", got, want)
}
for _, bad := range [][]string{{"Set-Cookie"}, {"Content-Encoding"}, {"Transfer-Encoding"}, {"Authorization"}, {"Proxy-Authenticate"}, {"X-Magpie-Note"}, {"a b"}, {"a:b"}} {
if ReplyHeadersOK(bad) == "" {
t.Errorf("%q passed as OK", bad)
}
}
if msg := ReplyHeadersOK([]string{"x-oneapi-request-id", " ", "X-Trace"}); msg != "" {
t.Errorf("OK list refused: %s", msg)
}
p := Provider{ReplyHeaders: []string{"x-trace"}}
h := http.Header{"X-Request-Id": {"r1"}, "x-trace": {"t1"}, "Set-Cookie": {"s"}, "X-Other": {"o"}}
out := p.PassedReplyHeaders(h)
if len(out) != 2 || out.Get("X-Request-Id") != "r1" || out.Get("X-Trace") != "t1" {
t.Errorf("passed %v", out)
}
// a list saved by hand with a denied name still passes nothing of it
p.ReplyHeaders = []string{"Set-Cookie"}
if out := p.PassedReplyHeaders(h); out.Get("Set-Cookie") != "" {
t.Errorf("passed %v", out)
}
if (Provider{}).PassedReplyHeaders(http.Header{"X-Other": {"o"}}) != nil {
t.Error("passed headers nobody listed")
}
}
// A provider's request headers to pass are kept canonical and once each,
// never one that carries magpie's key or the connection's own (3jRzfF52Qx
// on X).
func TestRequestHeadersList(t *testing.T) {
got := cleanRequestHeaders([]string{" x-tenant ", "X-TENANT", "authorization", "x-api-key", "host", "content-length", "x-magpie-agent", "bad name", "", "x-trace"})
if want := []string{"X-Tenant", "X-Trace"}; !slices.Equal(got, want) {
t.Errorf("cleaned %q, want %q", got, want)
}
for _, bad := range [][]string{{"Authorization"}, {"x-api-key"}, {"X-Goog-Api-Key"}, {"api-key"}, {"Cookie"}, {"Host"}, {"Content-Length"},
{"Connection"}, {"Transfer-Encoding"}, {"Proxy-Authorization"}, {"Accept-Encoding"}, {"X-Magpie-Session"}, {"a b"}} {
if RequestHeadersOK(bad) == "" {
t.Errorf("%q passed as OK", bad)
}
}
if msg := RequestHeadersOK([]string{"x-tenant", " ", "User-Agent", "Anthropic-Beta"}); msg != "" {
t.Errorf("OK list refused: %s", msg)
}
}
// Sign passes on what the provider lists, the agent's over the fixed
// Header, to that provider alone, and never magpie's key, even listed in a
// file written by hand (3jRzfF52Qx on X).
func TestSignPassesClientHeaders(t *testing.T) {
in := http.Header{"X-Tenant": {"t1"}, "Authorization": {"Bearer magpie-key"}, "X-Api-Key": {"magpie-key"}, "x-route": {"r1"}}
p := Provider{ID: "fake", Key: "sk-up", Chat: "https://up.example/v1", Headers: map[string]string{"X-Route": "fixed", "X-Only": "o"},
PassHeaders: []string{"X-Tenant", "Authorization", "X-Api-Key", "X-Route"}}
sign := func(p Provider, ctx context.Context) http.Header {
req, _ := http.NewRequest("POST", "https://up.example/v1/chat/completions", nil)
if err := p.Sign(ctx, req, Chat, nil); err != nil {
t.Fatal(err)
}
return req.Header
}
h := sign(p, WithClientHeaders(context.Background(), "fake", in))
if h.Get("X-Tenant") != "t1" || h.Get("X-Route") != "r1" || h.Get("X-Only") != "o" || len(h.Values("X-Route")) != 1 {
t.Errorf("sent %v", h)
}
if h.Get("Authorization") != "Bearer sk-up" || h.Get("X-Api-Key") == "magpie-key" {
t.Errorf("magpie's key passed on: %v", h)
}
// the agent's headers carried for another provider
h = sign(p, WithClientHeaders(context.Background(), "other", in))
if h.Get("X-Tenant") != "" || h.Get("X-Route") != "fixed" {
t.Errorf("another's request passed on %v", h)
}
// none sent: the fixed Header goes
h = sign(p, context.Background())
if h.Get("X-Route") != "fixed" || h.Get("X-Tenant") != "" {
t.Errorf("with nothing sent %v", h)
}
}