Skip to content

Commit c5fc969

Browse files
authored
Merge pull request #2167 from ntdatt812/fix/main-reauth-quarantine-background-refresh
fix(codex): stop the background main refresh from retracting a reauth quarantine (#327)
2 parents 00e333d + bbf2aad commit c5fc969

2 files changed

Lines changed: 94 additions & 6 deletions

File tree

‎src/codex/auth-api.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -644,12 +644,13 @@ async function retryMainAccountInfoIfIdentityChanged(
644644
requestAccountId: string | null,
645645
retriesRemaining: number,
646646
nativeMainLease: AdmissionLease,
647+
explicitRefresh: boolean,
647648
): Promise<MainAccountInfoFetchResult | null> {
648649
const currentAccountId = getMainChatgptAccountId();
649650
if (currentAccountId === null || currentAccountId === requestAccountId) return null;
650651
reconcileMainCodexAccountRuntimeState();
651652
return retriesRemaining > 0
652-
? fetchMainAccountInfoWhileOwned(true, retriesRemaining - 1, nativeMainLease)
653+
? fetchMainAccountInfoWhileOwned(true, retriesRemaining - 1, nativeMainLease, explicitRefresh)
653654
: { info: EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: true, hasCredential: true };
654655
}
655656

@@ -696,6 +697,13 @@ async function fetchMainAccountInfoWhileOwned(
696697
forceRefresh: boolean,
697698
retriesRemaining: number,
698699
nativeMainLease: AdmissionLease,
700+
/**
701+
* Whether the *caller* asked for this refresh. `forceRefresh` also means "bypass the
702+
* cache", and `retryMainAccountInfoIfIdentityChanged` re-enters with it set purely to
703+
* re-read after the identity changed. Keeping the two apart stops that retry from
704+
* promoting a background poll into operator intent below.
705+
*/
706+
explicitRefresh: boolean = forceRefresh,
699707
): Promise<MainAccountInfoFetchResult> {
700708
const writerGeneration = captureConfigGeneration();
701709
reconcileMainCodexAccountRuntimeState();
@@ -724,7 +732,7 @@ async function fetchMainAccountInfoWhileOwned(
724732
});
725733
if (!resp.ok) {
726734
const terminalAuthFailure = await isTerminalMainAuthResponse(resp, isMainAccountTokenVerifiablyLive());
727-
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
735+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease, explicitRefresh);
728736
if (retried) return retried;
729737
if (terminalAuthFailure) {
730738
clearMainAccountInfoCache();
@@ -733,7 +741,7 @@ async function fetchMainAccountInfoWhileOwned(
733741
return { info: EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: true, hasCredential: true };
734742
}
735743
const data = (await resp.json()) as WhamUsageResponse;
736-
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
744+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease, explicitRefresh);
737745
if (retried) return retried;
738746
const plan = nonEmptyPlan(data.plan_type) ?? nonEmptyPlan(cached?.plan) ?? nonEmptyPlan(getMainAccountPlan());
739747
const quota = parseUsageQuota({ ...data, ...(plan ? { plan_type: plan } : {}) });
@@ -745,7 +753,16 @@ async function fetchMainAccountInfoWhileOwned(
745753
ts: Date.now(),
746754
};
747755
setMainAccountInfoCache(result);
748-
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
756+
// Only an explicit refresh may retract a reauth quarantine. A 200 from
757+
// /wham/usage proves the token authenticates to the usage endpoint; it does not
758+
// prove the account can serve Responses traffic, which is a different backend path
759+
// and still answers 403 for a workspace the token may no longer select (#327).
760+
// Letting the background poll clear the flag put such an account straight back into
761+
// rotation: the next request failed the same way and re-marked it, so needsReauth
762+
// never settled and the dashboard kept showing nothing — the symptom #327 reported.
763+
// An explicit refresh is an operator asking to re-evaluate, normally right after
764+
// signing in again, so it stays authoritative.
765+
if (explicitRefresh) clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
749766
// Mirror main quota + plan into the shared stores so the rotation engine can
750767
// score and auto-switch the main account exactly like a pool account (Option A).
751768
setMainAccountPlan(result.plan);
@@ -760,7 +777,7 @@ async function fetchMainAccountInfoWhileOwned(
760777
...(freshResetCredits !== undefined ? { freshResetCredits } : {}),
761778
};
762779
} catch {
763-
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
780+
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease, explicitRefresh);
764781
return retried ?? { info: EMPTY_MAIN_ACCOUNT_INFO, credentialChecked: true, hasCredential: true };
765782
}
766783
}

