"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(channels): add Slack connection test for bot and app tokens
shadowinlifebec8ebf6f510
diff --git a/agent/src/channels/registry.py b/agent/src/channels/registry.pyindex eb6a4a2ee..51efaaf8a 100644--- a/agent/src/channels/registry.py+++ b/agent/src/channels/registry.py@@ -35,6 +35,7 @@ _INTERNAL = frozenset("registry","rich_text","runtime",+ "slack_probe","targets","token_probe","utils",diff --git a/agent/src/channels/slack.py b/agent/src/channels/slack.pyindex bc574f2ef..594197ff5 100644--- a/agent/src/channels/slack.py+++ b/agent/src/channels/slack.py@@ -13,6 +13,7 @@ from slack_sdk.socket_mode.websockets import SocketModeClientfrom slack_sdk.web.async_client import AsyncWebClientfrom slackify_markdown import slackify_markdown+from src.channels import slack_probefrom src.channels.bus.events import OutboundMessagefrom src.channels.bus.queue import MessageBusfrom src.channels.base import BaseChannel@@ -73,6 +74,7 @@ class SlackChannel(BaseChannel):name = "slack"display_name = "Slack"+ supports_connection_test = Truedelivery_target_label = "Slack destination"delivery_target_kind = "slack_destination"delivery_target_placeholder = "#channel, @user, or conversation ID"@@ -156,6 +158,18 @@ class SlackChannel(BaseChannel):self.logger.warning("socket close failed: %s", e)self._socket_client = None+ async def test_connection(self) -> dict[str, Any]:+ """Validate the Slack credentials with a standalone two-leg probe.++ Delegates to :func:`src.channels.slack_probe.test_connection`; see+ that function for the full contract. ``sdk_available=True`` is a+ constant because this module imports ``slack_sdk`` unconditionally+ at the top (no availability guard, unlike feishu): a missing SDK+ means this class never imports at all and the registry already+ reports ``available: false`` with the pip install hint.+ """+ return await slack_probe.test_connection(self.config, sdk_available=True)+async def send(self, msg: OutboundMessage) -> None:"""Send a message through Slack."""if not self._web_client:diff --git a/agent/src/channels/slack_probe.py b/agent/src/channels/slack_probe.pynew file mode 100644index 000000000..427e7d903--- /dev/null+++ b/agent/src/channels/slack_probe.py@@ -0,0 +1,112 @@+"""Standalone Slack credential probe, mirroring ``feishu_probe.py``.++The probe validates a (possibly unsaved) credential set with a two-leg+request sequence against the Slack Web API without touching the channel's+``slack_sdk`` clients. Everything here is stateless: functions take the+``SlackConfig`` explicitly so the module never imports the adapter at+runtime (only under ``TYPE_CHECKING``) — ``slack.py`` imports ``slack_sdk``+unconditionally at module top, and a credential check never needs it.+``sdk_available`` is still threaded through so the caller's envelope+carries it unchanged (the adapter passes a constant ``True``; see the+delegate in ``slack.py``). The request/classification logic lives in+:mod:`src.channels.token_probe`, the shared building block for+token-endpoint probes.++Slack authenticates via an ``Authorization: Bearer`` header rather than a+JSON body, so both legs pass the shared probe's optional ``headers`` with+an empty payload. Note that Slack answers HTTP 200 with ``{"ok": false,+"error": "invalid_auth"}`` for bad tokens; ``token_key="ok"`` routes that+through the shared "200 but no token" branch, which already classifies it+as ``invalid_credentials``.++Leg 1 (``auth.test``) validates the bot token. Leg 2+(``apps.connections.open``) validates the app token AND that Socket Mode+is enabled on the Slack app — the exact failure class that bites users (a+valid ``xoxb-`` bot token with Socket Mode never turned on). Its ``ok:+true`` body contains a ``wss://`` connection URL, a credential-adjacent+value: the shared probe keeps nothing but ``ok``/``code`` from a success+body, so the URL is never returned, logged, or cached.++Missing tokens short-circuit before any HTTP call, mirroring the+``start()`` guard in ``slack.py`` (``if not self.config.bot_token or not+self.config.app_token`` → logs "bot/app 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.slack import SlackConfig++SLACK_AUTH_TEST_URL = "https://slack.com/api/auth.test"+SLACK_CONNECTIONS_OPEN_URL = "https://slack.com/api/apps.connections.open"+++async def test_connection(+ config: SlackConfig, *, sdk_available: bool+) -> dict[str, Any]:+ """Validate the Slack credentials with a standalone two-leg probe.++ Uses fresh ``httpx.AsyncClient`` requests rather than the channel's+ ``slack_sdk`` clients (which only exist after+ :meth:`SlackChannel.start`), so an unsaved credential set can be+ checked before the channel is started. A successful leg 2 response+ carries a ``wss://`` URL; it is discarded: never returned, logged, or+ cached.++ Args:+ config: The Slack credential set to validate.+ sdk_available: Whether the ``slack_sdk`` package 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 both token values and names+ the failing leg with a ``"bot token: "`` / ``"app token: "``+ prefix.+ """+ secrets = (config.bot_token, config.app_token)++ if not config.bot_token:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "missing bot token",+ "sdk_available": sdk_available,+ }+ if config.mode == "socket" and not config.app_token:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "missing app token",+ "sdk_available": sdk_available,+ }++ result = await probe_token_endpoint(+ url=SLACK_AUTH_TEST_URL,+ payload={},+ headers={"Authorization": f"Bearer {config.bot_token}"},+ token_key="ok",+ secrets=secrets,+ sdk_available=sdk_available,+ )+ if not result["ok"]:+ return {**result, "detail": f"bot token: {result.get('detail', '')}"}++ result = await probe_token_endpoint(+ url=SLACK_CONNECTIONS_OPEN_URL,+ payload={},+ headers={"Authorization": f"Bearer {config.app_token}"},+ token_key="ok",+ secrets=secrets,+ sdk_available=sdk_available,+ )+ if not result["ok"]:+ return {**result, "detail": f"app token: {result.get('detail', '')}"}++ return {"ok": True, "code": "ok", "sdk_available": sdk_available}diff --git a/agent/src/channels/token_probe.py b/agent/src/channels/token_probe.pyindex adc91ed0d..f65138753 100644--- a/agent/src/channels/token_probe.py+++ b/agent/src/channels/token_probe.py@@ -74,6 +74,7 @@ async def probe_token_endpoint(token_key: str,secrets: Sequence[str],sdk_available: bool,+ headers: dict[str, str] | None = None,transport: httpx.AsyncHTTPTransport | None = None,timeout: float = 10.0,) -> dict[str, Any]:@@ -90,6 +91,8 @@ async def probe_token_endpoint(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 authenticate+ outside the JSON body (e.g. Slack's ``Authorization: Bearer``).transport: Optional custom transport (e.g. an IPv4-bound one).timeout: Per-phase timeout in seconds for the fresh client.@@ -103,7 +106,7 @@ async def probe_token_endpoint(timeout=httpx.Timeout(timeout, connect=timeout),transport=transport,) as client:- resp = await client.post(url, json=payload)+ resp = await client.post(url, json=payload, 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 071196eed..4b07e6971 100644--- a/agent/tests/test_channels_config_api.py+++ b/agent/tests/test_channels_config_api.py@@ -36,6 +36,8 @@ WS_TOKEN = "ws-token-secret-abcdefghij"WS_ISSUE_SECRET = "ws-issue-secret-987654321"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"# Captured before any test monkeypatches httpx, so repeated injections in a# single test still wrap the real client (test_dingtalk_connection_test idiom).@@ -1112,6 +1114,54 @@ def test_post_websocket_test_returns_probe_code_not_unsupported(assert path.read_bytes() == before+def test_post_slack_test_runs_two_leg_probe_not_unsupported(+ tmp_path: Path, monkeypatch+) -> None:+ """Slack's Test route runs the two-leg probe (auth.test then+ apps.connections.open) instead of short-circuiting ``unsupported``."""+ client, path = _client(tmp_path, monkeypatch, channels={})+ before = path.read_bytes()+ seen: list[str] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(str(request.url))+ if seen[-1].endswith("/api/auth.test"):+ return httpx.Response(200, json={"ok": True})+ return httpx.Response(+ 200, json={"ok": True, "url": "wss://wss-primary.slack.com/link/"}+ )++ _inject_mock_transport(monkeypatch, handler)++ response = client.post(+ "/channels/slack/test",+ json={+ "config": {+ "bot_token": SLACK_BOT_TOKEN,+ "app_token": SLACK_APP_TOKEN,+ }+ },+ )++ assert response.status_code == 200+ body = response.json()+ assert body["ok"] is True, body+ assert body["code"] == "ok"+ assert body["code"] != "unsupported"+ assert body["tested_saved_config"] is False+ assert body["sdk_available"] is True+ assert seen == [+ "https://slack.com/api/auth.test",+ "https://slack.com/api/apps.connections.open",+ ]+ # The test endpoint never persists anything, and neither the tokens nor+ # the wss:// URL from the success body reach the response.+ assert path.read_bytes() == before+ assert SLACK_BOT_TOKEN not in response.text+ assert SLACK_APP_TOKEN not in response.text+ assert "wss://" not in response.text++def test_post_email_test_empty_config_reports_missing_credentials(tmp_path: Path, monkeypatch) -> None:diff --git a/agent/tests/test_dingtalk_connection_test.py b/agent/tests/test_dingtalk_connection_test.pyindex 93fc8fb16..1ec0d54f0 100644--- a/agent/tests/test_dingtalk_connection_test.py+++ b/agent/tests/test_dingtalk_connection_test.py@@ -38,7 +38,6 @@ _REAL_ASYNC_CLIENT = httpx.AsyncClient_DEFAULT_CHANNEL_CANDIDATES: list[tuple[str, str]] = [("src.channels.discord", "DiscordChannel"),("src.channels.telegram", "TelegramChannel"),- ("src.channels.slack", "SlackChannel"),("src.channels.wecom", "WecomChannel"),]diff --git a/agent/tests/test_slack_connection_test.py b/agent/tests/test_slack_connection_test.pynew file mode 100644index 000000000..02f742e4c--- /dev/null+++ b/agent/tests/test_slack_connection_test.py@@ -0,0 +1,294 @@+"""Connection-test contract for the Slack channel.++Mirrors ``test_qq_connection_test.py``: Slack implements the standalone+two-leg credential probe (``auth.test`` for the bot token, then+``apps.connections.open`` for the app token / Socket Mode enablement) and+never touches the ``slack_sdk`` clients (which only exist after+``start()``). The contract codes the frontend dispatches on are+``ok | invalid_credentials | network`` plus an ``sdk_available`` flag, and+no token value or ``wss://`` URL may ever leak into the result or logs.+Slack-specific: the API answers HTTP 200 with ``{"ok": false, "error":+"invalid_auth"}`` for bad tokens, which the shared "200 but no token"+branch classifies as ``invalid_credentials``.+"""++from __future__ import annotations++import asyncio+import json+import logging+from typing import Any++import httpx+import pytest++from src.channels.bus.queue import MessageBus+from src.channels.slack import SlackChannel++AUTH_TEST_URL = "https://slack.com/api/auth.test"+CONNECTIONS_OPEN_URL = "https://slack.com/api/apps.connections.open"+BOT_TOKEN = "xoxb-test-bot-token-1234567890"+APP_TOKEN = "xapp-test-app-token-abcdefghij"+WSS_URL = "wss://wss-primary.slack.com/link/?ticket=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+++def _make_channel(+ bot_token: str = BOT_TOKEN,+ app_token: str = APP_TOKEN,+ **overrides: Any,+) -> SlackChannel:+ """Build a Slack channel that has NOT been started (no sdk clients)."""+ return SlackChannel(+ {"bot_token": bot_token, "app_token": app_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 both legs the way Slack answers valid credentials."""+ if str(request.url) == AUTH_TEST_URL:+ return httpx.Response(200, json={"ok": True, "user_id": "U12345"})+ if str(request.url) == CONNECTIONS_OPEN_URL:+ return httpx.Response(200, json={"ok": True, "url": WSS_URL})+ raise AssertionError(f"unexpected URL {request.url}") # pragma: no cover+++# --------------------------------------------------------------------------- #+# Slack standalone probe — success+# --------------------------------------------------------------------------- #+++def test_success_both_legs_ok_and_discards_wss_url(+ 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"+ # The delegate passes a constant True: slack.py imports slack_sdk+ # unconditionally, so a missing SDK means the class never imports.+ assert result["sdk_available"] is True+ # Two legs, in order, each with its own Bearer header and an empty body.+ assert [str(r.url) for r in requests] == [AUTH_TEST_URL, CONNECTIONS_OPEN_URL]+ assert requests[0].headers["authorization"] == f"Bearer {BOT_TOKEN}"+ assert requests[1].headers["authorization"] == f"Bearer {APP_TOKEN}"+ assert json.loads(requests[0].content.decode("utf-8")) == {}+ # The probe is standalone: it must not have created the sdk clients.+ assert channel._web_client is None+ assert channel._socket_client is None+ # Tokens and the wss:// URL are discarded, never returned.+ serialized = json.dumps(result)+ assert BOT_TOKEN not in serialized+ assert APP_TOKEN not in serialized+ assert WSS_URL not in serialized+ assert "wss://" not in serialized+++# --------------------------------------------------------------------------- #+# Slack standalone probe — invalid credentials+# --------------------------------------------------------------------------- #+++def test_bad_bot_token_200_ok_false_reports_invalid_credentials(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Slack answers bad tokens with HTTP 200 and ``ok: false``."""++ def handler(request: httpx.Request) -> httpx.Response:+ assert str(request.url) == AUTH_TEST_URL+ return httpx.Response(200, json={"ok": False, "error": "invalid_auth"})++ requests = _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["detail"].startswith("bot token:")+ assert result["sdk_available"] is True+ # Leg 2 never runs after a leg 1 failure.+ assert len(requests) == 1+ serialized = json.dumps(result)+ assert BOT_TOKEN not in serialized+ assert APP_TOKEN not in serialized+++def test_socket_mode_disabled_reports_invalid_credentials_on_leg_two(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """``apps.connections.open`` rejects when Socket Mode is not enabled."""++ def handler(request: httpx.Request) -> httpx.Response:+ if str(request.url) == AUTH_TEST_URL:+ return httpx.Response(200, json={"ok": True})+ return httpx.Response(200, json={"ok": False, "error": "not_allowed"})++ requests = _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["detail"].startswith("app token:")+ assert len(requests) == 2+ assert BOT_TOKEN not in json.dumps(result)+ assert APP_TOKEN not in json.dumps(result)+++ ("bot_token", "app_token", "detail"),+ [+ ("", "", "missing bot token"),+ ("", APP_TOKEN, "missing bot token"),+ (BOT_TOKEN, "", "missing app token"),+ ],+)+def test_missing_tokens_short_circuit_without_network(+ monkeypatch: pytest.MonkeyPatch,+ bot_token: str,+ app_token: str,+ detail: str,+) -> None:+ """Socket mode needs both tokens (the ``start()`` guard), so a missing+ one is reported before any HTTP call happens."""++ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover+ raise AssertionError("no network call may happen without tokens")++ requests = _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel(bot_token, app_token).test_connection())++ assert requests == []+ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["detail"] == detail+ # The short-circuit envelope is self-contained like every other branch.+ assert result["sdk_available"] is True+++# --------------------------------------------------------------------------- #+# Slack 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["detail"].startswith("bot token:")+ assert result["sdk_available"] is True+ assert BOT_TOKEN not in json.dumps(result)+++def test_leg_two_server_error_reports_network(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ if str(request.url) == AUTH_TEST_URL:+ return httpx.Response(200, json={"ok": True})+ return httpx.Response(503, text="upstream exploded")++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel().test_connection())++ assert result["ok"] is False+ assert result["code"] == "network"+ assert result["detail"].startswith("app token:")+++# --------------------------------------------------------------------------- #+# Secret hygiene+# --------------------------------------------------------------------------- #+++def test_rejection_detail_scrubs_echoed_tokens(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Both token values are declared secrets, so an echoing rejection body+ reaches the detail masked whichever leg produced it."""++ def handler(request: httpx.Request) -> httpx.Response:+ if str(request.url) == AUTH_TEST_URL:+ return httpx.Response(401, text=f"bad token {BOT_TOKEN}")+ return httpx.Response(500, text=f"exploded with {APP_TOKEN}")++ _inject_mock_transport(monkeypatch, handler)++ leg1 = _run(_make_channel().test_connection())+ assert leg1["code"] == "invalid_credentials"+ assert leg1["detail"].startswith("bot token:")+ assert "***" in leg1["detail"]+ assert BOT_TOKEN not in json.dumps(leg1)++ # Force leg 2 to be the echoing leg.+ def leg2_handler(request: httpx.Request) -> httpx.Response:+ if str(request.url) == AUTH_TEST_URL:+ return httpx.Response(200, json={"ok": True})+ return httpx.Response(500, text=f"exploded with {APP_TOKEN}")++ _inject_mock_transport(monkeypatch, leg2_handler)+ leg2 = _run(_make_channel().test_connection())+ assert leg2["code"] == "network"+ assert leg2["detail"].startswith("app token:")+ assert APP_TOKEN not in json.dumps(leg2)+++def test_probe_never_logs_tokens_or_wss_url(+ 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+ assert APP_TOKEN not in caplog.text+ assert WSS_URL not in caplog.text