The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stop exporting fallback CA bundles on import
ethernet3071d0bec8ad
diff --git a/gateway/run.py b/gateway/run.pyindex 376130c7a0b..e60de6e07d1 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1523,49 +1523,6 @@ def _collect_history_media_paths(agent_history: List[Dict[str, Any]]) -> set:breakreturn paths-def _ensure_ssl_certs() -> None:- """Set SSL_CERT_FILE when the system hides CA certs from Python (NixOS etc.); must run BEFORE any- HTTP library is imported. A set-but-missing path breaks every later httpx client: treat as unset."""- 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-- # 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-- # 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- return-def _home_target_env_var(platform_name: str) -> str:"""Home-target env var: built-in ``_HOME_TARGET_ENV_VARS``, plugin registry, then``<PLATFORM>_HOME_CHANNEL``."""@@ -1595,8 +1552,6 @@ def _planned_restart_notification_pending() -> bool:# Gateway marker so a lazily imported cli.py load_cli_config() doesn't clobber TERMINAL_CWD.os.environ["_HERMES_GATEWAY"] = "1"-_ensure_ssl_certs()-sys.path.insert(0, str(Path(__file__).parent.parent))from hermes_constants import get_hermes_home, get_hermes_home_override, get_process_hermes_homediff --git a/tests/agent/test_ssl_verify.py b/tests/agent/test_ssl_verify.pyindex 8457cd41a96..983a0f1b252 100644--- a/tests/agent/test_ssl_verify.py+++ b/tests/agent/test_ssl_verify.py@@ -11,10 +11,9 @@ from agent.ssl_verify import resolve_httpx_verify@pytest.fixturedef no_ca_env(monkeypatch):- """The developer shell (NixOS exports SSL_CERT_FILE) and the gateway's- own cert export both flip resolve_httpx_verify() from ``True`` to a- shared context. The contract under test is the fallback, so pin the- env the assertion assumes instead of inheriting the host's."""+ """An operator's SSL_CERT_FILE flips resolve_httpx_verify() from+ ``True`` to a shared platform context. Pin the env for this fallback+ assertion rather than inheriting a developer shell's values."""monkeypatch.delenv("SSL_CERT_FILE", raising=False)monkeypatch.delenv("SSL_CERT_DIR", raising=False)@@ -75,6 +74,85 @@ with httpx.Client(verify=resolve_httpx_verify()) as client:assert "truststore unavailable" in child.stderr+def test_explicit_provider_ca_replaces_platform_trust_on_real_https(tmp_path):+ """A private endpoint trusts only its provider CA, never a global fallback."""+ from datetime import datetime, timedelta, timezone+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+ from ipaddress import ip_address+ import os+ import ssl+ import subprocess+ import sys+ import threading++ from cryptography import x509+ from cryptography.hazmat.primitives import hashes, serialization+ from cryptography.hazmat.primitives.asymmetric import rsa+ from cryptography.x509.oid import NameOID++ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Private provider")])+ now = datetime.now(timezone.utc)+ cert = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject)+ .public_key(key.public_key()).serial_number(x509.random_serial_number())+ .not_valid_before(now - timedelta(days=1)).not_valid_after(now + timedelta(days=1))+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)+ .add_extension(x509.SubjectAlternativeName([x509.IPAddress(ip_address("127.0.0.1"))]), critical=False)+ .sign(key, hashes.SHA256()))+ ca = tmp_path / "provider-ca.pem"+ private = tmp_path / "provider.key"+ ca.write_bytes(cert.public_bytes(serialization.Encoding.PEM))+ private.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,+ serialization.NoEncryption()))++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"private provider")++ def log_message(self, format, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ # Earlier tests may have injected truststore; its wrapper is client-only.+ from agent.ssl_verify import _stdlib_ssl_context_class+ context = _stdlib_ssl_context_class()(ssl.PROTOCOL_TLS_SERVER)+ context.load_cert_chain(ca, private)+ server.socket = context.wrap_socket(server.socket, server_side=True)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ home = tmp_path / "home"+ home.mkdir()+ env = os.environ.copy()+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home), NO_PROXY="127.0.0.1")+ for key in ("SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE"):+ env.pop(key, None)+ script = """+import httpx, sys+from agent.ssl_verify import resolve_httpx_verify+url, ca = sys.argv[1:]+try:+ httpx.get(url, verify=resolve_httpx_verify(), timeout=5)+except httpx.ConnectError:+ pass+else:+ raise AssertionError('unconfigured platform store trusted private provider')+response = httpx.get(url, verify=resolve_httpx_verify(ca_bundle=ca), timeout=5)+assert response.content == b'private provider', response+"""+ try:+ child = subprocess.run(+ [sys.executable, "-c", script, f"https://127.0.0.1:{server.server_port}/", str(ca)],+ env=env, capture_output=True, text=True, timeout=30, check=False,+ )+ assert child.returncode == 0, child.stdout + child.stderr+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)++def test_explicit_bundle_works_without_truststore():"""A provider ``ssl_ca_cert`` on an interpreter without truststore(3.11–3.13 bridge installs) must still yield a verifying context builtdiff --git a/tests/gateway/test_ssl_cert_detection.py b/tests/gateway/test_ssl_cert_detection.pynew file mode 100644index 00000000000..f4baa5c1c96--- /dev/null+++ b/tests/gateway/test_ssl_cert_detection.py@@ -0,0 +1,44 @@+"""Gateway imports must not replace the platform trust store with a bundled CA file."""++import os+import subprocess+import sys+++def test_gateway_import_does_not_export_a_certifi_bundle(tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ env = os.environ.copy()+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home))+ env.pop("SSL_CERT_FILE", None)+ env.pop("SSL_CERT_DIR", None)+ # Mask only platform CA-file discovery. certifi remains installed, so the+ # old gateway fallback would publish certifi.where() process-wide.+ script = """+import os, ssl+original = ssl.get_default_verify_paths+ssl.get_default_verify_paths = lambda: original()._replace(cafile=None, openssl_cafile=None)+import gateway.run+assert 'SSL_CERT_FILE' not in os.environ, os.environ.get('SSL_CERT_FILE')+"""+ child = subprocess.run(+ [sys.executable, "-c", script], env=env, capture_output=True,+ text=True, timeout=60, check=False,+ )+ assert child.returncode == 0, child.stdout + child.stderr+++def test_gateway_import_preserves_explicit_certificate_override(tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ bundle = tmp_path / "operator.pem"+ bundle.write_text("operator-provided bundle")+ env = os.environ.copy()+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home), SSL_CERT_FILE=str(bundle))+ script = "import os, gateway.run; assert os.environ['SSL_CERT_FILE'] == os.environ['EXPECTED_CA']"+ env["EXPECTED_CA"] = str(bundle)+ child = subprocess.run(+ [sys.executable, "-c", script], env=env, capture_output=True,+ text=True, timeout=60, check=False,+ )+ assert child.returncode == 0, child.stdout + child.stderr