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 on5daba8337): 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 frome87140242, #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 ona3768cdd1(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 on2c90922b0(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 on898c314b7, then3e61d814eand8d4d8b2d5(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 at5daba8337on 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.
192 lines
6.3 KiB
Go
192 lines
6.3 KiB
Go
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()
|
|
}
|