"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(channels): add connection-test hook and harden the DingTalk adapter
shadowinlife9d8d7171a09a
diff --git a/agent/src/channels/base.py b/agent/src/channels/base.pyindex 2cb6b4464..c7367f1d9 100644--- a/agent/src/channels/base.py+++ b/agent/src/channels/base.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport loggingfrom abc import ABC, abstractmethod-from typing import Any+from typing import Any, ClassVarfrom src.channels.bus.events import DeliveryReceipt, InboundMessage, OutboundMessagefrom src.channels.bus.queue import MessageBus@@ -31,6 +31,8 @@ class BaseChannel(ABC):send_tool_hints: bool = Falseshow_reasoning: bool = True+ supports_connection_test: ClassVar[bool] = False+def __init__(self, config: Any, bus: MessageBus) -> None:"""Initialize the channel.@@ -54,6 +56,20 @@ class BaseChannel(ABC):"""return True+ async def test_connection(self) -> dict[str, Any]:+ """Probe this channel's credentials without starting it.++ Default implementation reports ``unsupported``; adapters that can+ validate credentials against a standalone endpoint override this and set+ :attr:`supports_connection_test` to True.++ Returns:+ A JSON-serializable envelope with a boolean ``ok`` and a string+ ``code`` of ``ok`` / ``invalid_credentials`` / ``network`` /+ ``unsupported``.+ """+ return {"ok": False, "code": "unsupported"}+@abstractmethodasync def start(self) -> None:"""Start the channel and begin listening for messages.diff --git a/agent/src/channels/dingtalk.py b/agent/src/channels/dingtalk.pyindex d0a53db79..874bf3396 100644--- a/agent/src/channels/dingtalk.py+++ b/agent/src/channels/dingtalk.py@@ -23,6 +23,7 @@ from src.security.network import validate_resolved_url, validate_url_targetDINGTALK_MAX_REMOTE_MEDIA_BYTES = 20 * 1024 * 1024DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS = 3+DINGTALK_ACCESS_TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"try:from dingtalk_stream import (@@ -174,6 +175,19 @@ class DingTalkConfig(BaseModel):allow_remote_media_redirects: bool = Falseremote_media_redirect_allowed_hosts: list[str] = Field(default_factory=list)group_user_isolation: bool = False # If True, each user in group chat gets their own session+ force_ipv4: bool = False # Bind outbound API calls to IPv4 (stable egress IP for app IP whitelists)+++def _build_http_transport(config: "DingTalkConfig") -> httpx.AsyncHTTPTransport | None:+ """Return an IPv4-bound transport when ``force_ipv4`` is set, else None.++ DingTalk's robot-send API enforces the app's egress-IP whitelist; on+ dual-stack networks the rotating IPv6 prefix keeps falling out of it, so+ operators can pin the egress to the (typically stable) IPv4 address.+ """+ if config.force_ipv4:+ return httpx.AsyncHTTPTransport(local_address="0.0.0.0")+ return Noneclass DingTalkChannel(BaseChannel):@@ -189,6 +203,7 @@ class DingTalkChannel(BaseChannel):name = "dingtalk"display_name = "DingTalk"+ supports_connection_test = True_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}_AUDIO_EXTS = {".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac"}_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}@@ -205,6 +220,7 @@ class DingTalkChannel(BaseChannel):self.config: DingTalkConfig = configself._client: Any = Noneself._http: httpx.AsyncClient | None = None+ self._stream_task: asyncio.Task | None = None# Access Token management for sending messagesself._access_token: str | None = None@@ -227,8 +243,10 @@ class DingTalkChannel(BaseChannel):returnself._running = True+ self._stream_task = asyncio.current_task()self._http = httpx.AsyncClient(- timeout=httpx.Timeout(10.0, connect=10.0, read=30.0, write=30.0, pool=10.0)+ timeout=httpx.Timeout(10.0, connect=10.0, read=30.0, write=30.0, pool=10.0),+ transport=_build_http_transport(self.config),)self.logger.info(@@ -260,6 +278,7 @@ class DingTalkChannel(BaseChannel):async def stop(self) -> None:"""Stop the DingTalk bot."""self._running = False+ await self._cancel_stream_task()# Close the shared HTTP clientif self._http:await self._http.aclose()@@ -269,6 +288,26 @@ class DingTalkChannel(BaseChannel):task.cancel()self._background_tasks.clear()+ async def _cancel_stream_task(self) -> None:+ """Terminate the Stream Mode task.++ The SDK ``start()`` loop catches the first ``CancelledError`` and+ sleeps before reconnecting, so a second cancellation is delivered+ during that sleep; otherwise a stopped channel keeps a zombie+ WebSocket that fights the replacement instance for the gateway.+ """+ task = self._stream_task+ self._stream_task = None+ if task is None or task.done() or task is asyncio.current_task():+ return+ task.cancel()+ await asyncio.sleep(0.05)+ if not task.done():+ task.cancel()+ done, _ = await asyncio.wait({task}, timeout=5)+ if not done:+ self.logger.warning("Stream task survived cancellation; connection may linger")+async def _get_access_token(self) -> str | None:"""Get or refresh Access Token."""if self._access_token and time.time() < self._token_expiry:@@ -296,6 +335,88 @@ class DingTalkChannel(BaseChannel):self.logger.exception("Failed to get access token")return None+ def _scrub_detail(self, text: str) -> str:+ """Return diagnostic text with any credential value replaced.++ Transport and rejection messages can echo the request or credential by+ accident; every value this channel holds as a secret is masked before the+ text reaches a result envelope.+ """+ cleaned = text+ for secret in (self.config.client_secret, self.config.client_id):+ if secret:+ cleaned = cleaned.replace(secret, "***")+ return cleaned++ @staticmethod+ def _response_detail(resp: httpx.Response) -> str:+ """Return a bounded ``HTTP <status>`` detail without echoing secrets."""+ body = (resp.text or "").strip()+ if not body:+ return f"HTTP {resp.status_code}"+ return f"HTTP {resp.status_code}: {body[:200]}"++ async def test_connection(self) -> dict[str, Any]:+ """Validate the DingTalk credentials with a standalone token request.++ Uses a fresh ``httpx.AsyncClient`` rather than ``self._http`` (which only+ exists after :meth:`start`), so an unsaved credential set can be checked+ before the channel is started. A successful access token is discarded: it+ is never returned, logged, or cached.++ Returns:+ A JSON-serializable envelope with ``ok`` and a ``code`` of ``ok`` /+ ``invalid_credentials`` / ``network``, plus an ``sdk_available``+ flag. Any ``detail`` is scrubbed of credential values.+ """+ if not self.config.client_id or not self.config.client_secret:+ return {"ok": False, "code": "invalid_credentials", "detail": "missing credentials"}++ payload = {"appKey": self.config.client_id, "appSecret": self.config.client_secret}++ try:+ async with httpx.AsyncClient(+ timeout=httpx.Timeout(10.0, connect=10.0),+ transport=_build_http_transport(self.config),+ ) as client:+ resp = await client.post(DINGTALK_ACCESS_TOKEN_URL, json=payload)+ except httpx.HTTPError as exc:+ return {+ "ok": False,+ "code": "network",+ "detail": self._scrub_detail(str(exc) or type(exc).__name__),+ "sdk_available": DINGTALK_AVAILABLE,+ }++ if resp.status_code == 200:+ try:+ access_token = resp.json().get("accessToken")+ except ValueError:+ access_token = None+ if not access_token:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "no access token in response",+ "sdk_available": DINGTALK_AVAILABLE,+ }+ return {"ok": True, "code": "ok", "sdk_available": DINGTALK_AVAILABLE}++ if 400 <= resp.status_code < 500:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": self._scrub_detail(self._response_detail(resp)),+ "sdk_available": DINGTALK_AVAILABLE,+ }++ return {+ "ok": False,+ "code": "network",+ "detail": self._scrub_detail(self._response_detail(resp)),+ "sdk_available": DINGTALK_AVAILABLE,+ }+@staticmethoddef _is_http_url(value: str) -> bool:return urlparse(value).scheme in ("http", "https")@@ -722,6 +843,7 @@ class DingTalkChannel(BaseChannel):"conversation_type": conversation_type,},session_key=session_key,+ is_dm=not is_group,)except Exception:self.logger.exception("Error publishing message")diff --git a/agent/tests/test_dingtalk_connection_test.py b/agent/tests/test_dingtalk_connection_test.pynew file mode 100644index 000000000..7330da26e--- /dev/null+++ b/agent/tests/test_dingtalk_connection_test.py@@ -0,0 +1,330 @@+"""Connection-test contract for IM channels.++Task 2 of the web IM channel-config plan: the base channel exposes a generic+``test_connection`` hook (default ``unsupported``), and DingTalk implements a+standalone credential probe that never touches ``self._http`` (which only exists+after ``start()``). The contract codes the frontend dispatches on are+``ok | invalid_credentials | network | unsupported`` plus an ``sdk_available``+flag, and no credential or token value may ever leak into the result or logs.+"""++from __future__ import annotations++import asyncio+import importlib+import json+import logging+from typing import Any++import httpx+import pytest++from src.channels.base import BaseChannel+from src.channels.bus.queue import MessageBus+from src.channels.dingtalk import DINGTALK_AVAILABLE, DingTalkChannel++TOKEN_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"+CLIENT_ID = "ding-client-id-1234567890"+CLIENT_SECRET = "ding-client-secret-abcdefghij"+ACCESS_TOKEN = "fresh-access-token-value-do-not-leak"++# Captured before any test monkeypatches the class, so repeated injections in a+# single test still wrap the real client instead of the previous factory.+_REAL_ASYNC_CLIENT = httpx.AsyncClient++# Other adapters whose *default* ``test_connection`` must report ``unsupported``.+# Modules whose optional SDK is absent are skipped at runtime rather than+# removed from the parametrization, so coverage grows wherever deps are installed.+_DEFAULT_CHANNEL_CANDIDATES: list[tuple[str, str]] = [+ ("src.channels.discord", "DiscordChannel"),+ ("src.channels.telegram", "TelegramChannel"),+ ("src.channels.slack", "SlackChannel"),+ ("src.channels.feishu", "FeishuChannel"),+ ("src.channels.wecom", "WecomChannel"),+]+++def _make_channel(+ client_id: str = CLIENT_ID,+ client_secret: str = CLIENT_SECRET,+) -> DingTalkChannel:+ """Build a DingTalk channel that has NOT been started (no ``self._http``)."""+ return DingTalkChannel(+ {"client_id": client_id, "client_secret": client_secret},+ MessageBus(),+ )+++def _inject_mock_transport(+ monkeypatch: pytest.MonkeyPatch,+ handler: "Any",+) -> list[httpx.Request]:+ """Route the probe's fresh ``httpx.AsyncClient`` through a MockTransport.++ The probe owns its client, so the only seam is the client class itself. The+ real class is kept and a ``transport`` is supplied, so every other client+ behaviour (timeout argument, context-manager close) still runs for real.+ """+ requests: list[httpx.Request] = []++ def recording_handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return handler(request)++ transport = httpx.MockTransport(recording_handler)+ real_client_cls = _REAL_ASYNC_CLIENT++ def factory(*args: Any, **kwargs: Any) -> httpx.AsyncClient:+ kwargs["transport"] = transport+ return real_client_cls(*args, **kwargs)++ monkeypatch.setattr(httpx, "AsyncClient", factory)+ return requests+++def _run(coro: Any) -> Any:+ return asyncio.run(coro)+++# --------------------------------------------------------------------------- #+# BaseChannel default hook+# --------------------------------------------------------------------------- #+++def test_base_channel_declares_no_connection_test() -> None:+ assert BaseChannel.supports_connection_test is False+++def test_base_channel_default_returns_unsupported() -> None:+ class _Probe(BaseChannel):+ async def start(self) -> None: # pragma: no cover - abstract filler+ return None++ async def stop(self) -> None: # pragma: no cover - abstract filler+ return None++ async def send(self, msg: Any) -> None: # pragma: no cover - filler+ return None++ result = _run(_Probe({}, MessageBus()).test_connection())++ assert result == {"ok": False, "code": "unsupported"}++[email protected](("module_name", "class_name"), _DEFAULT_CHANNEL_CANDIDATES)+def test_other_adapters_default_to_unsupported(+ module_name: str,+ class_name: str,+) -> None:+ try:+ module = importlib.import_module(module_name)+ except ModuleNotFoundError as exc: # optional SDK not installed here+ pytest.skip(f"{module_name} dependency unavailable: {exc}")++ channel_cls = getattr(module, class_name)+ assert channel_cls.supports_connection_test is False++ channel = channel_cls({}, MessageBus())+ result = _run(channel.test_connection())++ assert result == {"ok": False, "code": "unsupported"}+++# --------------------------------------------------------------------------- #+# DingTalk standalone probe — success+# --------------------------------------------------------------------------- #+++def test_success_returns_ok_and_discards_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ assert str(request.url) == TOKEN_URL+ assert request.method == "POST"+ assert json.loads(request.content.decode("utf-8")) == {+ "appKey": CLIENT_ID,+ "appSecret": CLIENT_SECRET,+ }+ return httpx.Response(+ 200,+ json={"accessToken": ACCESS_TOKEN, "expireIn": 7200},+ )++ requests = _inject_mock_transport(monkeypatch, handler)+ channel = _make_channel()++ result = _run(channel.test_connection())++ assert len(requests) == 1+ assert result["ok"] is True+ assert result["code"] == "ok"+ assert result["sdk_available"] is DINGTALK_AVAILABLE+ # The probe is standalone: it must not have created the shared client.+ assert channel._http is None+ # The token and secret are discarded, never returned.+ serialized = json.dumps(result)+ assert ACCESS_TOKEN not in serialized+ assert CLIENT_SECRET not in serialized+++def test_success_uses_fresh_client_even_when_shared_client_present(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A started channel's ``_http`` must not be reused by the probe."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"accessToken": ACCESS_TOKEN})++ requests = _inject_mock_transport(monkeypatch, handler)+ channel = _make_channel()+ sentinel = object()+ channel._http = sentinel # pretend start() ran++ result = _run(channel.test_connection())++ assert result["ok"] is True+ assert len(requests) == 1+ assert channel._http is sentinel+++# --------------------------------------------------------------------------- #+# DingTalk standalone probe — invalid credentials+# --------------------------------------------------------------------------- #++[email protected]("status", [400, 401, 403])+def test_http_client_error_reports_invalid_credentials(+ monkeypatch: pytest.MonkeyPatch,+ status: int,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(status, json={"message": "invalid appKey/appSecret"})++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["sdk_available"] is DINGTALK_AVAILABLE+ assert "detail" in result+ assert CLIENT_SECRET not in json.dumps(result)+ assert ACCESS_TOKEN not in json.dumps(result)+++def test_missing_token_in_ok_response_reports_invalid_credentials(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"message": "no token for you"})++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert CLIENT_SECRET not in json.dumps(result)+++ ("client_id", "client_secret"),+ [("", ""), (CLIENT_ID, ""), ("", CLIENT_SECRET)],+)+def test_missing_credentials_short_circuit_without_network(+ monkeypatch: pytest.MonkeyPatch,+ client_id: str,+ client_secret: str,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover+ raise AssertionError("no network call may happen without credentials")++ requests = _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel(client_id, client_secret).test_connection())++ assert requests == []+ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["detail"] == "missing credentials"+++# --------------------------------------------------------------------------- #+# DingTalk standalone probe — network+# --------------------------------------------------------------------------- #+++def test_transport_error_reports_network(monkeypatch: pytest.MonkeyPatch) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("connection refused")++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "network"+ assert result["sdk_available"] is DINGTALK_AVAILABLE+ assert CLIENT_SECRET not in json.dumps(result)++[email protected]("status", [500, 502, 503])+def test_server_error_reports_network(+ monkeypatch: pytest.MonkeyPatch,+ status: int,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(status, text="upstream exploded")++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "network"+++# --------------------------------------------------------------------------- #+# Secret hygiene+# --------------------------------------------------------------------------- #+++def test_probe_never_logs_secret_or_token(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ def ok_handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"accessToken": ACCESS_TOKEN})++ _inject_mock_transport(monkeypatch, ok_handler)+ with caplog.at_level(logging.DEBUG):+ success = _run(_make_channel().test_connection())++ def reject_handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"bad secret {CLIENT_SECRET}")++ _inject_mock_transport(monkeypatch, reject_handler)+ with caplog.at_level(logging.DEBUG):+ failure = _run(_make_channel().test_connection())++ assert success["code"] == "ok"+ assert failure["code"] == "invalid_credentials"+ assert CLIENT_SECRET not in caplog.text+ assert ACCESS_TOKEN not in caplog.text+ # And the rejection body's echoed secret is scrubbed from the detail too.+ assert CLIENT_SECRET not in json.dumps(failure)+++def test_rejection_detail_scrubs_echoed_secret(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"appSecret {CLIENT_SECRET} is invalid")++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["code"] == "invalid_credentials"+ assert CLIENT_SECRET not in json.dumps(result)+ assert "detail" in resultdiff --git a/agent/tests/test_dingtalk_message_flow.py b/agent/tests/test_dingtalk_message_flow.pynew file mode 100644index 000000000..8a4163592--- /dev/null+++ b/agent/tests/test_dingtalk_message_flow.py@@ -0,0 +1,122 @@+"""Regression tests for DingTalk inbound routing and stream task shutdown.++Covers two production defects found during live QA:+- ``_on_message`` never forwarded ``is_dm``, so unapproved DMs logged+ "Access denied" instead of receiving a pairing code.+- ``stop()`` never terminated the SDK stream loop (which swallows the first+ ``CancelledError``), leaving a zombie WebSocket after disable/hot-swap.+"""++from __future__ import annotations++import asyncio+from typing import Any++import pytest++from src.channels.bus.queue import MessageBus+from src.channels.dingtalk import DingTalkChannel+++def _make_channel() -> DingTalkChannel:+ return DingTalkChannel({"client_id": "cid", "client_secret": "sec"}, MessageBus())+++def _record_handle(channel: DingTalkChannel) -> list[dict[str, Any]]:+ recorded: list[dict[str, Any]] = []++ async def fake_handle(**kwargs: Any) -> None:+ recorded.append(kwargs)++ channel._handle_message = fake_handle+ return recorded+++def test_dm_message_is_flagged_as_dm() -> None:+ async def scenario() -> None:+ channel = _make_channel()+ recorded = _record_handle(channel)++ await channel._on_message("hello", "264099", "Alice", "1", None)++ assert recorded[0]["is_dm"] is True+ assert recorded[0]["chat_id"] == "264099"++ asyncio.run(scenario())+++def test_group_message_is_not_dm_and_uses_group_chat_id() -> None:+ async def scenario() -> None:+ channel = _make_channel()+ recorded = _record_handle(channel)++ await channel._on_message("hello", "264099", "Alice", "2", "cidXYZ")++ assert recorded[0]["is_dm"] is False+ assert recorded[0]["chat_id"] == "group:cidXYZ"++ asyncio.run(scenario())+++def test_stop_terminates_cancel_swallowing_stream_task() -> None:+ """The SDK start loop swallows one CancelledError; stop must still kill it."""++ async def scenario() -> None:+ channel = _make_channel()++ async def sdk_like_loop() -> None:+ while True:+ try:+ await asyncio.sleep(30)+ except asyncio.CancelledError:+ await asyncio.sleep(30)++ task = asyncio.create_task(sdk_like_loop())+ await asyncio.sleep(0)+ channel._stream_task = task++ await channel.stop()++ assert task.done()+ assert task.cancelled()++ asyncio.run(scenario())+++def test_stop_without_stream_task_is_safe() -> None:+ async def scenario() -> None:+ channel = _make_channel()++ await channel.stop()++ assert channel._stream_task is None+ assert channel.is_running is False++ asyncio.run(scenario())+++def test_force_ipv4_binds_transport_to_ipv4(monkeypatch: pytest.MonkeyPatch) -> None:+ """DingTalk's send API enforces the app egress-IP whitelist; force_ipv4 pins it."""+ import httpx++ from src.channels import dingtalk as dingtalk_mod++ captured: list[dict[str, Any]] = []+ real_transport_cls = httpx.AsyncHTTPTransport++ def spy(**kwargs: Any) -> Any:+ captured.append(kwargs)+ return real_transport_cls(**kwargs)++ monkeypatch.setattr(httpx, "AsyncHTTPTransport", spy)++ pinned = DingTalkChannel(+ {"client_id": "cid", "client_secret": "sec", "force_ipv4": True}, MessageBus()+ )+ transport = dingtalk_mod._build_http_transport(pinned.config)+ assert transport is not None+ assert captured == [{"local_address": "0.0.0.0"}]++ default = _make_channel()+ assert dingtalk_mod._build_http_transport(default.config) is None+ assert len(captured) == 1