The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(urllib): parse the CA bundle once instead of on every Hermes-owned request
John Paul Soliva966f746b5842
diff --git a/hermes_cli/urllib_security.py b/hermes_cli/urllib_security.pyindex ab48af84d67..222af97edb3 100644--- a/hermes_cli/urllib_security.py+++ b/hermes_cli/urllib_security.py@@ -82,33 +82,89 @@ class _CrossOriginRequestSanitizer(urllib.request.BaseHandler):https_request = _sanitize-def _resolved_https_context() -> ssl.SSLContext | None:- """Return the explicit CA context for Hermes-owned urllib openers."""+# Loading a CA bundle parses every certificate in it (certifi is ~230 KB / ~119 certs, ~4 ms), and+# this runs for EVERY Hermes-owned request: no opener is ever installed globally, so the branch in+# _secure_opener_from_installed_policy that builds one is taken every time. The result depends only+# on which bundle files get read, so it is memoised on their (path, mtime, size) — resolving that+# is a stat, not a parse, so an edited, rotated or reconfigured bundle is still picked up on the+# next request.+#+# The context is SHARED, never handed out for mutation: callers that need different TLS settings+# pass their own ``ssl_context`` (see _secure_opener_from_installed_policy), and the only in-tree+# mutator (``hermes_cli.models``) builds its own context. Reusing one context across connections is+# the same thing requests/httpx do — ``agent.ssl_verify._context_for_ca_bundle`` already shares one+# per bundle for the httpx clients; this is the urllib half of it. No lock: a race costs one+# duplicate parse, and either context is equally valid.+_HTTPS_CONTEXT_CACHE: tuple[tuple, ssl.SSLContext | None] | None = None+++def _ca_bundle_candidates() -> tuple[str, ...]:+ """Bundles to try in order; empty keeps the stdlib default.++ Resolving the candidates and loading them are split so the memo below can key on the files that+ are actually going to be read — one precedence rule, not one for the loader and a second for the+ cache key that could drift away from it.+ """+ candidates: list[str] = []ca_bundle = next((value for name in _CA_BUNDLE_ENV_VARS if (value := os.getenv(name, "").strip())), "")if ca_bundle:ca_path = Path(ca_bundle).expanduser()if ca_path.is_file():- try:- return ssl.create_default_context(cafile=str(ca_path))- except (OSError, ssl.SSLError) as exc:- logger.warning(- "CA bundle could not be loaded from %s: %s — falling back to default certificates",- ca_bundle, exc,- )+ candidates.append(str(ca_path))else:logger.warning("CA bundle path does not exist: %s — falling back to default certificates", ca_bundle)- if sys.platform != "darwin":- return None+ # Python on macOS has no usable system root store, so certifi stays the last resort even when a+ # configured bundle was found but turns out to be unloadable.+ if sys.platform == "darwin":+ try:+ import certifi++ candidates.append(certifi.where())+ except ImportError as exc:+ logger.warning(+ "Could not load certifi for urllib HTTPS verification: %s — falling back to default certificates",+ exc,+ )+ return tuple(candidates)+++def _bundle_signature(path: str) -> tuple:+ """``(path, mtime_ns, size)`` so an edited or rotated bundle invalidates the memo."""try:- import certifi-- return ssl.create_default_context(cafile=certifi.where())- except (ImportError, OSError, ssl.SSLError) as exc:- logger.warning(- "Could not load certifi for urllib HTTPS verification: %s — falling back to default certificates", exc- )- return None+ stat = Path(path).stat()+ except OSError:+ return (path, None, None)+ return (path, stat.st_mtime_ns, stat.st_size)+++def _resolved_https_context() -> ssl.SSLContext | None:+ """Return the shared explicit-CA context for Hermes-owned urllib openers.++ Memoised on the resolved bundle's signature; the returned context is shared and must not be+ mutated by callers.+ """+ global _HTTPS_CONTEXT_CACHE++ candidates = _ca_bundle_candidates()+ key = tuple(_bundle_signature(path) for path in candidates)+ cached = _HTTPS_CONTEXT_CACHE+ if cached is not None and cached[0] == key:+ return cached[1]+ context = _build_https_context(candidates)+ _HTTPS_CONTEXT_CACHE = (key, context)+ return context+++def _build_https_context(candidates: tuple[str, ...]) -> ssl.SSLContext | None:+ for path in candidates:+ try:+ return ssl.create_default_context(cafile=path)+ except (OSError, ssl.SSLError) as exc:+ logger.warning(+ "CA bundle could not be loaded from %s: %s — falling back to default certificates", path, exc+ )+ return Nonedef _secure_opener_from_installed_policy(original_url: str, *, ssl_context=None):diff --git a/tests/hermes_cli/test_urllib_security.py b/tests/hermes_cli/test_urllib_security.pyindex 18d847997e6..eab0397c95a 100644--- a/tests/hermes_cli/test_urllib_security.py+++ b/tests/hermes_cli/test_urllib_security.py@@ -381,6 +381,16 @@ def test_azure_anthropic_probe_drops_api_key_and_bearer_on_redirect():assert "api-key" not in headers[email protected](autouse=True)+def _reset_https_context_cache():+ """Keep the CA-context memo from carrying a previous test's env into the next one."""+ import hermes_cli.urllib_security as urllib_security++ urllib_security._HTTPS_CONTEXT_CACHE = None+ yield+ urllib_security._HTTPS_CONTEXT_CACHE = None++def _clear_ca_bundle_env(monkeypatch) -> None:for name in ("HERMES_CA_BUNDLE",@@ -511,3 +521,106 @@ def test_installed_https_context_is_preserved(monkeypatch):]assert len(https_handlers) == 1assert getattr(https_handlers[0], "_context", None) is context+++def _counting_context_factory():+ """Return (factory, calls) where each call yields a distinct context object."""+ calls: list[str | None] = []++ def create_default_context(*, cafile=None):+ calls.append(cafile)+ return ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)++ return create_default_context, calls+++def test_hermes_owned_openers_parse_the_ca_bundle_once(monkeypatch, tmp_path):+ """Every Hermes request builds an opener; the bundle must not be re-parsed each time."""+ import hermes_cli.urllib_security as urllib_security++ _clear_ca_bundle_env(monkeypatch)+ ca_bundle = tmp_path / "corporate-ca.pem"+ ca_bundle.write_text("-----BEGIN CERTIFICATE-----\n")+ factory, calls = _counting_context_factory()+ monkeypatch.setenv("HERMES_CA_BUNDLE", str(ca_bundle))+ monkeypatch.setattr(ssl, "create_default_context", factory)+ monkeypatch.setattr(urllib.request, "_opener", None)++ contexts = []+ for _ in range(5):+ opener = urllib_security._secure_opener_from_installed_policy("https://models.example.test/v1")+ contexts.extend(+ handler._context+ for handler in opener.handlers+ if isinstance(handler, urllib.request.HTTPSHandler)+ )++ assert calls == [str(ca_bundle)]+ assert len(contexts) == 5+ assert all(context is contexts[0] for context in contexts)+++def test_rotated_ca_bundle_is_picked_up(monkeypatch, tmp_path):+ import hermes_cli.urllib_security as urllib_security++ _clear_ca_bundle_env(monkeypatch)+ ca_bundle = tmp_path / "corporate-ca.pem"+ ca_bundle.write_text("first")+ factory, calls = _counting_context_factory()+ monkeypatch.setenv("HERMES_CA_BUNDLE", str(ca_bundle))+ monkeypatch.setattr(ssl, "create_default_context", factory)++ first = urllib_security._resolved_https_context()+ assert urllib_security._resolved_https_context() is first++ ca_bundle.write_text("a rotated bundle with a different length")+ rotated = urllib_security._resolved_https_context()++ assert rotated is not first+ assert calls == [str(ca_bundle), str(ca_bundle)]+++def test_changed_ca_bundle_env_is_picked_up(monkeypatch, tmp_path):+ import hermes_cli.urllib_security as urllib_security++ _clear_ca_bundle_env(monkeypatch)+ first_bundle = tmp_path / "first-ca.pem"+ second_bundle = tmp_path / "second-ca.pem"+ first_bundle.write_text("first")+ second_bundle.write_text("second")+ factory, calls = _counting_context_factory()+ monkeypatch.setattr(ssl, "create_default_context", factory)++ monkeypatch.setenv("HERMES_CA_BUNDLE", str(first_bundle))+ first = urllib_security._resolved_https_context()+ monkeypatch.setenv("HERMES_CA_BUNDLE", str(second_bundle))+ second = urllib_security._resolved_https_context()++ assert second is not first+ assert calls == [str(first_bundle), str(second_bundle)]+++def test_unloadable_ca_bundle_still_falls_back_to_certifi_on_macos(monkeypatch, tmp_path):+ """A configured bundle that exists but cannot be parsed must not strip macOS of a root store."""+ import certifi+ import hermes_cli.urllib_security as urllib_security++ _clear_ca_bundle_env(monkeypatch)+ ca_bundle = tmp_path / "corrupt-ca.pem"+ ca_bundle.write_text("not a certificate")+ expected_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)+ seen: list[str | None] = []++ def create_default_context(*, cafile=None):+ seen.append(cafile)+ if cafile == str(ca_bundle):+ raise ssl.SSLError("no certificate or crl found")+ return expected_context++ monkeypatch.setenv("HERMES_CA_BUNDLE", str(ca_bundle))+ monkeypatch.setattr(urllib_security.sys, "platform", "darwin")+ monkeypatch.setattr(certifi, "where", lambda: "/certifi/cacert.pem")+ monkeypatch.setattr(ssl, "create_default_context", create_default_context)++ assert urllib_security._resolved_https_context() is expected_context+ assert seen == [str(ca_bundle), "/certifi/cacert.pem"]