"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(channels): add Discord connection test for the bot token
shadowinlife46a9382956e0
diff --git a/agent/src/channels/discord.py b/agent/src/channels/discord.pyindex df740799c..c12b3cbc7 100644--- a/agent/src/channels/discord.py+++ b/agent/src/channels/discord.py@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, Literalfrom pydantic import Field+from src.channels import discord_probefrom src.channels.bus.events import OutboundMessagefrom src.channels.bus.queue import MessageBusfrom src.channels.base import BaseChannel@@ -355,6 +356,7 @@ class DiscordChannel(BaseChannel):name = "discord"display_name = "Discord"+ supports_connection_test = Truedelivery_target_label = "Discord channel"delivery_target_kind = "channel"delivery_target_placeholder = "Channel ID"@@ -476,6 +478,19 @@ class DiscordChannel(BaseChannel):self._running = Falseawait self._reset_runtime_state(close_client=True)+ async def test_connection(self) -> dict[str, Any]:+ """Validate the Discord bot token with a standalone REST probe.++ Delegates to :func:`src.channels.discord_probe.test_connection`; see+ that function for the full contract. ``sdk_available`` passes the real+ ``DISCORD_AVAILABLE`` guard (unlike slack's constant ``True``): this+ module imports the ``discord`` SDK conditionally, so the probe works+ — and reports SDK availability honestly — even without it.+ """+ return await discord_probe.test_connection(+ self.config, sdk_available=DISCORD_AVAILABLE+ )+async def send(self, msg: OutboundMessage) -> None:"""Send a message through Discord using discord.py."""client = self._clientdiff --git a/agent/src/channels/discord_probe.py b/agent/src/channels/discord_probe.pynew file mode 100644index 000000000..7a8b667ca--- /dev/null+++ b/agent/src/channels/discord_probe.py@@ -0,0 +1,89 @@+"""Standalone Discord credential probe, mirroring ``slack_probe.py``.++The probe validates a (possibly unsaved) bot token with a single request+to the Discord REST API without touching the channel's ``discord.py``+client. Everything here is stateless: functions take the ``DiscordConfig``+explicitly so the module never imports the adapter at runtime (only under+``TYPE_CHECKING``) — ``discord.py`` guards the heavy ``discord`` SDK behind+``DISCORD_AVAILABLE``, and a credential check never needs it.+``sdk_available`` is still threaded through so the caller's envelope+carries it unchanged (the adapter passes the real ``DISCORD_AVAILABLE``+flag; see the delegate in ``discord.py``). The request/classification+logic lives in :mod:`src.channels.token_probe`, the shared building block+for token-endpoint probes.++Discord authenticates via an ``Authorization: Bot`` header rather than a+JSON body, so the leg passes the shared probe's optional ``headers`` with+``method="GET"`` and an empty payload. ``token_key="bot"`` is deliberate:+a valid bot token returns the bot's user object carrying ``"bot": true``,+while a pasted OAuth *user* token answers HTTP 200 WITHOUT the flag — the+shared "200 but token_key missing/falsy" branch classifies that as+``invalid_credentials``, catching the wrong-token-type failure at probe+time (a user token cannot open a bot gateway session, so it would+otherwise only fail later at ``start()``). The success body (bot username,+id) is credential-adjacent: the shared probe keeps nothing but+``ok``/``code`` from a success body, so it is never returned, logged, or+cached — the same guarantee ``slack_probe.py`` relies on for the+``wss://`` URL.++Scope note: privileged-intent enablement (e.g. MESSAGE CONTENT INTENT) is+NOT probeable via REST — it only surfaces at gateway IDENTIFY (close code+4014) — so this probe deliberately does not attempt a gateway/WebSocket+leg; the Web UI setup guide covers the intent switches instead.++A missing token short-circuits before any HTTP call, mirroring the+``start()`` guard in ``discord.py`` (``if not self.config.token`` → logs+"bot token not configured" and returns without connecting).+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from src.channels.token_probe import probe_token_endpoint++if TYPE_CHECKING:+ from src.channels.discord import DiscordConfig++DISCORD_USERS_ME_URL = "https://discord.com/api/v10/users/@me"+++async def test_connection(+ config: DiscordConfig, *, sdk_available: bool+) -> dict[str, Any]:+ """Validate the Discord bot token with a standalone REST probe.++ Uses a fresh ``httpx.AsyncClient`` request rather than the channel's+ ``discord.py`` client (which only exists after+ :meth:`DiscordChannel.start`), so an unsaved credential set can be+ checked before the channel is started. A successful response carries+ the bot's user object; it is discarded: never returned, logged, or+ cached.++ Args:+ config: The Discord credential set to validate.+ sdk_available: Whether the optional ``discord`` SDK imported;+ echoed back so the caller's envelope carries it unchanged.++ 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 the token value.+ """+ if not config.token:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "missing bot token",+ "sdk_available": sdk_available,+ }++ return await probe_token_endpoint(+ url=DISCORD_USERS_ME_URL,+ payload={},+ method="GET",+ headers={"Authorization": f"Bot {config.token}"},+ token_key="bot",+ secrets=(config.token,),+ sdk_available=sdk_available,+ )diff --git a/agent/src/channels/registry.py b/agent/src/channels/registry.pyindex 51efaaf8a..8bca4e2ed 100644--- a/agent/src/channels/registry.py+++ b/agent/src/channels/registry.py@@ -27,6 +27,7 @@ _INTERNAL = frozenset("config_meta","dingtalk_media","dingtalk_probe",+ "discord_probe","email_probe","feishu_probe","manager",diff --git a/agent/src/channels/token_probe.py b/agent/src/channels/token_probe.pyindex f65138753..0d6f6fb26 100644--- a/agent/src/channels/token_probe.py+++ b/agent/src/channels/token_probe.py@@ -13,9 +13,9 @@ returned, logged, or cached.Adding another token-endpoint channel (checklist):-1. ``<name>_probe.py``: endpoint URL, payload shape, ``token_key``; import- the adapter's config type under ``TYPE_CHECKING`` only, so a credential- check never pulls the channel's SDK.+1. ``<name>_probe.py``: endpoint URL, HTTP method, payload shape,+ ``token_key``; import the adapter's config type under ``TYPE_CHECKING``+ only, so a credential check never pulls the channel's SDK.2. ``registry._INTERNAL``: add ``"<name>_probe"`` so channel discovery keepstreating the module as internal rather than as an adapter.3. Adapter: ``supports_connection_test = True`` plus a thin@@ -75,6 +75,7 @@ async def probe_token_endpoint(secrets: Sequence[str],sdk_available: bool,headers: dict[str, str] | None = None,+ method: str = "POST",transport: httpx.AsyncHTTPTransport | None = None,timeout: float = 10.0,) -> dict[str, Any]:@@ -85,14 +86,17 @@ async def probe_token_endpoint(A successful token is discarded: it is never returned, logged, or cached.Args:- url: The token endpoint to POST to.- payload: JSON body carrying the credentials.+ url: The token endpoint to request.+ payload: JSON body carrying the credentials; not sent on ``"GET"``.token_key: Response field whose truthy value means success.secrets: Credential values to scrub from every ``detail``.sdk_available: Whether the channel's optional SDK imported; echoedback so the caller's envelope carries it unchanged.headers: Optional request headers for endpoints that authenticateoutside the JSON body (e.g. Slack's ``Authorization: Bearer``).+ method: HTTP method for the request. ``"GET"`` sends no JSON body,+ for endpoints that authenticate purely through ``headers``+ (e.g. Discord's ``users/@me``).transport: Optional custom transport (e.g. an IPv4-bound one).timeout: Per-phase timeout in seconds for the fresh client.@@ -106,7 +110,12 @@ async def probe_token_endpoint(timeout=httpx.Timeout(timeout, connect=timeout),transport=transport,) as client:- resp = await client.post(url, json=payload, headers=headers)+ resp = await client.request(+ method,+ url,+ json=payload if method != "GET" else None,+ headers=headers,+ )except httpx.HTTPError as exc:return {"ok": False,diff --git a/agent/tests/test_channels_config_api.py b/agent/tests/test_channels_config_api.pyindex d9fc92bcd..6b91bc9e8 100644--- a/agent/tests/test_channels_config_api.py+++ b/agent/tests/test_channels_config_api.py@@ -38,6 +38,7 @@ FEISHU_APP_ID = "cli_feishu_app_id_1234567890"FEISHU_STORED_SECRET = "feishu-stored-secret-abcdefghij"SLACK_BOT_TOKEN = "xoxb-route-test-bot-token-123456"SLACK_APP_TOKEN = "xapp-route-test-app-token-abcdef"+DISCORD_STORED_TOKEN = "discord-route-test-bot-token-123456"# Captured before any test monkeypatches httpx, so repeated injections in a# single test still wrap the real client (test_dingtalk_connection_test idiom).@@ -167,6 +168,15 @@ def _feishu_section(**overrides: Any) -> dict[str, Any]:return section+def _discord_section(**overrides: Any) -> dict[str, Any]:+ section: dict[str, Any] = {+ "enabled": False,+ "token": DISCORD_STORED_TOKEN,+ }+ section.update(overrides)+ return section++def _free_port() -> int:"""Return a loopback port the OS just handed out (free at bind time)."""with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:@@ -708,6 +718,37 @@ def test_put_feishu_enable_with_bad_credentials_is_blocked_before_write(assert FEISHU_STORED_SECRET not in response.text+def test_put_discord_enable_with_bad_credentials_is_blocked_before_write(+ tmp_path: Path, monkeypatch+) -> None:+ """Discord answers a bad bot token with HTTP 401 on ``users/@me``; the+ enable-transition probe must block the write with 422."""+ client, path = _client(+ tmp_path, monkeypatch, channels={"discord": _discord_section()}+ )+ before = path.read_bytes()++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, json={"message": "401: Unauthorized"})++ requests = _inject_mock_transport(monkeypatch, handler)++ response = client.put("/channels/config/discord", json={"config": {"enabled": True}})++ assert response.status_code == 422+ detail = response.json()["detail"]+ assert detail["code"] == "invalid_credentials"+ assert detail["fields"] == []+ assert len(requests) == 1+ assert str(requests[0].url) == "https://discord.com/api/v10/users/@me"+ assert requests[0].method == "GET"+ assert requests[0].headers["authorization"] == f"Bot {DISCORD_STORED_TOKEN}"+ # The security property: bad credentials never reach disk.+ assert path.read_bytes() == before+ assert api_server._channel_runtime is None+ assert DISCORD_STORED_TOKEN not in response.text++def test_put_enable_rejection_carries_scrubbed_message(tmp_path: Path, monkeypatch) -> None:client, path = _client(tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}diff --git a/agent/tests/test_dingtalk_connection_test.py b/agent/tests/test_dingtalk_connection_test.pyindex 1ec0d54f0..db0ce25a2 100644--- a/agent/tests/test_dingtalk_connection_test.py+++ b/agent/tests/test_dingtalk_connection_test.py@@ -36,7 +36,6 @@ _REAL_ASYNC_CLIENT = httpx.AsyncClient# 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.wecom", "WecomChannel"),]diff --git a/agent/tests/test_discord_connection_test.py b/agent/tests/test_discord_connection_test.pynew file mode 100644index 000000000..de6384a3e--- /dev/null+++ b/agent/tests/test_discord_connection_test.py@@ -0,0 +1,304 @@+"""Connection-test contract for the Discord channel.++Mirrors ``test_slack_connection_test.py``: Discord implements the standalone+bot-token probe (``GET /api/v10/users/@me`` with an ``Authorization: Bot``+header) and never touches the ``discord.py`` client (which only exists after+``start()``). The contract codes the frontend dispatches on are ``ok |+invalid_credentials | network`` plus an ``sdk_available`` flag, and no token+value may ever leak into the result or logs. Discord-specific: a valid BOT+token answers 200 with ``"bot": true`` in the user object, while a pasted+OAuth *user* token answers 200 WITHOUT the flag — the shared "200 but+token_key missing/falsy" branch classifies that as ``invalid_credentials``,+catching the wrong token type at probe time. Unlike slack (constant True),+the adapter delegate passes the real ``DISCORD_AVAILABLE`` guard, so the+envelope echoes it in both states. The adapter itself imports without the+``discord`` SDK installed, which is the state of CI and this test env.+"""++from __future__ import annotations++import asyncio+import json+import logging+from typing import Any++import httpx+import pytest++import src.channels.discord as discord_channel+from src.channels import discord_probe+from src.channels.bus.queue import MessageBus+from src.channels.discord import DISCORD_AVAILABLE, DiscordChannel, DiscordConfig++USERS_ME_URL = "https://discord.com/api/v10/users/@me"+BOT_TOKEN = "fake-bot-token-do-not-leak-1234567890"+BOT_USER_BODY = {"id": "123", "username": "probe", "bot": True}++# 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+++def _make_channel(token: str = BOT_TOKEN, **overrides: Any) -> DiscordChannel:+ """Build a Discord channel that has NOT been started (no discord.py client)."""+ return DiscordChannel({"token": token, **overrides}, 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)+++def _ok_handler(request: httpx.Request) -> httpx.Response:+ """Answer the leg the way Discord answers a valid bot token."""+ assert str(request.url) == USERS_ME_URL+ assert request.method == "GET"+ assert request.headers["authorization"] == f"Bot {BOT_TOKEN}"+ # A GET must carry no JSON body.+ assert request.content == b""+ return httpx.Response(200, json=BOT_USER_BODY)+++# --------------------------------------------------------------------------- #+# Discord standalone probe — success+# --------------------------------------------------------------------------- #+++def test_success_valid_bot_token_returns_ok_and_discards_body(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ requests = _inject_mock_transport(monkeypatch, _ok_handler)+ channel = _make_channel()++ result = _run(channel.test_connection())++ assert result["ok"] is True+ assert result["code"] == "ok"+ assert result["sdk_available"] is DISCORD_AVAILABLE+ assert len(requests) == 1+ # The probe is standalone: it must not have created the discord.py client.+ assert channel._client is None+ # The token and the success body (bot username/id) are discarded.+ serialized = json.dumps(result)+ assert BOT_TOKEN not in serialized+ assert "username" not in serialized+ assert set(result) == {"ok", "code", "sdk_available"}+++def test_success_uses_fresh_client_even_when_sdk_client_present(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A started channel's discord.py client must not be reused by the probe."""+ requests = _inject_mock_transport(monkeypatch, _ok_handler)+ channel = _make_channel()+ sentinel = object()+ channel._client = sentinel # pretend start() ran++ result = _run(channel.test_connection())++ assert result["ok"] is True+ assert len(requests) == 1+ assert channel._client is sentinel+++# --------------------------------------------------------------------------- #+# Discord standalone probe — invalid credentials+# --------------------------------------------------------------------------- #+++def test_user_token_200_without_bot_flag_reports_invalid_credentials(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A pasted OAuth *user* token answers 200 without ``"bot": true``.++ ``token_key="bot"`` routes that through the shared "200 but token_key+ missing/falsy" branch: a user token cannot open a bot gateway session,+ so the wrong token type must be caught at probe time, not at start().+ """++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"id": "456", "username": "human"})++ requests = _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 DISCORD_AVAILABLE+ assert len(requests) == 1+ serialized = json.dumps(result)+ assert BOT_TOKEN not in serialized+ assert "human" not in serialized+++def test_http_401_reports_invalid_credentials(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, json={"message": "401: Unauthorized"})++ _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 DISCORD_AVAILABLE+ assert "detail" in result+ assert BOT_TOKEN not in json.dumps(result)+++def test_missing_token_short_circuits_without_network(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The ``start()`` guard rejects an empty token, so the probe reports it+ before any HTTP call happens."""++ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover+ raise AssertionError("no network call may happen without a token")++ requests = _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel(token="").test_connection())++ assert requests == []+ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["detail"] == "missing bot token"+ # The short-circuit envelope is self-contained like every other branch.+ assert result["sdk_available"] is DISCORD_AVAILABLE+++# --------------------------------------------------------------------------- #+# Discord 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 DISCORD_AVAILABLE+ assert BOT_TOKEN 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"+++# --------------------------------------------------------------------------- #+# sdk_available echo — both states, probe level and adapter level+# --------------------------------------------------------------------------- #++[email protected]("flag", [True, False])+def test_probe_echoes_sdk_available_in_both_states(flag: bool) -> None:+ """The probe is stateless: whatever the caller passes is echoed back."""+ result = _run(+ discord_probe.test_connection(DiscordConfig(token=""), sdk_available=flag)+ )+ assert result["sdk_available"] is flag++[email protected]("flag", [True, False])+def test_adapter_delegate_passes_the_real_availability_guard(+ monkeypatch: pytest.MonkeyPatch, flag: bool+) -> None:+ """Unlike slack's constant True, the delegate reads DISCORD_AVAILABLE at+ call time, so the envelope reports the SDK state honestly."""+ monkeypatch.setattr(discord_channel, "DISCORD_AVAILABLE", flag)+ result = _run(_make_channel(token="").test_connection())+ assert result["sdk_available"] is flag+++# --------------------------------------------------------------------------- #+# Secret hygiene+# --------------------------------------------------------------------------- #+++def test_rejection_detail_scrubs_echoed_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The token is declared a secret, so an echoing rejection body reaches+ the detail masked."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"bad token {BOT_TOKEN}")++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["code"] == "invalid_credentials"+ assert "***" in result["detail"]+ assert BOT_TOKEN not in json.dumps(result)+++def test_probe_never_logs_token(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ _inject_mock_transport(monkeypatch, _ok_handler)++ with caplog.at_level(logging.DEBUG):+ result = _run(_make_channel().test_connection())++ assert result["code"] == "ok"+ assert BOT_TOKEN not in caplog.text+++# --------------------------------------------------------------------------- #+# Adapter wiring+# --------------------------------------------------------------------------- #+++def test_adapter_imports_without_the_sdk_and_declares_support() -> None:+ """discord.py guards the SDK behind DISCORD_AVAILABLE, so the adapter and+ its probe delegate import in an SDK-less environment (CI, this test env)."""+ assert isinstance(DISCORD_AVAILABLE, bool)+ assert DiscordChannel.supports_connection_test is True