fix(quota): discard a Codex refresh whose login changed under it

The refresh reread auth.json before writing the rotated tokens but only
checked it was still ChatGPT mode, not that it was still the same login.
A `codex login` account switch, or a second CodeBurn process refreshing
the same credential, landing while our refresh was in flight let the late
response splice one account's tokens into another's document: a new
account id over an old refresh token, or an older refresh token over a
newer one. Either signs the user out or binds them to the wrong account.

The login the grant belongs to is now captured before the grant and
compared against the reread document on account id, refresh token and
id-token subject. A demonstrated mismatch discards the write and says so.
An unreadable or key-sparse file is not a mismatch and still writes, so a
rotated token is never dropped. Both the CLI and the Electron copy.
This commit is contained in:
iamtoruk 2026-09-03 07:59:42 -07:00
parent 5ffd4a7200
commit 7533e96fe3
4 changed files with 248 additions and 12 deletions

View file

@ -222,6 +222,88 @@ describe('Codex quota credential rotation', () => {
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
it('discards a rotation when the login on disk changes while the grant is in flight', async () => {
await writeAuth(authDoc())
const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined)
let grantStarted = (): void => {}
const reachedGrant = new Promise<void>(resolve => { grantStarted = resolve })
let releaseGrant = (): void => {}
const heldGrant = new Promise<void>(resolve => { releaseGrant = resolve })
const pending = fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({
token: async () => { grantStarted(); await heldGrant; return rotatedGrant() },
usage: usagePayload,
}),
})
// The user ran `codex login` and switched accounts while our grant was open.
await reachedGrant
await writeAuth({
auth_mode: 'chatgpt',
tokens: {
access_token: 'access-other',
refresh_token: 'refresh-other-account',
id_token: 'id-other',
account_id: 'account-2',
},
last_refresh: new Date(NOW).toISOString(),
})
releaseGrant()
await pending
// The new account's document is left exactly as the CLI wrote it: our grant
// spent account-1's refresh token, so writing it back here would splice
// account-1's token onto account-2's identity.
const saved = await readAuth()
expect(saved.tokens.account_id).toBe('account-2')
expect(saved.tokens.refresh_token).toBe('refresh-other-account')
expect(saved.tokens.refresh_token).not.toBe(NEW_REFRESH)
expect(errors).toHaveBeenCalledTimes(1)
})
it('still writes the rotation when the login on disk is unchanged', async () => {
await writeAuth(authDoc())
let grantStarted = (): void => {}
const reachedGrant = new Promise<void>(resolve => { grantStarted = resolve })
let releaseGrant = (): void => {}
const heldGrant = new Promise<void>(resolve => { releaseGrant = resolve })
const pending = fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({
token: async () => { grantStarted(); await heldGrant; return rotatedGrant() },
usage: usagePayload,
}),
})
// Same account, same refresh token: an unrelated rewrite is not a lineage change.
await reachedGrant
await writeAuth({ ...authDoc(), extra_field: 'harmless' })
releaseGrant()
await pending
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
it('keeps the rotated refresh token when the reread file merely omits lineage keys', async () => {
await writeAuth(authDoc())
await fetchCodexQuota({
authPath,
now: () => NOW,
// A cleanly parsed ChatGPT document that simply lacks account_id and
// refresh_token is not proof of a different login.
readFileSync: () => JSON.stringify({ auth_mode: 'chatgpt', tokens: { access_token: 'access-old' } }),
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
// POSIX mode bits do not exist on Windows, where the ACL carries the privacy.
it.skipIf(process.platform === 'win32')('rewrites the credential with the permissions it already had', async () => {
for (const mode of [0o600, 0o400]) {

View file

@ -245,12 +245,44 @@ function str(value: unknown): string | null {
return typeof value === 'string' && value ? value : null
}
/** The `sub` claim of a JWT id_token, or null when it is absent or does not
* decode. Defensive at every step: a malformed id_token is evidence of nothing,
* so it must never itself read as a login mismatch. */
function idTokenSubject(token: unknown): string | null {
if (typeof token !== 'string') return null
const payload = token.split('.')[1]
if (!payload) return null
try {
const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as { sub?: unknown }
return typeof claims.sub === 'string' && claims.sub ? claims.sub : null
} catch {
return null
}
}
/** Whether two documents belong to the same Codex login. A field counts as a
* mismatch only when it is a non-empty string on both sides and the two values
* differ: a document that merely omits account_id, refresh_token or id_token is
* not proof of a different login, and treating it as one would drop a rotated
* refresh token and sign the user out. */
function sameLogin(held: AuthDoc, latest: AuthDoc): boolean {
const differs = (a: unknown, b: unknown): boolean =>
typeof a === 'string' && a !== '' && typeof b === 'string' && b !== '' && a !== b
if (differs(held.tokens?.account_id, latest.tokens?.account_id)) return false
if (differs(held.tokens?.refresh_token, latest.tokens?.refresh_token)) return false
return !differs(idTokenSubject(held.tokens?.id_token), idTokenSubject(latest.tokens?.id_token))
}
/** The document the rotated tokens are merged into: whatever the Codex CLI has
* on disk right now, so a login it wrote since our own read is not clobbered.
* `null` means the login this rotation belongs to is gone (file removed, or no
* longer ChatGPT mode) and writing would resurrect it. An unreadable or
* unparseable file is NOT one of those cases: it falls back to the document we
* already hold, because dropping a rotated refresh token signs the user out. */
* `null` means writing would be wrong: the login this rotation belongs to is
* gone (file removed, or no longer ChatGPT mode), or the file now holds a
* different login (the user ran `codex login` and switched accounts, or another
* process rotated the credential while our grant was in flight) and merging our
* tokens in would splice one account's account_id onto another's refresh token.
* An unreadable or unparseable file is NOT one of those cases: it falls back to
* the document we already hold, because a lineage check may only fire on a file
* that reads cleanly, and dropping a rotated refresh token signs the user out. */
function mergeBase(auth: AuthDoc, deps: CodexDeps): AuthDoc | null {
let raw: string | null
try {
@ -267,7 +299,11 @@ function mergeBase(auth: AuthDoc, deps: CodexDeps): AuthDoc | null {
}
if (!latest || typeof latest !== 'object') return auth
const doc = latest as AuthDoc
return doc.auth_mode === 'chatgpt' ? doc : null
if (doc.auth_mode !== 'chatgpt') return null
// Serializing refreshes across processes with a file lock would also stop the
// wasted double grant, but the lineage check is what closes the corrupt-write
// hole on its own, so the lock is left out as more than the minimum here.
return sameLogin(auth, doc) ? doc : null
}
type RotatedTokens = { access: string | null; refresh: string | null; id: string | null }
@ -283,7 +319,7 @@ type RotatedTokens = { access: string | null; refresh: string | null; id: string
function persistRotated(auth: AuthDoc, rotated: RotatedTokens, deps: CodexDeps): AuthDoc | null {
const base = mergeBase(auth, deps)
if (!base) {
console.error(`Codex refreshed its login but the credential at ${deps.authPath} no longer holds that ChatGPT login, so the new token was discarded. Run \`codex login\` if Codex signs you out.`)
console.error(`Codex refreshed its login but the credential at ${deps.authPath} no longer holds the ChatGPT login this rotation belongs to, so the new token was discarded. Run \`codex login\` if Codex signs you out.`)
return null
}
const merged: AuthDoc = {

View file

@ -245,12 +245,44 @@ function str(value: unknown): string | null {
return typeof value === 'string' && value ? value : null
}
/** The `sub` claim of a JWT id_token, or null when it is absent or does not
* decode. Defensive at every step: a malformed id_token is evidence of nothing,
* so it must never itself read as a login mismatch. */
function idTokenSubject(token: unknown): string | null {
if (typeof token !== 'string') return null
const payload = token.split('.')[1]
if (!payload) return null
try {
const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as { sub?: unknown }
return typeof claims.sub === 'string' && claims.sub ? claims.sub : null
} catch {
return null
}
}
/** Whether two documents belong to the same Codex login. A field counts as a
* mismatch only when it is a non-empty string on both sides and the two values
* differ: a document that merely omits account_id, refresh_token or id_token is
* not proof of a different login, and treating it as one would drop a rotated
* refresh token and sign the user out. */
function sameLogin(held: AuthDoc, latest: AuthDoc): boolean {
const differs = (a: unknown, b: unknown): boolean =>
typeof a === 'string' && a !== '' && typeof b === 'string' && b !== '' && a !== b
if (differs(held.tokens?.account_id, latest.tokens?.account_id)) return false
if (differs(held.tokens?.refresh_token, latest.tokens?.refresh_token)) return false
return !differs(idTokenSubject(held.tokens?.id_token), idTokenSubject(latest.tokens?.id_token))
}
/** The document the rotated tokens are merged into: whatever the Codex CLI has
* on disk right now, so a login it wrote since our own read is not clobbered.
* `null` means the login this rotation belongs to is gone (file removed, or no
* longer ChatGPT mode) and writing would resurrect it. An unreadable or
* unparseable file is NOT one of those cases: it falls back to the document we
* already hold, because dropping a rotated refresh token signs the user out. */
* `null` means writing would be wrong: the login this rotation belongs to is
* gone (file removed, or no longer ChatGPT mode), or the file now holds a
* different login (the user ran `codex login` and switched accounts, or another
* process rotated the credential while our grant was in flight) and merging our
* tokens in would splice one account's account_id onto another's refresh token.
* An unreadable or unparseable file is NOT one of those cases: it falls back to
* the document we already hold, because a lineage check may only fire on a file
* that reads cleanly, and dropping a rotated refresh token signs the user out. */
function mergeBase(auth: AuthDoc, deps: CodexDeps): AuthDoc | null {
let raw: string | null
try {
@ -267,7 +299,11 @@ function mergeBase(auth: AuthDoc, deps: CodexDeps): AuthDoc | null {
}
if (!latest || typeof latest !== 'object') return auth
const doc = latest as AuthDoc
return doc.auth_mode === 'chatgpt' ? doc : null
if (doc.auth_mode !== 'chatgpt') return null
// Serializing refreshes across processes with a file lock would also stop the
// wasted double grant, but the lineage check is what closes the corrupt-write
// hole on its own, so the lock is left out as more than the minimum here.
return sameLogin(auth, doc) ? doc : null
}
type RotatedTokens = { access: string | null; refresh: string | null; id: string | null }
@ -283,7 +319,7 @@ type RotatedTokens = { access: string | null; refresh: string | null; id: string
function persistRotated(auth: AuthDoc, rotated: RotatedTokens, deps: CodexDeps): AuthDoc | null {
const base = mergeBase(auth, deps)
if (!base) {
console.error(`Codex refreshed its login but the credential at ${deps.authPath} no longer holds that ChatGPT login, so the new token was discarded. Run \`codex login\` if Codex signs you out.`)
console.error(`Codex refreshed its login but the credential at ${deps.authPath} no longer holds the ChatGPT login this rotation belongs to, so the new token was discarded. Run \`codex login\` if Codex signs you out.`)
return null
}
const merged: AuthDoc = {

View file

@ -336,6 +336,88 @@ describe('Codex quota credential rotation', () => {
expect(errors).toHaveBeenCalledTimes(1)
})
it('discards a rotation when the login on disk changes while the grant is in flight', async () => {
await writeAuth(authDoc())
const errors = vi.spyOn(console, 'error').mockImplementation(() => undefined)
let grantStarted = (): void => {}
const reachedGrant = new Promise<void>(resolve => { grantStarted = resolve })
let releaseGrant = (): void => {}
const heldGrant = new Promise<void>(resolve => { releaseGrant = resolve })
const pending = fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({
token: async () => { grantStarted(); await heldGrant; return rotatedGrant() },
usage: usagePayload,
}),
})
// The user ran `codex login` and switched accounts while our grant was open.
await reachedGrant
await writeAuth({
auth_mode: 'chatgpt',
tokens: {
access_token: 'access-other',
refresh_token: 'refresh-other-account',
id_token: 'id-other',
account_id: 'account-2',
},
last_refresh: new Date(NOW).toISOString(),
})
releaseGrant()
await pending
// The new account's document is left exactly as the CLI wrote it: our grant
// spent account-1's refresh token, so writing it back here would splice
// account-1's token onto account-2's identity.
const saved = await readAuth()
expect(saved.tokens.account_id).toBe('account-2')
expect(saved.tokens.refresh_token).toBe('refresh-other-account')
expect(saved.tokens.refresh_token).not.toBe(NEW_REFRESH)
expect(errors).toHaveBeenCalledTimes(1)
})
it('still writes the rotation when the login on disk is unchanged', async () => {
await writeAuth(authDoc())
let grantStarted = (): void => {}
const reachedGrant = new Promise<void>(resolve => { grantStarted = resolve })
let releaseGrant = (): void => {}
const heldGrant = new Promise<void>(resolve => { releaseGrant = resolve })
const pending = fetchCodexQuota({
authPath,
now: () => NOW,
fetch: routes({
token: async () => { grantStarted(); await heldGrant; return rotatedGrant() },
usage: usagePayload,
}),
})
// Same account, same refresh token: an unrelated rewrite is not a lineage change.
await reachedGrant
await writeAuth({ ...authDoc(), extra_field: 'harmless' })
releaseGrant()
await pending
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
it('keeps the rotated refresh token when the reread file merely omits lineage keys', async () => {
await writeAuth(authDoc())
await fetchCodexQuota({
authPath,
now: () => NOW,
// A cleanly parsed ChatGPT document that simply lacks account_id and
// refresh_token is not proof of a different login.
readFileSync: () => JSON.stringify({ auth_mode: 'chatgpt', tokens: { access_token: 'access-old' } }),
fetch: routes({ token: rotatedGrant, usage: usagePayload }),
})
expect((await readAuth()).tokens.refresh_token).toBe(NEW_REFRESH)
})
// POSIX mode bits do not exist on Windows, where the ACL carries the privacy.
it.skipIf(process.platform === 'win32')('rewrites the credential with the permissions it already had', async () => {
for (const mode of [0o600, 0o400]) {