The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(ssl): re-resolve certifi's CA bundle after an install-environment rotation
Pedro Relvas6bd9c10e322a
diff --git a/agent/ssl_verify.py b/agent/ssl_verify.pyindex 2cd20238b44..6ca3141637f 100644--- a/agent/ssl_verify.py+++ b/agent/ssl_verify.py@@ -130,6 +130,98 @@ def platform_ssl_context() -> ssl.SSLContext:return _shared_context(None)+def certifi_bundle_path() -> Optional[str]:+ """certifi's CA bundle path, re-derived when a rotation invalidated it.++ ``certifi.where()`` builds its path from the imported module's ``__file__``, so a+ process that outlives an install-environment rotation — the package manager creates+ a new environment directory and deletes the old one — keeps pointing into the+ deleted directory for the rest of its life, and every TLS client it builds+ afterwards fails. Re-executing the module re-derives ``__file__`` from the live+ ``sys.path``; when even that finds nothing, the platform store is the answer and+ never an exception.++ Returns a bundle path that exists on disk, else ``None``.+ """+ try:+ import certifi+ except ImportError:+ return None+ stale = certifi.where()+ if Path(stale).is_file():+ return stale+ recovered = _reload_certifi_bundle()+ if recovered is not None:+ logger.warning(+ "TLS trust: certifi's CA bundle %s no longer exists — the install "+ "environment it belongs to was replaced under this process; re-resolved "+ "to %s. TLS clients built before this point used the dead path.",+ stale,+ recovered,+ )+ return recovered+ logger.warning(+ "TLS trust: certifi's CA bundle %s no longer exists and certifi could not be "+ "re-resolved; using the platform trust store for the rest of this process.",+ stale,+ )+ return None+++def _reload_certifi_bundle() -> Optional[str]:+ """Re-execute the imported certifi module so its path follows the live ``sys.path``.++ ``None`` when certifi was never imported or its package is gone from every+ ``sys.path`` entry — the caller then falls back to the platform store.+ """+ import importlib+ import sys++ module = sys.modules.get("certifi")+ if module is None:+ return None+ # The replaced directory is gone; a finder holding a cached listing of it would+ # still resolve the old package.+ importlib.invalidate_caches()+ try:+ path = importlib.reload(module).where()+ except Exception as exc: # the reload re-executes third-party module code+ logger.debug("certifi could not be re-resolved: %s", exc, exc_info=True)+ return None+ return path if path and Path(path).is_file() else None+++def requests_verify() -> bool | str:+ """``verify`` for a ``requests`` call in this process.++ ``requests`` resolves ``verify=True`` through ``DEFAULT_CA_BUNDLE_PATH``, a string+ frozen when ``requests`` was imported — the one certifi consumer a module reload+ cannot reach, so a rotated environment leaves every ``requests`` call raising+ ``OSError: Could not find a suitable TLS CA certificate bundle``. The live bundle+ (certifi's, re-derived; else OpenSSL's own default) keeps those calls working;+ ``True`` only when nothing resolves, which is requests' own default.+ """+ bundle = certifi_bundle_path()+ if bundle:+ return bundle+ defaults = ssl.get_default_verify_paths()+ for candidate in (defaults.cafile, defaults.capath):+ if candidate and Path(candidate).exists():+ return candidate+ return True+++def _default_verify() -> bool | ssl.SSLContext:+ """``verify`` for the platform default path.++ httpx resolves ``verify=True`` through ``certifi.where()`` at client construction,+ which raises ``FileNotFoundError`` on a bundle path a rotation deleted. Hand the+ platform context over instead when no bundle can be found; a re-derivable bundle+ keeps ``True`` — the module reload already repaired certifi process-wide.+ """+ return True if certifi_bundle_path() else _shared_context(None)++def resolve_httpx_verify(*,ca_bundle: Optional[str] = None,@@ -142,7 +234,9 @@ def resolve_httpx_verify(2. explicit ``ca_bundle`` (the provider's ``ssl_ca_cert``) — thatbundle INSTEAD of the platform store, for an endpoint whose chainthe machine has no reason to trust- 3. ``True`` — the platform store, via the process-wide install+ 3. ``True`` — the platform store, via the process-wide install, or the+ platform context when the certifi bundle this process resolved at+ import no longer exists (a replaced install environment)``base_url`` only labels the insecure-mode warning."""@@ -171,4 +265,4 @@ def resolve_httpx_verify(# proxy environment handling remains enabled.if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"):return _shared_context(None)- return True+ return _default_verify()diff --git a/plugins/browser/_common.py b/plugins/browser/_common.pyindex 037906b79b7..93bf0c89148 100644--- a/plugins/browser/_common.py+++ b/plugins/browser/_common.py@@ -12,6 +12,7 @@ from typing import Any, Dict, List, Optionalimport requestsfrom agent.browser_provider import BrowserProvider+from agent.ssl_verify import requests_verify_CLOSE_OK = {200, 201, 204}@@ -65,7 +66,13 @@ class CloudBrowserProvider(BrowserProvider):return Nonedef _release(self, config: dict[str, Any], session_id: str, timeout: int) -> requests.Response:- kwargs: dict[str, Any] = {"headers": self._release_headers(config), "timeout": timeout}+ # requests resolves verify=True through a bundle path frozen at its own import,+ # which a replaced install environment leaves dangling; hand it a live one.+ kwargs: dict[str, Any] = {+ "headers": self._release_headers(config),+ "timeout": timeout,+ "verify": requests_verify(),+ }body = self._release_body(config)if body is not None:kwargs["json"] = body@@ -82,7 +89,7 @@ class CloudBrowserProvider(BrowserProvider):"""POST the create request; network failures → RuntimeError unless the managed gatewaycaller needs the raw exception to retry."""try:- return requests.post(url, headers=headers, json=payload, timeout=30)+ return requests.post(url, headers=headers, json=payload, timeout=30, verify=requests_verify())except requests.RequestException as exc:if not wrap_errors:raisediff --git a/plugins/web/keenable/provider.py b/plugins/web/keenable/provider.pyindex 63dec40ec66..a0e9ce25a4f 100644--- a/plugins/web/keenable/provider.py+++ b/plugins/web/keenable/provider.py@@ -9,6 +9,8 @@ from __future__ import annotationsimport loggingfrom typing import Any, Dict, List+from agent.ssl_verify import requests_verify+from plugins.web._common import (SEARCH_LIMIT_CAP, BaseWebSearchProvider, document, http_status_detail, keyless_extract, keyless_search,keyless_variant_schema, page_error, provider_env, run_extract, run_search, search_fail, search_ok, use_keyless, web_hit,@@ -42,11 +44,14 @@ class KeenableWebSearchProvider(BaseWebSearchProvider):if use_keyless("keenable", api_key):return keyless_search("Keenable", "keenable", query, limit, logger)import requests+logger.info("Keenable search: '%s' (limit=%d)", query, limit)+ # requests freezes its default CA bundle path at its own import; a replaced+ # install environment leaves it dangling, so hand over a live bundle.response = requests.post(f"{_KEENABLE_API_URL}/v1/search",json={"query": query, "max_results": min(max(1, int(limit)), SEARCH_LIMIT_CAP)},- headers=_keenable_headers(api_key), timeout=30,+ headers=_keenable_headers(api_key), timeout=30, verify=requests_verify(),)if response.status_code >= 400:return search_fail(f"Keenable search failed: {http_status_detail(response)}")@@ -67,7 +72,7 @@ class KeenableWebSearchProvider(BaseWebSearchProvider):results: list[dict[str, Any]] = []for url in urls:try:- response = requests.get(f"{_KEENABLE_API_URL}/v1/fetch", params={"url": url}, headers=_keenable_headers(api_key), timeout=30)+ response = requests.get(f"{_KEENABLE_API_URL}/v1/fetch", params={"url": url}, headers=_keenable_headers(api_key), timeout=30, verify=requests_verify())if response.status_code >= 400:raise ValueError(http_status_detail(response))data = response.json()diff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.pyindex 07b571346f3..1d0fdbdddbb 100644--- a/tests/agent/test_ssl_verify.py+++ b/tests/agent/test_ssl_verify.py@@ -186,3 +186,131 @@ assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.check_hostnameassert ctx.cert_store_stats()['x509_ca'] > 0"""], capture_output=True, text=True, timeout=30, check=False)assert child.returncode == 0, child.stderr+++# ---------------------------------------------------------------------------+# An install environment replaced under a live process: certifi's path dies+# ---------------------------------------------------------------------------+++def _stand_in_certifi_env(root: Path, name: str, bundle: bytes) -> Path:+ """A certifi package whose bundle sits next to its own ``__file__``."""+ package = root / 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)+ return package+++def _client_ssl_context(client):+ """The context httpx built for this client's connection pool."""+ from typing import Any, cast++ return cast(Any, client._transport)._pool._ssl_context+++def _rotated_certifi(tmp_path: Path, monkeypatch, *, replacement: bool):+ """Delete the environment directory the imported certifi points into.++ The package manager's rotation without a package manager: certifi is imported+ from ``env-a``, then that directory is removed. ``replacement`` adds the+ identical package the manager would have installed as ``env-b``.+ """+ import importlib+ import shutil+ import sys++ import certifi as real_certifi++ bundle = Path(real_certifi.where()).read_bytes() # a real PEM: contexts must load it+ old_env = _stand_in_certifi_env(tmp_path, "env-a", bundle)+ if replacement:+ new_env = _stand_in_certifi_env(tmp_path, "env-b", bundle)+ monkeypatch.syspath_prepend(str(new_env.parent))+ monkeypatch.syspath_prepend(str(old_env.parent))+ 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 == old_env+ shutil.rmtree(old_env)+ assert not Path(stand_in.where()).exists()+ return stand_in+++def test_replaced_install_environment_re_resolves_certifi_in_place(tmp_path, monkeypatch, caplog, no_ca_env):+ """A process that outlives an environment rotation holds certifi's path into the+ deleted directory, and httpx builds every SSL context through it. The module is+ re-executed against the live ``sys.path``, so client construction succeeds again+ for this process and every other certifi consumer in it."""+ import logging+ import ssl++ import httpx++ stand_in = _rotated_certifi(tmp_path, monkeypatch, replacement=True)++ with caplog.at_level(logging.WARNING, logger="agent.ssl_verify"):+ verify = resolve_httpx_verify()++ assert verify is True # httpx's own default, now backed by a bundle that exists+ with httpx.Client(verify=verify) as client: # the construction that raised FileNotFoundError+ assert _client_ssl_context(client).verify_mode == ssl.CERT_REQUIRED+ assert Path(stand_in.where()).is_file() # re-derived from the live sys.path+ logged = [r for r in caplog.records if r.name == "agent.ssl_verify"]+ assert len(logged) == 1 and "re-resolved" in logged[0].getMessage()+++def test_unrecoverable_bundle_hands_over_the_platform_context(tmp_path, monkeypatch, caplog, no_ca_env):+ """Nothing left to re-resolve: the platform store is handed over instead of+ raising, which is the difference between a degraded process and a fleet-wide+ TLS outage that only a restart clears."""+ import logging+ import ssl++ import httpx++ from agent import ssl_verify++ _rotated_certifi(tmp_path, monkeypatch, replacement=False)+ monkeypatch.setattr(ssl_verify, "_reload_certifi_bundle", lambda: None)++ with caplog.at_level(logging.WARNING, logger="agent.ssl_verify"):+ verify = resolve_httpx_verify()++ assert isinstance(verify, ssl.SSLContext)+ logged = [r for r in caplog.records if r.name == "agent.ssl_verify"]+ assert len(logged) == 1 and "could not be re-resolved" in logged[0].getMessage()+ with httpx.Client(verify=verify) as client:+ assert _client_ssl_context(client).verify_mode == ssl.CERT_REQUIRED+++def test_requests_verify_hands_over_a_bundle_that_exists(tmp_path, monkeypatch, no_ca_env):+ """``requests`` freezes its default bundle path when it is imported, so no reload+ can reach it: its call sites ask for a live bundle instead."""+ from agent import ssl_verify++ stand_in = _rotated_certifi(tmp_path, monkeypatch, replacement=True)++ verify = ssl_verify.requests_verify()++ assert verify == stand_in.where()+ assert Path(str(verify)).is_file()+++def test_requests_verify_never_hands_over_the_deleted_bundle(tmp_path, monkeypatch, no_ca_env):+ """With nothing re-resolvable the answer is OpenSSL's own bundle, or requests'+ own default — never the path the rotation deleted."""+ from agent import ssl_verify++ stand_in = _rotated_certifi(tmp_path, monkeypatch, replacement=False)+ dead = stand_in.where()+ monkeypatch.setattr(ssl_verify, "_reload_certifi_bundle", lambda: None)++ verify = ssl_verify.requests_verify()++ assert str(verify) != dead+ assert verify is True or Path(str(verify)).exists()