Files
magpie/internal/middleware/account_test.go
T
yetone e40675cc19 middleware: onAccount can pass an account over for a request (bm_rabbit)
bm_rabbit (Discord) is building MOD_Probe, a middleware that tells
Codex accounts apart and needs to keep some requests off some of them.
onProvider could only change a try's body, never which account took
it.

A JS middleware may now export onAccount(account, ctx). The gateway
calls it before each try on a subscription account, at the top of the
candidate loop (accountSkipped). That is before anything of the try is
done: no Codex reset is spent, no body is built, nothing is sent.

account is {ref, provider, name, kind, model}. ref is 32 hex
characters: an HMAC-SHA256 of the middleware's name and the account's
agent, lower-cased user and plan. Its key is random, made once per
install in account-ref.key in magpie's config folder. It is written to
a temp file and linked into place, so it never writes over a key that
is there. The ref is the same on every request and after a restart,
and different for each middleware. The email can't be found from it
without the key. A key file that can't be read is never overwritten:
that process uses a key of its own and logs it.

{skip: true} passes the account over for this request. The next
candidate is asked, as past an account that can't be used. The call's
fallback gets a "passed over by middleware <name>" line, and the
account is not rested or held against. When the last candidate is
passed over, nothing is sent (no fail-open). The agent gets the
failure of a candidate asked before it, or, if there was none, the
usual 404 "none of <model>'s models is ready".

Anything else uses the account: undefined, {}, null, a throw, or going
past the 250ms limit. The last three count as failures. A key's try
asks no onAccount. ctx.account holds the same object for the hooks
after it on that try, and is taken away on a key's try. ownAsk clears
the Accounts runs with the Tried ones.

Note: the plan is part of the ref, so a plan change gives the account
a new ref.

Docs: docs/subsystems/gateway-middleware.md (runtime path step 4,
limits, fail open, verification), docs/reference.md,
docs/integrating.md, and site/public/docs/{,zh/,ja/}plugins.html (an
onAccount row in the hooks table). The Bun plugin host is unchanged:
middleware runs in moejs in the gateway, not in host.js.

Tests:
- internal/middleware TestOnAccount: the ref is stable across runs and
  a key reload; it differs between two middlewares, users, plans and
  kinds, and is the same when only case differs; no email or plan
  reaches the hook. {skip:true} names the middleware; undefined,
  {skip:false}, throw and null use the account (2 failures counted);
  ctx.account reaches onProvider; a key's try clears it.
- internal/middleware TestAccountRefKey: the key file is made at 0600,
  read back, never written over when unreadable, and no temp file is
  left behind.
- internal/gateway TestOnAccountSkipMovesToNextAccount: two Codex
  accounts, Ordered. The first is passed over, only acct-2 is sent
  the request, acct-1 doesn't rest, and the same holds on a second
  request.
- internal/gateway TestOnAccountSkipEveryAccount: every account passed
  over gives a 404 "…models is ready", nothing is sent, nobody rests.

Broken by hand, each on mote, each red, then restored:
- skip ignored in accountSkipped: both gateway tests red (acct-1
  reached; 200 instead of 404)
- fail open on the last candidate: SkipEveryAccount red (200)
- the skipped account rested: both gateway tests red (rests)
- a random key per ref: TestOnAccount (refs changed between requests)
  and TestAccountRefKey red
- the middleware name left out of the hash: TestOnAccount red (two
  middlewares told one ref)
- an unreadable key overwritten: TestAccountRefKey red

Run at this commit's tree (rebased on origin/main 6a900e0d0):
- gofmt -l: clean
- mote-run go vet -tags nogui ./internal/... ./plugins/...,
  GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: ok
