Skip to content

The agent that grows with you

fix(ssl): route the auth and platform certifi pins through the shared re-derivation

Pedro Relvase681d6fae519
diff --git a/hermes_cli/auth_device_flow.py b/hermes_cli/auth_device_flow.py
index b8ca803f410..680f963f760 100644
--- a/hermes_cli/auth_device_flow.py
+++ b/hermes_cli/auth_device_flow.py
@@ -216,14 +216,14 @@ def _default_verify() -> bool | ssl.SSLContext:
"""Platform-aware default SSL verify for httpx clients.
On macOS with Homebrew Python the system OpenSSL cannot find the system trust store, so pin
- certifi's bundle when importable; elsewhere defer to httpx's built-in default.
+ certifi's bundle when importable; elsewhere defer to httpx's built-in default. The bundle is
+ resolved through ``agent.ssl_verify``, the one place that re-derives a path an
+ install-environment rotation deleted: the Nous credential exchange builds its context here, and
+ in a long-lived gateway it can be the first TLS client constructed after the rotation.
"""
if sys.platform == "darwin":
- try:
- import certifi
- return ssl.create_default_context(cafile=certifi.where())
- except ImportError:
- pass
+ from agent.ssl_verify import resolve_httpx_verify
+ return resolve_httpx_verify()
return True
diff --git a/plugins/model-providers/actual/__init__.py b/plugins/model-providers/actual/__init__.py
index a6c3a9574ec..d5fe75b506f 100644
--- a/plugins/model-providers/actual/__init__.py
+++ b/plugins/model-providers/actual/__init__.py
@@ -33,9 +33,12 @@ class ActualProfile(ProviderProfile):
)
):
return {}
- import certifi
+ from agent.ssl_verify import certifi_bundle_path
- return {"ssl_ca_cert": certifi.where()}
+ # Re-derived when an install-environment rotation deleted the directory certifi was
+ # imported from: a deleted path would otherwise be handed to the client as ssl_ca_cert.
+ bundle = certifi_bundle_path()
+ return {"ssl_ca_cert": bundle} if bundle else {}
def supported_reasoning_efforts(self, model: str | None) -> tuple[str, ...] | None:
from agent.reasoning_effort import ACTUAL_RELAY_EFFORTS
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index a77b6e6b192..9f967241316 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -224,13 +224,12 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAcc
async def _open_connection(self) -> None:
await self._cleanup_ws()
- # certifi's CA bundle so aiohttp trusts the same roots as urllib/requests (macOS stale OpenSSL path).
+ # certifi's CA bundle so aiohttp trusts the same roots as urllib/requests (macOS stale OpenSSL path),
+ # re-derived when an install-environment rotation deleted the imported one (#137255).
import ssl as _ssl
- try:
- import certifi
- cafile = certifi.where()
- except ImportError:
- cafile = None
+
+ from agent.ssl_verify import certifi_bundle_path
+ cafile = certifi_bundle_path()
_ssl_ctx = _ssl.create_default_context(cafile=cafile)
self._session = aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=aiohttp.TCPConnector(ssl=_ssl_ctx))
self._ws = await self._session.ws_connect(self._ws_url, heartbeat=HEARTBEAT_INTERVAL_SECONDS * 2, timeout=CONNECT_TIMEOUT_SECONDS)
diff --git a/plugins/platforms/weixin/adapter.py b/plugins/platforms/weixin/adapter.py
index dc1623cc689..e142535a10d 100644
--- a/plugins/platforms/weixin/adapter.py
+++ b/plugins/platforms/weixin/adapter.py
@@ -101,12 +101,18 @@ def _make_ssl_connector() -> Optional[aiohttp.TCPConnector]:
"""
try:
import ssl
- import certifi
+
+ from agent.ssl_verify import certifi_bundle_path
except ImportError:
return None
if not AIOHTTP_AVAILABLE:
return None
- return aiohttp.TCPConnector(ssl=ssl.create_default_context(cafile=certifi.where()), keepalive_timeout=2, enable_cleanup_closed=True)
+ # Re-derived when an install-environment rotation deleted the directory certifi was imported
+ # from, so a long-lived gateway does not pin a cacert.pem that no longer exists (#137255).
+ cafile = certifi_bundle_path()
+ if cafile is None:
+ return None # no bundle: aiohttp's default (honors SSL_CERT_FILE under trust_env) applies
+ return aiohttp.TCPConnector(ssl=ssl.create_default_context(cafile=cafile), keepalive_timeout=2, enable_cleanup_closed=True)
def _new_session(**kwargs: Any) -> aiohttp.ClientSession:
diff --git a/tests/hermes_cli/test_auth_nous_provider.py b/tests/hermes_cli/test_auth_nous_provider.py
index 22223b0a2ff..556aa4ecfc9 100644
--- a/tests/hermes_cli/test_auth_nous_provider.py
+++ b/tests/hermes_cli/test_auth_nous_provider.py
@@ -83,6 +83,70 @@ class TestResolveVerifyFallback:
result = _resolve_verify(auth_state={"tls": {"insecure": "true"}})
assert result is False
+
+def _rotate_certifi_out_from_under_the_process(tmp_path: Path, monkeypatch) -> None:
+ """Import certifi from ``env-a``, then delete the directory it lives in.
+
+ The package manager's environment rotation without a package manager: the replacement
+ ``env-b`` is what the next lookup finds, exactly as the new install generation would be.
+ """
+ import importlib
+ import shutil
+ import sys
+
+ import certifi as real_certifi
+
+ bundle = Path(real_certifi.where()).read_bytes()
+ for name in ("env-a", "env-b"):
+ package = tmp_path / name / "certifi"
+ package.mkdir(parents=True)
+ (package / "__init__.py").write_text(
+ "import os\n\n\ndef where():\n"
+ " return os.path.join(os.path.dirname(__file__), 'cacert.pem')\n")
+ (package / "cacert.pem").write_bytes(bundle)
+ monkeypatch.syspath_prepend(str(tmp_path / "env-b"))
+ monkeypatch.syspath_prepend(str(tmp_path / "env-a"))
+ monkeypatch.delitem(sys.modules, "certifi", raising=False)
+ importlib.invalidate_caches()
+ stand_in = importlib.import_module("certifi")
+ monkeypatch.setitem(sys.modules, "certifi", stand_in)
+ assert Path(stand_in.where()).parent == tmp_path / "env-a" / "certifi"
+ shutil.rmtree(tmp_path / "env-a")
+ assert not Path(stand_in.where()).exists()
+
+
+class TestDefaultVerifyAfterAnInstallRotation:
+ """The Nous credential exchange can be the first TLS client a long-lived gateway builds
+ after the package manager replaced the environment certifi was imported from (#137255).
+
+ On macOS that stand pinned ``certifi.where()`` directly, so it kept handing over the
+ deleted bundle and every credential refresh failed until the gateway was restarted.
+ """
+
+ @pytest.mark.platforms("macos")
+ def test_credential_verify_re_derives_the_rotated_bundle(self, tmp_path, monkeypatch):
+ import ssl
+
+ from hermes_cli.auth import _resolve_verify
+
+ for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"):
+ monkeypatch.delenv(var, raising=False)
+ _rotate_certifi_out_from_under_the_process(tmp_path, monkeypatch)
+
+ verify = _resolve_verify(auth_state={"tls": {"insecure": False}})
+
+ # Nothing in the process points at the deleted environment any more, and the value
+ # handed to httpx builds a client (it raised FileNotFoundError before the fix).
+ import certifi
+
+ assert Path(certifi.where()).is_file()
+ with httpx.Client(verify=verify) as client: # the construction that raised before the fix
+ from typing import Any, cast
+
+ transport = cast(Any, client._transport)
+ assert transport._pool._ssl_context.verify_mode == ssl.CERT_REQUIRED
+
+
def _setup_nous_auth(
hermes_home: Path,
*,