fix(codex): persist rejected refresh grants until credentials change (#1454)

This commit is contained in:
Bingxi Zhao (Frank)
2026-10-07 23:52:17 +08:00
parent b7904fef3a
commit f2e0f4ed1e
3 changed files with 64 additions and 34 deletions

View File

@@ -52,14 +52,6 @@ logger = logging.getLogger(__name__)
MANAGED_BY = "openai_codex_oauth"
CODEX_PROFILE_ID = "llm-profile-openai-codex-managed"
# After a refresh the provider rejects, get_token stays terminal for this
# long instead of calling the token endpoint again on every turn (#1454).
# A revoked / de-authorized session used to surface a fresh reauth per
# message; one acknowledged failure now fails fast with a clear error, and
# the short window leaves room for a transient outage to clear before the
# next attempt instead of permanently locking the credential.
CODE_AUTH_FAILURE_COOLDOWN_S = 60
@dataclass(frozen=True)
class CatalogSyncResult:
@@ -468,7 +460,6 @@ class CodexOAuthService:
self._inference_lock = asyncio.Lock()
self._active_inferences = 0
self._logging_out = False
self._reauth_until: float | None = None
@staticmethod
async def _start_default_callback(expected_state: str) -> LoopbackCallback:
@@ -639,7 +630,6 @@ class CodexOAuthService:
self._last_snapshot = snapshot
operation.activated = sync_result.activated
operation.operation_state = "completed"
self._clear_reauth_required()
except CodexAuthError as exc:
operation.error_code = exc.code
if exc.code == "login_cancelled":
@@ -727,11 +717,11 @@ class CodexOAuthService:
"Sign in to Codex before using this model.",
401,
)
if self._reauth_required():
# A recent refresh was rejected — the stored session no
if self._store.authentication_rejected(credentials.generation):
# A refresh was rejected — the stored session no
# longer refreshes (revoked, de-authorized). Fail fast with a
# terminal error instead of asking the token endpoint again
# on this turn or the next (#1454).
# on this turn, after a cooldown, or after restart (#1454).
raise CodexAuthError(
"authentication_required",
"Codex sign-in could not be renewed. Sign in to Codex again.",
@@ -802,7 +792,7 @@ class CodexOAuthService:
# Only a rejected refresh grant means the user must sign in again.
# Transport failures and provider 5xx responses are transient.
if exc.code == "token_refresh_rejected":
self._mark_reauth_required()
self._store.mark_authentication_rejected(credentials.generation)
raise
refreshed = self._credentials_from_payload(
payload,
@@ -819,7 +809,6 @@ class CodexOAuthService:
refreshed,
expected_generation=credentials.generation,
)
self._clear_reauth_required()
# Generation matching invalidates model data without discarding the
# same account's successful catalog client version.
return committed
@@ -835,6 +824,12 @@ class CodexOAuthService:
)
if credentials.generation != generation:
return
if self._store.authentication_rejected(generation):
raise CodexAuthError(
"authentication_required",
"Codex sign-in could not be renewed. Sign in to Codex again.",
401,
)
await self._refresh_credentials(credentials)
@asynccontextmanager
@@ -891,7 +886,6 @@ class CodexOAuthService:
pass
self._last_snapshot = None
self._operation = None
self._clear_reauth_required()
return self.public_status()
finally:
async with self._inference_lock:
@@ -951,28 +945,24 @@ class CodexOAuthService:
self._model_catalog.update(mutate)
return self.public_status()
def _mark_reauth_required(self) -> None:
self._reauth_until = self._clock() + CODE_AUTH_FAILURE_COOLDOWN_S
def _clear_reauth_required(self) -> None:
self._reauth_until = None
def _reauth_required(self) -> bool:
deadline = self._reauth_until
return deadline is not None and self._clock() < deadline
def public_status(self) -> dict[str, Any]:
operation = self._operation
credentials: CodexCredentials | None = None
storage_error: str | None = None
try:
credentials = self._store.load_credentials()
if credentials is not None and self._store.authentication_rejected(
credentials.generation
):
storage_error = "authentication_required"
except CodexAuthError as exc:
storage_error = exc.code
active_operation = self._operation_is_active()
if active_operation:
connection = "authorizing"
elif storage_error is not None:
connection = "error"
elif credentials is not None:
connection = "connected"
elif operation is not None and operation.operation_state == "failed":