- mote-run go test -tags nogui -count=1 -timeout 45m ./... (log kept
  whole): every package ok except three. internal/middleware's
  TestPointsLoadErrors was mine: its load-error text now names
  onAccount. The test is fixed in this commit, and the package and
  plugins/middleware were rerun ok at this tree. The other two are red
  on main and already filed: internal/cli TestLibraryMCPHub (#4140,
  TempDir cleanup) and internal/gui TestSettingsSaveKeepsWhatItDoesNotSend
  (#4514, SearchAll from b09349d17)
- Rebased again on origin/main 20482d71f (it changed
  internal/gateway/affinity.go): mote-run go test -tags nogui -count=1
  ./internal/middleware ./internal/gateway ./plugins/middleware: all ok
  (gateway 846s)

Not tried: a real MOD_Probe against real Codex accounts. Not changed:
probe keys can still reach deactivated accounts (out of scope).
2026-11-01 02:19:26 +08:00

185 lines
6.0 KiB
Go

package middleware
import (
"encoding/hex"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/gwmw"
)
// forgetRefKeys makes the next ref read its key from the file again, as a
// new start of magpie does.
func forgetRefKeys() {
refKeys.Lock()
clear(refKeys.m)
refKeys.Unlock()
}
// what onProvider was told of the account after onAccount: each
// middleware's ctx.account, "none" when it had none
type told struct {
A any `json:"a"`
B string `json:"b"`
}
func triedAfter(t *testing.T, r *Run, a gwmw.Account) (skip bool, by string, got told) {
t.Helper()
skip, by = r.Account(a)
if !skip {
json.Unmarshal(r.Tried([]byte(`{}`), gwmw.To{ID: a.ID, Model: a.Model}), &got)
}
return
}
// onAccount is told a ref for the account, never its email, the same on
// every request and after magpie starts again, and a different one for
// each middleware; {skip: true} passes the account over, naming the
// middleware, and anything else, a throw and null among them, uses it.
func TestOnAccount(t *testing.T) {
forgetRefKeys()
t.Cleanup(forgetRefKeys)
a := file(t, `
export function onAccount(account, ctx) {
if (account.provider === "throw") throw new Error("bad");
if (account.provider === "null") return null;
if (account.provider === "undef") return;
if (account.provider === "skip") return {skip: true};
if (account.provider === "no") return {skip: false};
return {};
}
export function onProvider(body, ctx) { body.a = ctx.account === undefined ? "none" : ctx.account; return body; }`)
b := file(t, `
export function onAccount(account) {}
export function onProvider(body, ctx) { body.b = ctx.account === undefined ? "none" : ctx.account.ref; return body; }`)
use(t, a, b)
me := gwmw.Account{Agent: "codex", User: "me@example.com", Plan: "plus", ID: "codex", Name: "Codex", Model: "gpt-5.5"}
refs := func() (string, string) {
t.Helper()
r := Begin(info())
if r == nil {
t.Fatal("no run")
}
defer r.End()
skip, _, got := triedAfter(t, r, me)
if skip {
t.Fatal("skipped")
}
raw, _ := json.Marshal(got)
if strings.Contains(strings.ToLower(string(raw)), "example.com") || strings.Contains(string(raw), "plus") {
t.Fatalf("the account's email or plan reached a middleware: %s", raw)
}
ac, _ := got.A.(map[string]any)
if ac["provider"] != "codex" || ac["name"] != "Codex" || ac["kind"] != "codex" || ac["model"] != "gpt-5.5" {
t.Fatalf("ctx.account %s", raw)
}
ref, _ := ac["ref"].(string)
if _, err := hex.DecodeString(ref); err != nil || len(ref) != 32 {
t.Fatalf("ref %q", ref)
}
return ref, got.B
}
refA, refB := refs()
if refA == refB {
t.Fatalf("two middlewares told one ref %s", refA)
}
// another request, and magpie started again: the same refs
if a2, b2 := refs(); a2 != refA || b2 != refB {
t.Fatalf("refs changed between requests: %s %s, then %s %s", refA, refB, a2, b2)
}
forgetRefKeys()
if a2, b2 := refs(); a2 != refA || b2 != refB {
t.Fatalf("refs changed after a restart: %s %s, then %s %s", refA, refB, a2, b2)
}
// the same account written in another case is the same account;
// another user, or the plan changed, is another
if got := accountRef(a.Spec, gwmw.Account{Agent: "codex", User: "ME@Example.com", Plan: "Plus"}); got != refA {
t.Fatalf("case changed the ref: %s, %s", got, refA)
}
for _, o := range []gwmw.Account{
{Agent: "codex", User: "spare@example.com", Plan: "plus"},
{Agent: "codex", User: "me@example.com", Plan: "pro"},
{Agent: "claude", User: "me@example.com", Plan: "plus"},
} {
if accountRef(a.Spec, o) == refA {
t.Fatalf("%+v has me's ref", o)
}
}
r := Begin(info())
defer r.End()
for _, c := range []struct {
id string
skip bool
}{{"skip", true}, {"no", false}, {"undef", false}, {"throw", false}, {"null", false}, {"ok", false}} {
acct := me
acct.ID = c.id
skip, by, got := triedAfter(t, r, acct)
if skip != c.skip {
t.Fatalf("%s: skip %v", c.id, skip)
}
if skip && by != a.Spec {
t.Fatalf("%s: passed over by %q, not %q", c.id, by, a.Spec)
}
if !skip && got.B != refB {
t.Fatalf("%s: the next middleware wasn't told the account: %+v", c.id, got)
}
}
if st := States()[a.Spec]; st.Failures != 2 || !strings.Contains(st.Last, "null") || !strings.Contains(strings.Join(st.Hooks, ","), "onAccount") {
t.Fatalf("state %+v", st)
}
// a try on a key asks no onAccount, and the account before it is gone
// from ctx
if skip, _, got := triedAfter(t, r, gwmw.Account{ID: "skip", Model: "m1"}); skip || got.A != "none" || got.B != "none" {
t.Fatalf("a key's try: skip %v, told %+v", skip, got)
}
var none *Run
if skip, _ := none.Account(me); skip {
t.Fatal("a nil Run skipped")
}
}
// The key refs are made with is kept: made once, read after, and one that
// can't be read is never written over, as every ref a middleware kept
// would change with it.
func TestAccountRefKey(t *testing.T) {
forgetRefKeys()
t.Cleanup(forgetRefKeys)
p := filepath.Join(appdir.Config(), "account-ref.key")
os.Remove(p)
acct := gwmw.Account{Agent: "codex", User: "me@example.com"}
first := accountRef("m", acct)
b, err := os.ReadFile(p)
if err != nil || len(strings.TrimSpace(string(b))) != 64 {
t.Fatalf("key file %q %v", b, err)
}
if fi, _ := os.Stat(p); fi != nil && fi.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' {
t.Fatalf("key file mode %v", fi.Mode())
}
forgetRefKeys()
if accountRef("m", acct) != first {
t.Fatal("the kept key wasn't read back")
}
// a key of its own makes other refs: the file is what keeps them
forgetRefKeys()
os.Remove(p)
if accountRef("m", acct) == first {
t.Fatal("a new key made the same ref")
}
forgetRefKeys()
os.WriteFile(p, []byte("not a key\n"), 0o600)
accountRef("m", acct)
if b, _ := os.ReadFile(p); string(b) != "not a key\n" {
t.Fatalf("a key that couldn't be read was written over: %q", b)
}
if left, _ := filepath.Glob(filepath.Join(appdir.Config(), ".account-ref-*")); len(left) > 0 {
t.Fatalf("temp files left: %v", left)
}
os.Remove(p)
}