Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(codex): fail closed on TLS certificate errors
chengyongruc8dba74fc5e3
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex de5bdee3b..1bc1bc531 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -159,6 +159,14 @@ If you need a known-good snippet instead of diagnosis, use [`provider-cookbook.m| xAI returns 400 `invalid-argument` | Read the bounded `Response body` appended to the provider error. Hosted `x_search` is sent only when xAI's model catalog advertises `supportsBackendSearch`; the model ID `grok-4.5` itself is valid. || xAI model or X Search stops working after an upstream release | The integration follows Grok Build's public OAuth/proxy client contract. Update nanobot if xAI changes that contract. |+### Codex certificate verification errors++Codex model requests fail if the server certificate is untrusted, expired, or does not match the hostname. nanobot does not retry these requests with certificate verification disabled. This also applies when WebSocket falls back to HTTP.++Check the gateway machine's clock and the certificate chain used by your network or proxy. If your organization requires a private CA, obtain its trusted PEM bundle from your administrator and set `SSL_CERT_FILE` in the gateway process environment before restarting. `SSL_CERT_DIR` is also supported for an OpenSSL-compatible certificate directory. For model requests, these CA settings work with or without the explicit Codex proxy; they do not change the selected proxy route. Never trust a certificate supplied by an unknown error page or disable certificate verification.++These model-request CA settings do not change OAuth login or model-catalog transport configuration. If those operations fail through a TLS-inspecting proxy, use an administrator-approved route that preserves the service's trusted certificate chain. Repeated sign-in does not repair a certificate error. Existing chats and credentials are not deleted by this failure.+### Local Token EstimationGateway loads the fallback tokenizer in the background, caching it beside the active config under `cache/tiktoken` unless `TIKTOKEN_CACHE_DIR` or `DATA_GYM_CACHE_DIR` is set; chats use UTF-8 byte estimates while loading or after failure (restart to retry), and token estimates may differ from model usage.diff --git a/nanobot/providers/openai_codex_provider.py b/nanobot/providers/openai_codex_provider.pyindex 82773d93c..1b64a11ce 100644--- a/nanobot/providers/openai_codex_provider.py+++ b/nanobot/providers/openai_codex_provider.py@@ -190,20 +190,20 @@ class OpenAICodexProvider(LLMProvider):self._responses = ResponsesBackend(websocket_options=ResponsesWebSocketOptions(beta_header="responses_websockets=2026-02-06",))- self._ssl_contexts: dict[bool, ssl.SSLContext] = {}+ self._tls_context: ssl.SSLContext | None = Noneasync def aclose(self) -> None:await self._responses.aclose()- def _ssl_context(self, *, verify: bool) -> ssl.SSLContext:- context = self._ssl_contexts.get(verify)- if context is None:- context = httpx.create_ssl_context(- verify=verify,- trust_env=self.proxy is None,+ def _ssl_context(self) -> ssl.SSLContext:+ """Reuse synchronous TLS setup across requests on the shared event loop."""+ if self._tls_context is None:+ self._tls_context = httpx.create_ssl_context(+ verify=True,+ # CA trust is independent of explicit proxy routing.+ trust_env=True,)- self._ssl_contexts[verify] = context- return context+ return self._tls_contextasync def _call_codex(self,@@ -325,39 +325,22 @@ class OpenAICodexProvider(LLMProvider):result = await self._responses.websocket_request(session_id, DEFAULT_CODEX_URL, headers, wire_body,provider=self._responses_state_provider(),- verify=self._ssl_context(verify=True), proxy=self.proxy,+ verify=self._ssl_context(), proxy=self.proxy,on_content_delta=on_content_delta if emit_deltas else None,on_thinking_delta=on_thinking_delta if emit_deltas else None,on_tool_call_delta=on_tool_call_delta if emit_deltas else None,)if result is None:- try:- result = await _request_codex(- DEFAULT_CODEX_URL,- headers,- wire_body,- verify=self._ssl_context(verify=True),- proxy=self.proxy,- on_content_delta=on_content_delta if emit_deltas else None,- on_thinking_delta=on_thinking_delta if emit_deltas else None,- on_tool_call_delta=on_tool_call_delta if emit_deltas else None,- )- except Exception as exc:- if "CERTIFICATE_VERIFY_FAILED" not in str(exc):- raise- logger.warning(- "SSL verification failed for Codex API; retrying with verify=False"- )- result = await _request_codex(- DEFAULT_CODEX_URL,- headers,- wire_body,- verify=self._ssl_context(verify=False),- proxy=self.proxy,- on_content_delta=on_content_delta if emit_deltas else None,- on_thinking_delta=on_thinking_delta if emit_deltas else None,- on_tool_call_delta=on_tool_call_delta if emit_deltas else None,- )+ result = await _request_codex(+ DEFAULT_CODEX_URL,+ headers,+ wire_body,+ verify=self._ssl_context(),+ proxy=self.proxy,+ on_content_delta=on_content_delta if emit_deltas else None,+ on_thinking_delta=on_thinking_delta if emit_deltas else None,+ on_tool_call_delta=on_tool_call_delta if emit_deltas else None,+ )if validate is not None:validate(result)except Exception as exc:diff --git a/tests/providers/test_openai_codex_provider.py b/tests/providers/test_openai_codex_provider.pyindex f0563ba37..135889263 100644--- a/tests/providers/test_openai_codex_provider.py+++ b/tests/providers/test_openai_codex_provider.py@@ -133,9 +133,9 @@ def test_codex_default_model_matches_curated_flagship() -> None:@pytest.mark.asyncio-async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeypatch) -> None:[email protected]("proxy", [None, "http://127.0.0.1:23458"])+async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeypatch, proxy) -> None:_mock_codex_token(monkeypatch)- proxy = "http://127.0.0.1:23458"context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)context_calls: list[tuple[bool, bool]] = []request_contexts: list[object] = []@@ -168,10 +168,49 @@ async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeyp))assert [response.content for response in responses] == ["ok", "ok", "ok"]- assert context_calls == [(True, False)]+ assert context_calls == [(True, True)]assert request_contexts == [context, context, context][email protected]("session_id", [None, "tls-failure"], ids=["http", "websocket-fallback"])+async def test_codex_certificate_failure_does_not_retry_without_verification(+ monkeypatch, session_id,+) -> None:+ _mock_codex_token(monkeypatch)+ request_contexts: list[ssl.SSLContext] = []+ websocket_contexts: list[ssl.SSLContext] = []++ async def fake_connect(_url, **kwargs):+ websocket_contexts.append(kwargs["ssl"])+ raise ssl.SSLCertVerificationError("CERTIFICATE_VERIFY_FAILED")++ async def fake_request(_url, headers, _body, *, verify, **_kwargs):+ request_contexts.append(verify)+ assert headers["Authorization"] == "Bearer token"+ if verify.verify_mode == ssl.CERT_NONE:+ return provider_base.LLMResponse(content="untrusted response")+ raise httpx.ConnectError("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed")++ monkeypatch.setattr("nanobot.providers.openai_responses.websocket.connect", fake_connect)+ monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)+ provider = OpenAICodexProvider()+ try:+ response = await provider.chat(+ [{"role": "user", "content": "private prompt"}],+ provider_context=provider_base.ProviderCallContext(session_id=session_id),+ )+ finally:+ await provider.aclose()++ assert response.finish_reason == "error"+ assert "CERTIFICATE_VERIFY_FAILED" in (response.content or "")+ assert len(request_contexts) == 1+ assert request_contexts[0].verify_mode == ssl.CERT_REQUIRED+ assert request_contexts[0].check_hostname is True+ assert websocket_contexts == (request_contexts if session_id else [])++@pytest.fixturedef codex_warning_log(monkeypatch):monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)