Skip to content

The agent that grows with you

fix(agent): keep custom-Codex-base credentials off chatgpt.com

liuhao1024602aa9a55b47
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index 1ab7008dbd9..6b4b8032987 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -1788,18 +1788,29 @@ _CODEX_OAUTH_CONTEXT_CACHE_TTL = 3600 # 1 hour
CODEX_MODELS_CATALOG_ENDPOINT = "https://chatgpt.com/backend-api/codex/models"
CODEX_NEWEST_CLIENT_VERSION = "99.0.0"
CODEX_UNGATED_CLIENT_VERSION = "0.0.0"
-CODEX_MODELS_CATALOG_URLS = tuple(
- f"{CODEX_MODELS_CATALOG_ENDPOINT}?client_version={v}"
- for v in (CODEX_NEWEST_CLIENT_VERSION, CODEX_UNGATED_CLIENT_VERSION)
-)
-def fetch_codex_catalog_entries(get: Callable[[str], Any]) -> Tuple[List[Any], Optional[int]]:
+def _codex_catalog_urls(base_url: str = "") -> Tuple[str, ...]:
+ """Catalog URLs against ``base_url`` when it names a Codex-compatible gateway, else the
+ hard-coded endpoint. A custom base's credential belongs to that service — sending it to
+ chatgpt.com (or fetching the direct catalog behind a gateway's back) is wrong (#121486)."""
+ base = (base_url or "").strip().rstrip("/")
+ endpoint = f"{base}/models" if base else CODEX_MODELS_CATALOG_ENDPOINT
+ return tuple(
+ f"{endpoint}?client_version={v}"
+ for v in (CODEX_NEWEST_CLIENT_VERSION, CODEX_UNGATED_CLIENT_VERSION)
+ )
+
+
+CODEX_MODELS_CATALOG_URLS = _codex_catalog_urls()
+
+
+def fetch_codex_catalog_entries(get: Callable[[str], Any], base_url: str = "") -> Tuple[List[Any], Optional[int]]:
"""``(models, last_status)`` from the first catalog URL that answers HTTP 200 with a non-empty
``models`` list; ``get(url)`` is any client returning an object with ``status_code``/``json()``.
An empty or non-200 answer on the newest-client URL falls through to the ``0.0.0`` sentinel."""
status: Optional[int] = None
- for url in CODEX_MODELS_CATALOG_URLS:
+ for url in _codex_catalog_urls(base_url):
resp = get(url)
status = resp.status_code
if status != 200:
@@ -1811,18 +1822,25 @@ def fetch_codex_catalog_entries(get: Callable[[str], Any]) -> Tuple[List[Any], O
return [], status
-def _codex_oauth_token_fingerprint(access_token: str) -> str:
- """Non-secret cache key for a Codex OAuth access token."""
- return hashlib.sha256(access_token.encode("utf-8")).hexdigest()[:16]
+def _codex_oauth_token_fingerprint(access_token: str, base_url: str = "") -> str:
+ """Non-secret cache key for a Codex OAuth access token (plus the base it was probed against —
+ a gateway's catalog can differ from chatgpt.com's for the same forwarded token)."""
+ return hashlib.sha256(f"{access_token}\n{(base_url or '').strip().rstrip('/')}".encode("utf-8")).hexdigest()[:16]
-def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[Dict[str, int], bool]:
+def _fetch_codex_oauth_context_lengths_with_source(access_token: str, base_url: str = "") -> Tuple[Dict[str, int], bool]:
"""Codex catalogue ``{slug: context_window}`` plus whether it came from HTTP. Cached per token
fingerprint (windows vary by entitlement); ``max_context_window`` lands in
``_codex_oauth_max_context_cache`` under the same key. An in-process hit reports False: not a
fresh provider confirmation, must not drive persistent writes."""
+ # Real Codex access tokens are JWTs; a gateway's API key is not one. Refusing to probe non-JWT
+ # credentials keeps the key off chatgpt.com — a service it does not belong to and cannot answer
+ # for (#121486), mirroring ``_probe_codex_quota_restored``'s gate — and skips a doomed request.
+ from hermes_cli.auth_constants import _decode_jwt_claims
+ if not access_token or not _decode_jwt_claims(access_token):
+ return {}, False
now = time.time()
- cache_key = _codex_oauth_token_fingerprint(access_token)
+ cache_key = _codex_oauth_token_fingerprint(access_token, base_url)
cached = _codex_oauth_context_cache.get(cache_key)
if cached is not None and now - cached[1] < _CODEX_OAUTH_CONTEXT_CACHE_TTL:
return cached[0], False
@@ -1832,7 +1850,8 @@ def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[D
headers = {"Authorization": f"Bearer {access_token}", **codex_account_headers(access_token)}
try:
entries, status = fetch_codex_catalog_entries(
- lambda url: model_metadata_http.get(url, headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
+ lambda url: model_metadata_http.get(url, headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify()),
+ base_url=base_url,
)
if status != 200:
logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", status)
@@ -1854,7 +1873,7 @@ def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[D
return result, True
-def _resolve_codex_oauth_context_length_with_source(model: str, access_token: str = "") -> Tuple[Optional[int], str]:
+def _resolve_codex_oauth_context_length_with_source(model: str, access_token: str = "", base_url: str = "") -> Tuple[Optional[int], str]:
"""``(context_length, source)`` for a Codex OAuth slug. source: "live" (fresh authenticated probe —
the only one eligible for persistent writes), "memory" (same-token in-process hit), "fallback"
(static table), or "" when unresolved."""
@@ -1877,8 +1896,8 @@ def _resolve_codex_oauth_context_length_with_source(model: str, access_token: st
# (#92797 review).
lookup_bare = _bare_codex_slug(strip_codex_context_variant_suffix(model_bare))
if access_token:
- live, fresh_probe = _fetch_codex_oauth_context_lengths_with_source(access_token)
- live_max = _codex_oauth_max_context_cache.get(_codex_oauth_token_fingerprint(access_token), {})
+ live, fresh_probe = _fetch_codex_oauth_context_lengths_with_source(access_token, base_url=base_url)
+ live_max = _codex_oauth_max_context_cache.get(_codex_oauth_token_fingerprint(access_token, base_url), {})
# Exact slug, then case-insensitive in case casing drifts.
slug = lookup_bare if lookup_bare in live else next((s for s in live if s.lower() == lookup_bare.lower()), None)
if slug is not None:
@@ -2118,7 +2137,7 @@ def _resolve_provider_aware_context_length(model: str, base_url: str, api_key: s
# OR-fallback or static-table value cached on a blip would be frozen in by step 1 forever.
sourced = {
"nous": lambda: _resolve_nous_context_length(model, base_url=base_url or "", api_key=api_key or "") + ("portal",),
- "openai-codex": lambda: _resolve_codex_oauth_context_length_with_source(model, access_token=api_key or "") + ("live",),
+ "openai-codex": lambda: _resolve_codex_oauth_context_length_with_source(model, access_token=api_key or "", base_url=base_url or "") + ("live",),
}.get(effective_provider)
if sourced is not None:
ctx, source, persist_on = sourced()
diff --git a/hermes_cli/codex_models.py b/hermes_cli/codex_models.py
index 84cda3acdc4..c38386139d5 100644
--- a/hermes_cli/codex_models.py
+++ b/hermes_cli/codex_models.py
@@ -154,13 +154,20 @@ def _ranked_slugs(entries: object) -> List[str]:
def _fetch_models_from_api(access_token: str) -> List[str]:
"""Fetch available models from the Codex API. Returns visible models sorted by priority."""
try:
+ # Real Codex access tokens are JWTs; a custom base's gateway key is not one. Refusing to
+ # probe non-JWT credentials keeps the key off chatgpt.com (#121486) and skips a request
+ # that can never answer for it — mirroring the quota probe's gate in auth_codex.
+ from hermes_cli.auth_constants import DEFAULT_CODEX_BASE_URL, _decode_jwt_claims
+ if not access_token or not _decode_jwt_claims(access_token):
+ return []
+ catalog_base = os.getenv("HERMES_CODEX_BASE_URL", "").strip().rstrip("/") or DEFAULT_CODEX_BASE_URL
import httpx
# The per-account catalog needs ChatGPT-Account-ID (else ``{"models":[]}`` with HTTP 200
# masquerades as "no models") and, for residency-enforced workspaces, the residency header.
from agent.codex_headers import codex_account_headers
headers = {"Authorization": f"Bearer {access_token}", **codex_account_headers(access_token)}
from agent.model_metadata import fetch_codex_catalog_entries
- entries, _status = fetch_codex_catalog_entries(lambda url: httpx.get(url, headers=headers, timeout=10))
+ entries, _status = fetch_codex_catalog_entries(lambda url: httpx.get(url, headers=headers, timeout=10), base_url=catalog_base)
except Exception as exc:
logger.debug("Failed to fetch Codex models from API: %s", exc)
return []
diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py
index 03c2f771764..734b39b862d 100644
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@ -34,6 +34,19 @@ from agent.model_metadata import (
)
+def _codex_jwt(subject: str) -> str:
+ """JWT-shaped test stand-in: the live-probe path gates on the token parsing as a JWT
+ (a gateway key is not a ChatGPT credential and must stay off chatgpt.com, #121486);
+ the signature itself is never verified client-side."""
+ import base64 as _b64
+ import json as _json
+ def _enc(raw: bytes) -> str:
+ return _b64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+ header = _enc(b'{"alg":"RS256"}')
+ payload = _enc(_json.dumps({"sub": subject}).encode())
+ return f"{header}.{payload}.test-signature"
+
+
# =========================================================================
# Token estimation
# =========================================================================
@@ -440,26 +453,26 @@ class TestCodexOAuthContextLength:
first = get_model_context_length(
"gpt-5.5",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="token-account-a",
+ api_key=_codex_jwt("token-account-a"),
provider="openai-codex",
)
first_again = get_model_context_length(
"gpt-5.5",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="token-account-a",
+ api_key=_codex_jwt("token-account-a"),
provider="openai-codex",
)
second = get_model_context_length(
"gpt-5.5",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="token-account-b",
+ api_key=_codex_jwt("token-account-b"),
provider="openai-codex",
)
assert (first, first_again, second) == (272_000, 272_000, 372_000)
assert mock_get.call_count == 2
- assert mock_get.call_args_list[0].kwargs["headers"]["Authorization"] == "Bearer token-account-a"
- assert mock_get.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer token-account-b"
+ assert mock_get.call_args_list[0].kwargs["headers"]["Authorization"] == f"Bearer {_codex_jwt('token-account-a')}"
+ assert mock_get.call_args_list[1].kwargs["headers"]["Authorization"] == f"Bearer {_codex_jwt('token-account-b')}"
assert mock_save.call_count == 2
assert all(
"token-account" not in key
@@ -481,11 +494,48 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model="gpt-5.5",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="expired-token",
+ api_key=_codex_jwt("expired-token"),
provider="openai-codex",
)
assert ctx == 272_000
+ def test_gateway_key_never_probes_the_direct_catalog(self):
+ """A custom base's credential is the gateway's key, not a ChatGPT token: sending it to
+ chatgpt.com leaks it to a service it does not belong to and can never answer (#121486).
+ The probe must decline (falling back to the static table) instead of firing."""
+ import agent.model_metadata as mm
+ mm._codex_oauth_context_cache = {}
+
+ with patch("agent.model_metadata.requests.get") as mock_get:
+ live, fresh = mm._fetch_codex_oauth_context_lengths_with_source("gateway-pool-key")
+
+ assert (live, fresh) == ({}, False)
+ mock_get.assert_not_called()
+
+ def test_custom_base_probes_its_own_catalog(self):
+ """A JWT reached through a custom Codex base probes that base's ``/models``, never the
+ hard-coded chatgpt.com host (#121486)."""
+ import agent.model_metadata as mm
+ mm._codex_oauth_context_cache = {}
+
+ fake_response = MagicMock()
+ fake_response.status_code = 200
+ fake_response.json.return_value = {
+ "models": [{"slug": "gpt-5.5", "context_window": 272_000}]
+ }
+ with patch("agent.model_metadata.requests.get", return_value=fake_response) as mock_get, \
+ patch("agent.model_metadata.get_cached_context_length", return_value=None), \
+ patch("agent.model_metadata.save_context_length"):
+ ctx = get_model_context_length(
+ model="gpt-5.5",
+ base_url="https://codex-gw.example/backend-api/codex",
+ api_key=_codex_jwt("acct"),
+ provider="openai-codex",
+ )
+
+ assert ctx == 272_000
+ assert mock_get.call_args.args[0].startswith(
+ "https://codex-gw.example/backend-api/codex/models?client_version=")
@pytest.mark.parametrize(
"stale_context,live_context",
@@ -522,7 +572,7 @@ class TestCodexOAuthContextLength:
ctx = mm.get_model_context_length(
model="gpt-5.5",
base_url=base_url,
- api_key="fake-token",
+ api_key=_codex_jwt("fake-token"),
provider="openai-codex",
)
@@ -554,7 +604,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model=slug,
base_url="https://chatgpt.com/backend-api/codex",
- api_key="fake-token",
+ api_key=_codex_jwt("fake-token"),
provider="openai-codex",
)
assert ctx == 272_000
@@ -579,7 +629,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model="gpt-5.6-sol-900k",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="fake-token",
+ api_key=_codex_jwt("fake-token"),
provider="openai-codex",
)
assert ctx == advertised, f"advertised {advertised} must be trusted"
@@ -603,7 +653,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model="gpt-5.6-luna-900k",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="fake-token",
+ api_key=_codex_jwt("fake-token"),
provider="openai-codex",
)
assert ctx == expected
@@ -624,7 +674,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model="gpt-5.6-sol",
base_url="https://chatgpt.com/backend-api/codex",
- api_key="fake-token",
+ api_key=_codex_jwt("fake-token"),
provider="openai-codex",
)
assert ctx == 272_000
@@ -646,7 +696,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model=slug,
base_url="https://chatgpt.com/backend-api/codex",
- api_key="expired-token",
+ api_key=_codex_jwt("expired-token"),
provider="openai-codex",
)
assert ctx == 900_000
@@ -666,7 +716,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model=slug,
base_url="https://chatgpt.com/backend-api/codex",
- api_key="expired-token",
+ api_key=_codex_jwt("expired-token"),
provider="openai-codex",
)
assert ctx == 272_000
@@ -719,7 +769,7 @@ class TestCodexOAuthContextLength:
ctx = get_model_context_length(
model=model_id,
base_url="https://chatgpt.com/backend-api/codex",
- api_key="fake-token",
+ api_key=_codex_jwt("fake-token"),
provider="openai-codex",
)
assert ctx == expected_ctx
diff --git a/tests/hermes_cli/test_codex_models.py b/tests/hermes_cli/test_codex_models.py
index 68e6eeaf634..c75a97301c8 100644
--- a/tests/hermes_cli/test_codex_models.py
+++ b/tests/hermes_cli/test_codex_models.py
@@ -1,3 +1,4 @@
+import base64
import json
from unittest.mock import patch
@@ -8,6 +9,19 @@ from hermes_cli.codex_models import (
)
+def _codex_jwt(subject: str) -> str:
+ """JWT-shaped test stand-in: the live catalog path gates on the token parsing as a JWT
+ (a custom base's gateway key must stay off chatgpt.com, #121486)."""
+ enc = lambda raw: base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
+ header = enc(b'{"alg":"RS256"}')
+ payload = enc(json.dumps({"sub": subject}).encode())
+ return f"{header}.{payload}.test-signature"
+
+
+# dummy fixture value (not a real credential): a gateway pool key is opaque, never a JWT
+_GATEWAY_POOL_KEY = "dummy-gateway-pool-key"
+
+
def _pro_slugs(model_ids):
return [m for m in model_ids if m.removesuffix("-900k").endswith("-pro")]
@@ -99,7 +113,7 @@ def test_fetch_from_api_keeps_supported_in_api_false_models(monkeypatch):
monkeypatch.setitem(sys.modules, "httpx", _FakeHttpx)
- models = codex_models._fetch_models_from_api(access_token="tok")
+ models = codex_models._fetch_models_from_api(access_token=_codex_jwt("acct"))
assert "gpt-5.5" in models
assert "gpt-5.3-codex-spark" in models
@@ -299,10 +313,10 @@ def test_catalog_requests_ask_as_the_newest_client(monkeypatch):
seen_urls = []
get = _gated_codex_catalog(seen_urls)
monkeypatch.setitem(sys.modules, "httpx", type("_FakeHttpx", (), {"get": staticmethod(get)}))
- assert "gpt-6-sol" in codex_models._fetch_models_from_api(access_token="tok")
+ assert "gpt-6-sol" in codex_models._fetch_models_from_api(access_token=_codex_jwt("acct"))
monkeypatch.setattr(model_metadata.model_metadata_http, "get", get)
monkeypatch.setattr(model_metadata, "_codex_oauth_context_cache", {})
- live, fresh = model_metadata._fetch_codex_oauth_context_lengths_with_source("tok")
+ live, fresh = model_metadata._fetch_codex_oauth_context_lengths_with_source(_codex_jwt("acct"))
assert fresh and "gpt-6-sol" in live
assert len(seen_urls) == 2 # one request per site: the newest-client answer was non-empty
@@ -312,6 +326,44 @@ def test_catalog_requests_ask_as_the_newest_client(monkeypatch):
assert parse_qs(parsed.query)["client_version"] != ["0.0.0"]
+def test_gateway_key_is_never_sent_to_the_direct_catalog(monkeypatch):
+ """A ``HERMES_CODEX_BASE_URL`` gateway's key is not a ChatGPT token; the picker must not
+ send it to chatgpt.com (a service it does not belong to, #121486). Discovery declines
+ and falls back to the offline sources instead of firing a doomed request."""
+ import sys
+ from hermes_cli import codex_models
+
+ calls = {"n": 0}
+
+ def _count(_url, **_kwargs):
+ calls["n"] += 1
+ raise RuntimeError("a gateway key must not reach any catalog endpoint")
+
+ monkeypatch.setitem(sys.modules, "httpx", type("_FakeHttpx", (), {"get": staticmethod(_count)}))
+ assert codex_models._fetch_models_from_api(access_token=_GATEWAY_POOL_KEY) == []
+ assert calls["n"] == 0
+
+
+def test_picker_catalog_honours_the_custom_codex_base(monkeypatch):
+ """With ``HERMES_CODEX_BASE_URL`` set, the picker's live discovery probes the gateway's
+ own ``/models``, not the hard-coded chatgpt.com host (#121486)."""
+ import sys
+ from urllib.parse import urlparse
+
+ from hermes_cli import codex_models
+
+ seen_urls = []
+ get = _gated_codex_catalog(seen_urls)
+ monkeypatch.setitem(sys.modules, "httpx", type("_FakeHttpx", (), {"get": staticmethod(get)}))
+ monkeypatch.setenv("HERMES_CODEX_BASE_URL", "https://codex-gw.example/backend-api/codex")
+
+ assert "gpt-6-sol" in codex_models._fetch_models_from_api(access_token=_codex_jwt("acct"))
+ assert seen_urls, "discovery must still run for a JWT credential"
+ for url in seen_urls:
+ parsed = urlparse(url)
+ assert parsed.netloc == "codex-gw.example" and parsed.path == "/backend-api/codex/models"
+
+
def test_catalog_falls_back_to_the_ungated_sentinel_when_newest_client_is_rejected():
"""If the backend goes back to rejecting out-of-sequence versions (empty list or non-200), the
``0.0.0`` sentinel is tried next; a sentinel that is itself empty yields no entries."""
diff --git a/tests/plugins/image_gen/test_openai_codex_provider.py b/tests/plugins/image_gen/test_openai_codex_provider.py
index fcd3302a01f..00f0bd1f66c 100644
--- a/tests/plugins/image_gen/test_openai_codex_provider.py
+++ b/tests/plugins/image_gen/test_openai_codex_provider.py
@@ -214,6 +214,18 @@ class TestGenerate:
# The whole point of the native route: nothing about a chat model in the request.
assert not any(key in body for key in ("tools", "input", "instructions"))
+ def test_custom_codex_base_receives_the_image_request(self, provider, codex_backend, tmp_path, monkeypatch):
+ """With ``HERMES_CODEX_BASE_URL`` set, image requests go to the gateway's base instead of
+ the hard-coded chatgpt.com host (#121486) — the text client honours the same override."""
+ monkeypatch.setenv("HERMES_CODEX_BASE_URL", "https://codex-gw.example/backend-api/codex")
+
+ result = provider.generate("a cat")
+
+ assert result["success"] is True
+ (request,) = codex_backend["requests"]
+ assert request.url.host == "codex-gw.example"
+ assert request.url.path.endswith("/backend-api/codex/images/generations")
+
def test_source_images_post_edits_with_inline_data_urls(self, provider, codex_backend, tmp_path):
local = tmp_path / "ref.png"
local.write_bytes(_png_bytes())