‎tests/codex-auth-api.test.ts‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
handleCodexAuthAPI, updateAccountQuota, getAccountQuota,
1414
checkAccountIdCollision, getMainChatgptAccountId,
1515
markAccountNeedsReauth, isAccountNeedsReauth, clearAccountNeedsReauth, clearAccountQuota,
16-
clearMainAccountInfoCache, maskEmail,
16+
clearMainAccountInfoCache, maskEmail, fetchMainAccountInfo,
1717
clearCodexQuotaPrimeState, primeCodexPoolQuotas, seedCodexAuthAdmissionForTests,
1818
type CodexAuthAccountDto,
1919
listCodexAuthAccounts,
@@ -858,6 +858,77 @@ describe("codex-auth API", () => {
858858
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
859859
});
860860

861+
test("a background main account refresh does not retract a reauth quarantine (#327)", async () => {
862+
// #327's own repro: the token is valid, but its workspace can no longer be
863+
// selected, so Responses traffic answers 403 and quarantines the account.
864+
// /wham/usage is a different backend path and keeps answering 200 for that same
865+
// token, so the periodic refresh must not read its own 200 as proof the account
866+
// can serve traffic again — doing so returned the account to rotation, the next
867+
// request failed identically and re-marked it, and needsReauth never settled.
868+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
869+
tokens: { access_token: "live-main", account_id: "acct-main" },
870+
}));
871+
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
872+
clearMainAccountInfoCache();
873+
let usageCalls = 0;
874+
globalThis.fetch = (async () => {
875+
usageCalls += 1;
876+
return Response.json({
877+
878+
plan_type: "pro",
879+
rate_limit: { primary_window: { used_percent: 10, reset_at: 1783000000 } },
880+
});
881+
}) as typeof fetch;
882+
883+
expect((await fetchMainAccountInfo(false)).email).toBe("[email protected]");
884+
// The probe really ran and really succeeded — the quarantine survives it anyway.
885+
expect(usageCalls).toBe(1);
886+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
887+
888+
// An explicit refresh is an operator asking to re-evaluate, so it stays
889+
// authoritative and still clears the flag (the test above pins that direction).
890+
clearMainAccountInfoCache();
891+
expect((await fetchMainAccountInfo(true)).email).toBe("[email protected]");
892+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
893+
});
894+
895+
test("an identity-change retry does not upgrade a background refresh into an explicit one (#327)", async () => {
896+
// `retryMainAccountInfoIfIdentityChanged` re-enters with forceRefresh=true so it can
897+
// re-read past a now-stale cache. That argument must not double as operator intent:
898+
// a background poll that crosses an identity change would otherwise come back with
899+
// the authority to retract a quarantine it was never allowed to touch.
900+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
901+
tokens: { access_token: "live-main", account_id: "acct-before" },
902+
}));
903+
clearMainAccountInfoCache();
904+
let usageCalls = 0;
905+
globalThis.fetch = (async () => {
906+
usageCalls += 1;
907+
if (usageCalls === 1) {
908+
// Identity changes on disk mid-probe. The retry's purge legitimately drops the
909+
// *previous* identity's runtime state — that is not what this test is about.
910+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
911+
tokens: { access_token: "live-main", account_id: "acct-after" },
912+
}));
913+
} else {
914+
// Real traffic quarantines the *new* identity while the retry probe is in
915+
// flight, exactly as recordCodexUpstreamOutcome does on a 401/403.
916+
markAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
917+
}
918+
return Response.json({
919+
920+
plan_type: "pro",
921+
rate_limit: { primary_window: { used_percent: 10, reset_at: 1783000000 } },
922+
});
923+
}) as typeof fetch;
924+
925+
await fetchMainAccountInfo(false);
926+
927+
// The retry really fired — otherwise this proves nothing about the retry path.
928+
expect(usageCalls).toBeGreaterThan(1);
929+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
930+
});
931+
861932
test("BUG-R327: main account exposes and updates needsReauth from WHAM auth responses", async () => {
862933
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
863934
tokens: {

0 commit comments

Comments
 (0)