"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(channels): QQ connection test on a shared token-endpoint probe
shadowinlifee389d3fbf4a0
diff --git a/agent/src/channels/config_meta.py b/agent/src/channels/config_meta.pyindex c2048f258..19ca76069 100644--- a/agent/src/channels/config_meta.py+++ b/agent/src/channels/config_meta.py@@ -76,8 +76,33 @@ def _dingtalk_hints() -> list[FieldHint]:]+def _qq_hints() -> list[FieldHint]:+ """Return the hand-written QQ field hints (``enabled`` excluded)."""+ specs = (+ ("app_id", "text", False, True),+ ("secret", "password", True, True),+ ("allow_from", "list", False, False),+ ("msg_format", "text", False, False),+ ("ack_message", "text", False, False),+ ("media_dir", "text", False, False),+ ("download_chunk_size", "text", False, False),+ ("download_max_bytes", "text", False, False),+ )+ return [+ {+ "key": key,+ "type": widget,+ "secret": secret,+ "required": required,+ "help_key": f"{_HELP_KEY_PREFIX}.qq.{key}",+ }+ for key, widget, secret, required in specs+ ]++FIELD_HINTS: dict[str, list[FieldHint]] = {"dingtalk": _dingtalk_hints(),+ "qq": _qq_hints(),}diff --git a/agent/src/channels/dingtalk_probe.py b/agent/src/channels/dingtalk_probe.pyindex 1ced24f82..87689dd23 100644--- a/agent/src/channels/dingtalk_probe.py+++ b/agent/src/channels/dingtalk_probe.py@@ -3,7 +3,10 @@The probe validates an (possibly unsaved) credential set against the tokenendpoint without touching the channel's shared HTTP client. Everything hereis stateless: functions take the ``DingTalkConfig`` explicitly so the module-never imports the adapter at runtime (only under ``TYPE_CHECKING``).+never imports the adapter at runtime (only under ``TYPE_CHECKING``). The+request/classification logic lives in :mod:`src.channels.token_probe`, the+shared building block for token-endpoint probes; this module keeps the+DingTalk-specific endpoint, payload shape and IPv4-pinning transport."""from __future__ import annotations@@ -12,6 +15,9 @@ from typing import TYPE_CHECKING, Anyimport httpx+from src.channels.token_probe import probe_token_endpoint, scrub_secrets+from src.channels.token_probe import response_detail as response_detail # re-export+if TYPE_CHECKING:from src.channels.dingtalk import DingTalkConfig@@ -37,19 +43,7 @@ def scrub_detail(config: DingTalkConfig, text: str) -> str:accident; every value the config holds as a secret is masked before thetext reaches a result envelope."""- cleaned = text- for secret in (config.client_secret, config.client_id):- if secret:- cleaned = cleaned.replace(secret, "***")- return cleaned---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]}"+ return scrub_secrets(text, (config.client_secret, config.client_id))async def test_connection(@@ -78,47 +72,11 @@ async def test_connection("detail": "missing credentials",}- payload = {"appKey": config.client_id, "appSecret": config.client_secret}-- try:- async with httpx.AsyncClient(- timeout=httpx.Timeout(10.0, connect=10.0),- transport=build_http_transport(config),- ) as client:- resp = await client.post(DINGTALK_ACCESS_TOKEN_URL, json=payload)- except httpx.HTTPError as exc:- return {- "ok": False,- "code": "network",- "detail": scrub_detail(config, str(exc) or type(exc).__name__),- "sdk_available": sdk_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": sdk_available,- }- return {"ok": True, "code": "ok", "sdk_available": sdk_available}-- if 400 <= resp.status_code < 500:- return {- "ok": False,- "code": "invalid_credentials",- "detail": scrub_detail(config, response_detail(resp)),- "sdk_available": sdk_available,- }-- return {- "ok": False,- "code": "network",- "detail": scrub_detail(config, response_detail(resp)),- "sdk_available": sdk_available,- }+ return await probe_token_endpoint(+ url=DINGTALK_ACCESS_TOKEN_URL,+ payload={"appKey": config.client_id, "appSecret": config.client_secret},+ token_key="accessToken",+ secrets=(config.client_secret, config.client_id),+ sdk_available=sdk_available,+ transport=build_http_transport(config),+ )diff --git a/agent/src/channels/qq.py b/agent/src/channels/qq.pyindex 94a70d7b9..74a98fa77 100644--- a/agent/src/channels/qq.py+++ b/agent/src/channels/qq.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport asyncioimport base64+import loggingimport mimetypesimport osimport re@@ -31,15 +32,13 @@ from typing import TYPE_CHECKING, Any, Literalfrom urllib.parse import unquote, urlparseimport aiohttp-import logging; logger = logging.getLogger(__name__)-from pydantic import Field+from pydantic import BaseModel, Field+from src.channels import qq_probefrom src.channels.bus.events import OutboundMessagefrom src.channels.bus.queue import MessageBusfrom src.channels.base import BaseChannel-from pydantic import BaseModelfrom src.channels.utils import validate_url_target-# logging_bridge not needed (using stdlib logging)try:from src.channels.utils import get_media_dir@@ -60,6 +59,7 @@ if TYPE_CHECKING:from botpy.message import BaseMessage, C2CMessage, GroupMessagefrom botpy.types.message import Media+logger = logging.getLogger(__name__)# QQ rich media file_type: 1=image, 4=file# (2=voice, 3=video are restricted; we only use image vs file)@@ -114,7 +114,7 @@ def _make_bot_class(channel: QQChannel) -> type[botpy.Client]:super().__init__(intents=intents, ext_handlers=False)async def on_ready(self):- logger.info("QQ bot ready: {}", self.robot.name)+ logger.info("QQ bot ready: %s", self.robot.name)async def on_c2c_message_create(self, message: C2CMessage):await channel._on_message(message, is_group=False)@@ -151,6 +151,7 @@ class QQChannel(BaseChannel):name = "qq"display_name = "QQ"+ supports_connection_test = True@classmethoddef default_config(cls) -> dict[str, Any]:@@ -188,7 +189,7 @@ class QQChannel(BaseChannel):root = Path.home() / ".vibe-trading" / "media" / "qq"root.mkdir(parents=True, exist_ok=True)- self.logger.info("media directory: {}", str(root))+ self.logger.info("media directory: %s", str(root))return rootasync def start(self) -> None:@@ -213,9 +214,11 @@ class QQChannel(BaseChannel):"""Run the bot connection with auto-reconnect."""while self._running:try:- await self._client.start(appid=self.config.app_id, secret=self.config.secret)+ await self._client.start(+ appid=self.config.app_id, secret=self.config.secret+ )except Exception as e:- self.logger.warning("bot error: {}", e)+ self.logger.warning("bot error: %s", e)if self._running:self.logger.info("Reconnecting bot in 5 seconds...")await asyncio.sleep(5)@@ -235,6 +238,14 @@ class QQChannel(BaseChannel):self.logger.info("bot stopped")+ async def test_connection(self) -> dict[str, Any]:+ """Validate the QQ credentials with a standalone token request.++ Delegates to :func:`src.channels.qq_probe.test_connection`; see that+ function for the full contract (codes, scrubbing, token discard).+ """+ return await qq_probe.test_connection(self.config, sdk_available=QQ_AVAILABLE)+# ---------------------------# Outbound (send)# ---------------------------@@ -283,7 +294,7 @@ class QQChannel(BaseChannel):# Network / transport errors — propagate so ChannelManager can retryraiseexcept Exception:- self.logger.exception("Error sending message to chat_id={}", msg.chat_id)+ self.logger.exception("Error sending message to chat_id=%s", msg.chat_id)async def _send_text_only(self,@@ -362,18 +373,22 @@ class QQChannel(BaseChannel):media=media_obj,)- self.logger.info("media sent: {}", filename)+ self.logger.info("media sent: %s", filename)return Trueexcept (aiohttp.ClientError, OSError) as e:# Network / transport errors — propagate for retry by caller- self.logger.warning("send media network error filename={} err={}", filename, e)+ self.logger.warning(+ "send media network error filename=%s err=%s", filename, e+ )raiseexcept Exception:# API-level or other non-network errors — return False so send() can fallback- self.logger.exception("send media failed filename={}", filename)+ self.logger.exception("send media failed filename=%s", filename)return False- async def _read_media_bytes(self, media_ref: str) -> tuple[bytes | None, str | None]:+ async def _read_media_bytes(+ self, media_ref: str+ ) -> tuple[bytes | None, str | None]:"""Read bytes from http(s) or local file path; return (data, filename)."""media_ref = (media_ref or "").strip()if not media_ref:@@ -391,19 +406,25 @@ class QQChannel(BaseChannel):local_path = Path(os.path.expanduser(media_ref))if not local_path.is_file():- self.logger.warning("outbound media file not found: {}", str(local_path))+ self.logger.warning(+ "outbound media file not found: %s", str(local_path)+ )return None, Nonedata = await asyncio.to_thread(local_path.read_bytes)return data, local_path.nameexcept Exception as e:- self.logger.warning("outbound media read error ref={} err={}", media_ref, e)+ self.logger.warning(+ "outbound media read error ref=%s err=%s", media_ref, e+ )return None, None# Remote URLok, err = validate_url_target(media_ref)if not ok:- self.logger.warning("outbound media URL validation failed url={} err={}", media_ref, err)+ self.logger.warning(+ "outbound media URL validation failed url=%s err=%s", media_ref, err+ )return None, Noneif not self._http:@@ -418,14 +439,14 @@ class QQChannel(BaseChannel):async with self._http.get(media_ref, allow_redirects=False) as resp:if 300 <= resp.status < 400:self.logger.warning(- "outbound media download redirect rejected url={} status={}",+ "outbound media download redirect rejected url=%s status=%s",media_ref,resp.status,)return None, Noneif resp.status >= 400:self.logger.warning(- "outbound media download failed status={} url={}",+ "outbound media download failed status=%s url=%s",resp.status,media_ref,)@@ -436,7 +457,9 @@ class QQChannel(BaseChannel):filename = os.path.basename(urlparse(media_ref).path) or "file.bin"return data, filenameexcept Exception as e:- self.logger.warning("outbound media download error url={} err={}", media_ref, e)+ self.logger.warning(+ "outbound media download error url=%s err=%s", media_ref, e+ )return None, None# https://github.com/tencent-connect/botpy/issues/198@@ -486,7 +509,9 @@ class QQChannel(BaseChannel):# Inbound (receive)# ---------------------------- async def _on_message(self, data: C2CMessage | GroupMessage, is_group: bool = False) -> None:+ async def _on_message(+ self, data: C2CMessage | GroupMessage, is_group: bool = False+ ) -> None:"""Parse inbound message, download attachments, and publish to the bus."""try:if is_group:@@ -524,7 +549,9 @@ class QQChannel(BaseChannel):# the data used by tests don't contain attachments property# so we use getattr with a default of [] to avoid AttributeError in testsattachments = getattr(data, "attachments", None) or []- media_paths, recv_lines, att_meta = await self._handle_attachments(attachments)+ media_paths, recv_lines, att_meta = await self._handle_attachments(+ attachments+ )# Compose content that always contains actionable saved pathsif recv_lines:@@ -535,7 +562,9 @@ class QQChannel(BaseChannel):)file_block = "Received files:\n" + "\n".join(recv_lines)content = (- f"{content}\n\n{file_block}".strip() if content else f"{tag}\n{file_block}"+ f"{content}\n\n{file_block}".strip()+ if content+ else f"{tag}\n{file_block}")if not content and not media_paths:@@ -550,7 +579,7 @@ class QQChannel(BaseChannel):content=self.config.ack_message,)except Exception:- self.logger.debug("ack message failed for chat_id={}", chat_id)+ self.logger.debug("ack message failed for chat_id=%s", chat_id)await self._handle_message(sender_id=user_id,@@ -564,7 +593,9 @@ class QQChannel(BaseChannel):is_dm=not is_group,)except Exception:- self.logger.exception("Error handling inbound message id={}", getattr(data, "id", "?"))+ self.logger.exception(+ "Error handling inbound message id=%s", getattr(data, "id", "?")+ )async def _handle_attachments(self,@@ -583,8 +614,10 @@ class QQChannel(BaseChannel):filename = getattr(att, "filename", None) or ""ctype = getattr(att, "content_type", None) or ""- self.logger.info("Downloading file: {}", filename or url)- local_path = await self._download_to_media_dir_chunked(url, filename_hint=filename)+ self.logger.info("Downloading file: %s", filename or url)+ local_path = await self._download_to_media_dir_chunked(+ url, filename_hint=filename+ )att_meta.append({@@ -634,7 +667,9 @@ class QQChannel(BaseChannel):allow_redirects=True,) as resp:if resp.status != 200:- self.logger.warning("download failed: status={} url={}", resp.status, url)+ self.logger.warning(+ "download failed: status=%s url=%s", resp.status, url+ )return Nonectype = (resp.headers.get("Content-Type") or "").lower()@@ -674,7 +709,8 @@ class QQChannel(BaseChannel):downloaded = 0chunk_size = max(1024, int(self.config.download_chunk_size or 262144))max_bytes = max(- 1024 * 1024, int(self.config.download_max_bytes or (200 * 1024 * 1024))+ 1024 * 1024,+ int(self.config.download_max_bytes or (200 * 1024 * 1024)),)def _open_tmp():@@ -689,7 +725,7 @@ class QQChannel(BaseChannel):downloaded += len(chunk)if downloaded > max_bytes:self.logger.warning(- "download exceeded max_bytes={} url={} -> abort",+ "download exceeded max_bytes=%s url=%s -> abort",max_bytes,url,)@@ -701,7 +737,7 @@ class QQChannel(BaseChannel):# Atomic renameawait asyncio.to_thread(os.replace, tmp_path, target)tmp_path = None # mark as moved- self.logger.info("file saved: {}", str(target))+ self.logger.info("file saved: %s", str(target))return str(target)except Exception:diff --git a/agent/src/channels/qq_probe.py b/agent/src/channels/qq_probe.pynew file mode 100644index 000000000..5e0f23e13--- /dev/null+++ b/agent/src/channels/qq_probe.py@@ -0,0 +1,59 @@+"""Standalone QQ credential probe, mirroring ``dingtalk_probe.py``.++The probe validates an (possibly unsaved) credential set against QQ's+``getAppAccessToken`` endpoint without touching the channel's shared HTTP+client. Everything here is stateless: functions take the ``QQConfig``+explicitly so the module never imports the adapter at runtime (only under+``TYPE_CHECKING``) — ``qq.py`` pulls ``aiohttp``/``botpy``, neither of which+a credential check needs. The request/classification logic lives in+:mod:`src.channels.token_probe`, the shared building block for+token-endpoint probes.++Note that QQ may answer HTTP 200 with an error body (e.g.+``{"code": 100007, "message": "..."}``) for bad credentials; the shared+"200 but no token" branch already classifies that as ``invalid_credentials``.+"""++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.qq import QQConfig++QQ_ACCESS_TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken"+++async def test_connection(config: QQConfig, *, sdk_available: bool) -> dict[str, Any]:+ """Validate the QQ credentials with a standalone token request.++ Uses a fresh ``httpx.AsyncClient`` rather than the channel's shared client+ (which only exists after :meth:`QQChannel.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.++ Args:+ config: The QQ credential set to validate.+ sdk_available: Whether the optional ``qq-botpy`` SDK imported.++ 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 config.app_id or not config.secret:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "missing credentials",+ }++ return await probe_token_endpoint(+ url=QQ_ACCESS_TOKEN_URL,+ payload={"appId": config.app_id, "clientSecret": config.secret},+ token_key="access_token",+ secrets=(config.secret, config.app_id),+ sdk_available=sdk_available,+ )diff --git a/agent/src/channels/registry.py b/agent/src/channels/registry.pyindex 04aec27d5..b261ee290 100644--- a/agent/src/channels/registry.py+++ b/agent/src/channels/registry.py@@ -29,21 +29,26 @@ _INTERNAL = frozenset("dingtalk_probe","manager","pairing",+ "qq_probe","registry","runtime","targets",+ "token_probe","utils",})_LEGACY_GLOBAL_CONFIG_KEYS = frozenset({"restrictToWorkspace", "restrict_to_workspace", "showReasoning", "show_reasoning"})-_GLOBAL_CONFIG_KEYS = frozenset(- key- for name, field in ChannelsConfig.model_fields.items()- for key in (name, field.alias)- if key-) | _LEGACY_GLOBAL_CONFIG_KEYS+_GLOBAL_CONFIG_KEYS = (+ frozenset(+ key+ for name, field in ChannelsConfig.model_fields.items()+ for key in (name, field.alias)+ if key+ )+ | _LEGACY_GLOBAL_CONFIG_KEYS+)_INSTALL_HINTS: dict[str, str] = {"dingtalk": "pip install 'vibe-trading-ai[dingtalk]'",@@ -110,7 +115,9 @@ def discover_channel_names() -> list[str]:]-def _channel_class_from_module(module: ModuleType, module_name: str) -> type[BaseChannel]:+def _channel_class_from_module(+ module: ModuleType, module_name: str+) -> type[BaseChannel]:"""Return the first BaseChannel subclass defined in *module*."""from src.channels.base import BaseChannel as _Base@@ -162,7 +169,9 @@ def inspect_channel(name: str) -> ChannelAvailability:available=False,display_name=str(display),error=missing,- install_hint=_INSTALL_HINTS.get(name, f"pip install 'vibe-trading-ai[{name}]'"),+ install_hint=_INSTALL_HINTS.get(+ name, f"pip install 'vibe-trading-ai[{name}]'"+ ),)return ChannelAvailability(name=name, available=True, display_name=str(display))except Exception as exc: # noqa: BLE001 - status API must report every adapter@@ -171,7 +180,9 @@ def inspect_channel(name: str) -> ChannelAvailability:available=False,display_name=name.replace("_", " ").title(),error=f"{type(exc).__name__}: {exc}",- install_hint=_INSTALL_HINTS.get(name, f"pip install 'vibe-trading-ai[{name}]'"),+ install_hint=_INSTALL_HINTS.get(+ name, f"pip install 'vibe-trading-ai[{name}]'"+ ),)@@ -191,7 +202,9 @@ def _config_section(config: Any, name: str) -> Any:def _configured_channel_names(config: Any) -> set[str]:if isinstance(config, Mapping):- return {str(key) for key in config.keys() if str(key) not in _GLOBAL_CONFIG_KEYS}+ return {+ str(key) for key in config.keys() if str(key) not in _GLOBAL_CONFIG_KEYS+ }model_dump = getattr(config, "model_dump", None)if callable(model_dump):return _configured_channel_names(model_dump(mode="json", by_alias=False))@@ -249,7 +262,9 @@ def discover_plugins(cls = ep.load()plugins[ep.name] = clsexcept Exception:- logger.warning("Failed to load channel plugin '%s': %s", ep.name, exc_info=True)+ logger.warning(+ "Failed to load channel plugin '%s': %s", ep.name, exc_info=True+ )return plugins@@ -278,12 +293,18 @@ def discover_enabled(external = discover_plugins(None if _include_all_external else enabled_names)shadowed = set(external) & set(result)if shadowed:- logger.warning("Plugin(s) shadowed by built-in channels (ignored): %s", shadowed)+ logger.warning(+ "Plugin(s) shadowed by built-in channels (ignored): %s", shadowed+ )if _include_all_external:result.update({k: v for k, v in external.items() if k not in shadowed})else:result.update(- {k: v for k, v in external.items() if k not in shadowed and k in enabled_names}+ {+ k: v+ for k, v in external.items()+ if k not in shadowed and k in enabled_names+ })return resultdiff --git a/agent/src/channels/token_probe.py b/agent/src/channels/token_probe.pynew file mode 100644index 000000000..66670088b--- /dev/null+++ b/agent/src/channels/token_probe.py@@ -0,0 +1,117 @@+"""Shared token-endpoint credential probe for IM channels.++This is the common building block for channels whose credentials validate+against a token endpoint (DingTalk's OAuth ``accessToken``, QQ's+``getAppAccessToken``). Everything here is stateless: callers pass the+endpoint URL, the JSON payload and the secret values explicitly, so a probe+never touches a channel's shared HTTP client and an unsaved credential set+can be checked before the channel is started.++Secrets are scrubbed from every ``detail`` before it reaches a result+envelope, and a successfully fetched token is discarded: it is never+returned, logged, or cached.+"""++from __future__ import annotations++from collections.abc import Iterable, Sequence+from typing import Any++import httpx+++def scrub_secrets(text: str, secrets: Iterable[str]) -> str:+ """Return diagnostic text with every non-empty secret value replaced.++ Transport and rejection messages can echo the request or credential by+ accident; each value the caller holds as a secret is masked before the+ text reaches a result envelope.+ """+ cleaned = text+ for secret in secrets:+ if secret:+ cleaned = cleaned.replace(secret, "***")+ return cleaned+++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 probe_token_endpoint(+ *,+ url: str,+ payload: dict[str, Any],+ token_key: str,+ secrets: Sequence[str],+ sdk_available: bool,+ transport: httpx.AsyncHTTPTransport | None = None,+ timeout: float = 10.0,+) -> dict[str, Any]:+ """Validate credentials with a standalone token-endpoint request.++ Uses a fresh ``httpx.AsyncClient`` rather than any channel's shared+ client, so the probe works before (or without) the channel being started.+ 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.+ 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; echoed+ back so the caller's envelope carries it unchanged.+ transport: Optional custom transport (e.g. an IPv4-bound one).+ timeout: Per-phase timeout in seconds for the fresh client.++ 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.+ """+ try:+ async with httpx.AsyncClient(+ timeout=httpx.Timeout(timeout, connect=timeout),+ transport=transport,+ ) as client:+ resp = await client.post(url, json=payload)+ except httpx.HTTPError as exc:+ return {+ "ok": False,+ "code": "network",+ "detail": scrub_secrets(str(exc) or type(exc).__name__, secrets),+ "sdk_available": sdk_available,+ }++ if resp.status_code == 200:+ try:+ token = resp.json().get(token_key)+ except ValueError:+ token = None+ if not token:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": "no access token in response",+ "sdk_available": sdk_available,+ }+ return {"ok": True, "code": "ok", "sdk_available": sdk_available}++ if 400 <= resp.status_code < 500:+ return {+ "ok": False,+ "code": "invalid_credentials",+ "detail": scrub_secrets(response_detail(resp), secrets),+ "sdk_available": sdk_available,+ }++ return {+ "ok": False,+ "code": "network",+ "detail": scrub_secrets(response_detail(resp), secrets),+ "sdk_available": sdk_available,+ }diff --git a/agent/tests/test_channel_config_meta.py b/agent/tests/test_channel_config_meta.pyindex 558950422..76b0d37b1 100644--- a/agent/tests/test_channel_config_meta.py+++ b/agent/tests/test_channel_config_meta.py@@ -1,8 +1,8 @@"""Tests for channel config field metadata and fail-safe secret masking.-Covers the uiHints registry (hand-written for DingTalk, derived elsewhere) and-the security acceptance criterion: no key matching :data:`SECRET_KEY_RE` ever-survives in the non-secret ``values`` half.+Covers the uiHints registry (hand-written for DingTalk and QQ, derived+elsewhere) and the security acceptance criterion: no key matching+:data:`SECRET_KEY_RE` ever survives in the non-secret ``values`` half."""from __future__ import annotations@@ -107,6 +107,70 @@ def test_dingtalk_field_hints_exact_snapshot() -> None:assert "enabled" not in {hint["key"] for hint in hints}+def test_qq_field_hints_exact_snapshot() -> None:+ """QQ hints match the frozen contract, with ``enabled`` excluded."""+ hints = channel_field_hints("qq")+ assert hints == [+ {+ "key": "app_id",+ "type": "text",+ "secret": False,+ "required": True,+ "help_key": "settings.channels.fields.qq.app_id",+ },+ {+ "key": "secret",+ "type": "password",+ "secret": True,+ "required": True,+ "help_key": "settings.channels.fields.qq.secret",+ },+ {+ "key": "allow_from",+ "type": "list",+ "secret": False,+ "required": False,+ "help_key": "settings.channels.fields.qq.allow_from",+ },+ {+ "key": "msg_format",+ "type": "text",+ "secret": False,+ "required": False,+ "help_key": "settings.channels.fields.qq.msg_format",+ },+ {+ "key": "ack_message",+ "type": "text",+ "secret": False,+ "required": False,+ "help_key": "settings.channels.fields.qq.ack_message",+ },+ {+ "key": "media_dir",+ "type": "text",+ "secret": False,+ "required": False,+ "help_key": "settings.channels.fields.qq.media_dir",+ },+ {+ "key": "download_chunk_size",+ "type": "text",+ "secret": False,+ "required": False,+ "help_key": "settings.channels.fields.qq.download_chunk_size",+ },+ {+ "key": "download_max_bytes",+ "type": "text",+ "secret": False,+ "required": False,+ "help_key": "settings.channels.fields.qq.download_max_bytes",+ },+ ]+ assert "enabled" not in {hint["key"] for hint in hints}++# --- (b) fallback derivation ------------------------------------------------- #diff --git a/agent/tests/test_qq_connection_test.py b/agent/tests/test_qq_connection_test.pynew file mode 100644index 000000000..542bd4921--- /dev/null+++ b/agent/tests/test_qq_connection_test.py@@ -0,0 +1,307 @@+"""Connection-test contract for the QQ channel.++Mirrors ``test_dingtalk_connection_test.py``: QQ implements the standalone+credential probe against ``getAppAccessToken`` and never touches+``self._http`` (which only exists after ``start()``). The contract codes the+frontend dispatches on are ``ok | invalid_credentials | network`` plus an+``sdk_available`` flag, and no credential or token value may ever leak into+the result or logs. QQ-specific: the endpoint may answer HTTP 200 with an+error body (``{"code": 100007, ...}``) for bad credentials, which the shared+"200 but no token" branch classifies as ``invalid_credentials``.+"""++from __future__ import annotations++import asyncio+import json+import logging+from pathlib import Path+from typing import Any++import httpx+import pytest++from src.channels.bus.queue import MessageBus+from src.channels.qq import QQ_AVAILABLE, QQChannel++TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken"+APP_ID = "qq-app-id-1234567890"+SECRET = "qq-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+++def _make_channel(+ tmp_path: Path,+ app_id: str = APP_ID,+ secret: str = SECRET,+) -> QQChannel:+ """Build a QQ channel that has NOT been started (no ``self._http``).++ ``QQChannel.__init__`` creates its media directory, so it is pinned under+ ``tmp_path`` to keep the test sandbox clean.+ """+ return QQChannel(+ {+ "app_id": app_id,+ "secret": secret,+ "media_dir": str(tmp_path / "qq-media"),+ },+ 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)+++# --------------------------------------------------------------------------- #+# QQ standalone probe — success+# --------------------------------------------------------------------------- #+++def test_success_returns_ok_and_discards_token(+ tmp_path: Path,+ 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")) == {+ "appId": APP_ID,+ "clientSecret": SECRET,+ }+ return httpx.Response(+ 200,+ json={"access_token": ACCESS_TOKEN, "expires_in": "7200"},+ )++ requests = _inject_mock_transport(monkeypatch, handler)+ channel = _make_channel(tmp_path)++ result = _run(channel.test_connection())++ assert len(requests) == 1+ assert result["ok"] is True+ assert result["code"] == "ok"+ assert result["sdk_available"] is QQ_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 SECRET not in serialized+++def test_success_uses_fresh_client_even_when_shared_client_present(+ tmp_path: Path,+ 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={"access_token": ACCESS_TOKEN})++ requests = _inject_mock_transport(monkeypatch, handler)+ channel = _make_channel(tmp_path)+ 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+++# --------------------------------------------------------------------------- #+# QQ standalone probe — invalid credentials+# --------------------------------------------------------------------------- #++[email protected]("status", [400, 401, 403])+def test_http_client_error_reports_invalid_credentials(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ status: int,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(status, json={"message": "invalid appId/clientSecret"})++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel(tmp_path).test_connection())++ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["sdk_available"] is QQ_AVAILABLE+ assert "detail" in result+ assert SECRET not in json.dumps(result)+ assert ACCESS_TOKEN not in json.dumps(result)+++def test_http_200_error_body_reports_invalid_credentials(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """QQ answers bad credentials with HTTP 200 and an error body."""++ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={"code": 100007, "message": "appId or clientSecret is invalid"},+ )++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel(tmp_path).test_connection())++ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["sdk_available"] is QQ_AVAILABLE+ assert SECRET not in json.dumps(result)+++ ("app_id", "secret"),+ [("", ""), (APP_ID, ""), ("", SECRET)],+)+def test_missing_credentials_short_circuit_without_network(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ app_id: str,+ 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(tmp_path, app_id, secret).test_connection())++ assert requests == []+ assert result["ok"] is False+ assert result["code"] == "invalid_credentials"+ assert result["detail"] == "missing credentials"+++# --------------------------------------------------------------------------- #+# QQ standalone probe — network+# --------------------------------------------------------------------------- #+++def test_transport_error_reports_network(+ tmp_path: Path,+ 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(tmp_path).test_connection())++ assert result["ok"] is False+ assert result["code"] == "network"+ assert result["sdk_available"] is QQ_AVAILABLE+ assert SECRET not in json.dumps(result)++[email protected]("status", [500, 502, 503])+def test_server_error_reports_network(+ tmp_path: Path,+ 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(tmp_path).test_connection())++ assert result["ok"] is False+ assert result["code"] == "network"+++# --------------------------------------------------------------------------- #+# Secret hygiene+# --------------------------------------------------------------------------- #+++def test_probe_never_logs_secret_or_token(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ def ok_handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"access_token": ACCESS_TOKEN})++ _inject_mock_transport(monkeypatch, ok_handler)+ with caplog.at_level(logging.DEBUG):+ # Construction happens INSIDE the capture block on purpose: the+ # constructor logs the media directory, so a loguru-style "{}" format+ # string (which stdlib logging cannot render) would make pytest's+ # caplog handler raise TypeError and fail this test.+ success = _run(_make_channel(tmp_path).test_connection())++ def reject_handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"bad secret {SECRET}")++ _inject_mock_transport(monkeypatch, reject_handler)+ with caplog.at_level(logging.DEBUG):+ failure = _run(_make_channel(tmp_path).test_connection())++ assert success["code"] == "ok"+ assert failure["code"] == "invalid_credentials"+ assert "media directory:" in caplog.text+ assert 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 SECRET not in json.dumps(failure)+++def test_rejection_detail_scrubs_echoed_secret(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"clientSecret {SECRET} is invalid")++ _inject_mock_transport(monkeypatch, handler)++ result = _run(_make_channel(tmp_path).test_connection())++ assert result["code"] == "invalid_credentials"+ assert SECRET not in json.dumps(result)+ assert "detail" in result