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.
137 lines
5.5 KiB
Go
137 lines
5.5 KiB
Go
package gui
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
func TestRecentCallBodiesOnDemand(t *testing.T) {
|
|
sandboxHome(t)
|
|
long := strings.Repeat("body", 70<<10)
|
|
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"`+long+`"}}]}`)
|
|
}))
|
|
defer up.Close()
|
|
if err := provider.Save(provider.Provider{ID: "recent", Name: "Recent", Chat: up.URL, Key: "fixture"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := gateway.New()
|
|
was := served.Load()
|
|
served.Store(s)
|
|
t.Cleanup(func() { served.Store(was) })
|
|
mux := http.NewServeMux()
|
|
providerRoutes(mux, nil)
|
|
get := func(path string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
w := httptest.NewRecorder()
|
|
mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
|
return w
|
|
}
|
|
query := func(c gateway.Call) string {
|
|
return "/api/gateway/call?" + url.Values{"id": {strconv.FormatUint(c.ID, 10)}}.Encode()
|
|
}
|
|
ask := func(content string) gateway.Call {
|
|
t.Helper()
|
|
w := httptest.NewRecorder()
|
|
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"recent/m","messages":[{"role":"user","content":"`+content+`"}]}`))
|
|
r.Header.Set("User-Agent", "codex")
|
|
s.Handler().ServeHTTP(w, r)
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("gateway: %d %.200s", w.Code, w.Body)
|
|
}
|
|
return s.Recent()[0]
|
|
}
|
|
first := ask(long)
|
|
w := get("/api/providers")
|
|
var state providersJSON
|
|
if err := json.Unmarshal(w.Body.Bytes(), &state); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if w.Code != http.StatusOK || len(state.Gateway.Calls) != 1 {
|
|
t.Fatalf("summary: %d, %d calls", w.Code, len(state.Gateway.Calls))
|
|
}
|
|
if c := state.Gateway.Calls[0]; c.RequestBody != "" || c.ResponseBody != "" || !c.Time.Equal(first.Time) || c.Model != first.Model || c.Status != first.Status {
|
|
t.Fatal("providers must keep call metadata without sending bodies")
|
|
}
|
|
// Saves return the same summary, not another copy of every body.
|
|
w = httptest.NewRecorder()
|
|
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/providers/arrange", strings.NewReader(`{"order":["recent"]}`)))
|
|
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), `"requestBody"`) || strings.Contains(w.Body.String(), `"responseBody"`) {
|
|
t.Fatal("a provider write returned call bodies")
|
|
}
|
|
w = get(query(first))
|
|
var detail gateway.Call
|
|
if err := json.Unmarshal(w.Body.Bytes(), &detail); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
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")
|
|
}
|
|
guard := webGuard("session", "fixture", 0, mux)
|
|
w = httptest.NewRecorder()
|
|
guard.ServeHTTP(w, httptest.NewRequest("GET", query(first), nil))
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Fatal("body detail bypassed the web session")
|
|
}
|
|
// the next call, the same agent's to the same model, is told apart
|
|
// from the first by its id, not by when it came (#1521)
|
|
second := ask("second " + long)
|
|
if second.ID == first.ID {
|
|
t.Fatalf("two calls share id %d", first.ID)
|
|
}
|
|
if err := json.Unmarshal(get(query(second)).Body.Bytes(), &detail); err != nil || !strings.Contains(detail.RequestBody, "second") {
|
|
t.Fatal("the second call's detail isn't its own")
|
|
}
|
|
if err := json.Unmarshal(get(query(first)).Body.Bytes(), &detail); err != nil || strings.Contains(detail.RequestBody, "second") {
|
|
t.Fatal("the first call's detail isn't its own")
|
|
}
|
|
for _, path := range []string{"/api/gateway/call", "/api/gateway/call?id=x", "/api/gateway/call?id=999999", "/api/gateway/call?time=" + url.QueryEscape(first.Time.Format(time.RFC3339Nano))} {
|
|
if w := get(path); w.Code != http.StatusNotFound {
|
|
t.Fatalf("unknown call: %d", w.Code)
|
|
}
|
|
}
|
|
for range 40 {
|
|
ask(long)
|
|
}
|
|
w = get("/api/providers")
|
|
if err := json.Unmarshal(w.Body.Bytes(), &state); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
summary, _ := json.Marshal(state.Gateway.Calls)
|
|
captured, _ := json.Marshal(s.Recent())
|
|
if len(state.Gateway.Calls) != 40 || len(summary)*100 >= len(captured) {
|
|
t.Fatalf("recent summaries: %d bytes, captured calls: %d bytes", len(summary), len(captured))
|
|
}
|
|
t.Logf("40 calls: %d bytes of metadata instead of %d bytes with bodies", len(summary), len(captured))
|
|
if w := get(query(first)); w.Code != http.StatusNotFound {
|
|
t.Fatalf("an evicted call returned %d", w.Code)
|
|
}
|
|
served.Store(nil)
|
|
if w := get(query(first)); w.Code != http.StatusNotFound {
|
|
t.Fatalf("a gateway served elsewhere returned %d", w.Code)
|
|
}
|
|
}
|