Files
magpie/internal/gateway/wire_headers_test.go
T
yetone 5ec2375688 gateway: a call's HTTP headers both ways, masked, folded under its bodies
usrname1833 on Discord asked to see the raw request and response HTTP
headers (查看原始请求和原始响应的http头), to debug as with a capture.
magpie kept the client's request headers and its own response headers
only in the request archive, and nothing of what went upstream.

Now a call keeps its headers both ways (internal/gateway/wire_headers.go):
- the client's, as they reached magpie: headerLogged in Handler() clones
  them for every request that isn't a GET, HEAD or OPTIONS;
- each request magpie sent upstream for the call: method, address,
  headers, and the answer's status, protocol, headers and time, or the
  error. rpmTransport (under s.client) records it as it is sent;
  provider.SendsThroughPlugin records a plugin account's hand-off, shown
  as handed to the plugin, since the plugin's own request to its vendor
  is made in Bun and magpie doesn't see it (the view says so). The first
  8 tries are kept, the rest counted.
Recording copies each header map; nothing is masked or sorted as a
request goes. Secrets are taken out when the headers are read
(Call.Headers): by what each header is (new redact.SecretHeader, now
behind redact.ScrubHeader: Authorization, cookies, x-api-key, api-key,
any *-Key, *-Token, *-Secret, *-Auth, *-Signature, but Idempotency-Key
and a count of tokens such as anthropic-ratelimit-tokens-remaining),
any Bearer or Basic value, and redact.Scrub on the rest; an address
loses its password, a secret-named query value (?key=) and its fragment.
They live with the call in the 40-call ring; /api/gateway/call gives
them as "headers". The request archive keeps the upstream ones as
"upstream" beside the request's and response's headers, masked the same
way. No body is stored that wasn't before.

GUI: under a recent call's bodies on Gateway and a request's on Routing,
"HTTP headers" folds open the client's headers, then each upstream
request beside its answer (wireHeadersView, plugins/usage/page.js); the
archive's copy shows its upstream requests too. Strings in all four
languages. docs/subsystems/gui-shell.md describes it.

Also changed by SecretHeader: the request archive no longer masks a
rate-limit count header (…-tokens-remaining), which the old name rule
took for a token. (provider.SecretHeader, which backups use, is another
function and unchanged.)

Tests: TestRecentCallHeadersBothWays (a fake vendor; the client's key and
cookie, magpie's upstream key and the vendor's Set-Cookie all masked;
status, protocol and response headers kept), TestRecentCallHeadersEachTry
(a 429 then the next key, both kept in order), TestPluginHandOffHeaders,
TestScrubURL, TestSecretHeaderRealNames (real header names both ways),
TestArchiveOnThisComputer and TestRecentCallBodiesOnDemand extended,
call-headers.test.cjs (Gateway, Routing and the archive's copy; chromium
and webkit; en at 1100px, zh, zh-TW, ja, de at 380px and Routing at 440;
nothing out of the box, no left-border accent).

