Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions deeptutor/services/codex_auth/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,42 @@ class OAuthCallbackResult:
_BASE64URL_STATE_CHARS = frozenset(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
)
_REFRESH_REJECTION_ERROR_CODES = frozenset(
{
"invalid_grant",
"invalid_token",
"refresh_token_expired",
"refresh_token_reused",
"refresh_token_invalidated",
}
)


def _is_refresh_rejection(payload: object) -> bool:
"""Return True when a 400/401 token refresh payload permanently rejects the grant.

OpenAI's token endpoint may return either a standard OAuth2 flat string
(``{"error": "invalid_grant"}``) or a nested error object
(``{"error": {"code": "refresh_token_reused", "type": "invalid_request_error", ...}}``).
Non-string values must never be hashed against a set.
"""
if not isinstance(payload, dict):
return False
candidates: list[str] = []
error = payload.get("error")
if isinstance(error, str):
candidates.append(error)
elif isinstance(error, dict):
for key in ("code", "type"):
value = error.get(key)
if isinstance(value, str):
candidates.append(value)
code = payload.get("code")
if isinstance(code, str):
candidates.append(code)
return any(
candidate.strip().lower() in _REFRESH_REJECTION_ERROR_CODES for candidate in candidates
)


def oauth_state_matches(value: str | None, expected: str) -> bool:
Expand Down Expand Up @@ -347,10 +383,7 @@ async def _token_request(
rejection = response.json()
except ValueError:
rejection = None
if isinstance(rejection, dict) and rejection.get("error") in {
"invalid_grant",
"invalid_token",
}:
if _is_refresh_rejection(rejection):
raise CodexAuthError(
"token_refresh_rejected",
"Codex sign-in could not be renewed. Sign in to Codex again.",
Expand Down
32 changes: 21 additions & 11 deletions deeptutor/services/codex_auth/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
CodexCredentials,
CodexModel,
CodexToken,
TokenClaims,
decode_codex_jwt,
normalize_codex_reasoning_levels,
)
Expand Down Expand Up @@ -1219,22 +1220,24 @@ def _credentials_from_payload(
payload.get("chatgpt_account_id"),
)
expires_at = self._positive_int(payload.get("expires_at"))
for token in (id_token, access_token):
if account_id is not None and expires_at is not None:
break
try:
claims = decode_codex_jwt(token)
except CodexAuthError:
continue
account_id = account_id or claims.account_id
expires_at = expires_at or claims.expires_at

if account_id is None and fallback is not None:
account_id = fallback.account_id
id_claims = self._decode_jwt_claims(id_token)
access_claims = self._decode_jwt_claims(access_token)

account_id = account_id or id_claims.account_id or access_claims.account_id
# Prefer the access token's expiry over the ID token's: OIDC ID tokens
# are short-lived (~1 hour) while Codex access tokens remain valid for
# days, so using id_token.exp triggers unnecessary hourly refreshes.
expires_at = expires_at or access_claims.expires_at
if expires_at is None:
expires_in = self._positive_int(payload.get("expires_in"))
if expires_in is not None:
expires_at = int(self._clock()) + expires_in
if expires_at is None:
expires_at = id_claims.expires_at

if account_id is None and fallback is not None:
account_id = fallback.account_id
if expires_at is None and fallback is not None:
expires_at = fallback.expires_at
if account_id is None or expires_at is None:
Expand Down Expand Up @@ -1279,6 +1282,13 @@ def _positive_int(value: object) -> int | None:
return None
return value

@staticmethod
def _decode_jwt_claims(token: str) -> TokenClaims:
try:
return decode_codex_jwt(token)
except CodexAuthError:
return TokenClaims(expires_at=None, account_id=None)


_SERVICE_INSTANCES: dict[str, CodexOAuthService] = {}
_RELOCATED_SECRET_ROOTS: set[str] = set()
Expand Down
92 changes: 92 additions & 0 deletions tests/services/codex_auth/test_oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,95 @@ def handler(_request: httpx.Request) -> httpx.Response:

assert exc_info.value.code == "token_refresh_rejected"
assert "refresh-secret" not in str(exc_info.value)


@pytest.mark.asyncio
@pytest.mark.parametrize(
("status_code", "payload"),
[
(
401,
{
"error": {
"message": "Your refresh token has already been used to generate a new access token.",
"type": "invalid_request_error",
"code": "refresh_token_reused",
}
},
),
(
401,
{
"error": {
"message": "Your refresh token has expired.",
"type": "invalid_request_error",
"code": "refresh_token_expired",
}
},
),
(
400,
{
"error": {
"message": "Your refresh token was invalidated.",
"type": "invalid_request_error",
"code": "refresh_token_invalidated",
}
},
),
(
400,
{
"error": {
"message": "Invalid grant.",
"type": "invalid_grant",
}
},
),
],
)
async def test_nested_dict_refresh_rejection_requires_new_sign_in(
status_code: int,
payload: dict[str, object],
) -> None:
def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code, json=payload)

