Skip to content

The agent that grows with you

fix(ssl): honour SSL_CERT_FILE in the shared Telegram TLS context

kshitijk4poor0c889a774ff9
diff --git a/agent/ssl_verify.py b/agent/ssl_verify.py
index 7fe34c84756..9cc0d13b152 100644
--- a/agent/ssl_verify.py
+++ b/agent/ssl_verify.py
@@ -21,6 +21,7 @@ statements about one endpoint, not an ambient guess about the machine.
from __future__ import annotations
import logging
+import os
import ssl
import threading
from pathlib import Path
@@ -110,8 +111,15 @@ def _shared_context(ca_path: str | None) -> ssl.SSLContext:
def platform_ssl_context() -> ssl.SSLContext:
- """The process-wide platform-trust client context (cheap after the first call)."""
+ """The process-wide client context (cheap after the first call).
+
+ An existing ``SSL_CERT_FILE`` bundle wins, as it did for httpx ``verify=True``;
+ a missing or stale path falls back to the platform store.
+ """
install_truststore()
+ ca = os.environ.get("SSL_CERT_FILE", "").strip()
+ if ca and Path(ca).is_file():
+ return _shared_context(str(Path(ca).resolve()))
return _shared_context(None)
@@ -154,8 +162,6 @@ def resolve_httpx_verify(
# HTTPX reads CA env vars before the injected verifier gets control. Pass
# the platform context directly so stale paths cannot break construction;
# proxy environment handling remains enabled.
- import os
-
if os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR"):
return _shared_context(None)
return True
diff --git a/tests/gateway/test_telegram_closewait_limits.py b/tests/gateway/test_telegram_closewait_limits.py
index c806b4b56bb..a59ad1351df 100644
--- a/tests/gateway/test_telegram_closewait_limits.py
+++ b/tests/gateway/test_telegram_closewait_limits.py
@@ -160,6 +160,16 @@ def test_all_ptb_clients_share_the_platform_ssl_context(monkeypatch):
assert transport._transport_kwargs.get("verify") is shared
asyncio.run(transport.aclose())
+ # An SSL_CERT_FILE bundle is honoured (as httpx verify=True did) and still cached once.
+ import certifi
+ from agent import ssl_verify
+ monkeypatch.setattr(ssl_verify, "_CA_CONTEXTS", {})
+ monkeypatch.setenv("SSL_CERT_FILE", certifi.where())
+ bundle_ctx = ssl_verify.platform_ssl_context()
+ assert bundle_ctx is ssl_verify.platform_ssl_context()
+ assert bundle_ctx is not ssl_verify._shared_context(None)
+ assert bundle_ctx.cert_store_stats()["x509_ca"] > 0
+
def test_proxy_branch_general_pool_has_tight_keepalive(monkeypatch):
"""The proxy path the #31599 reporter hit must wire tuned limits."""