gateway: X-Magpie-Account takes a percent-encoded name (plugins#615)

StockRabbit (magpie-community/plugins#615, Magpie 0.1.2587, Windows):
pinning the Fingerprint page to the WorkBuddy account 北冥 failed every
sample with "Header 'X-Magpie-Account' has invalid value". A header value
is ASCII on the wire and fetch refuses any other, and the gateway matched
the header only against the account's user (北冥) or its trace id
(workbuddy@北冥/…), so no ASCII form could name that account.

pinTo now matches the value as written or percent-decoded (pinnedName:
url.PathUnescape, kept only when it decodes to valid UTF-8). The trace's
Pinned, the call's error and the 404's "no account %q" name it decoded.
gateway.go:2701 is the one place that reads the value; codex_backend.go,
codex_relay.go and gateway.go:2523 test only that it is present, so they
need nothing. docs/reference.md and the gateway-routing page say how to
send such a name.

Run at this head (rebased on c3048cd26, which changed no gateway file):
- mote: go vet ./internal/gateway for darwin, GOOS=linux, GOOS=windows: ok.
- mote: go test -run 'TestAccountPinned|TestCodexPoolSaysTheClientsVersion|Pin'
  ./internal/gateway: ok. gofmt -l: clean.
- mote, at the pre-rebase head: go test -timeout 45m ./internal/gateway:
  one red, TestCodexPoolSaysTheClientsVersion (User-Agent 0.165.0 where
  0.161.0 was sent), which is #4807 (red in a full package run on mote,
  passes alone); it passes alone at this head and at origin/main c3048cd26.

Broken by hand: pinnedName returning the raw value turns
TestAccountPinnedPercentEncoded red (404 no account "%E5%8C%97%E5%86%A5").

Not tried: a real WorkBuddy account named 北冥 (the test uses a Codex
account of that name through the same pinTo); Windows.
This commit is contained in:
yetone
2026-11-02 07:20:01 +08:00
parent c3048cd266
commit ad53a23dc8
5 changed files with 70 additions and 9 deletions
+5 -1
View File
@@ -2186,7 +2186,11 @@ An optional `X-Magpie-Account: <account>` header (the account's email
or login, or its id on the Routing page) pins a request to one account of a
subscription with several: only it is tried, and an unknown account, one
whose plan lacks the model, or one resting is an error rather than another
account's reply. The header is not sent on to the vendor.
account's reply. The header is not sent on to the vendor. A header value is
ASCII, so an account named in other letters (`北冥`) is sent percent-encoded
(`X-Magpie-Account: %E5%8C%97%E5%86%A5`, JavaScript's `encodeURIComponent`);
magpie decodes it, and a value that isn't such an encoding is the name as
written.
A status bar can show where a turn went before its first token arrives:
send `X-Magpie-Session: <id>` with the requests (an agent's own session
File diff suppressed because one or more lines are too long
+24 -3
View File
@@ -23,12 +23,14 @@ import (
"io"
"log"
"net/http"
"net/url"
"regexp"
"slices"
"sort"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
@@ -3984,9 +3986,13 @@ func streamStatus(msg string) int {
// (its user, or its id in the routing trace), and pl with them. Nothing
// else is tried in its place: a caller that names one account asks about
// that one. The error says why none is left: no such account, one that
// doesn't list the model, or one resting.
func pinTo(want string, cands []candidate, pl planned) ([]candidate, planned, int, string) {
match := func(w Weighed) bool { return strings.EqualFold(want, w.Who) || want == w.ID }
// doesn't list the model, or one resting. A name that isn't ASCII comes
// percent-encoded (pinnedName), and matches as written or decoded.
func pinTo(raw string, cands []candidate, pl planned) ([]candidate, planned, int, string) {
want := pinnedName(raw)
match := func(w Weighed) bool {
return strings.EqualFold(want, w.Who) || want == w.ID || strings.EqualFold(raw, w.Who) || raw == w.ID
}
var out []candidate
var order []Weighed
var rests []string
@@ -4035,6 +4041,21 @@ func pinTo(want string, cands []candidate, pl planned) ([]candidate, planned, in
return nil, pl, http.StatusNotFound, msg
}
// pinnedName is the account AccountHeader names, raw as the request sent
// it. A header value is ASCII on the wire, and fetch refuses to send one
// that isn't, so a user named in other letters (北冥, plugins#615) is sent
// percent-encoded (encodeURIComponent): it is read back decoded. A value
// that isn't a valid encoding of UTF-8 is the name as written.
func pinnedName(raw string) string {
if !strings.Contains(raw, "%") {
return raw
}
if d, err := url.PathUnescape(raw); err == nil && utf8.ValidString(d) {
return strings.TrimSpace(d)
}
return raw
}
// unservedTry says c's try failed as the vendor refusing the model as one
// it doesn't serve the account or key (modelRefused, codeAssistModelMissing):
// what restAfterMarked rests for that model alone.
+4 -4
View File
@@ -2703,7 +2703,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
var status int
var msg string
if cands, pl, status, msg = pinTo(pin, cands, pl); status != 0 {
call.Status, call.Error = status, "account pinned: "+pin
call.Status, call.Error = status, "account pinned: "+pinnedName(pin)
writeError(w, from, status, msg)
finishCapture()
s.record(call)
@@ -2747,7 +2747,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
capture.tools = tools
}
tierAsked := bodyTier(from, body) // the service tier the client asked for (#1784)
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Compaction: compactionWho(checkpoint), Subagent: subagent, Moved: moved, SubagentEffort: subagentEffort, Sub: subOf(r.Header), SubagentID: subagentID, Affinity: shown, Order: pl.order, Left: append(slices.Clip(pl.left), smallW...)})
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pinnedName(pin), Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Compaction: compactionWho(checkpoint), Subagent: subagent, Moved: moved, SubagentEffort: subagentEffort, Sub: subOf(r.Header), SubagentID: subagentID, Affinity: shown, Order: pl.order, Left: append(slices.Clip(pl.left), smallW...)})
if watched != nil {
watched.routeID = tr.ID
}
@@ -8207,8 +8207,8 @@ func dshCompacts(h http.Header) bool {
const SessionHeader = "X-Magpie-Session"
// AccountHeader pins a request to one of a subscription's accounts, by its
// user (an email, a login) or its id in the routing trace: only it is
// tried, and when it can't take the request the caller is told why rather
// user (an email, a login) or its id in the routing trace, percent-encoded
// when it isn't ASCII (pinnedName): only it is tried, and when it can't take the request the caller is told why rather
// than another account answering — a probe of one account needs that one.
// It goes no further than magpie.
const AccountHeader = "X-Magpie-Account"
+36
View File
@@ -4,6 +4,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
@@ -129,3 +130,38 @@ func TestAccountPinnedResting(t *testing.T) {
t.Fatalf("unpinned: %d %s", rec.Code, rec.Body.String())
}
}
// An account whose user isn't ASCII (StockRabbit's 北冥, plugins#615) is
// named percent-encoded, as fetch can send no other header value; it is
// pinned as its user, on magpie's endpoint and on Codex's, and the trace
// names it decoded.
func TestAccountPinnedPercentEncoded(t *testing.T) {
heads := twoAccounts(t)
codexSignedIn(t, "北冥")
s := New()
for path, model := range pinPaths {
*heads = nil
code, body := pinnedPost(t, s, path, model, url.PathEscape("北冥"))
if code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("%s: %d %s", path, code, body)
}
if len(*heads) != 1 || (*heads)[0].Get("chatgpt-account-id") != "acct-2" {
t.Fatalf("%s: upstream %v", path, *heads)
}
if r := s.trace.routes[len(s.trace.routes)-1]; r.Pinned != "北冥" || len(r.Order) != 1 || r.Order[0].Who != "北冥" {
t.Errorf("%s: route pinned %q order %+v", path, r.Pinned, r.Order)
}
}
// one it doesn't have is named decoded in the error
code, body := pinnedPost(t, s, "/v1/responses", "codex/gpt-5.5", url.PathEscape("南海"))
if code != 404 || !strings.Contains(body, "南海") || !strings.Contains(body, "北冥") {
t.Fatalf("unknown: %d %s", code, body)
}
// a value that isn't an encoding is the name as written
if got := pinnedName("50%off"); got != "50%off" {
t.Errorf("pinnedName(50%%off) = %q", got)
}
if got := pinnedName("%E5%8C"); got != "%E5%8C" {
t.Errorf("pinnedName(half a rune) = %q", got)
}
}