Files
magpie/internal/provider/codex_workspace_switch_test.go
T
yetone 2d1b7c1b6c codex: a workspace sharing Codex's sign-in reads and sends as its own workspace
JdAZzzzzz (X) has a personal Pro and a Team seat of one ChatGPT login in
magpie, and switches workspace in the Codex app. Both cards read the
same plan ("Prolite"), week, reset time, pace and two reset cards; only
the token counts (local sessions) differed.

Cause: one ChatGPT sign-in reaches every workspace of its login with
one refresh token. Codex's workspace routing (codex-rs
login/src/auth/manager/workspace_routing.rs, /wham/accounts/check)
changes which one auth.json names in tokens.account_id. rememberLogins
saved each workspace as an account (codexWho goes by account_id), both
with that refresh token. renewSaved found the account not in use "held
by Codex" (heldByCodex: same refresh token), renewed through Codex's
store as it should, and returned that store's account id too: the
workspace Codex is on. So the other account's usage, plan, resets and
the gateway's requests for it named the workspace in use, and spent it.

- renewSaved returns the saved account's own workspace for a token read
  where Codex holds the sign-in, in ~/.codex and in another Codex folder
  (codexOwnWorkspace).
- A sign-in sync put Codex's auth.json on every record sharing its
  refresh token, so the other workspace's record was carried as the one
  in use. liveCodex and applyLogins no longer match by refresh token
  when the workspaces are known apart (codexWorkspacesApart).

