The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): reuse the shared platform TLS context for every Telegram client
luwen785cf8a3dec4
diff --git a/agent/ssl_verify.py b/agent/ssl_verify.pyindex 251513708d5..7fe34c84756 100644--- a/agent/ssl_verify.py+++ b/agent/ssl_verify.py@@ -109,6 +109,12 @@ def _shared_context(ca_path: str | None) -> ssl.SSLContext:return ctx+def platform_ssl_context() -> ssl.SSLContext:+ """The process-wide platform-trust client context (cheap after the first call)."""+ install_truststore()+ return _shared_context(None)++def resolve_httpx_verify(*,ca_bundle: Optional[str] = None,diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex b41b82963c6..3ab4c791fc2 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -2986,14 +2986,17 @@ class TelegramAdapter(TelegramHeldInboundMixin, BasePlatformAdapter):"TELEGRAM_PROXY", target_hosts=["api.telegram.org", *fallback_ips],configured=self.config.extra.get("proxy_url"))+ from agent.ssl_verify import platform_ssl_context+ ssl_context = platform_ssl_context()+def _pair(general_httpx: dict, updates_httpx: dict, **extra) -> tuple:- return (HTTPXRequest(**request_kwargs, **extra, httpx_kwargs=general_httpx),- HTTPXRequest(**request_kwargs, **extra, httpx_kwargs=updates_httpx))+ return (HTTPXRequest(**request_kwargs, **extra, httpx_kwargs={"verify": ssl_context, **general_httpx}),+ HTTPXRequest(**request_kwargs, **extra, httpx_kwargs={"verify": ssl_context, **updates_httpx}))if fallback_ips and not proxy_url and not disable_fallback:logger.info("[%s] Telegram fallback IPs active: %s", self.name, ", ".join(fallback_ips))# Separate request/update pools reduce contention during polling reconnect + bootstrap calls.- _transport_kwargs: dict = {"socket_options": tcp_keepalive_socket_options()}+ _transport_kwargs: dict = {"socket_options": tcp_keepalive_socket_options(), "verify": ssl_context}# Keep request/update pools separate to reduce contention during polling reconnect + bot API# bootstrap/delete_webhook calls. httpx ignores the client-level `limits` kwarg when a custom# `transport` is supplied (#58790). Unlike the proxy/direct branches (which inject limits at thediff --git a/plugins/platforms/telegram/telegram_network.py b/plugins/platforms/telegram/telegram_network.pyindex d39bebb3d87..6421fda318d 100644--- a/plugins/platforms/telegram/telegram_network.py+++ b/plugins/platforms/telegram/telegram_network.py@@ -265,7 +265,8 @@ async def discover_fallback_ips() -> list[str]:IP is the most reliable path to api.telegram.org and a transient primary-path failure should be retriedagainst the same address via the IP-rewrite path before the seed list is consulted (#14520)."""- async with httpx.AsyncClient(timeout=httpx.Timeout(_DOH_TIMEOUT)) as client:+ from agent.ssl_verify import platform_ssl_context+ async with httpx.AsyncClient(timeout=httpx.Timeout(_DOH_TIMEOUT), verify=platform_ssl_context()) as client:system_dns_task = asyncio.ensure_future(asyncio.to_thread(_resolve_system_dns))results = await asyncio.gather(*[_query_doh_provider(client, p) for p in _DOH_PROVIDERS], return_exceptions=True)# The getaddrinfo leg has no timeout of its own and only feeds the log line below — bound it.diff --git a/tests/gateway/test_telegram_closewait_limits.py b/tests/gateway/test_telegram_closewait_limits.pyindex 0aa30475afb..c47a00e7fc3 100644--- a/tests/gateway/test_telegram_closewait_limits.py+++ b/tests/gateway/test_telegram_closewait_limits.py@@ -27,6 +27,7 @@ client-level limits when a custom transport is supplied.import asyncioimport socket+import sslfrom unittest.mock import MagicMockimport httpx@@ -141,6 +142,25 @@ def _assert_updates_pool_never_reuses(instance):assert limits.max_keepalive_connections == 0+def test_all_ptb_clients_share_the_platform_ssl_context(monkeypatch):+ """Every client/transport _build_ptb_requests builds verifies with the one cached+ platform-trust context — a fresh verify=True context per client reloads CAs on the+ event loop on every reconnect (#133339)."""+ shared = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)+ monkeypatch.setattr("agent.ssl_verify.platform_ssl_context", lambda: shared, raising=False)+ for proxy_url in ("http://127.0.0.1:9/", None):+ instances = _drive_connect(monkeypatch, proxy_url=proxy_url)+ assert len(instances) >= 2+ assert all(inst.kwargs["httpx_kwargs"].get("verify") is shared for inst in instances)++ instances = _drive_connect(monkeypatch, proxy_url=None, fallback_ips=["149.154.167.220"])+ assert len(instances) >= 2+ for inst in instances:+ transport = inst.kwargs["httpx_kwargs"]["transport"]+ assert transport._transport_kwargs.get("verify") is shared+ asyncio.run(transport.aclose())++def test_proxy_branch_general_pool_has_tight_keepalive(monkeypatch):"""The proxy path the #31599 reporter hit must wire tuned limits."""instances = _drive_connect(monkeypatch, proxy_url="http://127.0.0.1:9/")