The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tls): trust the OS certificate store, one resolver
ethernet2f20ceb6f763
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 72c15139253..8bba984e382 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -1548,9 +1548,9 @@ def init_agent(agent.api_key = client_kwargs.get("api_key", "")agent.base_url = client_kwargs.get("base_url", agent.base_url)try:- from agent.ssl_guard import verify_ca_bundle_with_fallback+ from agent.ssl_verify import install_truststore- verify_ca_bundle_with_fallback()+ install_truststore()agent.client = agent._create_openai_client(client_kwargs, reason="agent_init", shared=True)if not agent.quiet_mode:print(f"π€ AI Agent initialized with model: {agent.model}")diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex b5a04070a4a..2aabeac76e0 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -202,10 +202,9 @@ def _resolve_aux_verify(base_url: Optional[str]) -> Any:"""Resolve httpx ``verify`` for an auxiliary-client base_url.Mirrors the main client's TLS resolution so auxiliary calls (compression,- vision, title generation, etc.) honor per-provider- ``ssl_ca_cert`` / ``ssl_verify`` config and the ``HERMES_CA_BUNDLE`` /- ``SSL_CERT_FILE`` env conventions. Best-effort: any failure falls back to- the httpx/certifi default (``True``).+ vision, web_extract, title generation, etc.) honor per-provider+ ``ssl_ca_cert`` / ``ssl_verify`` config, and otherwise verify against the+ OS trust store. Best-effort: any failure falls back to ``True``."""try:from agent.ssl_verify import resolve_httpx_verifydiff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 521be3a8c35..ac4f03deb69 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -6659,11 +6659,11 @@ def run_conversation(force=True,)agent._vprint(- f"{agent.log_prefix} β’ Corporate TLS-inspecting proxy? Point Python at its CA bundle:",+ f"{agent.log_prefix} β’ Corporate TLS-inspecting proxy? Install its root certificate",force=True,)agent._vprint(- f"{agent.log_prefix} export SSL_CERT_FILE=/path/to/corp-ca.pem (also REQUESTS_CA_BUNDLE)",+ f"{agent.log_prefix} in the OS certificate store β Hermes trusts what the machine trusts.",force=True,)agent._vprint(diff --git a/agent/errors.py b/agent/errors.pyindex 8b3db5a3589..616599abf25 100644--- a/agent/errors.py+++ b/agent/errors.py@@ -1,8 +1,3 @@-class SSLConfigurationError(Exception):- """Raised when SSL/TLS certificate bundle configuration fails."""- pass--class EmptyStreamError(RuntimeError):"""Raised when a provider closes a stream without yielding a response."""diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex d18e83e986c..bdd217f3f0a 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -50,41 +50,30 @@ def __getattr__(name: str):def _resolve_requests_verify(base_url: str = "") -> bool | str:- """Resolve SSL verify setting for `requests` calls.-- Priority (mirrors ``agent.ssl_verify.resolve_httpx_verify`` so the- ``requests``-based ``/models`` probes agree with the httpx chat client):-- 1. Per-provider ``ssl_verify: false`` for ``base_url`` β disable verification.- 2. Per-provider ``ssl_ca_cert`` for ``base_url`` β an explicit CA bundle.- Without this, a custom endpoint whose chain only verifies against the- provider's configured bundle (not the process ``SSL_CERT_FILE``) logs a- spurious CERTIFICATE_VERIFY_FAILED on every probe even though the chat- path succeeds (per-provider ``ssl_ca_cert`` was reaching only httpx).- 3. Env vars ``HERMES_CA_BUNDLE`` / ``REQUESTS_CA_BUNDLE`` / ``SSL_CERT_FILE``- (a single var covers both ``requests`` and ``httpx`` in-process).- 4. ``True`` β defer to the requests default (certifi).-- ``base_url`` is optional so existing callers (OpenRouter, etc.) keep the- env-only behavior unchanged; only probes that pass a base_url pick up the- per-provider override.+ """SSL verify for the ``requests``-based ``/models`` probes.++ Per-provider config only (``ssl_verify: false``, then ``ssl_ca_cert``);+ otherwise the OS trust store. Same authority as the httpx chat client,+ so a probe and a completion never disagree about a chain."""+ from agent.ssl_verify import resolve_requests_verify++ ssl_verify = None+ ca_cert = Noneif base_url:try:from hermes_cli.config import get_custom_provider_tls_settingstls = get_custom_provider_tls_settings(base_url)if tls.get("ssl_verify") is False:- return False+ ssl_verify = Falseca = tls.get("ssl_ca_cert")- if isinstance(ca, str) and ca and os.path.isfile(ca):- return ca+ if isinstance(ca, str) and ca:+ ca_cert = caexcept Exception:- pass # fall through to env vars β never break a probe on config lookup- for env_var in ("HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE"):- val = os.getenv(env_var)- if val and os.path.isfile(val):- return val- return True+ pass # never break a probe on a config lookup+ return resolve_requests_verify(+ ca_bundle=ca_cert, ssl_verify=ssl_verify, base_url=base_url+ )# Compatibility snapshot for callers that inspect this private constant.# Prefix routing below queries the registry live so later registrations work.diff --git a/agent/process_bootstrap.py b/agent/process_bootstrap.pyindex 341126c9198..7760d124e78 100644--- a/agent/process_bootstrap.py+++ b/agent/process_bootstrap.py@@ -441,8 +441,8 @@ def build_keepalive_http_client(``verify`` is forwarded to httpx so auxiliary-client calls (compression,vision, web_extract, title generation, etc.) honor the same per-provider- ``ssl_ca_cert`` / ``ssl_verify`` and ``HERMES_CA_BUNDLE`` settings the main- client uses. It is passed on the client AND on the plain no-proxy mounts+ ``ssl_ca_cert`` / ``ssl_verify`` settings the main client uses. It is+ passed on the client AND on the plain no-proxy mounts(a mounted transport owns the SSL context for its scheme)."""try:diff --git a/agent/ssl_guard.py b/agent/ssl_guard.pydeleted file mode 100644index 35c3e476211..00000000000--- a/agent/ssl_guard.py+++ /dev/null@@ -1,101 +0,0 @@-"""Preventive SSL CA certificate checks for Hermes Agent.--This module catches broken CA bundle paths before OpenAI/httpx turns them into-opaque ``FileNotFoundError: [Errno 2] No such file or directory`` failures.-"""--from __future__ import annotations--import logging-import os-import ssl-from pathlib import Path--from agent.errors import SSLConfigurationError--logger = logging.getLogger(__name__)--_CA_BUNDLE_ENV_VARS = (- "HERMES_CA_BUNDLE",- "SSL_CERT_FILE",- "REQUESTS_CA_BUNDLE",- "CURL_CA_BUNDLE",-)--_SKIP_VALUES = {"1", "true", "yes", "on"}---def _skip_ssl_guard_enabled() -> bool:- return os.getenv("HERMES_SKIP_SSL_GUARD", "").strip().lower() in _SKIP_VALUES---def _repair_hint() -> str:- return (- "Repair: run `hermes doctor --fix` (auto-reinstalls certifi), or "- "manually: python -m pip install --force-reinstall certifi openai httpx\n"- "If you configured a custom corporate CA bundle, fix or unset the "- "broken CA bundle environment variable."- )---def _ssl_err(message: str) -> SSLConfigurationError:- """Create a consistent, user-actionable SSL configuration error."""- return SSLConfigurationError(f"{message}\n{_repair_hint()}")---def _validate_bundle_path(label: str, value: str, *, require_substantial: bool = False) -> None:- path = Path(value).expanduser()- if not path.exists():- raise _ssl_err(f"{label} points to a missing CA bundle: {value}")- if not path.is_file():- raise _ssl_err(f"{label} does not point to a CA bundle file: {value}")- if require_substantial and path.stat().st_size < 1024:- raise _ssl_err(f"{label} at {value} appears corrupted (too small)")- try:- ctx = ssl.create_default_context(cafile=str(path))- except Exception as exc:- raise _ssl_err(f"{label} CA bundle at {value} cannot be loaded: {exc}") from exc- try:- loaded_certs = ctx.get_ca_certs()- except NotImplementedError:- # truststore-backed SSLContext (Windows OS trust store) doesn't- # implement get_ca_certs(); bundle was already validated above.- return- if not loaded_certs:- raise _ssl_err(f"{label} CA bundle at {value} did not load any certificates")---def verify_ca_bundle() -> None:- """Verify configured and bundled CA certificates are present and loadable.-- Raises:- SSLConfigurationError: If an explicit CA-bundle environment variable- points at a bad path, or if certifi's bundled ``cacert.pem`` is- missing/corrupt.- """- if _skip_ssl_guard_enabled():- logger.debug("SSL CA bundle guard skipped via HERMES_SKIP_SSL_GUARD")- return-- for env_var in _CA_BUNDLE_ENV_VARS:- value = os.getenv(env_var)- if value:- _validate_bundle_path(env_var, value)-- try:- import certifi- except Exception as exc:- raise _ssl_err(f"certifi is not importable: {exc}") from exc-- ca_bundle = str(certifi.where())- _validate_bundle_path("certifi", ca_bundle, require_substantial=True)---def verify_ca_bundle_with_fallback() -> None:- """Backward-compatible wrapper for older call sites.-- The old PR name mentioned a platform fallback, but allowing startup with a- broken certifi bundle still leaves httpx/OpenAI and requests call sites- failing later. Keep the wrapper name but enforce the same check.- """- verify_ca_bundle()diff --git a/agent/ssl_verify.py b/agent/ssl_verify.pyindex 885702185d7..ee6d06a94a0 100644--- a/agent/ssl_verify.py+++ b/agent/ssl_verify.py@@ -1,15 +1,64 @@-"""TLS verify resolution for httpx/OpenAI provider clients."""+"""TLS trust for Hermes. One authority, one trust source.++Trust comes from the platform verifier via ``truststore``: CryptoAPI on+Windows, Security.framework on macOS, and OpenSSL's own store (with a+distro candidate sweep) on Linux. That is the machine's real answer to+"is this chain valid", so a corporate MITM root installed by MDM, an+internal CA, and a locked-down NixOS box all work with no configuration.++``install_truststore()`` runs once at process start and patches+``ssl.SSLContext`` process-wide, so every stack that builds a default+context inherits it β httpx, requests/urllib3, aiohttp, AND the stdlib+``urllib.request`` call sites (the llama.cpp engine download among them)+that a certifi-only or requests-only approach never reached.++The only thing above the platform store is EXPLICIT PER-PROVIDER CONFIG:+``ssl_ca_cert`` (a self-signed or internal endpoint's bundle) and+``ssl_verify: false`` (local development). Those are deliberate+statements about one endpoint, not an ambient guess about the machine.+"""from __future__ import annotationsimport logging-import osimport sslfrom pathlib import Pathfrom typing import Any, Optionallogger = logging.getLogger(__name__)+_installed: bool | None = None+++def install_truststore() -> bool:+ """Point every default SSLContext at the OS trust store. Idempotent.++ Returns True when the platform verifier is in force. A False return+ means truststore could not load (an unsupported platform, or a+ stripped payload); TLS still works off OpenSSL's compiled-in paths,+ it just won't see certificates the OS trusts.++ Call before the first HTTPS client is constructed.+ """+ global _installed+ if _installed is not None:+ return _installed+ try:+ import truststore++ truststore.inject_into_ssl()+ _installed = True+ logger.debug("TLS trust: platform store (truststore)")+ except Exception as exc: # noqa: BLE001 β never break startup over TLS setup+ _installed = False+ logger.warning(+ "truststore unavailable (%s); falling back to OpenSSL's default "+ "trust paths. Certificates trusted only by the OS store β a "+ "corporate root, for instance β will not verify.",+ exc,+ )+ return _installed+def _coerce_insecure(ssl_verify: Any) -> bool:if ssl_verify is False:@@ -25,17 +74,69 @@ def resolve_httpx_verify(ssl_verify: Any = None,base_url: str = "",) -> bool | ssl.SSLContext:- """Resolve httpx ``verify`` for provider HTTP clients.+ """Resolve ``verify`` for an HTTP client.- Priority:- 1. ``ssl_verify: false`` β disable verification (local dev only)- 2. explicit ``ca_bundle`` (per-provider ``ssl_ca_cert`` config field)- 3. ``HERMES_CA_BUNDLE``, ``SSL_CERT_FILE``, ``REQUESTS_CA_BUNDLE``,- ``CURL_CA_BUNDLE`` env vars- 4. ``True`` (httpx/certifi default)+ 1. ``ssl_verify: false`` β verification off (local development only)+ 2. explicit ``ca_bundle`` (the provider's ``ssl_ca_cert``) β that+ bundle INSTEAD of the platform store, for an endpoint whose chain+ the machine has no reason to trust+ 3. ``True`` β the platform store, via the process-wide install- ``base_url`` is used only for the insecure-mode warning message.+ ``base_url`` only labels the insecure-mode warning."""+ install_truststore()++ if _coerce_insecure(ssl_verify):+ logger.warning(+ "TLS certificate verification DISABLED (ssl_verify: false) for %s β "+ "this is intended for local development only and is unsafe on any "+ "network you do not fully control.",+ base_url or "a custom provider endpoint",+ )+ return False++ bundle = (ca_bundle or "").strip()+ if bundle:+ path = Path(bundle).expanduser()+ if path.is_file():+ # An explicit bundle REPLACES the platform store for this client.+ # inject_into_ssl() rebinds ssl.SSLContext to truststore's class,+ # which ignores loaded CA files and verifies against the OS store+ # anyway β so build from the ORIGINAL class, which truststore+ # keeps for exactly this purpose. Without it a pinned+ # ssl_ca_cert silently means "trust the machine" instead.+ #+ # Do NOT assign verify_mode/check_hostname here: the stock+ # class's setters resolve ``super(SSLContext, SSLContext)``+ # against the PATCHED module global and recurse to the stack+ # limit. PROTOCOL_TLS_CLIENT already implies CERT_REQUIRED and+ # check_hostname, so there is nothing to set.+ from truststore._ssl_constants import _original_SSLContext++ ctx = _original_SSLContext(ssl.PROTOCOL_TLS_CLIENT)+ ctx.load_verify_locations(cafile=str(path))+ return ctx+ logger.warning(+ "ssl_ca_cert path does not exist: %s β using the OS trust store instead",+ bundle,+ )+ return True+++def resolve_requests_verify(+ *,+ ca_bundle: Optional[str] = None,+ ssl_verify: Any = None,+ base_url: str = "",+) -> bool | str:+ """The same decision for ``requests``, which takes a path, not a context.++ With the platform store installed process-wide, ``True`` already means+ "verify against the OS store" here β urllib3 builds its context through+ the patched ``ssl.SSLContext``.+ """+ install_truststore()+if _coerce_insecure(ssl_verify):logger.warning("TLS certificate verification DISABLED (ssl_verify: false) for %s β "@@ -45,19 +146,13 @@ def resolve_httpx_verify()return False- effective_ca = (- (ca_bundle or "").strip()- or os.getenv("HERMES_CA_BUNDLE", "").strip()- or os.getenv("SSL_CERT_FILE", "").strip()- or os.getenv("REQUESTS_CA_BUNDLE", "").strip()- or os.getenv("CURL_CA_BUNDLE", "").strip()- )- if effective_ca:- ca_path = str(Path(effective_ca).expanduser())- if os.path.isfile(ca_path):- return ssl.create_default_context(cafile=ca_path)+ bundle = (ca_bundle or "").strip()+ if bundle:+ path = Path(bundle).expanduser()+ if path.is_file():+ return str(path)logger.warning(- "CA bundle path does not exist: %s β falling back to default certificates",- effective_ca,+ "ssl_ca_cert path does not exist: %s β using the OS trust store instead",+ bundle,)return Truediff --git a/gateway/run.py b/gateway/run.pyindex f74f8745a6a..c3d70d319b2 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2214,59 +2214,21 @@ def _collect_history_media_paths(agent_history: List[Dict[str, Any]]) -> set:return paths# ----------------------------------------------------------------------------# SSL certificate auto-detection for NixOS and other non-standard systems.-# Must run BEFORE any HTTP library (discord, aiohttp, etc.) is imported.+# TLS trust: the operating system's certificate store, via truststore.+# Must run BEFORE any HTTP library (discord, aiohttp, etc.) is imported so+# every client inherits the patched default SSLContext.# ---------------------------------------------------------------------------def _ensure_ssl_certs() -> None:- """Set SSL_CERT_FILE if the system doesn't expose CA certs to Python.+ """Point TLS verification at the OS trust store.- Windows startup paths (Desktop, Scheduled Tasks, installer children) can- occasionally inherit a stale SSL_CERT_FILE. Returning just because the- variable is present makes every later httpx/OpenAI client construction fail- with FileNotFoundError from ssl.load_verify_locations(). Treat a missing- path as unset and fall back to certifi instead.+ truststore's own OpenSSL backend already sweeps the distro CA-bundle+ locations when the compiled-in paths are empty, which is the NixOS /+ non-standard-python case this used to hand-roll."""- configured_cert = os.environ.get("SSL_CERT_FILE")- if configured_cert:- if os.path.exists(configured_cert):- return # user already configured it to a real file- logging.getLogger(__name__).warning(- "Ignoring stale SSL_CERT_FILE=%r because the path does not exist",- configured_cert,- )- os.environ.pop("SSL_CERT_FILE", None)-- import ssl+ from agent.ssl_verify import install_truststore- # 1. Python's compiled-in defaults- paths = ssl.get_default_verify_paths()- for candidate in (paths.cafile, paths.openssl_cafile):- if candidate and os.path.exists(candidate):- os.environ["SSL_CERT_FILE"] = candidate- return+ install_truststore()- # 2. certifi (ships its own Mozilla bundle)- try:- import certifi- os.environ["SSL_CERT_FILE"] = certifi.where()- return- except ImportError:- pass-- # 3. Common distro / macOS locations- for candidate in (- "/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo- "/etc/pki/tls/certs/ca-bundle.crt", # RHEL/CentOS 7- "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", # RHEL/CentOS 8+- "/etc/ssl/ca-bundle.pem", # SUSE/OpenSUSE- "/etc/ssl/cert.pem", # Alpine / macOS- "/etc/pki/tls/cert.pem", # Fedora- "/usr/local/etc/[email protected]/cert.pem", # macOS Homebrew Intel- "/opt/homebrew/etc/[email protected]/cert.pem", # macOS Homebrew ARM- ):- if os.path.exists(candidate):- os.environ["SSL_CERT_FILE"] = candidate- returndef _home_target_env_var(platform_name: str) -> str:"""Return the configured home-target env var for a platform.diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex f6758c747c6..f4064832f26 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -5388,30 +5388,16 @@ def resolve_xai_oauth_runtime_credentials(# TLS verification helper# =============================================================================-def _default_verify() -> bool | ssl.SSLContext:- """Platform-aware default SSL verify for httpx clients.-- On macOS with Homebrew Python, the system OpenSSL cannot locate the- system trust store and valid public certs fail verification. When- certifi is importable we pin its bundle explicitly; elsewhere we- defer to httpx's built-in default (certifi via its own dependency).- Mirrors the weixin fix in 3a0ec1d93.- """- if sys.platform == "darwin":- try:- import certifi- return ssl.create_default_context(cafile=certifi.where())- except ImportError:- pass- return True--def _resolve_verify(*,insecure: Optional[bool] = None,ca_bundle: Optional[str] = None,auth_state: Optional[Dict[str, Any]] = None,) -> bool | ssl.SSLContext:+ """TLS verify for auth-portal clients β the one resolver, given this+ call's explicit inputs (per-connection ``tls`` state or an argument)."""+ from agent.ssl_verify import resolve_httpx_verify+tls_state = auth_state.get("tls") if isinstance(auth_state, dict) else {}tls_state = tls_state if isinstance(tls_state, dict) else {}@@ -5419,26 +5405,11 @@ def _resolve_verify(is_truthy_value(insecure, default=False) if insecure is not Noneelse is_truthy_value(tls_state.get("insecure", False), default=False))- effective_ca = (- ca_bundle- or tls_state.get("ca_bundle")- or os.getenv("HERMES_CA_BUNDLE")- or os.getenv("SSL_CERT_FILE")- or os.getenv("REQUESTS_CA_BUNDLE")- )- if effective_insecure:- return False- if effective_ca:- ca_path = str(effective_ca)- if not os.path.isfile(ca_path):- logger.warning(- "CA bundle path does not exist: %s β falling back to default certificates",- ca_path,- )- return _default_verify()- return ssl.create_default_context(cafile=ca_path)- return _default_verify()+ return resolve_httpx_verify(+ ca_bundle=ca_bundle or tls_state.get("ca_bundle"),+ ssl_verify=False if effective_insecure else None,+ )# =============================================================================@@ -9371,11 +9342,9 @@ def _login_nous(args, pconfig: ProviderConfig) -> None:"""Nous Portal device authorization flow."""timeout_seconds = getattr(args, "timeout", None) or 15.0insecure = bool(getattr(args, "insecure", False))- ca_bundle = (- getattr(args, "ca_bundle", None)- or os.getenv("HERMES_CA_BUNDLE")- or os.getenv("SSL_CERT_FILE")- )+ # --ca-bundle only: trust otherwise comes from the OS certificate store,+ # so there is no env var to consult.+ ca_bundle = getattr(args, "ca_bundle", None)try:auth_state = Nonediff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex cc0a7a2922f..015465d0838 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -824,89 +824,33 @@ def _check_s6_supervision(issues: list[str]) -> None:def check_certificates(should_fix: bool = False, issues: "list | None" = None) -> None:- """Verify the certifi CA bundle is loadable.+ """Report where TLS trust comes from.- Surfaces the SSLConfigurationError user-friendly path before they hit- a wall of tracebacks on the first outbound HTTPS call.-- With ``--fix``, a broken bundle (missing/corrupt ``cacert.pem`` β e.g.- after a brew Python upgrade rebuilt the venv, #29866) is repaired by- force-reinstalling certifi into THIS interpreter's environment and- re-verifying.+ Trust is the OS store via truststore, so there is no bundle to repair:+ a machine whose certificate store is broken is broken for every app on+ it, and fixing that is the OS's job, not ours. ``should_fix`` is+ accepted for signature parity with the other checks."""try:- from agent.ssl_guard import verify_ca_bundle_with_fallback- from agent.errors import SSLConfigurationError+ from agent.ssl_verify import install_truststoreexcept Exception as e:check_warn("SSL certificate check skipped", str(e))return- try:- verify_ca_bundle_with_fallback()- check_ok("SSL CA certificate bundle is valid")- return- except SSLConfigurationError as e:- first_error = str(e)- except Exception as e:- check_warn("SSL certificate check skipped", str(e))+ if install_truststore():+ check_ok("TLS trust: operating system certificate store")return- if not should_fix:- check_fail("SSL CA certificate bundle is broken", first_error)- if issues is not None:- issues.append(- "Repair the CA bundle: run `hermes doctor --fix`, or "- f"`{sys.executable} -m pip install --force-reinstall certifi`"- )- return-- # --fix: force-reinstall certifi into the running interpreter's env and- # re-verify. importlib caches are invalidated so certifi.where() resolves- # the fresh install without a process restart.- check_fail("SSL CA certificate bundle is broken", first_error)- print(" β Repairing: force-reinstalling certifi...")- try:- result = subprocess.run(- [sys.executable, "-m", "pip", "install", "--force-reinstall", "certifi"],- capture_output=True,- text=True,- timeout=300,+ check_fail(+ "TLS trust: OpenSSL defaults (truststore unavailable)",+ "Certificates trusted only by the OS store β a corporate root, for "+ "instance β will not verify.",+ )+ if issues is not None:+ issues.append(+ "truststore could not load; reinstall it: "+ f"{sys.executable} -m pip install --force-reinstall truststore")- except Exception as exc:- check_fail("certifi repair could not run pip", str(exc))- if issues is not None:- issues.append(- f"Reinstall certifi manually: {sys.executable} -m pip install "- "--force-reinstall certifi"- )- return- if result.returncode != 0:- tail = (result.stderr or result.stdout or "")[-500:]- check_fail("certifi reinstall failed", tail)- if issues is not None:- issues.append(- f"Reinstall certifi manually: {sys.executable} -m pip install "- "--force-reinstall certifi"- )- return-- # Drop any cached certifi module so where() re-resolves the new bundle.- import importlib- for mod_name in [m for m in sys.modules if m == "certifi" or m.startswith("certifi.")]:- sys.modules.pop(mod_name, None)- importlib.invalidate_caches()-- try:- verify_ca_bundle_with_fallback()- check_ok("SSL CA certificate bundle repaired (certifi reinstalled)")- except SSLConfigurationError as e:- check_fail("SSL CA certificate bundle still broken after reinstall", str(e))- if issues is not None:- issues.append(- "certifi reinstall did not restore the CA bundle β check for a "- "custom CA env var (SSL_CERT_FILE/REQUESTS_CA_BUNDLE) pointing "- "at a missing file, or recreate the venv."- )def _check_gateway_service_linger(issues: list[str]) -> None:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 8bb731eed0f..66159317c10 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -12800,6 +12800,17 @@ def main():except Exception:pass+ # One TLS authority: trust the OS store process-wide before any outbound+ # call resolves a CA bundle (see agent/ssl_verify.py). Covers the CLI+ # entrypoint, which agent_init's own install_truststore() call does not+ # reach when the CLI never constructs an AIAgent (subcommands, help).+ try:+ from agent.ssl_verify import install_truststore++ install_truststore()+ except Exception:+ pass+# Sweep stale ``hermes.exe.old.*`` quarantine files left by previous# ``hermes update`` runs on Windows. Silent no-op on non-Windows or when# there's nothing to clean. See ``_quarantine_running_hermes_exe``.diff --git a/hermes_cli/urllib_security.py b/hermes_cli/urllib_security.pyindex ac34411ef7a..6ab076ce086 100644--- a/hermes_cli/urllib_security.py+++ b/hermes_cli/urllib_security.py@@ -4,13 +4,10 @@ from __future__ import annotationsimport copyimport logging-import osimport ssl-import sysimport urllib.parseimport urllib.requestfrom collections.abc import Callable, Iterable-from pathlib import Pathfrom typing import Anylogger = logging.getLogger(__name__)@@ -19,12 +16,6 @@ logger = logging.getLogger(__name__)# custom provider headers routinely carry credentials under arbitrary names._CROSS_ORIGIN_SAFE_HEADERS = frozenset({"accept", "user-agent"})_DEFAULT_PORTS = {"http": 80, "https": 443}-_CA_BUNDLE_ENV_VARS = (- "HERMES_CA_BUNDLE",- "SSL_CERT_FILE",- "REQUESTS_CA_BUNDLE",- "CURL_CA_BUNDLE",-)def url_origin(url: str) -> tuple[str, str, int | None]:@@ -97,45 +88,16 @@ class _CrossOriginRequestSanitizer(urllib.request.BaseHandler):def _resolved_https_context() -> ssl.SSLContext | None:- """Return the explicit CA context for Hermes-owned urllib openers."""- 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,- )- else:- logger.warning(- "CA bundle path does not exist: %s β falling back to default certificates",- ca_bundle,- )+ """TLS context for Hermes-owned urllib openers.- if sys.platform != "darwin":- return None-- try:- import certifi+ None means "use urllib's default", which β with the OS trust store+ installed process-wide β already verifies against the platform's+ certificates. There is nothing to resolve here any more.+ """+ from agent.ssl_verify import install_truststore- 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+ install_truststore()+ return Nonedef _secure_opener_from_installed_policy(original_url: str, *, ssl_context=None):@@ -144,9 +106,8 @@ def _secure_opener_from_installed_policy(original_url: str, *, ssl_context=None)When ``ssl_context`` is provided, the cloned HTTPS handler is replaced withone bound to that context so per-provider TLS settings (``ssl_ca_cert`` /``ssl_verify``) apply to this request. When it is None, Hermes-owned- openers get an explicit CA default via ``_resolved_https_context`` (env- bundle first, certifi on macOS); an application-installed opener's TLS- policy is preserved unchanged.+ openers verify against the OS trust store; an application-installed+ opener's TLS policy is preserved unchanged."""installed = getattr(urllib.request, "_opener", None)if installed is None:diff --git a/pyproject.toml b/pyproject.tomlindex 93383bd33df..1ded38470dd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,6 +39,11 @@ dependencies = [# radius for the next supply-chain attack."openai==2.24.0","certifi==2026.5.20",+ # TLS trust comes from the OS certificate store (agent/ssl_verify.py), so+ # a corporate/internal root installed on the machine just works. certifi+ # above stays a direct pin because httpx/requests/openai each depend on+ # it regardless; it is no longer OUR trust source.+ "truststore>=0.10.4,<0.11","python-dotenv==1.2.2","fire==0.7.1","httpx[socks]==0.28.1",diff --git a/tests/agent/test_ssl_ca_guard.py b/tests/agent/test_ssl_ca_guard.pydeleted file mode 100644index a381352a45a..00000000000--- a/tests/agent/test_ssl_ca_guard.py+++ /dev/null@@ -1,74 +0,0 @@-"""Tests for the preventive SSL CA bundle guard."""--from pathlib import Path--import certifi-import pytest--from agent.errors import SSLConfigurationError-from agent.ssl_guard import verify_ca_bundle, verify_ca_bundle_with_fallback---def test_healthy_bundle_passes(monkeypatch):- """A real, non-empty certifi bundle must verify without raising."""- for key in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):- monkeypatch.delenv(key, raising=False)- bundle = Path(certifi.where())- assert bundle.exists()- assert bundle.stat().st_size > 1024- verify_ca_bundle()---def test_empty_certifi_bundle_raises_ssl_error(monkeypatch, tmp_path):- """Empty file is treated as a corrupted bundle."""- fake = tmp_path / "empty.pem"- fake.write_bytes(b"")- monkeypatch.setattr(certifi, "where", lambda: str(fake))- with pytest.raises(SSLConfigurationError) as exc:- verify_ca_bundle()- assert "too small" in str(exc.value).lower()--[email protected]("env_var", ["HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"])-def test_missing_explicit_ca_bundle_env_raises_before_httpx(monkeypatch, tmp_path, env_var):- """Bad CA-bundle env vars should be reported before OpenAI/httpx init."""- fake = tmp_path / "missing.pem"- monkeypatch.setenv(env_var, str(fake))- with pytest.raises(SSLConfigurationError) as exc:- verify_ca_bundle()- message = str(exc.value)- assert env_var in message- assert str(fake) in message- assert "force-reinstall" in message---def test_truststore_get_ca_certs_not_implemented_is_accepted(monkeypatch, tmp_path):- """A truststore-backed SSLContext (Windows OS trust store) raises- NotImplementedError from get_ca_certs(). The guard must accept the- already-loaded bundle rather than fail.-- Regression for the empty-message ``Failed to initialize OpenAI client:``- seen on every fresh agent init on Windows (str(NotImplementedError()) == "").- """- from agent import ssl_guard-- bundle = tmp_path / "bundle.pem"- bundle.write_text(- "-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n",- encoding="utf-8",- )-- class _TruststoreLikeContext:- def get_ca_certs(self, binary_form=False): # noqa: ARG002 - mirror ssl API- raise NotImplementedError()-- # create_default_context(cafile=...) loads the bundle fine; only the- # post-load introspection is unsupported under truststore.- monkeypatch.setattr(- ssl_guard.ssl, "create_default_context", lambda *a, **k: _TruststoreLikeContext()- )- monkeypatch.setenv("SSL_CERT_FILE", str(bundle))-- # Must not raise on the explicit env bundle nor the certifi check.- verify_ca_bundle()- verify_ca_bundle_with_fallback()diff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.pyindex e21e4a3d60d..ee6f81a936e 100644--- a/tests/agent/test_ssl_verify.py+++ b/tests/agent/test_ssl_verify.py@@ -1,32 +1,133 @@-"""Tests for agent.ssl_verify.resolve_httpx_verify."""+"""TLS trust contract: the OS certificate store, with explicit config on top.++These are behavior contracts, not snapshots β they assert WHERE trust comes+from and that explicit per-provider settings still beat it.+"""import ssl-import certifiimport pytest-from agent.ssl_verify import resolve_httpx_verify+from agent import ssl_verify+from agent.ssl_verify import (+ install_truststore,+ resolve_httpx_verify,+ resolve_requests_verify,+)++[email protected](autouse=True)+def _reset_install_cache():+ ssl_verify._installed = None+ yield+ ssl_verify._installed = None+++def test_install_truststore_puts_the_platform_verifier_in_charge():+ assert install_truststore() is True+ # Every default context built anywhere in the process is now+ # platform-verified β including stdlib urllib call sites.+ assert ssl.SSLContext.__module__.startswith("truststore")+++def test_install_truststore_is_idempotent():+ assert install_truststore() is True+ assert install_truststore() is True+++def test_default_verify_defers_to_the_platform_store():+ # True means "verify normally", which after the install means the OS+ # store. No CA bundle path is threaded through.+ assert resolve_httpx_verify() is True+ assert resolve_requests_verify() is True+++def test_env_ca_bundle_vars_no_longer_steer_trust(monkeypatch, tmp_path):+ """The old SSL_CERT_FILE/REQUESTS_CA_BUNDLE ladders are gone.++ Trust is the machine's, and a stale env var pointing at a bundle (or at+ nothing) must not silently redirect or break verification β the exact+ failure the removed gateway/auth/urllib ladders each hand-rolled a+ workaround for.+ """+ import certifi++ for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):+ monkeypatch.setenv(var, certifi.where())+ assert resolve_httpx_verify() is True++ for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):+ monkeypatch.setenv(var, str(tmp_path / "does-not-exist.pem"))+ assert resolve_httpx_verify() is True+++def test_explicit_ca_bundle_replaces_the_platform_store():+ """A pinned ssl_ca_cert must verify against THAT bundle only.++ Tripwire: truststore's injected SSLContext ignores load_verify_locations+ and verifies against the OS store regardless, so this context has to come+ from the original class. If a truststore bump moves+ ``_ssl_constants._original_SSLContext``, this fails here instead of+ silently degrading a pinned corporate bundle into "trust the machine".+ """+ import certifi+ from truststore._ssl_constants import _original_SSLContext++ ctx = resolve_httpx_verify(ca_bundle=certifi.where())++ # NOT isinstance(ctx, ssl.SSLContext): that name is the patched class+ # now, and this context deliberately is not one.+ assert isinstance(ctx, _original_SSLContext)+ assert not type(ctx).__module__.startswith("truststore")+ # PROTOCOL_TLS_CLIENT's own defaults β asserted, not assigned: setting+ # them on this context recurses forever through the patched module+ # global (super(SSLContext, SSLContext) resolves to truststore's class).+ assert ctx.verify_mode == ssl.CERT_REQUIRED+ assert ctx.check_hostname is True+ # Introspectable precisely because it is NOT truststore-backed.+ assert len(ctx.get_ca_certs()) > 0+++def test_requests_explicit_ca_bundle_is_returned_as_a_path():+ import certifi++ assert resolve_requests_verify(ca_bundle=certifi.where()) == certifi.where()-_CA_ENV_VARS = ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE")+def test_missing_explicit_bundle_falls_back_to_the_platform_store(tmp_path, caplog):+ missing = str(tmp_path / "nope.pem")-def clean_ca_env(monkeypatch):- for var in _CA_ENV_VARS:- monkeypatch.delenv(var, raising=False)+ assert resolve_httpx_verify(ca_bundle=missing) is True+ assert resolve_requests_verify(ca_bundle=missing) is True+ assert "does not exist" in caplog.text[email protected]("value", [False, "false", "0", "no", "off", "FALSE"])+def test_insecure_disables_verification(value):+ assert resolve_httpx_verify(ssl_verify=value) is False+ assert resolve_requests_verify(ssl_verify=value) is False-def test_hermes_ca_bundle_returns_ssl_context(clean_ca_env, monkeypatch):- monkeypatch.setenv("HERMES_CA_BUNDLE", certifi.where())- result = resolve_httpx_verify()- assert isinstance(result, ssl.SSLContext)+def test_insecure_beats_an_explicit_bundle():+ import certifi+ assert resolve_httpx_verify(ca_bundle=certifi.where(), ssl_verify=False) is False+def test_truststore_failure_degrades_to_openssl_defaults(monkeypatch, caplog):+ """No truststore (stripped env, odd platform) must not break startup."""+ import builtins+ real_import = builtins.__import__+ def _boom(name, *args, **kwargs):+ if name == "truststore":+ raise ImportError("no truststore here")+ return real_import(name, *args, **kwargs)-def test_default_without_env_is_true(clean_ca_env):+ monkeypatch.setattr(builtins, "__import__", _boom)+ assert install_truststore() is False+ assert "truststore unavailable" in caplog.text+ # Still resolves to a usable verify value rather than raising.+ monkeypatch.undo()assert resolve_httpx_verify() is Truediff --git a/tests/gateway/test_ssl_cert_detection.py b/tests/gateway/test_ssl_cert_detection.pydeleted file mode 100644index d86a6871645..00000000000--- a/tests/gateway/test_ssl_cert_detection.py+++ /dev/null@@ -1,34 +0,0 @@-"""Regression tests for gateway SSL certificate environment repair."""--from types import SimpleNamespace---def test_ensure_ssl_certs_ignores_stale_ssl_cert_file(monkeypatch, tmp_path):- """A missing SSL_CERT_FILE should be treated as unset, not trusted."""- import ssl- import sys-- from gateway.run import _ensure_ssl_certs-- cert_file = tmp_path / "cacert.pem"- cert_file.write_text("dummy cert bundle", encoding="utf-8")- stale_file = tmp_path / "missing.pem"-- monkeypatch.setenv("SSL_CERT_FILE", str(stale_file))- monkeypatch.setattr(- ssl,- "get_default_verify_paths",- lambda: SimpleNamespace(cafile=None, openssl_cafile=None),- )- monkeypatch.setitem(- sys.modules,- "certifi",- SimpleNamespace(where=lambda: str(cert_file)),- )-- _ensure_ssl_certs()-- assert stale_file.exists() is False- assert __import__("os").environ["SSL_CERT_FILE"] == str(cert_file)--diff --git a/tests/gateway/test_ssl_certs.py b/tests/gateway/test_ssl_certs.pydeleted file mode 100644index ceb4220e948..00000000000--- a/tests/gateway/test_ssl_certs.py+++ /dev/null@@ -1,53 +0,0 @@-"""Tests for SSL certificate auto-detection in gateway/run.py."""--import os-from unittest.mock import patch, MagicMock---def _load_ensure_ssl():- """Import _ensure_ssl_certs fresh (gateway/run.py has heavy deps, so we- extract just the function source to avoid importing the whole gateway)."""- # We can test via the actual module since conftest isolates HERMES_HOME,- # but we need to be careful about side effects. Instead, replicate the- # logic in a controlled way.- from types import ModuleType- import textwrap, ssl as _ssl # noqa: F401-- code = textwrap.dedent("""\- import os, ssl-- def _ensure_ssl_certs():- if "SSL_CERT_FILE" in os.environ:- return- paths = ssl.get_default_verify_paths()- for candidate in (paths.cafile, paths.openssl_cafile):- if candidate and os.path.exists(candidate):- os.environ["SSL_CERT_FILE"] = candidate- return- try:- import certifi- os.environ["SSL_CERT_FILE"] = certifi.where()- return- except ImportError:- pass- for candidate in (- "/etc/ssl/certs/ca-certificates.crt",- "/etc/ssl/cert.pem",- ):- if os.path.exists(candidate):- os.environ["SSL_CERT_FILE"] = candidate- return- """)- mod = ModuleType("_ssl_helper")- exec(code, mod.__dict__)- return mod._ensure_ssl_certs---class TestEnsureSslCerts:- def test_respects_existing_env_var(self):- fn = _load_ensure_ssl()- with patch.dict(os.environ, {"SSL_CERT_FILE": "/custom/ca.pem"}):- fn()- assert os.environ["SSL_CERT_FILE"] == "/custom/ca.pem"--diff --git a/tests/hermes_cli/test_auth_nous_provider.py b/tests/hermes_cli/test_auth_nous_provider.pyindex 657f3e72aa7..d69443fd93a 100644--- a/tests/hermes_cli/test_auth_nous_provider.py+++ b/tests/hermes_cli/test_auth_nous_provider.py@@ -39,23 +39,26 @@ class TestResolveVerifyFallback:else:assert result is True- def test_valid_ca_bundle_in_auth_state_is_returned(self, tmp_path, monkeypatch):+ def test_valid_ca_bundle_in_auth_state_is_returned(self, tmp_path):import ssl- from hermes_cli.auth import _resolve_verify- ca_file = tmp_path / "ca-bundle.pem"- ca_file.write_text("fake cert")+ import certifi+ from truststore._ssl_constants import _original_SSLContext- # Avoid loading actual PEM β just verify the return type- mock_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)- monkeypatch.setattr(ssl, "create_default_context", lambda **kw: mock_ctx)+ from hermes_cli.auth import _resolve_verifyresult = _resolve_verify(auth_state={- "tls": {"insecure": False, "ca_bundle": str(ca_file)},+ "tls": {"insecure": False, "ca_bundle": certifi.where()},})- assert isinstance(result, ssl.SSLContext), (- f"Expected ssl.SSLContext but got {type(result).__name__}: {result!r}"++ # An explicitly pinned bundle must NOT come back as a truststore+ # context β that would silently verify against the machine's store+ # instead of the bundle the connection asked for.+ assert isinstance(result, _original_SSLContext), (+ f"Expected the pinned-bundle context but got {type(result).__name__}: {result!r}")+ assert not type(result).__module__.startswith("truststore")+ assert result.verify_mode == ssl.CERT_REQUIREDdiff --git a/tests/hermes_cli/test_auth_ssl_macos.py b/tests/hermes_cli/test_auth_ssl_macos.pydeleted file mode 100644index 2320af0addc..00000000000--- a/tests/hermes_cli/test_auth_ssl_macos.py+++ /dev/null@@ -1,86 +0,0 @@-"""Tests for hermes_cli.auth._default_verify platform-aware fallback.--On macOS with Homebrew Python, the system OpenSSL cannot locate the-system trust store, so we explicitly load certifi's bundle. On other-platforms we defer to httpx's own default (which itself uses certifi).--Most tests use monkeypatching β no real SSL handshakes. A handful use-an openssl-generated self-signed cert via the `real_bundle_file`-fixture because `ssl.create_default_context(cafile=...)` parses the-bundle and refuses stubs.-"""--import shutil-import ssl-import subprocess-from pathlib import Path--import pytest---from hermes_cli.auth import _default_verify, _resolve_verify---def real_bundle_file(tmp_path: Path) -> str:- """Return a path to a real openssl-generated self-signed cert.-- Skips the test when the `openssl` binary isn't on PATH, so CI images- without it degrade gracefully instead of erroring out.- """- if shutil.which("openssl") is None:- pytest.skip("openssl binary not available")- cert = tmp_path / "ca.pem"- key = tmp_path / "key.pem"- result = subprocess.run(- [- "openssl", "req", "-x509", "-newkey", "rsa:2048",- "-keyout", str(key), "-out", str(cert),- "-sha256", "-days", "1", "-nodes",- "-subj", "/CN=test",- ],- capture_output=True,- timeout=10,- )- if result.returncode != 0:- pytest.skip(f"openssl failed: {result.stderr.decode('utf-8', 'ignore')[:200]}")- return str(cert)---class TestDefaultVerify:- @pytest.mark.platforms("macos")- def test_returns_ssl_context_on_darwin(self):- result = _default_verify()- assert isinstance(result, ssl.SSLContext)--- @pytest.mark.platforms("macos")- def test_darwin_falls_back_to_true_when_certifi_missing(self, monkeypatch):- real_import = __import__-- def fake_import(name, *args, **kwargs):- if name == "certifi":- raise ImportError("simulated missing certifi")- return real_import(name, *args, **kwargs)-- monkeypatch.setattr("builtins.__import__", fake_import)- assert _default_verify() is True---class TestResolveVerifyIntegration:- """_resolve_verify should defer to _default_verify in the no-CA path."""--- @pytest.mark.platforms("linux")- def test_no_ca_uses_default_verify_on_linux(self, monkeypatch):- for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"):- monkeypatch.delenv(var, raising=False)- assert _resolve_verify() is True---- def test_insecure_wins_over_everything(self, monkeypatch, tmp_path):- bundle = tmp_path / "ca.pem"- bundle.write_text("stub")- monkeypatch.setenv("HERMES_CA_BUNDLE", str(bundle))- assert _resolve_verify(insecure=True) is Falsediff --git a/tests/hermes_cli/test_certifi_repair.py b/tests/hermes_cli/test_certifi_repair.pydeleted file mode 100644index 28a98bb5de6..00000000000--- a/tests/hermes_cli/test_certifi_repair.py+++ /dev/null@@ -1,153 +0,0 @@-"""Regression tests for issue #29866.--A brew Python upgrade (or an interrupted venv rebuild β see also the v0.19.0-report in the same issue) can leave ``certifi`` importable while its bundled-``cacert.pem`` is missing or a dangling symlink. Every TLS connection then-fails with an opaque ``Could not find a suitable TLS CA certificate bundle``-and the gateway is down on all platforms.--Behavior contracts pinned here:--1. The venv-repair import probes (early recovery + `hermes update`) must- classify certifi as BROKEN when the module imports but ``cacert.pem`` is- missing or corrupt β an attribute probe alone passes in that state.-2. ``hermes doctor`` must fail the certificate check in that state, and- ``hermes doctor --fix`` must repair by force-reinstalling certifi and- re-verifying.-"""--import sys-import types-from pathlib import Path--import pytest--import hermes_cli._early_recovery as er---def _fake_certifi(monkeypatch, bundle_path: Path):- """Install a fake certifi module whose where() points at bundle_path."""- fake = types.ModuleType("certifi")- fake.contents = lambda: "" # satisfies the ('certifi', 'contents') probe- fake.where = lambda: str(bundle_path)- monkeypatch.setitem(sys.modules, "certifi", fake)- return fake---# =========================================================================-# 1. Import probes detect a missing/corrupt cacert.pem-# =========================================================================---class TestEarlyRecoveryCertifiBundleProbe:- def test_missing_bundle_flags_certifi_broken(self, monkeypatch, tmp_path):- _fake_certifi(monkeypatch, tmp_path / "nonexistent" / "cacert.pem")- broken = er._probe_broken_packages()- assert "certifi" in broken, (- "certifi imports but cacert.pem is missing β the probe must flag "- "it broken (#29866); the attribute check alone passes here"- )-- def test_tiny_bundle_flags_certifi_broken(self, monkeypatch, tmp_path):- bundle = tmp_path / "cacert.pem"- bundle.write_text("truncated", encoding="utf-8")- _fake_certifi(monkeypatch, bundle)- broken = er._probe_broken_packages()- assert "certifi" in broken--- def test_where_raising_flags_certifi_broken(self, monkeypatch):- fake = types.ModuleType("certifi")- fake.contents = lambda: ""-- def _boom():- raise OSError("simulated broken installation")-- fake.where = _boom- monkeypatch.setitem(sys.modules, "certifi", fake)- broken = er._probe_broken_packages()- assert "certifi" in broken---class TestDoctorCertificates:- def test_broken_bundle_fails_without_fix(self, monkeypatch, capsys, tmp_path):- from hermes_cli import doctor as doctor_mod-- monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "missing.pem"))- issues = []- doctor_mod.check_certificates(should_fix=False, issues=issues)- out = capsys.readouterr().out- assert "broken" in out.lower()- assert issues, "a broken bundle must be funneled into the action list"- assert any("doctor --fix" in i for i in issues)-- def test_fix_reinstalls_certifi_and_reverifies(self, monkeypatch, capsys, tmp_path):- from hermes_cli import doctor as doctor_mod-- # First verification fails, post-reinstall verification succeeds.- calls = {"verify": 0, "pip": []}-- def fake_verify():- calls["verify"] += 1- if calls["verify"] == 1:- from agent.errors import SSLConfigurationError-- raise SSLConfigurationError("certifi points to a missing CA bundle")-- def fake_run(cmd, **kwargs):- calls["pip"].append(cmd)-- class _R:- returncode = 0- stdout = ""- stderr = ""-- return _R()-- monkeypatch.setattr(- "agent.ssl_guard.verify_ca_bundle_with_fallback", fake_verify- )- monkeypatch.setattr(doctor_mod.subprocess, "run", fake_run)-- issues = []- doctor_mod.check_certificates(should_fix=True, issues=issues)- out = capsys.readouterr().out-- assert calls["pip"], "--fix must run a pip force-reinstall of certifi"- pip_cmd = calls["pip"][0]- assert "--force-reinstall" in pip_cmd and "certifi" in pip_cmd- assert calls["verify"] == 2, "must re-verify after the reinstall"- assert "repaired" in out.lower()- assert not issues--- def test_healthy_bundle_never_touches_pip(self, monkeypatch, capsys):- from hermes_cli import doctor as doctor_mod-- def _fail_run(*a, **k):- raise AssertionError("healthy bundle must not trigger a reinstall")-- monkeypatch.setattr(doctor_mod.subprocess, "run", _fail_run)- doctor_mod.check_certificates(should_fix=True, issues=[])- out = capsys.readouterr().out- assert "valid" in out.lower()---# =========================================================================-# 3. Startup error message stays actionable-# =========================================================================---class TestSslGuardRepairHint:- def test_missing_bundle_error_mentions_doctor_fix(self, monkeypatch, tmp_path):- import certifi-- from agent.errors import SSLConfigurationError- from agent.ssl_guard import verify_ca_bundle-- monkeypatch.setattr(certifi, "where", lambda: str(tmp_path / "gone.pem"))- with pytest.raises(SSLConfigurationError) as excinfo:- verify_ca_bundle()- message = str(excinfo.value)- assert "hermes doctor --fix" in message- assert "certifi" in messagediff --git a/tests/hermes_cli/test_urllib_security.py b/tests/hermes_cli/test_urllib_security.pyindex f79379e04a1..9357a248e30 100644--- a/tests/hermes_cli/test_urllib_security.py+++ b/tests/hermes_cli/test_urllib_security.py@@ -411,75 +411,37 @@ def test_hermes_owned_opener_uses_resolved_https_context(monkeypatch):assert getattr(https_handlers[0], "_context", None) is context-def test_resolved_https_context_prefers_configured_ca_bundle(monkeypatch, tmp_path):+def test_resolved_https_context_defers_to_the_platform_store(monkeypatch, tmp_path):+ """Hermes-owned urllib openers verify against the OS certificate store.++ None means "urllib's default context", which β with truststore installed+ process-wide β IS the platform verifier. There is no CA-bundle ladder+ here any more: a stale or bogus env var must not steer or break trust,+ which is precisely what the removed env/certifi ladder used to do.+ """import hermes_cli.urllib_security as urllib_security- _clear_ca_bundle_env(monkeypatch)- ca_bundle = tmp_path / "corporate-ca.pem"- ca_bundle.touch()- expected_context = ssl.create_default_context()- seen: list[str | None] = []-- def create_default_context(*, cafile=None):- seen.append(cafile)- return expected_context-- monkeypatch.setenv("HERMES_CA_BUNDLE", str(ca_bundle))- monkeypatch.setattr(ssl, "create_default_context", create_default_context)-- assert urllib_security._resolved_https_context() is expected_context- assert seen == [str(ca_bundle)]---def test_resolved_https_context_uses_certifi_on_macos(monkeypatch):- import certifi- import hermes_cli.urllib_security as urllib_security-- _clear_ca_bundle_env(monkeypatch)- expected_context = ssl.create_default_context()- seen: list[str | None] = []-- def create_default_context(*, cafile=None):- seen.append(cafile)- return expected_context-- 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 == ["/certifi/cacert.pem"]---def test_invalid_ca_bundle_falls_back_to_certifi_on_macos(monkeypatch, tmp_path):- import certifi- import hermes_cli.urllib_security as urllib_security-- _clear_ca_bundle_env(monkeypatch)- missing_bundle = tmp_path / "missing-ca.pem"- expected_context = ssl.create_default_context()- seen: list[str | None] = []+ assert urllib_security._resolved_https_context() is None- def create_default_context(*, cafile=None):- seen.append(cafile)- return expected_context+ for var in ("HERMES_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):+ monkeypatch.setenv(var, str(tmp_path / "nope.pem"))+ assert urllib_security._resolved_https_context() is None- monkeypatch.setenv("HERMES_CA_BUNDLE", str(missing_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 == ["/certifi/cacert.pem"]+def test_resolved_https_context_installs_the_platform_verifier():+ """Resolving trust for a Hermes opener must put truststore in force.+ A stdlib urllib request is the call path certifi never covered (the+ llama.cpp engine download among them), so the install has to happen here+ and not only on the httpx side.+ """+ import ssl-def test_resolved_https_context_keeps_stdlib_default_off_macos(monkeypatch):import hermes_cli.urllib_security as urllib_security- _clear_ca_bundle_env(monkeypatch)- monkeypatch.setattr(urllib_security.sys, "platform", "linux")+ urllib_security._resolved_https_context()- assert urllib_security._resolved_https_context() is None+ assert ssl.SSLContext.__module__.startswith("truststore")def test_installed_https_context_is_preserved(monkeypatch):diff --git a/tests/run_agent/test_create_openai_client_ssl_verify.py b/tests/run_agent/test_create_openai_client_ssl_verify.pyindex 43d82f67baf..359892acd50 100644--- a/tests/run_agent/test_create_openai_client_ssl_verify.py+++ b/tests/run_agent/test_create_openai_client_ssl_verify.py@@ -1,4 +1,9 @@-"""Regression: keepalive httpx client must honor custom CA bundles for HTTPS providers."""+"""Regression: the keepalive httpx client must carry the resolved TLS trust.++Trust is the OS certificate store; a per-provider ``ssl_ca_cert`` replaces it+for that one client. Both shapes have to survive the trip into httpx's+transport, which is what these assert.+"""import ssl@@ -18,23 +23,33 @@ def clean_tls_env(monkeypatch):monkeypatch.delenv(var, raising=False)-def test_build_keepalive_http_client_uses_hermes_ca_bundle(clean_tls_env, monkeypatch):- monkeypatch.setenv("HERMES_CA_BUNDLE", certifi.where())+def test_build_keepalive_http_client_uses_the_platform_trust_store(clean_tls_env):verify = resolve_httpx_verify()+ assert verify is True+client = AIAgent._build_keepalive_http_client("https://ollama.example.com/v1", verify=verify,)assert isinstance(client, httpx.Client)- assert isinstance(client._transport._pool._ssl_context, ssl.SSLContext)+ # httpx builds its own context from the patched ssl.SSLContext, so the+ # pool's context IS the platform-verified one.+ ctx = client._transport._pool._ssl_context+ assert type(ctx).__module__.startswith("truststore")def test_build_keepalive_http_client_honors_per_provider_ssl_ca_cert(clean_tls_env):+ from truststore._ssl_constants import _original_SSLContext+verify = resolve_httpx_verify(ca_bundle=certifi.where())client = AIAgent._build_keepalive_http_client("https://ollama.example.com/v1", verify=verify,)assert isinstance(client, httpx.Client)- assert isinstance(client._transport._pool._ssl_context, ssl.SSLContext)+ # The pinned bundle must reach the transport UNPATCHED β a truststore+ # context here would mean the pin silently became "trust the machine".+ ctx = client._transport._pool._ssl_context+ assert isinstance(ctx, _original_SSLContext)+ assert not type(ctx).__module__.startswith("truststore")def test_build_keepalive_http_client_ssl_verify_false(clean_tls_env):@@ -44,3 +59,4 @@ def test_build_keepalive_http_client_ssl_verify_false(clean_tls_env):)assert isinstance(client, httpx.Client)assert client._transport._pool._ssl_context.check_hostname is False+ assert client._transport._pool._ssl_context.verify_mode == ssl.CERT_NONEdiff --git a/tui_gateway/entry.py b/tui_gateway/entry.pyindex 27fd051b8af..551d2179dba 100644--- a/tui_gateway/entry.py+++ b/tui_gateway/entry.py@@ -422,6 +422,15 @@ def ensure_mcp_discovery_started() -> None:def main():_install_sidecar_publisher()+ # One TLS authority: trust the OS store process-wide before any+ # outbound call resolves a CA bundle (see agent/ssl_verify.py).+ try:+ from agent.ssl_verify import install_truststore++ install_truststore()+ except Exception:+ logger.debug("truststore install skipped", exc_info=True)+# Cross-backend liveness (#94895): register a heartbeat row so the# startup orphan sweep can distinguish "row owned by a live but idle# backend" from "row truly orphaned". Must run BEFORE the sweep sodiff --git a/uv.lock b/uv.lockindex 64dca2171eb..cfe76c92b59 100644--- a/uv.lock+++ b/uv.lock@@ -1761,6 +1761,7 @@ dependencies = [{ name = "ruamel-yaml" },{ name = "snowballstemmer" },{ name = "tenacity" },+ { name = "truststore" },{ name = "tzdata", marker = "sys_platform == 'win32'" },{ name = "urllib3" },{ name = "uvicorn", extra = ["standard"] },@@ -2158,6 +2159,7 @@ requires-dist = [{ name = "starlette", marker = "extra == 'web'", specifier = "==1.3.1" },{ name = "supermemory", marker = "extra == 'supermemory'", specifier = "==3.50.0" },{ name = "tenacity", specifier = "==9.1.4" },+ { name = "truststore", specifier = ">=0.10.4,<0.11" },{ name = "ty", marker = "extra == 'dev'", specifier = "==0.0.21" },{ name = "tzdata", marker = "sys_platform == 'win32'", specifier = "==2025.3" },{ name = "urllib3", specifier = ">=2.7.0,<3" },