The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): extract residency claims from Codex OAuth JWT for workspace auth
liuhao10240bbf7b7997ec
diff --git a/agent/codex_headers.py b/agent/codex_headers.pyindex d967ae2e8ad..810260844bb 100644--- a/agent/codex_headers.py+++ b/agent/codex_headers.py@@ -36,16 +36,29 @@ def codex_cloudflare_headers(access_token: str, *, base_url: str = CODEX_AUX_BASOpenAI requires third-party harnesses to identify themselves: the officialendpoint gets Hermes' originator and version, custom endpoints keep the- codex_cli_rs compatibility identity. ``ChatGPT-Account-ID`` comes from the- OAuth JWT's ``chatgpt_account_id`` claim; a malformed token drops the header- rather than raising, so it surfaces as a 401 instead of a crash at client- construction.+ codex_cli_rs compatibility identity. The account headers come from the+ OAuth JWT (see :func:`codex_account_headers`)."""if is_official_codex_base_url(base_url):from hermes_cli import __version__headers = {"User-Agent": f"HermesAgent/{__version__}", "originator": "hermes-agent"}else:headers = {"User-Agent": "codex_cli_rs/0.0.0 (Hermes Agent)", "originator": "codex_cli_rs"}+ headers.update(codex_account_headers(access_token))+ return headers+++def codex_account_headers(access_token: str) -> Dict[str, str]:+ """Workspace headers the Codex backend derives from the OAuth JWT.++ ``ChatGPT-Account-ID`` (canonical casing, from codex-rs ``auth.rs``) comes from+ ``chatgpt_account_id``; ``x-openai-internal-codex-residency`` from+ ``chatgpt_data_residency`` (fallback ``chatgpt_compute_residency``) — without+ it residency-enforced workspaces answer 401 "Workspace is not authorized in+ this region". A malformed token drops the headers rather than raising, so it+ surfaces as a 401 instead of a crash at client construction.+ """+ headers: Dict[str, str] = {}if not isinstance(access_token, str) or not access_token.strip():return headerstry:@@ -53,10 +66,13 @@ def codex_cloudflare_headers(access_token: str, *, base_url: str = CODEX_AUX_BASif len(parts) < 2:return headerspayload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)- claims = json.loads(base64.urlsafe_b64decode(payload_b64))- acct_id = claims.get("https://api.openai.com/auth", {}).get("chatgpt_account_id")+ auth = json.loads(base64.urlsafe_b64decode(payload_b64)).get("https://api.openai.com/auth", {})+ acct_id = auth.get("chatgpt_account_id")if isinstance(acct_id, str) and acct_id:headers["ChatGPT-Account-ID"] = acct_id+ residency = auth.get("chatgpt_data_residency") or auth.get("chatgpt_compute_residency")+ if isinstance(residency, str) and residency.strip():+ headers["x-openai-internal-codex-residency"] = residency.strip()except Exception:passreturn headersdiff --git a/tests/agent/test_codex_cloudflare_headers.py b/tests/agent/test_codex_cloudflare_headers.pyindex 9cd1e68a6db..3467c14b779 100644--- a/tests/agent/test_codex_cloudflare_headers.py+++ b/tests/agent/test_codex_cloudflare_headers.py@@ -33,18 +33,27 @@ from hermes_cli import __version__# Fixtures# ----------------------------------------------------------------------------def _make_codex_jwt(account_id: str = "acct-test-123") -> str:+def _make_codex_jwt(+ account_id: str = "acct-test-123",+ data_residency: str | None = None,+ compute_residency: str | None = None,+) -> str:"""Build a syntactically valid Codex-style JWT with the account_id claim."""def b64url(data: bytes) -> str:return base64.urlsafe_b64encode(data).rstrip(b"=").decode()header = b64url(b'{"alg":"RS256","typ":"JWT"}')+ auth_claims: dict = {+ "chatgpt_account_id": account_id,+ "chatgpt_plan_type": "plus",+ }+ if data_residency is not None:+ auth_claims["chatgpt_data_residency"] = data_residency+ if compute_residency is not None:+ auth_claims["chatgpt_compute_residency"] = compute_residencyclaims = {"sub": "user-xyz","exp": 9999999999,- "https://api.openai.com/auth": {- "chatgpt_account_id": account_id,- "chatgpt_plan_type": "plus",- },+ "https://api.openai.com/auth": auth_claims,}payload = b64url(json.dumps(claims).encode())sig = b64url(b"fake-sig")@@ -88,6 +97,40 @@ class TestCodexCloudflareHeaders:assert headers["originator"] == "hermes-agent"assert "ChatGPT-Account-ID" not in headers+ def test_residency_header_from_data_residency_claim(self):+ """chatgpt_data_residency claim should populate x-openai-internal-codex-residency."""+ from agent.auxiliary_client import _codex_cloudflare_headers+ headers = _codex_cloudflare_headers(_make_codex_jwt(data_residency="us"))+ assert headers["x-openai-internal-codex-residency"] == "us"++ def test_residency_header_from_compute_residency_fallback(self):+ """When data_residency is absent, compute_residency should be used."""+ from agent.auxiliary_client import _codex_cloudflare_headers+ headers = _codex_cloudflare_headers(_make_codex_jwt(compute_residency="eu"))+ assert headers["x-openai-internal-codex-residency"] == "eu"++ def test_data_residency_takes_precedence_over_compute(self):+ """When both claims exist, data_residency should win."""+ from agent.auxiliary_client import _codex_cloudflare_headers+ headers = _codex_cloudflare_headers(+ _make_codex_jwt(data_residency="us", compute_residency="eu"),+ )+ assert headers["x-openai-internal-codex-residency"] == "us"++ def test_no_residency_claims_omits_header(self):+ """When neither residency claim exists, the header should be absent."""+ from agent.auxiliary_client import _codex_cloudflare_headers+ headers = _codex_cloudflare_headers(_make_codex_jwt())+ assert "x-openai-internal-codex-residency" not in headers++ def test_malformed_token_drops_residency_without_raising(self):+ """Malformed tokens should not raise; residency header should be absent."""+ from agent.auxiliary_client import _codex_cloudflare_headers+ for bad in ["not-a-jwt", "", "only.one", " ", "...."]:+ headers = _codex_cloudflare_headers(bad)+ assert headers["originator"] == "codex_cli_rs"+ assert "x-openai-internal-codex-residency" not in headers+# ---------------------------------------------------------------------------# Primary chat client wiring (run_agent.AIAgent)