# Conflicts: # apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts # apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts # apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts # apps/desktop/e2e/bot-mode-roster-localized.spec.ts # apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts # apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts # apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts # apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts # apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts # apps/desktop/e2e/bot-roster-user-sections.spec.ts # apps/desktop/e2e/bot-routines-pane-narrow.spec.ts # apps/desktop/e2e/bot-row-open-recent-session.spec.ts # apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts # apps/desktop/e2e/group-composer-auto-grow.spec.ts # apps/desktop/e2e/group-create-gate-remote-roster.spec.ts # apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts # apps/desktop/e2e/hosted-room-backend-continuity.spec.ts # apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts # apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts # apps/desktop/e2e/worktree-branch-status.spec.ts # apps/desktop/electron/backend-probes.test.ts # apps/desktop/electron/connection-apply.test.ts # apps/desktop/electron/desktop-electron-pin.test.ts # apps/desktop/electron/desktop-uninstall.test.ts # apps/desktop/electron/gateway-file-download-transport.test.ts # apps/desktop/electron/gateway-stop-before-update.test.ts # apps/desktop/electron/github-api-auth.test.ts # apps/desktop/electron/registry-primary-profile-scope.test.ts # apps/desktop/electron/update-api-check.test.ts # apps/desktop/electron/update-handoff-marker.test.ts # apps/desktop/electron/venv-blocker-scan.test.ts # apps/desktop/scripts/after-extract.test.mjs # apps/desktop/scripts/local-pack-publish.test.mjs # apps/desktop/scripts/tasks-scroll.test.mjs # apps/desktop/src/app/settings/model-settings.test.tsx # apps/desktop/src/app/updates-overlay.blockers.test.tsx # apps/desktop/src/components/desktop-install-overlay.test.tsx # apps/desktop/src/lib/update-copy.test.ts # scripts/ci/check_os_marker_fakes.py # tests-js/desktop-mac-usage-descriptions.test.ts # tests-js/node-engine-alignment.test.ts # tests/agent/lsp/test_install_and_lint_fixes.py # tests/agent/test_command_token_source.py # tests/agent/test_compression_boundary_hook.py # tests/agent/test_create_openai_client_ssl_verify.py # tests/agent/test_custom_provider_ca_probes.py # tests/agent/test_endpoint_blackhole.py # tests/agent/test_estimator_parity.py # tests/agent/test_in_place_compaction.py # tests/agent/test_moa_loop_mode.py # tests/agent/test_model_metadata.py # tests/agent/test_skill_session_platform_gate.py # tests/agent/test_skill_utils.py # tests/agent/test_ssl_ca_guard.py # tests/computer_use/test_doctor.py # tests/cron/test_codex_execution_paths.py # tests/cron/test_cron_bot_chat_delivery.py # tests/cron/test_cron_script.py # tests/cron/test_media_delivery_parity.py # tests/cron/test_misfire_catchup.py # tests/cron/test_parallel_pool.py # tests/cron/test_recurring_eagain_redispatch.py # tests/gateway/test_choice_picker.py # tests/gateway/test_control_socket_windows_live.py # tests/gateway/test_dingtalk.py # tests/gateway/test_feishu.py # tests/gateway/test_feishu_onboard.py # tests/gateway/test_gateway_shutdown.py # tests/gateway/test_matrix.py # tests/gateway/test_model_command_custom_providers.py # tests/gateway/test_reasoning_command.py # tests/gateway/test_runtime_footer.py # tests/gateway/test_session.py # tests/gateway/test_session_hygiene.py # tests/gateway/test_status.py # tests/gateway/test_teams.py # tests/gateway/test_turn_lease.py # tests/gateway/test_whatsapp_connect.py # tests/hermes_cli/test_approvals_command.py # tests/hermes_cli/test_auth_store_lock_concurrent.py # tests/hermes_cli/test_backup.py # tests/hermes_cli/test_banner_git_state.py # tests/hermes_cli/test_certifi_repair.py # tests/hermes_cli/test_cmd_update.py # tests/hermes_cli/test_compat_manifest_targets.py # tests/hermes_cli/test_computer_use_cli.py # tests/hermes_cli/test_cpr_local_leak.py # tests/hermes_cli/test_dashboard_auth_gate.py # tests/hermes_cli/test_dashboard_procs_kill_grace.py # tests/hermes_cli/test_desktop_lifecycle_windows_live.py # tests/hermes_cli/test_doctor.py # tests/hermes_cli/test_doctor_command_install.py # tests/hermes_cli/test_fleet_config_migration_windows_live.py # tests/hermes_cli/test_gateway.py # tests/hermes_cli/test_gateway_platform_gating.py # tests/hermes_cli/test_gateway_restart_loop.py # tests/hermes_cli/test_gateway_task_probe.py # tests/hermes_cli/test_gateway_wsl.py # tests/hermes_cli/test_gui_command.py # tests/hermes_cli/test_install_cua_driver.py # tests/hermes_cli/test_kanban_db.py # tests/hermes_cli/test_lazy_command_exports.py # tests/hermes_cli/test_lazy_refresh_venv_repair.py # tests/hermes_cli/test_linux_desktop_entry.py # tests/hermes_cli/test_local_runtime.py # tests/hermes_cli/test_local_runtime_updates.py # tests/hermes_cli/test_managed_uv.py # tests/hermes_cli/test_mcp_reload_confirm_gate.py # tests/hermes_cli/test_nous_subscription.py # tests/hermes_cli/test_npm_engine.py # tests/hermes_cli/test_personality_none.py # tests/hermes_cli/test_pet_toggle.py # tests/hermes_cli/test_plan_reconciliation_windows_live.py # tests/hermes_cli/test_plugin_event_bus.py # tests/hermes_cli/test_plugin_manifest_v2.py # tests/hermes_cli/test_plugin_packs.py # tests/hermes_cli/test_plugins_cmd.py # tests/hermes_cli/test_plugins_cmd_enable_disable_nested.py # tests/hermes_cli/test_process_identity.py # tests/hermes_cli/test_profiles.py # tests/hermes_cli/test_profiles_sidebar_cache.py # tests/hermes_cli/test_pty_bridge.py # tests/hermes_cli/test_resolve_turn_limit.py # tests/hermes_cli/test_serve_runtime_inventory.py # tests/hermes_cli/test_session_vacuum_config.py # tests/hermes_cli/test_set_config_value.py # tests/hermes_cli/test_signal_handler_kanban_worker.py # tests/hermes_cli/test_slash_confirm_windows.py # tests/hermes_cli/test_stale_pid_guard.py # tests/hermes_cli/test_startup_fast_guards.py # tests/hermes_cli/test_status.py # tests/hermes_cli/test_telegram_managed_bot.py # tests/hermes_cli/test_tools_config.py # tests/hermes_cli/test_update_apply_shallow_count.py # tests/hermes_cli/test_update_autostash.py # tests/hermes_cli/test_update_concurrent_quarantine.py # tests/hermes_cli/test_update_fetch_failure_classifier.py # tests/hermes_cli/test_update_fleet_probe_resume_token.py # tests/hermes_cli/test_update_handoff_backend_reap.py # tests/hermes_cli/test_update_handoff_desktop_rebuild.py # tests/hermes_cli/test_update_head_moved_gate.py # tests/hermes_cli/test_update_host_obligation.py # tests/hermes_cli/test_update_import_guard.py # tests/hermes_cli/test_update_interrupted_recovery.py # tests/hermes_cli/test_update_inventory.py # tests/hermes_cli/test_update_launchd_unloaded_gateway.py # tests/hermes_cli/test_update_missing_configured_deps.py # tests/hermes_cli/test_update_modified_notice.py # tests/hermes_cli/test_update_multiplex_migration_hook.py # tests/hermes_cli/test_update_no_gateway_restart.py # tests/hermes_cli/test_update_orphan_backend_reap.py # tests/hermes_cli/test_update_parked_branch_guard.py # tests/hermes_cli/test_update_post_pull_syntax_guard.py # tests/hermes_cli/test_update_receipt.py # tests/hermes_cli/test_update_self_lock.py # tests/hermes_cli/test_update_shim_fail_closed.py # tests/hermes_cli/test_update_shim_self_lock.py # tests/hermes_cli/test_update_sqlite_remediation.py # tests/hermes_cli/test_update_stale_dashboard.py # tests/hermes_cli/test_update_stale_virtualenv.py # tests/hermes_cli/test_update_venv_health.py # tests/hermes_cli/test_update_venv_ownership_preflight.py # tests/hermes_cli/test_update_wedged_gateway.py # tests/hermes_cli/test_update_yes_flag.py # tests/hermes_cli/test_update_zip_two_phase.py # tests/hermes_cli/test_urllib_security.py # tests/hermes_cli/test_ux_messages_auth_config.py # tests/hermes_cli/test_ux_messages_startup.py # tests/hermes_cli/test_venv_holder_classifier.py # tests/hermes_cli/test_verify_console_scripts.py # tests/hermes_cli/test_verify_core_dependencies.py # tests/hermes_cli/test_web_server.py # tests/hermes_cli/test_web_server_console_ws.py # tests/hermes_cli/test_web_server_ws_ping.py # tests/hermes_cli/test_web_ui_build.py # tests/hermes_state/test_fts_rebuild_admission.py # tests/hermes_state/test_hermes_state.py # tests/plugins/memory/test_memory_lazy_install.py # tests/plugins/test_google_meet_plugin.py # tests/plugins/test_langfuse_plugin.py # tests/plugins/test_security_guidance_plugin.py # tests/plugins/test_transform_llm_output_hook.py # tests/scripts/desktop_update/test_desktop_update_windows_gateway_flag.py # tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py # tests/scripts/desktop_update/test_desktop_update_windows_timestamp.py # tests/scripts/install/test_install_clone_throttle_fallback.py # tests/scripts/install/test_install_lockfile_churn.py # tests/scripts/install/test_install_no_initial_commit.py # tests/scripts/install/test_install_sh_browser_install.py # tests/scripts/install/test_install_sh_node_prerelease.py # tests/scripts/install/test_install_sh_symlink_stomp.py # tests/scripts/install/test_install_sh_uv_lock_config.py # tests/scripts/install/test_install_unmerged_index.py # tests/scripts/test_contributor_map.py # tests/scripts/test_run_tests_parallel.py # tests/skills/test_competitor_news_monitor_skill.py # tests/skills/test_document_to_action_items_skill.py # tests/skills/test_google_workspace_setup.py # tests/skills/test_google_workspace_setup_deps.py # tests/skills/test_grounded_citations_skill.py # tests/skills/test_ip_as_logo_skill.py # tests/skills/test_live_dashboard_skill.py # tests/skills/test_mcp_oauth_remote_gateway_skill.py # tests/skills/test_office_document_skills.py # tests/skills/test_openclaw_migration.py # tests/skills/test_product_price_monitor_skill.py # tests/skills/test_scrollcraft_skill.py # tests/skills/test_setup_wizard_generator_skill.py # tests/skills/test_weekly_review_planning_skill.py # tests/test_engines_satisfiable.py # tests/test_fast_safe_load.py # tests/test_hermes_bootstrap.py # tests/test_hermes_constants.py # tests/test_hermes_logging.py # tests/test_managed_runtime_resolution.py # tests/test_model_tools_async_bridge.py # tests/test_packaging_build_guard.py # tests/test_packaging_metadata.py # tests/test_yaml_indent_consistency.py # tests/tools/test_approval_timeout_overflow.py # tests/tools/test_base_environment.py # tests/tools/test_bot_mode_dm.py # tests/tools/test_browser_chromium_check.py # tests/tools/test_browser_hardening.py # tests/tools/test_browser_homebrew_paths.py # tests/tools/test_browser_npx_warmup.py # tests/tools/test_browser_orphan_reaper.py # tests/tools/test_browser_real_profile.py # tests/tools/test_browser_use_cli.py # tests/tools/test_clipboard.py # tests/tools/test_code_execution.py # tests/tools/test_code_execution_modes.py # tests/tools/test_code_execution_windows_env.py # tests/tools/test_computer_use.py # tests/tools/test_delegate_liveness_timeout.py # tests/tools/test_execute_code_approval_cluster.py # tests/tools/test_execution_flag_detection.py # tests/tools/test_fal_common.py # tests/tools/test_file_operations.py # tests/tools/test_file_tools.py # tests/tools/test_file_tools_cwd_resolution.py # tests/tools/test_file_tools_live.py # tests/tools/test_lazy_deps.py # tests/tools/test_lazy_deps_durable_target.py # tests/tools/test_lazy_deps_managed.py # tests/tools/test_local_env_blocklist.py # tests/tools/test_local_tempdir.py # tests/tools/test_macos_protected_search.py # tests/tools/test_mcp_npx_cached_bin.py # tests/tools/test_oneshot_completion_linger.py # tests/tools/test_process_registry.py # tests/tools/test_read_file_schema_gating.py # tests/tools/test_skill_improvements.py # tests/tools/test_skills_sync.py # tests/tools/test_termux_api_detection.py # tests/tools/test_tirith_security.py # tests/tools/test_transcription_tools.py # tests/tools/test_tts_streaming.py # tests/tools/test_wake_word.py # tests/tui_gateway/test_compute_host_borrowed_lease.py # tests/tui_gateway/test_compute_host_turn_protocol.py # tests/tui_gateway/test_isolated_orphan_activity.py # tests/tui_gateway/test_protocol.py # tests/tui_gateway/test_slash_worker_profile_home.py # tests/tui_gateway/test_subprocess_encoding.py # tests/tui_gateway/test_tui_gateway_server.py # ui-tui/src/__tests__/terminalParity.test.ts # ui-tui/src/__tests__/termuxComposerLayout.test.ts # ui-tui/src/__tests__/textInputFastEcho.test.ts
482 lines
22 KiB
Python
482 lines
22 KiB
Python
"""Tests for plugins.platforms.telegram.telegram_network – fallback transport layer.
|
||
|
||
Background
|
||
----------
|
||
api.telegram.org resolves to an IP (e.g. 149.154.166.110) that is unreachable
|
||
from some networks. The workaround: route TCP through a different IP in the
|
||
same Telegram-owned 149.154.160.0/20 block (e.g. 149.154.167.220) while
|
||
keeping TLS SNI and the Host header as api.telegram.org so Telegram's edge
|
||
servers still accept the request. This is the programmatic equivalent of:
|
||
|
||
curl --resolve api.telegram.org:443:149.154.167.220 https://api.telegram.org/bot<token>/getMe
|
||
|
||
The TelegramFallbackTransport implements this: try known IPv4 Telegram API
|
||
IPs first (so a blackholed IPv6 AAAA for the hostname cannot hang
|
||
initialize — #87015), then fall through to the dual-stack hostname last,
|
||
and "stick" to whichever path works.
|
||
"""
|
||
|
||
import httpx
|
||
import pytest
|
||
import socket
|
||
|
||
import plugins.platforms.telegram.telegram_network as tnet
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Helpers
|
||
# ---------------------------------------------------------------------------
|
||
|
||
class FakeTransport(httpx.AsyncBaseTransport):
|
||
"""Records calls and raises / returns based on a host→action mapping."""
|
||
|
||
def __init__(self, calls, behavior):
|
||
self.calls = calls
|
||
self.behavior = behavior
|
||
self.closed = False
|
||
|
||
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
||
self.calls.append(
|
||
{
|
||
"url_host": request.url.host,
|
||
"host_header": request.headers.get("host"),
|
||
"sni_hostname": request.extensions.get("sni_hostname"),
|
||
"path": request.url.path,
|
||
}
|
||
)
|
||
action = self.behavior.get(request.url.host, "ok")
|
||
if action == "timeout":
|
||
raise httpx.ConnectTimeout("timed out")
|
||
if action == "connect_error":
|
||
raise httpx.ConnectError("connect error")
|
||
if isinstance(action, Exception):
|
||
raise action
|
||
return httpx.Response(200, request=request, text="ok")
|
||
|
||
async def aclose(self) -> None:
|
||
self.closed = True
|
||
|
||
def _fake_transport_factory(calls, behavior):
|
||
"""Returns a factory that creates FakeTransport instances."""
|
||
instances = []
|
||
|
||
def factory(**kwargs):
|
||
t = FakeTransport(calls, behavior)
|
||
instances.append(t)
|
||
return t
|
||
|
||
factory.instances = instances
|
||
return factory
|
||
|
||
def _telegram_request(path="/botTOKEN/getMe"):
|
||
return httpx.Request("GET", f"https://api.telegram.org{path}")
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# IP parsing & validation
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
class TestParseFallbackIpEnv:
|
||
def test_filters_invalid_and_ipv6(self):
|
||
ips = tnet.parse_fallback_ip_env("149.154.167.220, bad, 2001:67c:4e8:f004::9,149.154.167.220")
|
||
assert ips == ["149.154.167.220", "149.154.167.220"]
|
||
|
||
def test_none_returns_empty(self):
|
||
assert tnet.parse_fallback_ip_env(None) == []
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# Request rewriting
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
class TestRewriteRequestForIp:
|
||
def test_preserves_host_and_sni(self):
|
||
request = _telegram_request()
|
||
rewritten = tnet._rewrite_request_for_ip(request, "149.154.167.220")
|
||
|
||
assert rewritten.url.host == "149.154.167.220"
|
||
assert rewritten.headers["host"] == "api.telegram.org"
|
||
assert rewritten.extensions["sni_hostname"] == "api.telegram.org"
|
||
assert rewritten.url.path == "/botTOKEN/getMe"
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# Fallback transport – core behavior
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
class TestFallbackTransport:
|
||
"""IPv4 literals first → hostname last → stick to whichever works."""
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_ipv4_literal_tried_before_hostname_and_becomes_sticky(self, monkeypatch):
|
||
calls = []
|
||
behavior = {"api.telegram.org": "timeout", "149.154.167.220": "ok"}
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", _fake_transport_factory(calls, behavior))
|
||
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
|
||
resp = await transport.handle_async_request(_telegram_request())
|
||
|
||
assert resp.status_code == 200
|
||
assert transport._sticky_ip == "149.154.167.220"
|
||
assert [c["url_host"] for c in calls] == ["149.154.167.220"]
|
||
assert calls[0]["host_header"] == "api.telegram.org"
|
||
assert calls[0]["sni_hostname"] == "api.telegram.org"
|
||
|
||
# Second request goes straight to sticky IP
|
||
calls.clear()
|
||
resp2 = await transport.handle_async_request(_telegram_request())
|
||
assert resp2.status_code == 200
|
||
assert calls[0]["url_host"] == "149.154.167.220"
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_sticky_ip_tried_first_but_falls_through_if_stale(self, monkeypatch):
|
||
"""If the sticky IP stops working, the transport retries others."""
|
||
calls = []
|
||
behavior = {
|
||
"api.telegram.org": "timeout",
|
||
"149.154.167.220": "ok",
|
||
"149.154.167.221": "ok",
|
||
}
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", _fake_transport_factory(calls, behavior))
|
||
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220", "149.154.167.221"])
|
||
|
||
# First request: .220 works immediately (IPv4-first) → becomes sticky
|
||
await transport.handle_async_request(_telegram_request())
|
||
assert transport._sticky_ip == "149.154.167.220"
|
||
|
||
# Now .220 goes bad too
|
||
calls.clear()
|
||
behavior["149.154.167.220"] = "timeout"
|
||
|
||
resp = await transport.handle_async_request(_telegram_request())
|
||
assert resp.status_code == 200
|
||
# Sticky .220 fails → remaining IPv4 .221 works. Hostname is last
|
||
# and is never needed.
|
||
assert [c["url_host"] for c in calls] == ["149.154.167.220", "149.154.167.221"]
|
||
assert transport._sticky_ip == "149.154.167.221"
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_hostname_tried_last_when_ipv4_fails(self, monkeypatch):
|
||
"""IPv6-only / seed-IP-blocked hosts still reach the hostname last."""
|
||
calls = []
|
||
behavior = {"149.154.167.220": "timeout", "api.telegram.org": "ok"}
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", _fake_transport_factory(calls, behavior))
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
|
||
resp = await transport.handle_async_request(_telegram_request())
|
||
assert resp.status_code == 200
|
||
assert [c["url_host"] for c in calls] == ["149.154.167.220", "api.telegram.org"]
|
||
assert transport._sticky_ip is None
|
||
|
||
class TestFallbackTransportPassthrough:
|
||
"""Requests that don't need fallback behavior."""
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_non_telegram_host_bypasses_fallback(self, monkeypatch):
|
||
calls = []
|
||
behavior = {}
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", _fake_transport_factory(calls, behavior))
|
||
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
|
||
request = httpx.Request("GET", "https://example.com/path")
|
||
resp = await transport.handle_async_request(request)
|
||
|
||
assert resp.status_code == 200
|
||
assert calls[0]["url_host"] == "example.com"
|
||
assert transport._sticky_ip is tnet._UNSET
|
||
|
||
class TestFallbackTransportInit:
|
||
|
||
def test_uses_proxy_env_for_primary_and_fallback_transports(self, monkeypatch):
|
||
seen_kwargs = []
|
||
|
||
def factory(**kwargs):
|
||
seen_kwargs.append(kwargs.copy())
|
||
return FakeTransport([], {})
|
||
|
||
for key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy", "TELEGRAM_PROXY", "NO_PROXY", "no_proxy"):
|
||
monkeypatch.delenv(key, raising=False)
|
||
monkeypatch.setenv("HTTPS_PROXY", "http://proxy.example:8080")
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", factory)
|
||
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
|
||
|
||
assert transport._fallback_ips == ["149.154.167.220"]
|
||
# Fallback pools are now built lazily (#63311), so __init__ constructs
|
||
# only the primary transport. Force the fallback pool to materialize to
|
||
# observe its kwargs.
|
||
import asyncio
|
||
|
||
asyncio.run(transport._get_fallback("149.154.167.220"))
|
||
assert len(seen_kwargs) == 2
|
||
assert all(kwargs["proxy"] == "http://proxy.example:8080" for kwargs in seen_kwargs)
|
||
|
||
def test_no_proxy_bypasses_fallback_ip_cidr(self, monkeypatch):
|
||
seen_kwargs = []
|
||
|
||
def factory(**kwargs):
|
||
seen_kwargs.append(kwargs.copy())
|
||
return FakeTransport([], {})
|
||
|
||
for key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy", "TELEGRAM_PROXY", "NO_PROXY", "no_proxy"):
|
||
monkeypatch.delenv(key, raising=False)
|
||
monkeypatch.setenv("HTTPS_PROXY", "http://proxy.example:8080")
|
||
monkeypatch.setenv("NO_PROXY", "149.154.160.0/20")
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", factory)
|
||
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220"])
|
||
|
||
assert transport._fallback_ips == ["149.154.167.220"]
|
||
# Lazy fallback build (#63311): materialize the fallback pool.
|
||
import asyncio
|
||
|
||
asyncio.run(transport._get_fallback("149.154.167.220"))
|
||
assert len(seen_kwargs) == 2
|
||
assert all("proxy" not in kwargs for kwargs in seen_kwargs)
|
||
|
||
def test_forwards_limits_to_inner_transports(self, monkeypatch):
|
||
"""Verify that caller-supplied limits reach the inner
|
||
AsyncHTTPTransport instances (#58790). httpx ignores the
|
||
client-level limits kwarg when a custom transport is
|
||
supplied, so the limits must be forwarded via transport_kwargs.
|
||
"""
|
||
seen_kwargs = []
|
||
|
||
def factory(**kwargs):
|
||
seen_kwargs.append(kwargs.copy())
|
||
return FakeTransport([], {})
|
||
|
||
for key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy", "TELEGRAM_PROXY", "NO_PROXY", "no_proxy"):
|
||
monkeypatch.delenv(key, raising=False)
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", factory)
|
||
|
||
custom_limits = httpx.Limits(
|
||
max_connections=42,
|
||
max_keepalive_connections=10,
|
||
keepalive_expiry=30.0,
|
||
)
|
||
transport = tnet.TelegramFallbackTransport(
|
||
["149.154.167.220"], limits=custom_limits
|
||
)
|
||
|
||
# Lazy fallback build (#63311): __init__ builds only the primary; the
|
||
# fallback pool is constructed on demand. Materialize it so both the
|
||
# primary and the fallback are observed.
|
||
import asyncio
|
||
|
||
asyncio.run(transport._get_fallback("149.154.167.220"))
|
||
# 1 primary + 1 fallback = 2 AsyncHTTPTransport instances
|
||
assert len(seen_kwargs) == 2
|
||
for kw in seen_kwargs:
|
||
assert "limits" in kw
|
||
# Caller-supplied limits must win over the setdefault default.
|
||
assert kw["limits"] is custom_limits
|
||
assert "socket_options" in kw
|
||
assert any(
|
||
opt[0] == socket.SOL_SOCKET
|
||
and opt[1] == socket.SO_KEEPALIVE
|
||
and opt[2] == 1
|
||
for opt in kw["socket_options"]
|
||
)
|
||
|
||
class TestFallbackTransportClose:
|
||
@pytest.mark.asyncio
|
||
async def test_aclose_closes_all_transports(self, monkeypatch):
|
||
factory = _fake_transport_factory([], {})
|
||
monkeypatch.setattr(tnet.httpx, "AsyncHTTPTransport", factory)
|
||
|
||
transport = tnet.TelegramFallbackTransport(["149.154.167.220", "149.154.167.221"])
|
||
# Lazy fallback build (#63311): materialize both fallback pools so
|
||
# aclose() has something to tear down.
|
||
await transport._get_fallback("149.154.167.220")
|
||
await transport._get_fallback("149.154.167.221")
|
||
await transport.aclose()
|
||
|
||
# 1 primary + 2 fallback transports
|
||
assert len(factory.instances) == 3
|
||
assert all(t.closed for t in factory.instances)
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# Config layer – TELEGRAM_FALLBACK_IPS env → config.extra
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
class TestConfigFallbackIps:
|
||
def test_env_var_populates_config_extra(self, monkeypatch):
|
||
from gateway.config import GatewayConfig, Platform, PlatformConfig, _apply_env_overrides
|
||
|
||
monkeypatch.setenv("TELEGRAM_FALLBACK_IPS", "149.154.167.220,149.154.167.221")
|
||
config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="tok")})
|
||
_apply_env_overrides(config)
|
||
|
||
assert config.platforms[Platform.TELEGRAM].extra["fallback_ips"] == [
|
||
"149.154.167.220", "149.154.167.221",
|
||
]
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# Adapter layer – _fallback_ips() reads config correctly
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
class TestAdapterFallbackIps:
|
||
def _make_adapter(self, extra=None):
|
||
import sys
|
||
from unittest.mock import MagicMock
|
||
|
||
# Ensure telegram mock is in place
|
||
if "telegram" not in sys.modules or not hasattr(sys.modules["telegram"], "__file__"):
|
||
mod = MagicMock()
|
||
mod.ext.ContextTypes.DEFAULT_TYPE = type(None)
|
||
mod.constants.ParseMode.MARKDOWN_V2 = "MarkdownV2"
|
||
mod.constants.ChatType.GROUP = "group"
|
||
mod.constants.ChatType.SUPERGROUP = "supergroup"
|
||
mod.constants.ChatType.CHANNEL = "channel"
|
||
mod.constants.ChatType.PRIVATE = "private"
|
||
for name in ("telegram", "telegram.ext", "telegram.constants", "telegram.request"):
|
||
sys.modules.setdefault(name, mod)
|
||
|
||
from gateway.config import PlatformConfig
|
||
from plugins.platforms.telegram.adapter import TelegramAdapter
|
||
|
||
config = PlatformConfig(enabled=True, token="test-token")
|
||
if extra:
|
||
config.extra.update(extra)
|
||
return TelegramAdapter(config)
|
||
|
||
def test_list_in_extra(self):
|
||
adapter = self._make_adapter(extra={"fallback_ips": ["149.154.167.220"]})
|
||
assert adapter._fallback_ips() == ["149.154.167.220"]
|
||
|
||
def test_csv_string_in_extra(self):
|
||
adapter = self._make_adapter(extra={"fallback_ips": "149.154.167.220,149.154.167.221"})
|
||
assert adapter._fallback_ips() == ["149.154.167.220", "149.154.167.221"]
|
||
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
# DoH auto-discovery
|
||
# ═══════════════════════════════════════════════════════════════════════════
|
||
|
||
def _doh_answer(*ips: str) -> dict:
|
||
"""Build a minimal DoH JSON response with A records."""
|
||
return {"Answer": [{"type": 1, "data": ip} for ip in ips]}
|
||
|
||
class FakeDoHClient:
|
||
"""Mock httpx.AsyncClient for DoH queries."""
|
||
|
||
def __init__(self, responses: dict):
|
||
# responses: URL prefix → (status, json_body) | Exception
|
||
self._responses = responses
|
||
self.requests_made: list[dict] = []
|
||
|
||
@staticmethod
|
||
def _make_response(status, body, url):
|
||
"""Build an httpx.Response with a request attached (needed for raise_for_status)."""
|
||
request = httpx.Request("GET", url)
|
||
return httpx.Response(status, json=body, request=request)
|
||
|
||
async def get(self, url, *, params=None, headers=None, **kwargs):
|
||
self.requests_made.append({"url": url, "params": params, "headers": headers})
|
||
for prefix, action in self._responses.items():
|
||
if url.startswith(prefix):
|
||
if isinstance(action, Exception):
|
||
raise action
|
||
status, body = action
|
||
return self._make_response(status, body, url)
|
||
return self._make_response(200, {}, url)
|
||
|
||
async def __aenter__(self):
|
||
return self
|
||
|
||
async def __aexit__(self, *args):
|
||
pass
|
||
|
||
class TestDiscoverFallbackIps:
|
||
"""Tests for discover_fallback_ips() — DoH-based auto-discovery."""
|
||
|
||
def _patch_doh(self, monkeypatch, responses, system_dns_ips=None):
|
||
"""Wire up fake DoH client and system DNS."""
|
||
client = FakeDoHClient(responses)
|
||
monkeypatch.setattr(tnet.httpx, "AsyncClient", lambda **kw: client)
|
||
|
||
if system_dns_ips is not None:
|
||
addrs = [(None, None, None, None, (ip, 443)) for ip in system_dns_ips]
|
||
monkeypatch.setattr(tnet.socket, "getaddrinfo", lambda *a, **kw: addrs)
|
||
else:
|
||
def _fail(*a, **kw):
|
||
raise OSError("dns failed")
|
||
monkeypatch.setattr(tnet.socket, "getaddrinfo", _fail)
|
||
return client
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_google_and_cloudflare_ips_collected(self, monkeypatch):
|
||
self._patch_doh(monkeypatch, {
|
||
"https://dns.google": (200, _doh_answer("149.154.167.220")),
|
||
"https://cloudflare-dns.com": (200, _doh_answer("149.154.167.221")),
|
||
}, system_dns_ips=["149.154.166.110"])
|
||
|
||
ips = await tnet.discover_fallback_ips()
|
||
assert "149.154.167.220" in ips
|
||
assert "149.154.167.221" in ips
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_system_dns_ip_kept_when_doh_confirms(self, monkeypatch):
|
||
"""DoH-confirmed IPs are kept even when they match system DNS (#14520).
|
||
|
||
The system-DNS IP is often the most reliable path; including it as a
|
||
fallback lets the IP-rewrite retry recover from transient primary-path
|
||
failures instead of jumping straight to the hardcoded seed list.
|
||
"""
|
||
self._patch_doh(monkeypatch, {
|
||
"https://dns.google": (200, _doh_answer("149.154.166.110", "149.154.167.220")),
|
||
"https://cloudflare-dns.com": (200, _doh_answer("149.154.166.110")),
|
||
}, system_dns_ips=["149.154.166.110"])
|
||
|
||
ips = await tnet.discover_fallback_ips()
|
||
assert ips == ["149.154.166.110", "149.154.167.220"]
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_doh_results_deduplicated(self, monkeypatch):
|
||
self._patch_doh(monkeypatch, {
|
||
"https://dns.google": (200, _doh_answer("149.154.167.220")),
|
||
"https://cloudflare-dns.com": (200, _doh_answer("149.154.167.220")),
|
||
}, system_dns_ips=["149.154.166.110"])
|
||
|
||
ips = await tnet.discover_fallback_ips()
|
||
assert ips == ["149.154.167.220"]
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_all_doh_ips_same_as_system_dns_kept(self, monkeypatch):
|
||
"""DoH agrees with system DNS — keep that IP instead of seed list (#14520).
|
||
|
||
Previous behavior fell through to ``_SEED_FALLBACK_IPS`` here, but the
|
||
seed addresses are not routable on every network. When DoH confirms
|
||
the system IP, that IP is the best candidate we have and should be
|
||
used as the fallback target.
|
||
"""
|
||
self._patch_doh(monkeypatch, {
|
||
"https://dns.google": (200, _doh_answer("149.154.166.110")),
|
||
"https://cloudflare-dns.com": (200, _doh_answer("149.154.166.110")),
|
||
}, system_dns_ips=["149.154.166.110"])
|
||
|
||
ips = await tnet.discover_fallback_ips()
|
||
assert ips == ["149.154.166.110"]
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_hung_system_dns_does_not_gate_doh_results(self, monkeypatch):
|
||
"""#63309: socket.getaddrinfo has no timeout of its own — a wedged OS
|
||
resolver must not stall discovery. DoH answers must come back promptly
|
||
even while the system-DNS worker thread is still hanging."""
|
||
import time as _time
|
||
|
||
self._patch_doh(monkeypatch, {
|
||
"https://dns.google": (200, _doh_answer("149.154.167.220")),
|
||
"https://cloudflare-dns.com": (200, _doh_answer()),
|
||
}, system_dns_ips=["149.154.166.110"])
|
||
monkeypatch.setattr(tnet, "_DOH_TIMEOUT", 0.2)
|
||
|
||
def _hung_getaddrinfo(*a, **kw):
|
||
_time.sleep(0.2) # far beyond the discovery bound
|
||
raise OSError("resolver wedged")
|
||
|
||
monkeypatch.setattr(tnet.socket, "getaddrinfo", _hung_getaddrinfo)
|
||
|
||
start = _time.monotonic()
|
||
ips = await tnet.discover_fallback_ips()
|
||
elapsed = _time.monotonic() - start
|
||
|
||
assert ips == ["149.154.167.220"]
|
||
assert elapsed < 1.4, f"discovery gated on hung system DNS ({elapsed:.2f}s)"
|