The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: cap Codex OAuth/device-auth response bodies at 1 MiB in CLI and dashboard
teknium1c6d12dafa069
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex d0e8cab951d..083b1a93f2d 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -294,8 +294,48 @@ def _codex_login_post(url: str, *, failure: Tuple[str, str], **kwargs: Any) -> "attempt += 1+_CODEX_AUTH_BODY_MAX_BYTES = 1024 * 1024 # real OAuth/device-auth payloads are a few hundred bytes+++class _CappedByteStream(httpx.SyncByteStream):+ """Body stream that raises once more than ``_CODEX_AUTH_BODY_MAX_BYTES`` came off the wire.++ httpx type-checks ``response.stream`` against ``SyncByteStream``, so the cap has to be a+ stream subclass rather than a bare generator.+ """++ def __init__(self, response: "httpx.Response") -> None:+ self._response, self._raw = response, response.stream++ def __iter__(self) -> Iterator[bytes]:+ total = 0+ for chunk in self._raw: # type: ignore[union-attr] # sync client only+ total += len(chunk)+ if total > _CODEX_AUTH_BODY_MAX_BYTES:+ self.close()+ raise _codex_err(+ f"Codex auth response from {self._response.url.host} exceeded "+ f"{_CODEX_AUTH_BODY_MAX_BYTES // 1024} KiB; refusing to parse it.",+ "codex_auth_response_too_large", relogin=False)+ yield chunk++ def close(self) -> None:+ self._raw.close() # type: ignore[union-attr]+++def _cap_codex_response_body(response: "httpx.Response") -> None:+ """httpx response hook: refuse to buffer an auth body above ``_CODEX_AUTH_BODY_MAX_BYTES``.++ Runs before ``client.post()`` reads the body, so a hostile or broken endpoint/proxy answering+ 200 with megabytes of "JSON" is cut off at the cap instead of being fully buffered and parsed+ (#55253). Same cap for every status: error bodies are small diagnostics too.+ """+ response.stream = _CappedByteStream(response)++def _codex_http_client(**kwargs: Any) -> "httpx.Client":- """Build an ``httpx.Client`` for Codex OAuth/probe endpoints with Happy-Eyeballs racing.+ """Build an ``httpx.Client`` for Codex OAuth/probe endpoints with Happy-Eyeballs racing and a+ 1 MiB response-body cap (``_cap_codex_response_body``).A host advertising AAAA records but blackholing IPv6 makes each serial connect eat the fulltimeout before IPv4 is tried (same failure mode as the chat transport). Best-effort: if the@@ -306,7 +346,9 @@ def _codex_http_client(**kwargs: Any) -> "httpx.Client":token refresh / device login / usage probes time out where the official Codex CLI (which races familiesper RFC 8305) works."""- client = httpx.Client(**kwargs)+ hooks = dict(kwargs.pop("event_hooks", None) or {})+ hooks["response"] = [_cap_codex_response_body, *hooks.get("response", [])]+ client = httpx.Client(event_hooks=hooks, **kwargs)with suppress(Exception):from agent.process_bootstrap import enable_happy_eyeballs_on_clientenable_happy_eyeballs_on_client(client)diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 3b2eb16da41..49db119e6a0 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -150,6 +150,17 @@ def _codex_cancelled(sess: Dict[str, Any], session_id: str, stage: str = "") ->return True+def _codex_body_cap() -> Dict[str, list]:+ """``event_hooks`` applying the CLI flow's 1 MiB auth-body cap to the dashboard's own client (#55253).++ The helpers take the ``httpx`` module as a parameter (tests inject a scripted one), so the+ dashboard keeps building its client here and only shares the hook, not the client factory.+ """+ from hermes_cli.auth_codex import _cap_codex_response_body++ return {"response": [_cap_codex_response_body]}++def _codex_post(httpx, url: str, **kwargs: Any) -> Any:"""One 15s POST for the device-login flow, mirroring ``auth_codex._codex_login_post``.@@ -162,7 +173,7 @@ def _codex_post(httpx, url: str, **kwargs: Any) -> Any:attempt, attempts = 1, 3while True:try:- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:+ with httpx.Client(timeout=httpx.Timeout(15.0), event_hooks=_codex_body_cap()) as client:return client.post(url, **kwargs)except Exception as exc:if attempt == attempts or not _is_transient_transport_error(exc):@@ -196,7 +207,7 @@ def _codex_poll_authorization(httpx, sess: Dict[str, Any], session_id: str) -> Apayload = {"device_auth_id": sess["device_auth_id"], "user_code": sess["user_code"]}max_consecutive_blips = 6 # same cap as the CLI poll loop: survives drops, fails fast on a dead networkconsecutive_blips = 0- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:+ with httpx.Client(timeout=httpx.Timeout(15.0), event_hooks=_codex_body_cap()) as client:while time.monotonic() < deadline:if _codex_cancelled(sess, session_id):return _CANCELLEDdiff --git a/tests/hermes_cli/test_auth_codex_bounded_body.py b/tests/hermes_cli/test_auth_codex_bounded_body.pynew file mode 100644index 00000000000..9179545e117--- /dev/null+++ b/tests/hermes_cli/test_auth_codex_bounded_body.py@@ -0,0 +1,67 @@+"""Codex OAuth/device-auth responses are read through a 1 MiB body cap (#55253).++A hostile or broken auth endpoint/proxy answering 200 with megabytes of "JSON" used to be+fully buffered and parsed by every ``client.post(...).json()`` in the CLI device-code flow,+the dashboard login worker and ``refresh_codex_oauth_pure``. All of them build their client via+``auth_codex._codex_http_client``, whose response hook cuts the read off at the cap.+"""+from __future__ import annotations++import functools+import json++import httpx+import pytest++from hermes_cli import auth_codex+from hermes_cli.auth import AuthError+from hermes_cli.web_routers import oauth as web_oauth+++class _LazyBody(httpx.SyncByteStream):+ """Like a socket: chunks are only produced when pulled, and the pull count is observable."""++ def __init__(self, data: bytes, pulled: list) -> None:+ self._data, self._pulled = data, pulled++ def __iter__(self):+ for i in range(0, len(self._data), 65536):+ self._pulled[0] += len(self._data[i:i + 65536])+ yield self._data[i:i + 65536]++ def close(self) -> None:+ pass+++def _serve(monkeypatch, payload: dict) -> list:+ pulled = [0]+ body = json.dumps(payload).encode()++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, headers={"content-type": "application/json"}, stream=_LazyBody(body, pulled))++ monkeypatch.setattr(httpx, "Client", functools.partial(httpx.Client, transport=httpx.MockTransport(handler)))+ return pulled+++def test_oversized_200_auth_body_is_rejected_before_being_buffered(monkeypatch):+ pulled = _serve(monkeypatch, {"access_token": "at", "refresh_token": "rt", "pad": "a" * (3 * 1024 * 1024)})++ with pytest.raises(AuthError) as excinfo:+ auth_codex.refresh_codex_oauth_pure("old-at", "old-rt")+ assert excinfo.value.code == "codex_auth_response_too_large"+ assert "exceeded 1024 KiB" in str(excinfo.value)+ # Stopped within one chunk of the cap, not the full 3 MiB.+ assert auth_codex._CODEX_AUTH_BODY_MAX_BYTES < pulled[0] <= auth_codex._CODEX_AUTH_BODY_MAX_BYTES + 65536++ with pytest.raises(AuthError, match="exceeded 1024 KiB"):+ web_oauth._codex_exchange_tokens(httpx, {"authorization_code": "c", "code_verifier": "v"})+++def test_normal_auth_body_still_parses(monkeypatch):+ _serve(monkeypatch, {"access_token": "at-new", "refresh_token": "rt-new"})++ refreshed = auth_codex.refresh_codex_oauth_pure("old-at", "old-rt")+ assert refreshed["access_token"] == "at-new"+ assert web_oauth._codex_exchange_tokens(httpx, {"authorization_code": "c", "code_verifier": "v"}) == {+ "access_token": "at-new", "refresh_token": "rt-new"}