Run (on mote, macOS 27.2, through mote-run, unless named):
- Full suite at ebd22b1b4 (the same change on 5daba8337): gofmt -l
  empty, GOOS=windows go vet ./... ok, GOOS=linux go vet -tags nogui
  ./... ok, go test -count=1 -timeout 45m ./...: every package ok but
  four tests, none in this change's code, each filed:
  TestEveryRouteHasACommandOrIsNamed (internal/cli,
  /api/usage/checkin-account from e87140242, #4826),
  TestCodexPoolSaysTheClientsVersion (#4807: another test's Codex
  identity, passes alone, 3 of 3 here), TestMainWindowCorners/macOS_26_SDK
  (#3949, macOS 27), TestClosingWindowMarksPageOutOfSight (passes
  alone; filed #4924).
- Rebased on a3768cdd1 (it changed internal/gateway, routing/client.js
  and i18n.js): gofmt, go vet, Linux (nogui) and Windows vet of
  internal/... ok; go test of internal/gateway, gui, redact, provider:
  ok but TestCodexPoolSaysTheClientsVersion (#4807, ok 3 of 3 alone
  with this change's gateway tests) and TestMainWindowCorners (#3949);
  TestCoreScriptBudget ok. GUI: call-headers, routing-bodies,
  recent-call-bodies, request-archive and i18n-keys, 58 of 58.
- Rebased again on 2c90922b0 (app.js and internal/provider, no file of
  this change): TestCoreScriptBudget and TestRecentCall* ok;
  i18n-keys plus call-headers 24 of 24 three times out of four at load
  ~130 on mote. The first try had 1 red of 24 whose name was lost
  (its output was grepped, not kept); it did not come back in 3 runs.
- At the pushed head, rebased on 898c314b7, then 3e61d814e and 8d4d8b2d5 (gateway search, redact; vet, internal/redact and the header tests again ok) (app.css, app.js, i18n.js,
  gui-shell.md and internal/gateway changed): gofmt, vet of gateway and
  gui ok; TestCoreScriptBudget, TestRecentCall*, TestRouteCall,
  TestPluginHandOffHeaders, TestArchiveOnThisComputer, TestScrubURL ok;
  i18n-keys, call-headers, routing-bodies, recent-call-bodies 54 of 54.
- call-headers.test.cjs 20 of 20 (chromium and webkit; en at 1100, zh,
  zh-TW, ja, de at 380; Routing at 440), screenshots looked over.
- GUI: not the whole suite. mote had three other sessions' full GUI
  suites running and the Linux box one, so 131 files the change can
  reach (gateway*, routing bodies/log/steady/story/time, recent*,
  call-*, request-archive, masking*, usage*, i18n*, gui-*, account-eye)
  ran on the Windows box: 1739 of 1862. Every red file was run again at
  5daba8337 on the same box: routing-bodies, gateway-card,
  gateway-systemone, masking-demo, usage-ledger's Requests and the rest
  are red there too (Windows WebKit and Windows-only), and account-eye,
  routing-log-icons, usage-ledger-leave and -probe pass alone at this
  change. call-headers' 4 webkit Routing reds on Windows are
  routing-bodies' own (".rt-day" never visible in Windows WebKit).

Broken by hand, each then put back:
- ScrubHeader back on the name rule: TestSecretHeaderRealNames red
  ("a count of tokens: [REDACTED]").
- rpm.go's upstreamBegins taken out: TestRecentCallHeadersBothWays,
  TestRecentCallHeadersEachTry, TestArchiveOnThisComputer and
  TestRecentCallBodiesOnDemand red.
- scrubHeaders off the sent headers: TestPluginHandOffHeaders red with
  the plugin's key shown.
- Gateway client.js's toggle taken out: the 5 chromium recent-call GUI
  tests red.

Not tried:
- The whole GUI suite (above), and the GUI on Linux.
- A real account or the real app: only fakes.
- What a plugin sends its vendor (made in Bun, not seen by magpie; the
  view says so), and headers Go's transport adds itself
  (Accept-Encoding, Content-Length).
- magpie's own requests (System One's decision, titles, search) keep no
  headers; a gateway served by another magpie shows none.

Asked by usrname1833 on Discord.
2026-11-03 02:25:23 +08:00

135 lines
5.2 KiB
Go

package gateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A recent call keeps its HTTP headers both ways (usrname1833 on Discord:
// 查看原始请求和原始响应的http头): the client's, what magpie sent upstream,
// and the head of what came back, every secret taken out by what the
// header is, the rest as it went.
func TestRecentCallHeadersBothWays(t *testing.T) {
fresh(t)
const upKey = "sk-upstream-0123456789abcdefghij"
vendor := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Anthropic-Ratelimit-Tokens-Remaining", "9000")
w.Header().Set("X-Request-Id", "req-vendor-77")
archiveVendor{}.ServeHTTP(w, r) // and its Set-Cookie
})
serveOn(t, "fake", upKey, []string{"m1"}, vendor)
s := New()
archivePost(t, s)
c := s.Recent()[0]
h := c.Headers()
if h == nil {
t.Fatal("no headers kept")
}
data, _ := json.Marshal(h)
for _, secret := range []string{upKey, "magpie-gateway-key", "another-secret", "cookie-secret", "abc123"} {
if strings.Contains(string(data), secret) {
t.Errorf("%s shown:\n%s", secret, data)
}
}
// the client's, as it reached magpie
if got := h.Request["User-Agent"]; len(got) != 1 || got[0] != "claude-cli/2.1.0" {
t.Errorf("client's User-Agent %v", got)
}
if got := h.Request["Authorization"]; len(got) != 1 || got[0] == "" {
t.Errorf("client's Authorization %v: masked, not gone", got)
}
if len(h.Upstream) != 1 {
t.Fatalf("upstream %+v", h.Upstream)
}
u := h.Upstream[0]
if u.Method != "POST" || !strings.HasSuffix(u.URL, "/v1/chat/completions") || u.Plugin != "" {
t.Errorf("sent %s %s (plugin %q)", u.Method, u.URL, u.Plugin)
}
if got := u.Request["Authorization"]; len(got) != 1 || strings.Contains(got[0], upKey) {
t.Errorf("upstream Authorization %v", got)
}
if http.Header(u.Request).Get("Content-Type") == "" {
t.Errorf("upstream headers %v", u.Request)
}
if u.Status != 200 || u.Proto != "HTTP/1.1" || u.Error != "" {
t.Errorf("answered %d %s %q", u.Status, u.Proto, u.Error)
}
resp := http.Header(u.Response)
if resp.Get("X-Request-Id") != "req-vendor-77" || resp.Get("Anthropic-Ratelimit-Tokens-Remaining") != "9000" ||
resp.Get("Content-Type") != "application/json" || resp.Get("Set-Cookie") == "" {
t.Errorf("upstream response headers %v", resp)
}
}
// Each upstream try is kept in the order it went, a retry on the next key
// too.
func TestRecentCallHeadersEachTry(t *testing.T) {
fresh(t)
k := &keyed{fail: map[string]int{"ka-first-secret": 429}}
serveOn(t, "fake", "ka-first-secret", []string{"m1"}, k, "kb-second-secret")
s := New()
if code, body := postAs(t, s, "", `{"model":"fake/m1","messages":[{"role":"user","content":"hi"}]}`); code != 200 {
t.Fatalf("%d %s", code, body)
}
h := s.Recent()[0].Headers()
if h == nil || len(h.Upstream) != 2 || h.Upstream[0].Status != 429 || h.Upstream[1].Status != 200 {
t.Fatalf("tries %+v (vendor saw %v)", h, k.tried)
}
data, _ := json.Marshal(h)
if strings.Contains(string(data), "first-secret") || strings.Contains(string(data), "second-secret") {
t.Errorf("a key shown:\n%s", data)
}
}
// A request handed to a plugin is kept as handed, under the plugin's name;
// past headerTriesMost, only counted; and a call whose context keeps no
// log (magpie's own) keeps nothing.
func TestPluginHandOffHeaders(t *testing.T) {
l := &headerLog{in: http.Header{"Cookie": {"a=b"}}}
ctx := t.Context()
req := httptest.NewRequest("POST", "https://plugin.invalid/v1/messages", nil).WithContext(context.WithValue(ctx, headerLogKey{}, l))
req.Header.Set("X-Api-Key", "plugin-key-secret-123")
req.Header.Set("Anthropic-Version", "2023-06-01")
for range headerTriesMost + 3 {
provider.SendsThroughPlugin("cursor", req)(&http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}}}, nil)
}
h := l.masked()
if len(h.Upstream) != headerTriesMost || h.More != 3 {
t.Fatalf("%d kept, %d more", len(h.Upstream), h.More)
}
u := h.Upstream[0]
if u.Plugin != "cursor" || u.Request["X-Api-Key"][0] == "plugin-key-secret-123" || u.Request["Anthropic-Version"][0] != "2023-06-01" ||
u.Response["Content-Type"][0] != "text/event-stream" || h.Request["Cookie"][0] == "a=b" {
t.Errorf("%+v", h)
}
// none kept for a request with no log
bare := httptest.NewRequest("POST", "https://plugin.invalid/v1/messages", nil)
provider.SendsThroughPlugin("cursor", bare)(nil, io.EOF)
if (Call{}).Headers() != nil {
t.Error("a call with no log has headers")
}
}
// An address keeps no secret: a password, a key in its query or path.
func TestScrubURL(t *testing.T) {
u, _ := url.Parse("https://user:pass-secret@generativelanguage.googleapis.com/v1beta/models/g:streamGenerateContent?alt=sse&key=AIzaSyA-0123456789abcdefghijklmnopqrstu#frag")
got := scrubURL(u)
for _, secret := range []string{"pass-secret", "user:", "AIzaSyA-0123456789abcdefghijklmnopqrstu", "frag"} {
if strings.Contains(got, secret) {
t.Errorf("%s in %s", secret, got)
}
}
if !strings.Contains(got, "generativelanguage.googleapis.com/v1beta/models/g:streamGenerateContent") || !strings.Contains(got, "alt=sse") {
t.Errorf("address lost: %s", got)
}
}