TestCodexAppWorkspaceSwitchReadsEachWorkspace: one sign-in (same
refresh token, the real token's claim layout), the app's switch with
only account_id rewritten or with the tokens naming the new workspace,
Codex left on either one. On the old code all 4 cases are red with the
report's picture ("jd@example.com · ws-team (ws-team) reads plan
"prolite" ... 2 resets; its workspace has "team" ... 0 resets"), the
account's requests signed for the other workspace, and CollectSignIns
carrying each record as the other workspace. Green with the change.

Run at 9a00bfed1 (origin/main) plus this change, on mote (macOS):
- gofmt -l internal/provider: nothing
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/provider; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok
- go test -count=1 ./internal/provider: ok (134s)
Not run: go test ./... (mote's suite.lock queue had five suites ahead;
shipped without holding behind it).
Not tried: a real Team seat (no such account here); that ChatGPT's
backend honours chatgpt-account-id for a token whose claim names the
other workspace is what Codex's routing does, not checked by hand.
Not changed: once Codex rotates the shared refresh token, the other
workspace's saved copy holds a spent one (#5779).
2026-11-09 17:13:17 +08:00

152 lines
5.0 KiB
Go

package provider
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
)
// codexAppSignIn writes auth.json as the Codex app keeps one ChatGPT
// sign-in routed to workspace: the tokens of a single sign-in, its
// refresh token the same whichever workspace is picked. Real tokens carry
// the workspace in id_token's and access_token's
// https://api.openai.com/auth claims and in tokens.account_id; reclaimed
// says the switch got tokens naming the new workspace, else only
// account_id was rewritten.
func codexAppSignIn(t *testing.T, home, workspace, plan string, reclaimed bool) {
t.Helper()
claimWS, claimPlan := "ws-personal", "prolite" // as signed in
if reclaimed {
claimWS, claimPlan = workspace, plan
}
auth := map[string]any{"chatgpt_account_id": claimWS, "chatgpt_plan_type": claimPlan, "chatgpt_user_id": "user-jd"}
writeFile(t, filepath.Join(home, ".codex", "auth.json"), map[string]any{
"auth_mode": "chatgpt", "OPENAI_API_KEY": nil,
"tokens": map[string]any{
"id_token": fakeJWT(map[string]any{"email": "jd@example.com", "sid": "sid-jd",
"https://api.openai.com/auth": auth}),
"access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix()), "session_id": "sid-jd",
"https://api.openai.com/auth": auth}),
"refresh_token": "r-jd", "account_id": workspace,
},
"last_refresh": time.Now().UTC().Format(time.RFC3339),
})
}
// JdAZzzzzz on X: one ChatGPT login with a personal Pro and a Team seat,
// both in magpie, the workspace switched in the Codex app. Both cards
// read the personal plan ("Prolite"), its week, its reset time and its
// two resets: the account not in use shares the sign-in Codex holds (one
// refresh token), and was read with Codex's sign-in as it is, workspace
// and all. Each card is its own workspace's.
func TestCodexAppWorkspaceSwitchReadsEachWorkspace(t *testing.T) {
for _, reclaimed := range []bool{false, true} {
for _, backHome := range []bool{false, true} {
t.Run(fmt.Sprintf("reclaimed=%v/backHome=%v", reclaimed, backHome), func(t *testing.T) {
workspaceSwitchReadsApart(t, reclaimed, backHome)
})
}
}
}
func workspaceSwitchReadsApart(t *testing.T, reclaimed, backHome bool) {
home := signIn(t)
if err := ForgetLogin("codex", "me@example.com"); err != nil {
t.Logf("forget: %v", err)
}
codexAppSignIn(t, home, "ws-personal", "prolite", reclaimed)
rememberLogins(true)
codexAppSignIn(t, home, "ws-team", "team", reclaimed) // the Codex app's switch
rememberLogins(true)
if backHome {
codexAppSignIn(t, home, "ws-personal", "prolite", reclaimed)
rememberLogins(true)
}
type seat struct {
plan string
used float64
resets int
}
seats := map[string]seat{"ws-personal": {"prolite", 25, 2}, "ws-team": {"team", 60, 0}}
asked := map[string]int{}
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ws := r.Header.Get("chatgpt-account-id")
s, ok := seats[ws]
if !ok {
t.Errorf("%s asked for workspace %q", r.URL.Path, ws)
w.WriteHeader(403)
return
}
if r.URL.Path != "/backend-api/wham/usage" {
w.WriteHeader(404)
return
}
asked[ws]++
body := map[string]any{"plan_type": s.plan, "rate_limit": map[string]any{
"secondary_window": map[string]any{"used_percent": s.used, "limit_window_seconds": 604800}}}
if s.resets > 0 {
body["rate_limit_reset_credits"] = map[string]any{"available_count": s.resets}
}
json.NewEncoder(w).Encode(body)
}))
defer fake.Close()
old := CodexBase
CodexBase = fake.URL + "/backend-api/codex"
t.Cleanup(func() { CodexBase = old })
ls := Logins("codex")
if len(ls) != 2 {
t.Fatalf("accounts: %+v", ls)
}
wsOf := map[string]string{}
for _, l := range ls {
wsOf[l.User], _ = workspaceOf(t, l.User)
}
t.Logf("accounts: %v", wsOf)
for _, l := range ls {
if l.Active {
continue
}
_, acct, err := savedLoginToken(context.Background(), "codex", l.User)
if err != nil || acct != wsOf[l.User] {
t.Errorf("%s (not in use) signs its requests for %q (%v), its workspace is %s", l.User, acct, err, wsOf[l.User])
}
}
for user, q := range LoginUsage(context.Background(), "codex") {
want := seats[wsOf[user]]
resets := 0
if q.Resets != nil {
resets = q.Resets.Count
}
if q.Error != "" || len(q.Windows) == 0 || q.Windows[0].Used != want.used || q.Plan != want.plan || resets != want.resets {
t.Errorf("%s (%s) reads plan %q, %+v, %d resets (%s); its workspace has %q, %v%% used, %d resets",
user, wsOf[user], q.Plan, q.Windows, resets, q.Error, want.plan, want.used, want.resets)
}
}
if asked["ws-team"] == 0 || asked["ws-personal"] == 0 {
t.Errorf("workspaces read: %v", asked)
}
// carried to another machine, each account keeps its own workspace:
// Codex's sign-in here goes only on the record it is
s, err := CollectSignIns()
if err != nil {
t.Fatal(err)
}
for _, l := range s.Logins {
if l.Agent != "codex" {
continue
}
if _, ws := codexWho(l.Auth); ws != wsOf[l.User] {
t.Errorf("%s is carried as a sign-in to %s, its workspace is %s", l.User, ws, wsOf[l.User])
}
}
}