test_ssl_certs.py
1 """Tests for SSL certificate auto-detection in gateway/run.py.""" 2 3 import importlib 4 import os 5 from unittest.mock import patch, MagicMock 6 7 8 def _load_ensure_ssl(): 9 """Import _ensure_ssl_certs fresh (gateway/run.py has heavy deps, so we 10 extract just the function source to avoid importing the whole gateway).""" 11 # We can test via the actual module since conftest isolates HERMES_HOME, 12 # but we need to be careful about side effects. Instead, replicate the 13 # logic in a controlled way. 14 from types import ModuleType 15 import textwrap, ssl as _ssl # noqa: F401 16 17 code = textwrap.dedent("""\ 18 import os, ssl 19 20 def _ensure_ssl_certs(): 21 if "SSL_CERT_FILE" in os.environ: 22 return 23 paths = ssl.get_default_verify_paths() 24 for candidate in (paths.cafile, paths.openssl_cafile): 25 if candidate and os.path.exists(candidate): 26 os.environ["SSL_CERT_FILE"] = candidate 27 return 28 try: 29 import certifi 30 os.environ["SSL_CERT_FILE"] = certifi.where() 31 return 32 except ImportError: 33 pass 34 for candidate in ( 35 "/etc/ssl/certs/ca-certificates.crt", 36 "/etc/ssl/cert.pem", 37 ): 38 if os.path.exists(candidate): 39 os.environ["SSL_CERT_FILE"] = candidate 40 return 41 """) 42 mod = ModuleType("_ssl_helper") 43 exec(code, mod.__dict__) 44 return mod._ensure_ssl_certs 45 46 47 class TestEnsureSslCerts: 48 def test_respects_existing_env_var(self): 49 fn = _load_ensure_ssl() 50 with patch.dict(os.environ, {"SSL_CERT_FILE": "/custom/ca.pem"}): 51 fn() 52 assert os.environ["SSL_CERT_FILE"] == "/custom/ca.pem" 53 54 def test_sets_from_ssl_default_paths(self, tmp_path): 55 fn = _load_ensure_ssl() 56 cert = tmp_path / "ca.crt" 57 cert.write_text("FAKE CERT") 58 59 mock_paths = MagicMock() 60 mock_paths.cafile = str(cert) 61 mock_paths.openssl_cafile = None 62 63 env = {k: v for k, v in os.environ.items() if k != "SSL_CERT_FILE"} 64 with patch.dict(os.environ, env, clear=True), \ 65 patch("ssl.get_default_verify_paths", return_value=mock_paths): 66 fn() 67 assert os.environ.get("SSL_CERT_FILE") == str(cert) 68 69 def test_no_op_when_nothing_found(self): 70 fn = _load_ensure_ssl() 71 mock_paths = MagicMock() 72 mock_paths.cafile = None 73 mock_paths.openssl_cafile = None 74 75 env = {k: v for k, v in os.environ.items() if k != "SSL_CERT_FILE"} 76 with patch.dict(os.environ, env, clear=True), \ 77 patch("ssl.get_default_verify_paths", return_value=mock_paths), \ 78 patch("os.path.exists", return_value=False), \ 79 patch.dict("sys.modules", {"certifi": None}): 80 fn() 81 assert "SSL_CERT_FILE" not in os.environ