View File

@@ -184,6 +184,20 @@ class CodexCredentialStore:
with self._locked():
return int(self._read_state_unlocked()["generation"])
def mark_authentication_rejected(self, generation: int) -> None:
"""Remember a rejected grant across turns, workers and restarts (#1454)."""
with self._locked():
state = self._read_state_unlocked()
if state["generation"] != generation:
return # an old request must never invalidate a newly signed-in session
_atomic_write_json(self.state_path, {**state, "rejected_generation": generation})
def authentication_rejected(self, generation: int) -> bool:
with self._locked():
state = self._read_state_unlocked()
rejected = state.get("rejected_generation")
return type(rejected) is int and rejected == generation == state["generation"]
def load_credentials(self) -> CodexCredentials | None:
with self._locked():
state_generation = int(self._read_state_unlocked()["generation"])
@@ -220,6 +234,7 @@ class CodexCredentialStore:
"schema_version": _SCHEMA_VERSION,
"generation": next_generation,
}
next_state.pop("rejected_generation", None)
_atomic_write_json(self.state_path, next_state)
_atomic_write_json(self.credentials_path, committed.to_dict())
return committed
@@ -231,6 +246,7 @@ class CodexCredentialStore:
if expected_generation is not None and current_generation != expected_generation:
raise self._generation_changed()
next_generation = current_generation + 1
state.pop("rejected_generation", None)
_atomic_write_json(
self.state_path,
{

View File

@@ -1730,7 +1730,7 @@ async def test_get_token_stops_refreshing_after_a_failed_refresh(tmp_path: Path)
When the stored credential no longer refreshes (a revoked session, an
account the provider no longer authorizes), every turn used to call the
token endpoint again, fail again, and surface a fresh reauth each message.
One failure is enough to hold the auth state for the cooldown window and
One failure is enough to hold the auth state until a new sign-in and
fail fast with a clear error instead of hammering the provider per turn.
"""
clock = [1_000]
@@ -1761,8 +1761,8 @@ async def test_get_token_stops_refreshing_after_a_failed_refresh(tmp_path: Path)
@pytest.mark.asyncio
async def test_get_token_retries_after_the_reauth_cooldown_elapses(tmp_path: Path) -> None:
"""The cooldown is not a permanent lock: a transient failure can recover."""
async def test_rejected_grant_stays_terminal_after_time_and_service_restart(tmp_path: Path) -> None:
"""#1454: a revoked grant cannot become valid just because 60 seconds elapsed."""
clock = [1_000]
service, _callback, oauth, _catalog, store, _models = await _oauth_service(
tmp_path, clock=clock
@@ -1777,12 +1777,36 @@ async def test_get_token_retries_after_the_reauth_cooldown_elapses(tmp_path: Pat
await service.get_token()
assert oauth.refresh_calls == 1
# Let the cooldown elapse; the next call is allowed one fresh attempt.
clock[0] += 120
clock[0] += 3600
oauth.refresh_error = None
token = await service.get_token()
assert oauth.refresh_calls == 2
assert token.access_token == "refreshed-access"
with pytest.raises(CodexAuthError, match="Sign in to Codex again"):
await service.get_token()
assert oauth.refresh_calls == 1
assert service.public_status()["connection"] == "error"
assert service.public_status()["error_code"] == "authentication_required"
restarted, _callback, restarted_oauth, _catalog, _store, _models = await _oauth_service(
tmp_path, clock=clock
)
with pytest.raises(CodexAuthError, match="Sign in to Codex again"):
await restarted.get_token()
with pytest.raises(CodexAuthError, match="Sign in to Codex again"):
await restarted.recover_after_unauthorized(store.current_generation())
assert restarted_oauth.refresh_calls == 0
@pytest.mark.asyncio
async def test_old_refresh_rejection_does_not_block_a_new_credential_generation(
tmp_path: Path,
) -> None:
service, _callback, oauth, _catalog, store, _models = await _oauth_service(tmp_path)
old = store.commit_credentials(_stored_credentials(expires_at=20_000), expected_generation=0)
current = store.commit_credentials(
_stored_credentials(expires_at=30_000), expected_generation=old.generation
)
store.mark_authentication_rejected(old.generation)
assert await service.get_token() == current.public_token()
assert oauth.refresh_calls == 0
@pytest.mark.asyncio