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.
This commit is contained in:
yetone
2026-11-03 02:25:23 +08:00
parent 8d4d8b2d5f
commit 5ec2375688
23 changed files with 770 additions and 13 deletions
+31
View File
@@ -446,6 +446,37 @@ bucket and `RequestArchiveLocal` while it has none; `GET
`TestRoutingRequestOpensItsBodies`, `TestArchiveWholeBodies` and
`routing-bodies.test.cjs`.
Under the bodies, on Gateway and on Routing, "HTTP headers" folds open a
call's headers both ways (usrname1833 on Discord: 查看原始请求和原始响应的
http头): the client's, as they reached magpie, then each request magpie
sent upstream for the call, its method, address and headers, and the
status, protocol, headers and time of its answer, or the error in place of
one (`wireHeadersView` in plugins/usage/page.js; `headers` in
`/api/gateway/call`, `Call.Headers`,
[`wire_headers.go`](../../internal/gateway/wire_headers.go)). The client's
are taken by `headerLogged` in `Handler()` for every request that isn't a
GET, HEAD or OPTIONS; what goes upstream by `rpmTransport`, under
`s.client`, as it is sent (so a header Go's transport adds itself,
`Accept-Encoding` or `Content-Length`, isn't there), and by
`provider.SendsThroughPlugin` for an account served by a plugin, which is
shown as handed to the plugin: the plugin sends it on to its vendor with
headers of its own that magpie doesn't see, and the view says so. A call
keeps its first 8 upstream requests (`headerTriesMost`) and a count of the
rest. Recording is a copy of each header map; nothing is masked as a
request goes. Secrets are taken out when the headers are read, by what
each header is (`redact.SecretHeader`: Authorization, cookies, `x-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 any
secret `redact.Scrub` finds in the rest; an address loses its password, a
secret-named query value (`?key=`) and its fragment (`scrubURL`). They live
with the call in the 40-call ring, and the request archive keeps the
upstream ones as `upstream` beside the request's and response's headers,
masked the same way; magpie's own requests (System One's decision, a
title, a search) keep none. See `TestRecentCallHeadersBothWays`,
`TestRecentCallHeadersEachTry`, `TestPluginHandOffHeaders`,
`TestSecretHeaderRealNames` and `call-headers.test.cjs`.
### Plugin check-in switches
A plugin's Usage-card Auto check-in button reads the persisted
+9
View File
@@ -186,6 +186,12 @@ type Archived struct {
Call Call `json:"call"` // as Recent calls has it, its bodies below
Request ArchivePart `json:"request"`
Response ArchivePart `json:"response"`
// Upstream: each request magpie sent upstream for it, its headers
// both ways (wire_headers.go), their secrets taken out; none in an
// archive from before them
Upstream []UpstreamHeaders `json:"upstream,omitempty"`
// UpstreamMore: the upstream requests past those, not kept
UpstreamMore int `json:"upstreamMore,omitempty"`
}
// ArchivePart is one way of a call: the request, or the response.
@@ -286,6 +292,9 @@ func upload(j archiveJob) {
Response: ArchivePart{Status: c.Status, Headers: scrubHeaders(j.resHead),
Body: string(redact.ScrubJSON(resBody)), Size: j.res.size, Truncated: j.res.cut()},
}
if h := j.c.headers.masked(); h != nil {
a.Upstream, a.UpstreamMore = h.Upstream, h.More
}
// as it reads in the bucket: a query's & and a body's <tags> as they are
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
+6
View File
@@ -52,6 +52,12 @@ func TestArchiveOnThisComputer(t *testing.T) {
!strings.Contains(a.Request.Body, "deploy with [REDACTED:API_KEY]") || !strings.Contains(a.Response.Body, `"content":"done"`) {
t.Errorf("archived %+v", a)
}
// what went upstream for it, and the head of what came back, masked
// as the rest (usrname1833 on Discord)
if len(a.Upstream) != 1 || a.Upstream[0].Status != 200 || len(a.Upstream[0].Request["Authorization"]) != 1 ||
a.Upstream[0].Request["Authorization"][0] != "[REDACTED]" || len(a.Upstream[0].Response["Set-Cookie"]) != 1 {
t.Errorf("upstream %+v", a.Upstream)
}
if fi, _ := os.Stat(path); runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 {
t.Errorf("mode %v, want 0600", fi.Mode().Perm())
}
+3 -3
View File
@@ -1349,7 +1349,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
writeError(w, provider.Responses, res.StatusCode, codexKeyRefused(msg))
s.record(Call{Route: routeOf(tr), Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
Provider: "openai", Agent: callerOf(r).agent, Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Error: res.Status})
Millis: time.Since(start).Milliseconds(), Error: res.Status, headers: headerLogOf(r.Context())})
end(res.StatusCode, res.Status, 0, 0)
return
}
@@ -1372,7 +1372,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
failWith(res.StatusCode, said)
s.record(Call{Route: routeOf(tr), Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
Provider: "openai", Agent: callerOf(r).agent, Kind: callKind(r.Header), Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Error: said})
Millis: time.Since(start).Milliseconds(), Error: said, headers: headerLogOf(r.Context())})
end(res.StatusCode, said, 0, 0)
return
}
@@ -1480,7 +1480,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
}
call := Call{Time: start, From: provider.Responses, To: provider.Responses, Model: modelOf(body),
Provider: "openai", Agent: callerOf(r).agent, Kind: kind, Status: res.StatusCode,
Millis: time.Since(start).Milliseconds(), Fallback: resetNote}
Millis: time.Since(start).Milliseconds(), Fallback: resetNote, headers: headerLogOf(r.Context())}
if len(tried) > 0 {
// the overloads it was asked again for, before the one that answered
call.Fallback = strings.Join(append(tried, call.Fallback), "; ")
+1 -1
View File
@@ -159,7 +159,7 @@ func (s *Server) serveDecideTries(w http.ResponseWriter, r *http.Request, body [
capture := &captureResponseWriter{ResponseWriter: w}
w = capture
call := Call{Time: start, From: provider.Chat, To: provider.Chat, Model: asked, Provider: cs[0].p.ID, Agent: who.agent, Via: who.via,
wire: archiving(r, capture, start, body)}
wire: archiving(r, capture, start, body), headers: headerLogOf(r.Context())}
call.RequestBody, call.RequestTruncated = captureRequestBody(body)
defer discardArchive(capture)
tr := s.trace.beginFor(r, Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: cs[0].p.ID,
+1 -1
View File
@@ -500,7 +500,7 @@ func (s *Server) images(edit bool) http.HandlerFunc {
return
}
who := callerOf(r)
call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: d.Model}
call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: d.Model, headers: headerLogOf(r.Context())}
usage.Saw(agentOf(r))
fail := func(code int, msg string) {
call.Status, call.Error, call.Millis = code, msg, time.Since(start).Milliseconds()
+1 -1
View File
@@ -88,7 +88,7 @@ func (j *jsonRetrieval) forModel(model string) ([]byte, string, error) {
// provider, or over a group's members, and passes the answer back.
func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, operation string, start time.Time, asked string, req retrieval) {
who := callerOf(r)
call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: asked}
call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: asked, headers: headerLogOf(r.Context())}
usage.Saw(agentOf(r))
// a model the user disabled (#1867), or a group of them all
if msg, off := idOff(asked); off {
+5 -2
View File
@@ -450,6 +450,9 @@ type Call struct {
// when it was on (archive.go); wire what it keeps besides
Archive string `json:"archive,omitempty"`
wire *wire
// headers: its headers both ways, as they went (wire_headers.go),
// read masked by Headers
headers *headerLog
// wholeIn/wholeOut are the whole bodies for an observer that asks for
// them uncut (the OTLP export, #538): nil leaves it to the 256 KiB
// bodies above, which is all the Recent-calls page keeps
@@ -886,7 +889,7 @@ func (s *Server) Handler() http.Handler {
// the goroutine dump first, ahead of every lock the rest can be stuck
// on (dumpFirst)
// a socket's turns go through all of it again (socketEntry)
return socketEntry(s.dumpFirst(s.counted(holdCatalog(corsGuard(callerGuard(readOnlyGuard(mux, withCaller(keyLimited(mux)))))))))
return socketEntry(s.dumpFirst(s.counted(headerLogged(holdCatalog(corsGuard(callerGuard(readOnlyGuard(mux, withCaller(keyLimited(mux))))))))))
}
// routes are the client APIs, each by its pattern: readOnlyGuard reads
@@ -2028,7 +2031,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
metadata := requestSessionMetadata(r.Header, body)
var clientResponseID string // only a reply released to the client owns this ID
call := Call{Time: start, From: from, Model: unprefixed(modelOf(body)), Agent: who.agent, Via: who.via, Kind: requestCallKind(r.Header, metadata),
wire: archiving(r, capture, start, nil)}
wire: archiving(r, capture, start, nil), headers: headerLogOf(r.Context())}
// the log has the body as it went: masked, or as written where it
// went so
logBody := func(b []byte) {
+5 -1
View File
@@ -286,5 +286,9 @@ func (t rpmTransport) RoundTrip(r *http.Request) (*http.Response, error) {
return nil, err
}
}
return t.next.RoundTrip(r)
// its headers, both ways, for the call it is for (wire_headers.go)
done := upstreamBegins(r, "")
res, err := t.next.RoundTrip(r)
done(res, err)
return res, err
}
+1 -1
View File
@@ -744,7 +744,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
return
}
who := callerOf(r)
call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: f.Model}
call := Call{Time: start, From: provider.Chat, Agent: who.agent, Via: who.via, Model: f.Model, headers: headerLogOf(r.Context())}
usage.Saw(agentOf(r))
fail := func(code int, msg string) {
call.Status, call.Error, call.Millis = code, msg, time.Since(start).Milliseconds()
+191
View File
@@ -0,0 +1,191 @@
package gateway
// A call's headers, both ways (usrname1833 on Discord: 查看原始请求和原始响应的
// http头, for debugging what a capture would show): the client's request
// as it reached magpie, and each request magpie sent upstream for it —
// its method and address, the headers it went with, and the status,
// protocol and headers that came back. Recent calls and the Routing page
// open them beside the bodies, and the request archive keeps them.
//
// They cost a request one map copy each way, at most headerTriesMost of
// them: nothing is masked, sorted or written as it goes. The secrets are
// taken out only when they are read (CallHeaders), by what each header is
// (redact.ScrubHeader): Authorization, x-api-key, cookies, any *-Token,
// *-Secret, *-Key a credential is in, and any value that is a Bearer or a
// key. Nothing is kept past the ring's 40 calls but in the archive, which
// keeps them masked, as it keeps everything.
import (
"context"
"net/http"
"net/url"
"slices"
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/redact"
)
// headerTriesMost is how many upstream requests a call keeps the headers
// of: the first ones, then a count of the rest.
const headerTriesMost = 8
// headerLog is one call's headers, as they went: the client's, and each
// upstream request's.
type headerLog struct {
mu sync.Mutex
in http.Header
tries []headerTry
more int
}
type headerTry struct {
method string
url *url.URL
sent http.Header
plugin string // the plugin the request was handed to, "" for a vendor's address
start time.Time
took time.Duration
status int
proto string
got http.Header
err string
}
type headerLogKey struct{}
// headerLogged gives each request a client makes of the gateway a log of
// its headers, the client's taken now, before a guard takes a key off
// them. A GET (a model list, a page) has none: it is no call.
func headerLogged(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions {
h.ServeHTTP(w, r)
return
}
if _, ok := r.Context().Value(headerLogKey{}).(*headerLog); ok {
h.ServeHTTP(w, r) // a socket's turn, or one handed on inside
return
}
l := &headerLog{in: r.Header.Clone()}
h.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), headerLogKey{}, l)))
})
}
// headerLogOf is the log of the call ctx is for, nil when it keeps none.
func headerLogOf(ctx context.Context) *headerLog {
l, _ := ctx.Value(headerLogKey{}).(*headerLog)
return l
}
// upstreamBegins notes req, about to go out for the call its context is
// for, and is to be told what came back for it. plugin names the plugin
// it is handed to, "" for one sent to its address. Its headers are taken
// now, as they go, before a transport under it can add to them.
func upstreamBegins(req *http.Request, plugin string) func(*http.Response, error) {
l := headerLogOf(req.Context())
if l == nil {
return func(*http.Response, error) {}
}
t := headerTry{method: req.Method, url: req.URL, sent: req.Header.Clone(), plugin: plugin, start: time.Now()}
if t.sent == nil {
t.sent = http.Header{}
}
if req.Host != "" && req.URL != nil && req.Host != req.URL.Host {
t.sent.Set("Host", req.Host)
}
return func(res *http.Response, err error) {
t.took = time.Since(t.start)
if err != nil {
t.err = err.Error()
} else if res != nil {
t.status, t.proto, t.got = res.StatusCode, res.Proto, res.Header.Clone()
}
l.mu.Lock()
defer l.mu.Unlock()
if len(l.tries) >= headerTriesMost {
l.more++
return
}
l.tries = append(l.tries, t)
}
}
func init() {
// a plugin's account sends through the plugin, past the gateway's
// transport (provider.Provider.Do)
provider.SendsThroughPlugin = func(id string, req *http.Request) func(*http.Response, error) {
return upstreamBegins(req, id)
}
}
// CallHeaders is a call's headers both ways, every secret taken out.
type CallHeaders struct {
// Request: the client's, as it reached magpie
Request map[string][]string `json:"request"`
// Upstream: each request magpie sent for it, in order
Upstream []UpstreamHeaders `json:"upstream"`
// More: the upstream requests past the first headerTriesMost, not kept
More int `json:"more,omitempty"`
}
// UpstreamHeaders is one request magpie sent upstream, and its answer's
// head.
type UpstreamHeaders struct {
Method string `json:"method"`
URL string `json:"url"`
// Plugin: the plugin it was handed to, which sends it on to its
// vendor itself, with headers of its own magpie doesn't see
Plugin string `json:"plugin,omitempty"`
Request map[string][]string `json:"request"`
Millis int64 `json:"ms"`
Status int `json:"status,omitempty"`
Proto string `json:"proto,omitempty"`
Response map[string][]string `json:"response,omitempty"`
Error string `json:"error,omitempty"`
}
// Headers is c's headers both ways, masked, nil when none were kept (a
// call from before this, or one magpie made for itself).
func (c Call) Headers() *CallHeaders {
return c.headers.masked()
}
func (l *headerLog) masked() *CallHeaders {
if l == nil {
return nil
}
l.mu.Lock()
tries := append([]headerTry(nil), l.tries...)
more := l.more
l.mu.Unlock()
// kept as each was answered: shown as each went
slices.SortStableFunc(tries, func(a, b headerTry) int { return a.start.Compare(b.start) })
out := &CallHeaders{Request: scrubHeaders(l.in), Upstream: make([]UpstreamHeaders, 0, len(tries)), More: more}
for _, t := range tries {
u := UpstreamHeaders{Method: t.method, URL: scrubURL(t.url), Plugin: t.plugin, Request: scrubHeaders(t.sent),
Millis: t.took.Milliseconds(), Status: t.status, Proto: t.proto, Error: redact.Scrub(t.err)}
if t.got != nil {
u.Response = scrubHeaders(t.got)
}
out.Upstream = append(out.Upstream, u)
}
return out
}
// scrubURL is an address with what may be a secret in it taken out: a
// password, a key= in its query, a key in its path.
func scrubURL(u *url.URL) string {
if u == nil {
return ""
}
c := *u
c.User = nil
c.Path, c.RawPath = redact.Scrub(c.Path), ""
if c.RawQuery != "" {
c.RawQuery = scrubQuery(c.RawQuery)
}
c.Fragment, c.RawFragment = "", ""
return c.String()
}
+134
View File
@@ -0,0 +1,134 @@
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)
}
}
+8
View File
@@ -2608,6 +2608,14 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.jt-sum::after { content: " " attr(data-n) " "; font-size: .9em; color: var(--faint); }
.call-body code.empty { color: var(--faint); font-family: var(--ui-font, var(--font)); }
:where(html[data-fonts]) .call-body code.empty { font-style: var(--ui-style, inherit); font-weight: var(--ui-weight, inherit); font-stretch: var(--ui-stretch, 100%); }
/* a call's HTTP headers both ways, folded under its bodies (wireHeadersView) */
.call-wire { border-top: 1px solid var(--line-2); background: var(--card); }
.call-wire-toggle { display: flex; align-items: center; gap: 6px; width: 100%; height: 27px; padding: 0 10px; border-radius: 0; font-size: 10.5px; font-weight: 600; color: var(--muted); justify-content: flex-start; }
.call-wire-toggle:hover { color: var(--fg); background: var(--pill); }
.call-wire.open > .call-wire-toggle .call-chev { transform: rotate(90deg); }
.call-wire:not(.open) > .call-wire-toggle .call-chev { transform: none; } /* not the open call's turn */
.call-wire-wide, .call-wire-note { grid-column: 1 / -1; }
.call-wire-note { margin: 0; padding: 8px 10px; font-size: 11px; line-height: 1.45; color: var(--muted); background: var(--card); }
@media (max-width: 760px) { .call-details { grid-template-columns: 1fr; } }
/* a call the request archive kept: read back under the bodies, the whole width */
.call-archive { grid-column: 1 / -1; min-width: 0; background: var(--card); }
+32
View File
@@ -2930,6 +2930,14 @@ const I18N = {
"Request Headers": "请求头",
"Response Headers": "响应头",
"Secrets taken out": "已去除密钥",
"HTTP headers": "HTTP 头",
"From the client": "客户端发来的",
"Sent upstream": "发往上游",
"Handed to plugin {name}": "交给插件 {name}",
"Upstream response": "上游响应",
"No request went upstream.": "没有请求发往上游。",
"{n} more requests upstream, not kept": "另有 {n} 个上游请求,未保留",
"A plugin sends a request on to its vendor with headers of its own, which magpie doesn't see.": "插件会带着自己的请求头再发给服务商,这些 magpie 看不到。",
"Too long to show here. Download the archive to read it whole.": "内容过长,不在此显示。下载存档可查看完整内容。",
"This archive is {size}, too large to show here. Download it to read it.": "存档 {size},过大无法在此显示,请下载后查看。",
"very large": "非常大",
@@ -7344,6 +7352,14 @@ const I18N = {
"Request Headers": "請求頭",
"Response Headers": "回應頭",
"Secrets taken out": "已去除金鑰",
"HTTP headers": "HTTP 標頭",
"From the client": "用戶端送來的",
"Sent upstream": "送往上游",
"Handed to plugin {name}": "交給外掛 {name}",
"Upstream response": "上游回應",
"No request went upstream.": "沒有請求送往上游。",
"{n} more requests upstream, not kept": "另有 {n} 個上游請求,未保留",
"A plugin sends a request on to its vendor with headers of its own, which magpie doesn't see.": "外掛會帶著自己的標頭再送給服務商,這些 magpie 看不到。",
"Too long to show here. Download the archive to read it whole.": "內容過長,不在此顯示。下載存檔可檢視完整內容。",
"This archive is {size}, too large to show here. Download it to read it.": "存檔 {size},過大無法在此顯示,請下載後檢視。",
"very large": "非常大",
@@ -11755,6 +11771,14 @@ const I18N = {
"Request Headers": "リクエストヘッダー",
"Response Headers": "レスポンスヘッダー",
"Secrets taken out": "秘密情報を除去済み",
"HTTP headers": "HTTP ヘッダー",
"From the client": "クライアントから",
"Sent upstream": "上流へ送信",
"Handed to plugin {name}": "プラグイン {name} に渡した",
"Upstream response": "上流の応答",
"No request went upstream.": "上流へ送ったリクエストはありません。",
"{n} more requests upstream, not kept": "ほかに上流へのリクエスト {n} 件(保存なし)",
"A plugin sends a request on to its vendor with headers of its own, which magpie doesn't see.": "プラグインは独自のヘッダーを付けてベンダーに送ります。それは magpie からは見えません。",
"Too long to show here. Download the archive to read it whole.": "長すぎるためここには表示できません。全体を読むにはアーカイブをダウンロードしてください。",
"This archive is {size}, too large to show here. Download it to read it.": "このアーカイブは {size} あり、大きすぎてここには表示できません。ダウンロードして読んでください。",
"very large": "非常に大きい",
@@ -16177,6 +16201,14 @@ const I18N = {
"Request Headers": "Anfrage-Header",
"Response Headers": "Antwort-Header",
"Secrets taken out": "Geheimnisse entfernt",
"HTTP headers": "HTTP-Header",
"From the client": "Vom Client",
"Sent upstream": "An den Anbieter gesendet",
"Handed to plugin {name}": "An Plugin {name} übergeben",
"Upstream response": "Antwort des Anbieters",
"No request went upstream.": "Keine Anfrage ging an den Anbieter.",
"{n} more requests upstream, not kept": "{n} weitere Anfragen an den Anbieter, nicht behalten",
"A plugin sends a request on to its vendor with headers of its own, which magpie doesn't see.": "Ein Plugin sendet die Anfrage mit eigenen Headern an seinen Anbieter weiter; die sieht magpie nicht.",
"Too long to show here. Download the archive to read it whole.": "Zu lang für die Anzeige hier. Laden Sie das Archiv herunter, um alles zu lesen.",
"This archive is {size}, too large to show here. Download it to read it.": "Dieses Archiv ist {size} groß, zu groß für die Anzeige hier. Laden Sie es zum Lesen herunter.",
"very large": "sehr groß",
@@ -21,6 +21,7 @@ let connectFolded = true;
try { connectFolded = localStorage.getItem("magpie.gwConnectFolded") !== "0"; } catch {}
const expandedCalls = new Set(); // recent-call ids whose wire bodies are open
const callBodies = new Map(); // callRow → its bodies, read when it is opened (#1521)
const wireOpen = new Set(); // recent-call ids whose HTTP headers are open
// recent calls drawn a page at a time, as many as the plugin's setting
// says (callsPage)
let callsPage = 20;
@@ -691,6 +692,7 @@ function renderActivity() {
const ids = new Set(g.calls.map(callRow));
for (const id of callBodies.keys()) if (!ids.has(id)) callBodies.delete(id);
for (const id of expandedCalls) if (!ids.has(id)) expandedCalls.delete(id);
for (const id of wireOpen) if (!ids.has(id)) wireOpen.delete(id);
const box = $("#activity");
// a body being read keeps its place as new calls come in
const kept = new Map();
@@ -744,6 +746,11 @@ function renderActivity() {
);
item.dataset.id = id;
item.append(details);
// the headers both ways, folded (wireHeadersView, usage/page.js)
if (body.headers) item.append(wireHeadersView(body.headers, wireOpen.has(id), () => {
if (wireOpen.has(id)) wireOpen.delete(id); else wireOpen.add(id);
renderActivity();
}));
}
box.append(item);
}
@@ -2846,6 +2846,7 @@ function routingPage(part) {
// request archive's copy, when it was on. Nothing more is recorded for
// it: without the archive an older request says how to keep them.
const bodiesGot = new Map(); // route id → { busy } | its bodies | { gone } | { error }
const wireOpen = new Set(); // route ids whose HTTP headers are open
async function loadBodies(id) {
const pending = { busy: true };
bodiesGot.set(id, pending);
@@ -2872,7 +2873,7 @@ function routingPage(part) {
}
if (!bodiesGot.has(r.id)) loadBodies(r.id);
const got = bodiesGot.get(r.id);
const key = JSON.stringify([document.documentElement.lang, r.id, r.archive || "", !!providers?.gateway?.archive?.on, got.busy ? "busy" : got.gone ? "gone" : got.error ? "error" : "in"]);
const key = JSON.stringify([document.documentElement.lang, r.id, r.archive || "", !!providers?.gateway?.archive?.on, got.busy ? "busy" : got.gone ? "gone" : got.error ? "error" : "in", wireOpen.has(r.id)]);
if (key === bodiesKey) return;
bodiesKey = key;
if (got.busy) { bodies.replaceChildren(el("div", "none", t("Fetching…"))); return; }
@@ -2902,6 +2903,12 @@ function routingPage(part) {
callBodyPanel("Response Body", got.responseBody, got.responseTruncated, "rt|" + r.id),
);
bodies.replaceChildren(grid);
// the headers both ways, folded (wireHeadersView, usage/page.js)
if (got.headers) bodies.append(wireHeadersView(got.headers, wireOpen.has(r.id), () => {
if (wireOpen.has(r.id)) wireOpen.delete(r.id); else wireOpen.add(r.id);
bodiesKey = "";
renderBodies(logR);
}));
}
// holdStory keeps the story of the live request, its head and its lines,
// as tall as the tallest of the last few requests told, at this
+46
View File
@@ -18,6 +18,50 @@ function headersPanel(label, first, headers) {
return panel;
}
// A call's HTTP headers both ways (usrname1833 on Discord: 查看原始请求和
// 原始响应的http头, to debug what a capture would show), as the gateway
// read them out, secrets taken out: the client's, then each request magpie
// sent upstream for it and the head of its answer. Folded under the bodies
// on the Gateway page's recent calls and on Routing; open when open is.
// h is /api/gateway/call's headers, or the archive's upstream ones.
function wireHeadersView(h, open, toggle) {
const box = el("section", "call-wire" + (open ? " open" : ""));
const b = el("button", "text call-wire-toggle");
b.setAttribute("aria-expanded", String(open));
const chev = el("span", "call-chev");
chev.append(svg(CHEV_R, 11, 1.6));
b.append(chev, el("span", "", t("HTTP headers")));
b.onclick = (ev) => { ev.stopPropagation(); toggle(); };
box.append(b);
if (!open) return box;
box.append(wireHeadersGrid(h, true));
return box;
}
// the panels: the client's request (when withClient), and each upstream
// request with its answer
function wireHeadersGrid(h, withClient) {
const grid = el("div", "call-details call-wire-grid");
if (withClient) {
const client = headersPanel(t("From the client"), "", h.request);
client.classList.add("call-wire-wide");
grid.append(client);
}
const ups = h.upstream || [];
if (!ups.length) grid.append(el("p", "call-wire-note", t("No request went upstream.")));
let plugin = false;
for (const u of ups) {
plugin ||= !!u.plugin;
grid.append(
headersPanel(u.plugin ? t("Handed to plugin {name}", { name: u.plugin }) : t("Sent upstream"), `${u.method} ${u.url}`, u.request),
headersPanel(t("Upstream response"), u.error ? u.error : `${u.proto || "HTTP"} ${u.status} · ${ledTook(u.ms)}`, u.response),
);
}
if (h.more) grid.append(el("p", "call-wire-note", t("{n} more requests upstream, not kept", { n: h.more })));
if (plugin) grid.append(el("p", "call-wire-note", t("A plugin sends a request on to its vendor with headers of its own, which magpie doesn't see.")));
return grid;
}
// The archived file, whole, however large: to the browser in magpie web,
// to Downloads in the app (#447).
async function downloadArchive(name, b) {
@@ -102,6 +146,8 @@ function archivePanel(name, id, redraw) {
archiveBodyPanel("Response Body", got.response, id + "|archive"),
);
box.append(grid);
// what magpie sent upstream for it, and the heads that came back
if (got.upstream?.length) box.append(wireHeadersGrid({ upstream: got.upstream, more: got.upstreamMore }, false));
return box;
}
+3
View File
@@ -1236,6 +1236,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
writeJSON(rw, map[string]any{
"requestBody": c.RequestBody, "responseBody": c.ResponseBody,
"requestTruncated": c.RequestTruncated, "responseTruncated": c.ResponseTruncated,
// the headers both ways, the client's and each upstream
// request's, masked (usrname1833 on Discord)
"headers": c.Headers(),
})
return
}
+9
View File
@@ -78,6 +78,15 @@ func TestRecentCallBodiesOnDemand(t *testing.T) {
if w.Code != http.StatusOK || detail.RequestBody != first.RequestBody || detail.ResponseBody != first.ResponseBody || !detail.RequestTruncated || !detail.ResponseTruncated || w.Header().Get("Cache-Control") != "no-store" {
t.Fatal("the detail must keep both captured previews and truncation flags")
}
// and its headers both ways, the key it went upstream with taken out
// (usrname1833 on Discord)
var wire struct{ Headers *gateway.CallHeaders }
json.Unmarshal(w.Body.Bytes(), &wire)
if h := wire.Headers; h == nil || h.Request["User-Agent"][0] != "codex" || len(h.Upstream) != 1 ||
h.Upstream[0].Status != 200 || h.Upstream[0].Response["Content-Type"][0] != "application/json" ||
len(h.Upstream[0].Request["Authorization"]) != 1 || strings.Contains(w.Body.String(), "Bearer fixture") {
t.Fatalf("headers: %s", w.Body.String()[:min(w.Body.Len(), 2000)])
}
if s.Recent()[0].RequestBody == "" || s.Recent()[0].ResponseBody == "" {
t.Fatal("building a summary changed the gateway's captured bodies")
}
+184
View File
@@ -0,0 +1,184 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A call's HTTP headers both ways (usrname1833 on Discord: 查看原始请求和原始
// 响应的http头, to debug what a capture would show): folded under its bodies
// on the Gateway page's recent calls and on the Routing page, the client's
// headers, then each request magpie sent upstream and the head of its
// answer, an error in place of one that had none, a plugin's hand-off said
// as one, and the tries not kept counted. The request archive's copy shows
// what went upstream too. Opening the bodies doesn't open them; the bodies'
// own panels stay two. Both engines, a narrow window, every language;
// nothing runs out of the call, no left-border accent. The API is faked.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { reach } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const now = new Date();
const day = [now.getFullYear(), now.getMonth() + 1, now.getDate()].map((n) => String(n).padStart(2, "0")).join("-");
const headers = {
request: { "User-Agent": ["claude-cli/2.1.0"], Authorization: ["[REDACTED]"], "Content-Type": ["application/json"] },
upstream: [
{ method: "POST", url: "https://api.example.com/v1/chat/completions", request: { Authorization: ["[REDACTED]"], "Content-Type": ["application/json"] }, ms: 812, status: 429, proto: "HTTP/2.0", response: { "Retry-After": ["3"], "X-Request-Id": ["req-UP-1"] } },
{ method: "POST", url: "https://plugin.invalid/v1/messages", plugin: "cursor", request: { "X-Api-Key": ["[REDACTED]"] }, ms: 1200, status: 200, response: { "Content-Type": ["text/event-stream"] } },
{ method: "POST", url: "https://down.example.com/v1/chat/completions", request: {}, ms: 30, error: "dial tcp: connection refused" },
],
more: 2,
};
const bodies = { requestBody: '{"messages":[{"role":"user","content":"hello"}]}', responseBody: '{"reply":"world"}', headers };
const call = { id: 7, time: now.toISOString(), agent: "codex", model: "fixture/m", from: "chat", to: "chat", status: 200, ms: 900 };
const key = { id: "deepseek", provider: "deepseek", name: "DeepSeek", kind: "provider", model: "deepseek-chat" };
const route = (id, i, extra) => ({ id, seq: id, time: new Date(now.getTime() - (i + 1) * 60e3).toISOString(), agent: "codex", kind: "chat", model: "deepseek/deepseek-chat", provider: "deepseek", order: [key],
tries: [{ id: key.id, model: "deepseek-chat", start: now.toISOString(), done: true, status: 200, ms: 900 }], done: true, status: 200, ms: 900, tokens: 300, served: "deepseek-chat", ...extra });
const routes = [route(101, 0), route(100, 1, { archive: day + "/abc100" })];
const want = {
en: { toggle: "HTTP headers", client: "From the client", sent: "Sent upstream", plugin: "Handed to plugin cursor", answer: "Upstream response" },
zh: { toggle: "HTTP 头", client: "客户端发来的", sent: "发往上游", plugin: "交给插件 cursor", answer: "上游响应" },
"zh-TW": { toggle: "HTTP 標頭", client: "用戶端送來的", sent: "送往上游", plugin: "交給外掛 cursor", answer: "上游回應" },
ja: { toggle: "HTTP ヘッダー", client: "クライアントから", sent: "上流へ送信", plugin: "プラグイン cursor に渡した", answer: "上流の応答" },
de: { toggle: "HTTP-Header", client: "Vom Client", sent: "An den Anbieter gesendet", plugin: "An Plugin cursor übergeben", answer: "Antwort des Anbieters" },
};
function serve(lang) {
return async (r) => {
const url = new URL(r.request().url());
const json = (data, status = 200) => r.fulfill({ json: data, status });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [{ id: "codex", name: "Codex", path: "/test/config.toml", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ presets: [], excluded: [], providers: [{ id: "fixture", name: "Fixture", icon: "generic", key: { set: true, masked: "fixture" }, models: [{ id: "m", name: "M", on: true }], agents: [] }], gateway: { running: true, window: true, mine: true, url: "http://127.0.0.1:3999", calls: [call], groups: [] } });
if (url.pathname === "/api/gateway/call") {
if (url.searchParams.get("id") === "7" || url.searchParams.get("route") === "101") return json(bodies);
return json({ error: "This request is no longer in the recent calls." }, 404);
}
if (url.pathname === "/api/archive") return json({ request: { method: "POST", path: "/v1/chat/completions", headers: { "Content-Type": ["application/json"] }, body: "{}", size: 2 }, response: { status: 200, headers: {}, body: "{}", size: 2 },
upstream: [{ method: "POST", url: "https://archived.example.com/v1/chat/completions", request: { Authorization: ["[REDACTED]"] }, ms: 400, status: 200, proto: "HTTP/1.1", response: { "X-Request-Id": ["req-ARCH-9"] } }] });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) await new Promise((res) => setTimeout(res, 20e3));
return json({ mine: true, now: now.toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [{ day, requests: routes.length }], routes: url.searchParams.get("day") ? routes : [] });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
return r.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
};
}
// nothing under box runs past it or the window, and nothing has a
// left-border accent
const fits = (box) => box.evaluate((b) => {
const r0 = b.getBoundingClientRect();
const right = Math.min(r0.right, document.documentElement.clientWidth);
return {
out: [...b.querySelectorAll("*")].filter((e) => { const r = e.getBoundingClientRect(); return r.width > 0 && (r.left < r0.left - 0.5 || r.right > right + 0.5); }).map((e) => e.className),
accent: [...b.querySelectorAll("*")].filter((e) => { const s = getComputedStyle(e); return s.borderLeftWidth !== "0px" && s.borderLeftWidth !== s.borderRightWidth; }).map((e) => e.className),
scroll: document.scrollingElement.scrollWidth > document.documentElement.clientWidth + 0.5,
};
});
async function open(engine, lang, t, width) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await browser.newPage({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-call-headers.png`), fullPage: true });
}
await browser.close();
});
return { page, errors };
}
// the panels the headers show, by label, and their text
async function shown(box) {
return { labels: await box.locator(".call-wire-grid .call-body-label").allTextContents(), text: await box.locator(".call-wire-grid").innerText() };
}
function checkPanels(w, { labels, text }) {
assert.deepEqual(labels, [w.client, w.sent, w.answer, w.plugin, w.answer, w.sent, w.answer]);
for (const s of ["User-Agent: claude-cli/2.1.0", "POST https://api.example.com/v1/chat/completions", "Authorization: [REDACTED]", "HTTP/2.0 429", "Retry-After: 3",
"X-Request-Id: req-UP-1", "POST https://plugin.invalid/v1/messages", "X-Api-Key: [REDACTED]", "Content-Type: text/event-stream", "dial tcp: connection refused"]) assert(text.includes(s), `${s} in\n${text}`);
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(want)) {
const w = want[lang];
test(`${engine} ${lang}: a recent call's HTTP headers fold open under its bodies`, async (t) => {
const { page, errors } = await open(engine, lang, t, lang === "en" ? 1100 : 380);
await page.goto("http://magpie.test/?view=gateway");
const item = page.locator("#activity .call-item").first();
await item.waitFor();
await item.locator(".call").click();
await item.locator(".call-body pre").first().waitFor();
assert.equal(await item.locator(".call-body").count(), 2, "bodies open, headers folded");
const toggle = item.locator(".call-wire-toggle");
assert.equal(await toggle.innerText(), w.toggle);
assert.equal(await toggle.getAttribute("aria-expanded"), "false");
await toggle.click();
await item.locator(".call-wire-grid").waitFor();
assert.equal(await toggle.getAttribute("aria-expanded"), "true");
checkPanels(w, await shown(item));
assert.equal(await item.locator(".call-wire-note").count(), 2, "the tries not kept, and the plugin's own headers");
if (process.env.ARTIFACT_DIR) await item.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-call-headers-open.png`) });
assert.deepEqual(await fits(item), { out: [], accent: [], scroll: false });
// a refresh of the list keeps it open
await page.evaluate(() => loadProviders());
await item.locator(".call-wire-grid").waitFor();
await item.locator(".call-wire-toggle").click();
await item.locator(".call-wire-grid").waitFor({ state: "detached" });
assert.equal(await item.locator(".call-body").count(), 2);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a Routing request's HTTP headers, and the archive's`, async (t) => {
const { page, errors } = await open(engine, lang, t, 440);
const tap = async (loc) => {
await reach(page, loc);
const [x, y] = await loc.evaluate((e) => { const r = e.getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; });
await page.mouse.click(x, y);
};
await page.goto("http://magpie.test/?view=routing");
await page.locator(".rt-day").nth(1).waitFor({ state: "visible", timeout: 15000 });
await page.locator(".rt-day").nth(1).click();
await page.locator(".rt-req").nth(routes.length - 1).waitFor();
await page.locator(".rt-req").nth(0).click();
await tap(page.locator(".rt-log-head .rt-bodies-b"));
const box = page.locator(".rt-bodies");
await box.locator(".call-body").nth(1).waitFor();
assert.equal(await box.locator(".call-body").count(), 2);
const toggle = box.locator(".call-wire-toggle");
assert.equal(await toggle.getAttribute("aria-expanded"), "false");
await tap(toggle);
await box.locator(".call-wire-grid").waitFor();
checkPanels(w, await shown(box));
assert.deepEqual(await fits(box), { out: [], accent: [], scroll: false });
if (process.env.ARTIFACT_DIR) await box.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-routing-headers-open.png`) });
await tap(box.locator(".call-wire-toggle"));
await box.locator(".call-wire-grid").waitFor({ state: "detached" });
// the archive's copy: what went upstream, under its bodies
await tap(page.locator(".rt-req").nth(1));
await page.locator(".rt-req").nth(1).and(page.locator('[aria-pressed="true"]')).waitFor();
await tap(page.locator(".rt-log-head .rt-bodies-b"));
const fetch = box.locator(".call-archive button.text").first();
await fetch.waitFor();
await tap(fetch);
await box.locator(".call-archive .call-wire-grid").waitFor();
const a = await shown(box);
assert.deepEqual(a.labels, [w.sent, w.answer]);
assert(a.text.includes("POST https://archived.example.com/v1/chat/completions") && a.text.includes("X-Request-Id: req-ARCH-9") && a.text.includes("HTTP/1.1 200"), a.text);
assert.deepEqual(await fits(box), { out: [], accent: [], scroll: false });
assert.deepEqual(errors, []);
});
}
}
+13 -1
View File
@@ -928,9 +928,21 @@ func (p Provider) Do(client *http.Client, req *http.Request) (*http.Response, er
return p.do(client, req)
}
// SendsThroughPlugin, set by the gateway, is told of each request handed
// to a plugin's account, which goes past the gateway's own transport, as
// it goes, and what came back for it: the call's headers both ways, for
// Recent calls (gateway's wire_headers.go).
var SendsThroughPlugin func(id string, req *http.Request) func(*http.Response, error)
func (p Provider) do(client *http.Client, req *http.Request) (*http.Response, error) {
if p.Account != nil && p.Account.transport != nil {
return p.Account.transport(req)
if SendsThroughPlugin == nil {
return p.Account.transport(req)
}
done := SendsThroughPlugin(p.ID, req)
res, err := p.Account.transport(req)
done(res, err)
return res, err
}
if p.Account != nil && p.Account.clientFor != nil {
if c := p.Account.clientFor(req); c != nil {
+41 -1
View File
@@ -141,12 +141,52 @@ func (m *memo) add(k [32]byte, e scrubEntry) {
// Scrub finds in it.
func ScrubHeader(name, value string) string {
v := strings.ToLower(strings.TrimSpace(value))
if SecretName(name) || strings.HasPrefix(v, "bearer ") || strings.HasPrefix(v, "basic ") {
if SecretHeader(name) || strings.HasPrefix(v, "bearer ") || strings.HasPrefix(v, "basic ") {
return Scrubbed
}
return Scrub(value)
}
// SecretHeader says a header called name carries a credential, by the
// words of its name: Authorization, Cookie and Set-Cookie, x-api-key and
// api-key, X-Goog-Api-Key, an X-Client-Key, any *-Token (Copilot's
// Copilot-Session-Token, X-Amz-Security-Token), *-Secret, *-Auth, a
// request's *-Signature. A count of tokens is no secret: Anthropic's
// anthropic-ratelimit-tokens-remaining and OpenAI's
// x-ratelimit-remaining-tokens are what a rate limit is debugged by. Nor
// is a key that names no credential: Idempotency-Key.
func SecretHeader(name string) bool {
n := strings.ToLower(name)
words := strings.FieldsFunc(n, func(r rune) bool { return r == '-' || r == '_' || r == '.' })
kept := words[:0:0]
for i, w := range words {
switch w {
case "authorization", "authorisation", "auth", "cookie", "token", "secret", "password", "passwd",
"pass", "credential", "credentials", "signature", "apikey", "csrf", "xsrf":
return true
case "key":
if i == 0 || !headerKeyNotSecret[words[i-1]] {
return true
}
case "tokens":
continue // a count of them
}
for _, end := range []string{"token", "secret", "cookie", "apikey", "password"} {
if strings.HasSuffix(w, end) {
return true // accesstoken, clientsecret, setcookie
}
}
kept = append(kept, w)
}
// what a field's name says (x-access-key, x-private-key-id), its count
// of tokens left out
return SecretName(strings.Join(kept, "-"))
}
// headerKeyNotSecret are the words before "key" in a header that names no
// credential.
var headerKeyNotSecret = map[string]bool{"idempotency": true, "cache": true, "public": true, "sort": true, "partition": true}
// ScrubJSON is a body with its secrets taken out: a JSON one string by
// string, a field named for a secret wholly; a stream's events each as
// JSON, line by line; anything else as text. A picture's data is left as
+31
View File
@@ -59,3 +59,34 @@ func TestScrub(t *testing.T) {
t.Errorf("cut body: %q", got)
}
}
// A header's name says whether it holds a credential, by its words, for
// the names vendors and clients really send (usrname1833's header view
// shows them all): a count of tokens, a request id or an idempotency key
// is what debugging reads, and stays.
func TestSecretHeaderRealNames(t *testing.T) {
for _, name := range []string{
"Authorization", "Proxy-Authorization", "x-api-key", "api-key", "X-Goog-Api-Key", "Cookie", "Set-Cookie",
"Copilot-Session-Token", "X-Amz-Security-Token", "cf-access-client-secret", "X-Client-Key", "X-Auth-Token",
"X-Csrf-Token", "X-Amz-Signature", "Ocp-Apim-Subscription-Key", "X-Github-Token", "x-goog-user-project-key",
} {
if !SecretHeader(name) {
t.Errorf("%s shown", name)
}
}
for _, name := range []string{
"anthropic-ratelimit-tokens-remaining", "anthropic-ratelimit-input-tokens-limit", "x-ratelimit-remaining-tokens",
"x-ratelimit-limit-tokens", "Idempotency-Key", "Content-Type", "User-Agent", "Anthropic-Version", "request-id",
"X-Request-Id", "Anthropic-Beta", "Openai-Processing-Ms", "Retry-After", "Content-Length", "Cf-Ray",
} {
if SecretHeader(name) {
t.Errorf("%s taken out", name)
}
}
if got := ScrubHeader("X-Forwarded-Client", "Bearer abcdef"); got != Scrubbed {
t.Errorf("a Bearer in another header: %q", got)
}
if got := ScrubHeader("anthropic-ratelimit-tokens-remaining", "9000"); got != "9000" {
t.Errorf("a count of tokens: %q", got)
}
}