Skip to content

Commit aaf0469

Browse files
authored
Merge pull request #2021 from lidge-jun/codex/land-1932
fix(codex): treat a bare WHAM 401 as transient only for a verifiably live token (lands #1932)
2 parents 0128e4d + f2b507f commit aaf0469

3 files changed

Lines changed: 99 additions & 8 deletions

File tree

‎src/codex/auth-api.ts‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export {
8383
updateAccountQuota,
8484
} from "./quota";
8585
import { extractAccountId } from "../oauth/chatgpt";
86-
import { getMainAccountPlan, MAIN_CODEX_ACCOUNT_ID, setMainAccountPlan } from "./main-account";
86+
import { getMainAccountPlan, isMainAccountTokenVerifiablyLive, MAIN_CODEX_ACCOUNT_ID, setMainAccountPlan } from "./main-account";
8787
import { captureConfigGeneration, registerStateSweepAfterTick } from "../lib/state-store-sweeper";
8888
import { reconcileLiveStateStores } from "../lib/state-store-registrations";
8989
import {
@@ -566,12 +566,31 @@ const MAIN_TERMINAL_AUTH_CODES = new Set([
566566
"invalid_refresh_token",
567567
]);
568568

569-
async function isTerminalMainAuthResponse(resp: Response): Promise<boolean> {
570-
if (resp.status === 401) return true;
569+
/**
570+
* A WHAM 401 is not itself proof the local credential died. Upstream edges can
571+
* transiently reject a still-valid access token (region/anti-abuse/rotation
572+
* races), and fail-closing on every bare 401 makes a healthy main account flip
573+
* needs-reauth on the next GUI quota poll. Only treat the response as terminal
574+
* when the body carries a known terminal code or the local access token is not
575+
* verifiably live (`accessTokenLive`). Liveness must be strict: a JWT whose
576+
* `exp` cannot be decoded is NOT live — an undecodable token that vouched for
577+
* itself would make a real 401 permanently transient.
578+
*/
579+
async function isTerminalMainAuthResponse(resp: Response, accessTokenLive: boolean): Promise<boolean> {
580+
if (resp.status === 401) {
581+
if (!accessTokenLive) return true;
582+
const code = await readMainAuthErrorCode(resp);
583+
return typeof code === "string" && MAIN_TERMINAL_AUTH_CODES.has(code);
584+
}
571585
if (resp.status !== 403) return false;
586+
const code = await readMainAuthErrorCode(resp);
587+
return typeof code === "string" && MAIN_TERMINAL_AUTH_CODES.has(code);
588+
}
589+
590+
async function readMainAuthErrorCode(resp: Response): Promise<unknown> {
572591
try {
573592
const body = await readBoundedResponseBody(resp, { totalTimeoutMs: 1_000, inactivityTimeoutMs: 1_000 });
574-
if (!body.displaySafe) return false;
593+
if (!body.displaySafe) return undefined;
575594
const parsed = JSON.parse(body.text) as {
576595
detail?: { code?: unknown } | string;
577596
error?: { code?: unknown } | string;
@@ -582,9 +601,9 @@ async function isTerminalMainAuthResponse(resp: Response): Promise<boolean> {
582601
: typeof parsed.error === "object" && parsed.error !== null
583602
? parsed.error.code
584603
: parsed.code;
585-
return typeof code === "string" && MAIN_TERMINAL_AUTH_CODES.has(code);
604+
return code;
586605
} catch {
587-
return false;
606+
return undefined;
588607
}
589608
}
590609

@@ -704,7 +723,7 @@ async function fetchMainAccountInfoWhileOwned(
704723
signal: AbortSignal.timeout(8000),
705724
});
706725
if (!resp.ok) {
707-
const terminalAuthFailure = await isTerminalMainAuthResponse(resp);
726+
const terminalAuthFailure = await isTerminalMainAuthResponse(resp, isMainAccountTokenVerifiablyLive());
708727
const retried = await retryMainAccountInfoIfIdentityChanged(requestAccountId, retriesRemaining, nativeMainLease);
709728
if (retried) return retried;
710729
if (terminalAuthFailure) {

‎src/codex/main-account.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,20 @@ export function isMainAccountTokenLive(now = Date.now()): boolean {
4949
const exp = typeof payload?.exp === "number" ? payload.exp * 1000 : undefined;
5050
return exp === undefined || exp > now;
5151
}
52+
53+
/**
54+
* Strict liveness for auth-terminality decisions: true only when the access-token JWT
55+
* carries a decodable `exp` that is still in the future.
56+
*
57+
* Unlike {@link isMainAccountTokenLive}, an undecodable `exp` counts as NOT live here.
58+
* This gate decides whether a bare WHAM 401 is downgraded to a transient failure; if an
59+
* undecodable token could vouch for itself, a genuinely dead credential would keep every
60+
* 401 "transient" and needsReauth could never flip.
61+
*/
62+
export function isMainAccountTokenVerifiablyLive(now = Date.now()): boolean {
63+
const tokens = readCodexTokens();
64+
if (!tokens?.access_token) return false;
65+
const payload = decodeJwtPayload(tokens.access_token);
66+
const exp = typeof payload?.exp === "number" ? payload.exp * 1000 : undefined;
67+
return exp !== undefined && exp > now;
68+
}

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

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ let previousCodexHome: string | undefined;
8080
let previousManualImportEnv: string | undefined;
8181
let previousFetch: typeof fetch;
8282

83+
function jwtWithExp(exp: number): string {
84+
const enc = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
85+
return enc({ alg: "RS256", typ: "JWT" }) + "." + enc({ exp }) + ".sig";
86+
}
87+
8388
function makeConfig(overrides: Partial<OcxConfig> = {}): OcxConfig {
8489
return {
8590
port: 10100,
@@ -742,7 +747,9 @@ describe("codex-auth API", () => {
742747
expect(main?.needsReauth).toBe(true);
743748
});
744749

745-
test("main account 401 marks needsReauth and exposes it in the DTO (#327)", async () => {
750+
test("main account 401 with an undecodable-exp token is terminal and marks needsReauth (#327, #1932)", async () => {
751+
// "expired-main" is not a decodable JWT, so its exp cannot vouch for liveness.
752+
// Undecodable exp must fail toward reauth: only a decodable future exp counts as live.
746753
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
747754
tokens: { access_token: "expired-main", account_id: "acct-main" },
748755
}));
@@ -757,6 +764,54 @@ describe("codex-auth API", () => {
757764
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
758765
});
759766

767+
test("bare main account 401 with a verifiably live token is transient, not reauth (#1932)", async () => {
768+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
769+
tokens: { access_token: jwtWithExp(Math.floor(Date.now() / 1000) + 3600), account_id: "acct-main" },
770+
}));
771+
globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch;
772+
773+
const req = new Request("http://localhost/api/codex-auth/accounts?refresh=1");
774+
const resp = await handleCodexAuthAPI(req, new URL(req.url), makeConfig());
775+
const data = await resp!.json() as { accounts: Array<{ id: string; hasCredential: boolean; needsReauth?: boolean }> };
776+
const main = data.accounts.find(account => account.id === MAIN_CODEX_ACCOUNT_ID);
777+
778+
expect(main).toMatchObject({ hasCredential: true, needsReauth: false });
779+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false);
780+
});
781+
782+
test("main account 401 with a live token but terminal body code is still terminal (#1932)", async () => {
783+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
784+
tokens: { access_token: jwtWithExp(Math.floor(Date.now() / 1000) + 3600), account_id: "acct-main" },
785+
}));
786+
globalThis.fetch = (async () => Response.json(
787+
{ detail: { code: "invalid_refresh_token" } },
788+
{ status: 401 },
789+
)) as typeof fetch;
790+
791+
const req = new Request("http://localhost/api/codex-auth/accounts?refresh=1");
792+
const resp = await handleCodexAuthAPI(req, new URL(req.url), makeConfig());
793+
const data = await resp!.json() as { accounts: Array<{ id: string; needsReauth?: boolean }> };
794+
795+
expect(data.accounts.find(account => account.id === MAIN_CODEX_ACCOUNT_ID)?.needsReauth).toBe(true);
796+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
797+
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
798+
});
799+
800+
test("main account 401 with an expired access token is terminal (#1932)", async () => {
801+
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
802+
tokens: { access_token: jwtWithExp(1), account_id: "acct-main" },
803+
}));
804+
globalThis.fetch = (async () => new Response("", { status: 401 })) as typeof fetch;
805+
806+
const req = new Request("http://localhost/api/codex-auth/accounts?refresh=1");
807+
const resp = await handleCodexAuthAPI(req, new URL(req.url), makeConfig());
808+
const data = await resp!.json() as { accounts: Array<{ id: string; needsReauth?: boolean }> };
809+
810+
expect(data.accounts.find(account => account.id === MAIN_CODEX_ACCOUNT_ID)?.needsReauth).toBe(true);
811+
expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(true);
812+
clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
813+
});
814+
760815
test("main account invalid-workspace 403 is terminal but a generic 403 is not (#327)", async () => {
761816
writeFileSync(join(TEST_CODEX_HOME, "auth.json"), JSON.stringify({
762817
tokens: { access_token: "workspace-main", account_id: "acct-main" },

0 commit comments

Comments
 (0)