diff options
| author | Claude <noreply@anthropic.com> | 2026-11-16 18:54:17 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-11-16 18:54:17 +0000 |
| commit | 7d95efc2dce00c0eae8307aaa261f6c65e8e6236 (patch) | |
| tree | 57fe5210bfc8671d42839ff7f2bf73ef943cb158 /plugins | |
| parent | f59aa2e6dd7d93e45910afcb7569d73b375f31f7 (diff) | |
security-guidance: use the CA file macOS ships when Python has nonemhegazy/sg-macos-ca-file
A python.org Python on macOS has no CA certificates until its "Install
Certificates" command is run, so every review from it failed to verify
the API's certificate. Where Python's default TLS context holds no
certificate at all, the plugin now adds /etc/ssl/cert.pem, the file
Apple's own Python uses. Verification is unchanged.
Co-authored-by: mhegazy <mhegazy@anthropic.com>
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 98 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_tls_macos_ca_file.py | 193 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_tls_store_unreadable_cert.py | 2 |
3 files changed, 274 insertions, 19 deletions
diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index 793da3c3..8084665e 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -265,12 +265,21 @@ def _anthropic_base_url() -> str: # the ones that fail; _urlopen does the same on the releases that do not. _STORE_TLS_UNSET = object() -_store_tls_context = _STORE_TLS_UNSET # None once Python's default context is known to build +# The context the API calls use; None once Python's default one is known to do. +_store_tls_context = _STORE_TLS_UNSET _store_tls_lock = threading.Lock() # Store entries left out of that context; emit_metrics reports it. _store_certs_skipped = 0 +def _as_http_client_would(context): + """Sets what http.client sets on the context it makes itself.""" + context.set_alpn_protocols(["http/1.1"]) + if context.post_handshake_auth is not None: + context.post_handshake_auth = True + return context + + def _context_without_unreadable_store_certs(): """(context, skipped): Python's default TLS context built from the Windows store entries OpenSSL can parse, and how many it could not. @@ -307,31 +316,82 @@ def _context_without_unreadable_store_certs(): if context is None: return None, skipped context.set_default_verify_paths() - # What http.client sets on the context it would have made. - context.set_alpn_protocols(["http/1.1"]) - if context.post_handshake_auth is not None: - context.post_handshake_auth = True - return context, skipped + return _as_http_client_would(context), skipped + + +# ── macOS Python with no certificates ──────────────────────────────────── +# A Python from the python.org installer has no CA certificates until its +# "Install Certificates" command is run, and every HTTPS call from it fails +# to verify. macOS ships a CA file, the one Apple's /usr/bin/python3 uses; +# with it the calls verify as they do there. + +_ON_MACOS = sys.platform == "darwin" +_MACOS_CA_FILE = "/etc/ssl/cert.pem" + + +def _context_with_os_ca_file(): + """Python's default TLS context plus the CA file macOS ships, or None. + Only where the default one has no certificate at all, so a Python that + can verify anything keeps exactly what it trusts. SSL_CERT_FILE and + SSL_CERT_DIR are the user's own choice of what to trust and win, also + when they point at nothing.""" + if not _ON_MACOS or ssl is None: + return None + if "SSL_CERT_FILE" in os.environ or "SSL_CERT_DIR" in os.environ: + return None + if not _anthropic_base_url().lower().startswith("https:"): + return None + paths = ssl.get_default_verify_paths() + if paths.cafile or not os.path.isfile(_MACOS_CA_FILE): + return None + # The factory urllib uses, so a site that replaced it keeps its choice. + context = ssl._create_default_https_context() + if context.verify_mode != ssl.CERT_REQUIRED or context.cert_store_stats()["x509"]: + return None + # A CA directory is read during the handshake and is not in those counts. + # OpenSSL reads only hashed names (1a2b3c4d.0) from it; Homebrew keeps a + # placeholder file there. + with contextlib.suppress(OSError): + if paths.capath and any(re.fullmatch(r"[0-9a-f]{8}\.\d+", name) + for name in os.listdir(paths.capath)): + return None + context.load_verify_locations(cafile=_MACOS_CA_FILE) + return _as_http_client_would(context) + + +def _own_tls_context(): + """The context for API calls where Python's default one fails every call + (see above), else None.""" + global _store_certs_skipped + try: + context, skipped = _context_without_unreadable_store_certs() + except Exception as e: + debug_log(f"TLS: certificate store check failed: {type(e).__name__}") + context, skipped = None, 0 + if context is not None: + debug_log(f"TLS: the Windows certificate store has {skipped} certificate(s) " + "OpenSSL cannot read; using the store without them") + _store_certs_skipped = skipped + return context + try: + context = _context_with_os_ca_file() + except Exception as e: + debug_log(f"TLS: check for a Python without CA certificates failed: {type(e).__name__}") + return None + if context is not None: + debug_log(f"TLS: this Python has no CA certificates; using {_MACOS_CA_FILE}") + return context def _urlopen(request, timeout): """urllib.request.urlopen for the plugin's API calls. Uses Python's - default TLS context unless that cannot be built because of the Windows - certificate store (see above); checked once per process.""" - global _store_tls_context, _store_certs_skipped + default TLS context unless that one fails every call (see + _own_tls_context); checked once per process.""" + global _store_tls_context if _store_tls_context is _STORE_TLS_UNSET: with _store_tls_lock: if _store_tls_context is _STORE_TLS_UNSET: - try: - context, skipped = _context_without_unreadable_store_certs() - except Exception as e: - debug_log(f"TLS: certificate store check failed: {type(e).__name__}") - context, skipped = None, 0 - if context is not None: - debug_log(f"TLS: the Windows certificate store has {skipped} certificate(s) " - "OpenSSL cannot read; using the store without them") - _store_certs_skipped = skipped - _store_tls_context = context + _store_tls_context = _own_tls_context() if _store_tls_context is None: return urllib.request.urlopen(request, timeout=timeout) return urllib.request.urlopen(request, timeout=timeout, context=_store_tls_context) diff --git a/plugins/security-guidance/tests/test_tls_macos_ca_file.py b/plugins/security-guidance/tests/test_tls_macos_ca_file.py new file mode 100644 index 00000000..f2e73798 --- /dev/null +++ b/plugins/security-guidance/tests/test_tls_macos_ca_file.py @@ -0,0 +1,193 @@ +"""A macOS Python without any CA certificate uses the CA file macOS ships. + +A python.org Python has none until its "Install Certificates" command is run. +The machine and that Python are stood in for here, so the cases run on every +platform. +""" +import http.client +import ssl +import types +import urllib.error + +import pytest + +# The certificates, the HTTPS endpoint and the review call of the store tests. +from test_tls_store_unreadable_cert import ( # noqa: F401 + UNRELATED_CA_PEM, _head, _review, https_api, pki, store, urlopen_calls) + +import llm + +_real_create_default_context = ssl.create_default_context + + +def _no_certificates(*args, **kwargs): + """What create_default_context gives on a Python with no CA file.""" + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + default = _real_create_default_context(cadata=UNRELATED_CA_PEM) + context.verify_flags, context.options = default.verify_flags, default.options + return context + + +@pytest.fixture +def mac(store, monkeypatch, tmp_path): + """A Mac whose Python has no certificates and whose OS CA file holds one.""" + os_file = tmp_path / "cert.pem" + os_file.write_text(UNRELATED_CA_PEM) + paths = types.SimpleNamespace(cafile=None, capath=None) + monkeypatch.delattr(ssl, "enum_certificates", raising=False) # Windows only + monkeypatch.setattr(llm, "_ON_MACOS", True) + monkeypatch.setattr(llm, "_MACOS_CA_FILE", str(os_file)) + monkeypatch.setattr(ssl, "get_default_verify_paths", lambda: paths) + monkeypatch.setattr(ssl, "_create_default_https_context", _no_certificates) + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + return types.SimpleNamespace(paths=paths, os_file=os_file, tmp=tmp_path) + + +def _names(context): + return {dict(x[0] for x in c["subject"])["commonName"] for c in context.get_ca_certs()} + + +def _context(): + return llm._context_with_os_ca_file() + + +class TestContext: + def test_holds_the_os_file_and_nothing_else(self, mac): + assert _names(_context()) == {"sg test unrelated CA"} + + def test_verifies_as_any_default_context(self, mac): + context = _context() + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname is True + default = _real_create_default_context(cadata=UNRELATED_CA_PEM) + assert context.verify_flags == default.verify_flags + assert context.options == default.options + assert context.minimum_version == default.minimum_version + + def test_is_set_up_as_http_client_does(self, mac, monkeypatch): + offered = [] + monkeypatch.setattr(ssl.SSLContext, "set_alpn_protocols", + lambda self, protocols: offered.append(protocols)) + ours = _context() + theirs = http.client.HTTPSConnection("localhost")._context + assert offered == [["http/1.1"], ["http/1.1"]] + assert ours.post_handshake_auth == theirs.post_handshake_auth + + def test_a_python_with_a_ca_file_is_left_alone(self, mac): + mac.paths.cafile = str(mac.tmp / "own.pem") + assert _context() is None + + def test_a_python_with_a_ca_directory_is_left_alone(self, mac): + certs = mac.tmp / "certs" + certs.mkdir() + (certs / "1a2b3c4d.0").write_text(UNRELATED_CA_PEM) + mac.paths.capath = str(certs) + assert _context() is None + + @pytest.mark.parametrize("contents", [[], [".keepme"], ["notes.txt"]]) + def test_a_directory_without_certificates_counts_as_none(self, mac, contents): + certs = mac.tmp / "certs" + certs.mkdir() + for name in contents: # Homebrew keeps a .keepme there + (certs / name).write_text("") + mac.paths.capath = str(certs) + assert _context() is not None + + def test_a_directory_that_cannot_be_listed_counts_as_none(self, mac, monkeypatch): + def listdir(path): + raise PermissionError(path) + mac.paths.capath = str(mac.tmp) + monkeypatch.setattr(llm.os, "listdir", listdir) + assert _context() is not None + + def test_certificates_found_another_way_are_left_alone(self, mac, monkeypatch): + """A default context can hold some though the paths name no file.""" + monkeypatch.setattr(ssl, "_create_default_https_context", + lambda: _real_create_default_context(cadata=UNRELATED_CA_PEM)) + assert _context() is None + + def test_a_site_that_replaced_the_default_is_left_alone(self, mac, monkeypatch): + monkeypatch.setattr(ssl, "_create_default_https_context", + ssl._create_unverified_context) + assert _context() is None + + @pytest.mark.parametrize("value", ["/nonexistent", ""]) + @pytest.mark.parametrize("var", ["SSL_CERT_FILE", "SSL_CERT_DIR"]) + def test_the_users_own_choice_wins(self, mac, monkeypatch, var, value): + monkeypatch.setenv(var, value) + assert _context() is None + + def test_a_plain_http_endpoint_needs_none(self, mac, monkeypatch): + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://127.0.0.1:4000") + assert _context() is None + + def test_other_platforms_are_untouched(self, mac, monkeypatch): + monkeypatch.setattr(llm, "_ON_MACOS", False) + assert _context() is None + + def test_no_os_file_means_no_change(self, mac): + mac.os_file.unlink() + assert _context() is None + + +class TestCalls: + def test_the_context_is_built_once(self, mac, urlopen_calls, monkeypatch): + real, builds = llm._context_with_os_ca_file, [] + monkeypatch.setattr(llm, "_context_with_os_ca_file", + lambda: builds.append(1) or real()) + llm._urlopen(_head(), 5) + llm._urlopen(_head(), 5) + assert len(builds) == 1 + first, second = [c["context"] for c in urlopen_calls] + assert first is second + assert _names(first) == {"sg test unrelated CA"} + + @pytest.mark.parametrize("problem", ["not a certificate", PermissionError]) + def test_an_os_file_that_cannot_be_used_changes_nothing( + self, mac, urlopen_calls, monkeypatch, problem): + if isinstance(problem, str): + mac.os_file.write_text(problem) + else: + def refuse(self, **kwargs): + raise problem("denied") + monkeypatch.setattr(ssl.SSLContext, "load_verify_locations", refuse) + monkeypatch.setattr(ssl, "_create_default_https_context", + lambda: ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)) + llm._urlopen(_head(), 5) + assert urlopen_calls == [{"timeout": 5}] + + +class TestHandshake: + """Real TLS against a local endpoint that only the OS file can vouch for.""" + + @staticmethod + def _os_file_trusts(mac, pki): + mac.os_file.write_text(ssl.DER_cert_to_PEM_cert(pki["trusted"]["ca"])) + + @staticmethod + def _refused(srv): + with pytest.raises(urllib.error.URLError) as raised: + llm._urlopen(_head(), 5) + assert isinstance(raised.value.reason, ssl.SSLCertVerificationError) + _review() + assert llm.last_review_failed() + assert srv.calls == [] + + def test_a_review_runs(self, mac, pki, https_api): + srv = https_api("trusted") + self._os_file_trusts(mac, pki) + _review() + assert not llm.last_review_failed() + assert len(srv.calls) == 1 + + def test_without_the_os_file_the_review_fails(self, mac, https_api): + srv = https_api("trusted") + mac.os_file.unlink() + self._refused(srv) + + @pytest.mark.parametrize("server", ["untrusted", "other-host"]) + def test_a_certificate_it_does_not_cover_is_still_refused( + self, mac, pki, https_api, server): + srv = https_api(server) + self._os_file_trusts(mac, pki) + self._refused(srv) diff --git a/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py b/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py index c76aa8aa..89452630 100644 --- a/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py +++ b/plugins/security-guidance/tests/test_tls_store_unreadable_cert.py @@ -85,6 +85,8 @@ def store(monkeypatch): # The store is checked once per process. monkeypatch.setattr(llm, "_store_tls_context", llm._STORE_TLS_UNSET) monkeypatch.setattr(llm, "_store_certs_skipped", 0) + # Not this machine's: a Mac whose Python has no certificates. + monkeypatch.setattr(llm, "_ON_MACOS", False) for var in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR"): monkeypatch.delenv(var, raising=False) |