async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
with pytest.raises(CodexAuthError) as exc_info:
await CodexOAuthClient(http).refresh("refresh-secret")

assert exc_info.value.code == "token_refresh_rejected"
assert exc_info.value.http_status == 401
assert "refresh-secret" not in str(exc_info.value)


@pytest.mark.asyncio
@pytest.mark.parametrize(
"payload",
[
{
"error": {
"message": "private-upstream-detail",
"type": "server_error",
"code": "temporarily_unavailable",
}
},
{"error": ["private-upstream-detail"]},
{"error": 42},
],
)
async def test_non_rejection_unhashable_error_payload_fails_as_transient(
payload: dict[str, object],
) -> None:
def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(400, json=payload)

async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
with pytest.raises(CodexAuthError) as exc_info:
await CodexOAuthClient(http).refresh("refresh-secret")

assert exc_info.value.code == "token_refresh_failed"
assert exc_info.value.http_status == 502
assert "private-upstream-detail" not in str(exc_info.value)
assert "refresh-secret" not in str(exc_info.value)
86 changes: 86 additions & 0 deletions tests/services/codex_auth/test_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import base64
from copy import deepcopy
import hashlib
import json
Expand Down Expand Up @@ -1996,3 +1997,88 @@ async def test_periodic_refresh_discards_logout_response(tmp_path: Path) -> None
assert await task is False
assert model_catalog.load() == before
assert all(value is None for value in store.load_catalog_refresh_state().values())


def _jwt_for_test(payload: dict[str, object]) -> str:
def encode(value: dict[str, object]) -> str:
raw = json.dumps(value, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")

return f"{encode({'alg': 'none'})}.{encode(payload)}."


@pytest.mark.asyncio
async def test_credentials_prefer_access_token_expiry_over_shorter_id_token_expiry(
tmp_path: Path,
) -> None:
clock = [1_000]
service, _callback, oauth, _catalog, store, _models = await _oauth_service(
tmp_path,
clock=clock,
)
id_token = _jwt_for_test(
{
"exp": 4_600, # 1 hour — OIDC ID token lifetime
"https://api.openai.com/auth": {"chatgpt_account_id": "account-123"},
}
)
access_token = _jwt_for_test(
{
"exp": 865_000, # 10 days — actual API access token lifetime
}
)
creds = service._credentials_from_payload(
{
"access_token": access_token,
"refresh_token": "refresh-1",
"id_token": id_token,
},
expected_generation=0,
)

assert creds.account_id == "account-123"
assert creds.expires_at == 865_000

store.commit_credentials(creds, expected_generation=0)
# Two hours later: past id_token.exp, still well before access_token.exp.
clock[0] = 8_200
token = await service.get_token()
assert token.access_token == access_token
assert oauth.refresh_calls == 0


@pytest.mark.asyncio
async def test_credentials_expiry_fallbacks_for_opaque_access_token(tmp_path: Path) -> None:
clock = [1_000]
service, _callback, _oauth, _catalog, _store, _models = await _oauth_service(
tmp_path,
clock=clock,
)
id_token = _jwt_for_test(
{
"exp": 4_600,
"https://api.openai.com/auth": {"chatgpt_account_id": "account-123"},
}
)

from_expires_in = service._credentials_from_payload(
{
"access_token": "opaque-access-token",
"refresh_token": "refresh-1",
"id_token": id_token,
"expires_in": 7_200,
},
expected_generation=0,
)
assert from_expires_in.account_id == "account-123"
assert from_expires_in.expires_at == 8_200

from_id_token = service._credentials_from_payload(
{
"access_token": "opaque-access-token",
"refresh_token": "refresh-1",
"id_token": id_token,
},
expected_generation=0,
)
assert from_id_token.expires_at == 4_600
Loading