test(ssl_guard): fix macOS fallback test that passed for the wrong reason

The previous test patched ssl.create_default_context globally with a bare
SSLContext that has zero CA certs. Both verify_ca_bundle() and the macOS
fallback got the same mocked context, so the test verified nothing useful:
both paths produced empty get_ca_certs() and the assertion that no
exception escaped was vacuously satisfied.

Only mock the fallback call (no cafile) — let the certifi call hit the
real SSL stack and fail with SSLError on the broken PEM. The mock
fallback returns a context with load_default_certs() so the test now
verifies the real scenario: broken certifi → SSLConfigurationError,
macOS system trust store → success.

Also pads the broken PEM past the 1 KB size guard so the size check
doesn't short-circuit before ssl.create_default_context(cafile=...) runs.

Reported by @liuhao1024 in PR review.
This commit is contained in:
chromalinx 2026-06-02 17:02:39 +02:00 committed by Teknium
parent a218a0f156
commit b42c5bf652

View file

@ -52,13 +52,31 @@ def test_skip_env_var_disables_guard(monkeypatch, tmp_path):
def test_macos_fallback_allows_startup(monkeypatch, tmp_path):
"""On Darwin, an unloadable certifi bundle must fall back to system trust."""
"""On Darwin, an unloadable certifi bundle must fall back to system trust.
Only the fallback call (no cafile) is mocked the certifi call must
fail naturally with SSLError from the broken PEM. The mock returns a
context with system CAs loaded, so the fallback succeeds.
"""
fake = tmp_path / "broken.pem"
fake.write_bytes(b"not a real bundle")
# > 1024 bytes so the size guard doesn't short-circuit before ssl runs.
fake.write_bytes(b"not a real bundle" + b" " * 2000)
monkeypatch.setattr(certifi, "where", lambda: str(fake))
monkeypatch.setattr("platform.system", lambda: "Darwin")
fake_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with patch("ssl.create_default_context", return_value=fake_ctx):
# Should NOT raise — macOS fallback lets startup proceed.
_real_create = ssl.create_default_context
def _mock_create(purpose=ssl.Purpose.SERVER_AUTH, **kwargs):
if kwargs.get("cafile"):
# Let the certifi call hit the real SSL stack → raises SSLError
# on the broken PEM, which verify_ca_bundle() wraps as
# SSLConfigurationError. This is the path the fallback rescues.
return _real_create(purpose, **kwargs)
# Fallback call: simulate a healthy system trust store.
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_default_certs()
return ctx
with patch("ssl.create_default_context", side_effect=_mock_create):
# Should NOT raise — macOS system trust store covers the broken bundle.
verify_ca_bundle_with_fallback()