Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(api): channel-agnostic form metadata and symmetric unknown-key rejection

shadowinlife5e9883e058eb
diff --git a/agent/src/api/channels_config_routes.py b/agent/src/api/channels_config_routes.py
index 8c92ec2c1..d0f271606 100644
--- a/agent/src/api/channels_config_routes.py
+++ b/agent/src/api/channels_config_routes.py
@@ -136,12 +136,24 @@ def _effective_section(name: str, section: dict[str, Any]) -> dict[str, Any]:
try:
defaults = load_channel_class(name).default_config()
except Exception: # noqa: BLE001 - an unloadable adapter keeps the raw section
+ logger.debug("Config defaults unavailable for channel '%s'", name, exc_info=True)
return section
if not isinstance(defaults, dict):
return section
return {**defaults, **section}
+def _unknown_keys(cls: type, patch: dict[str, Any]) -> list[str]:
+ """Return patch keys that are neither adapter fields nor manager overrides.
+
+ Shared by PUT and POST /test so both reject an unrecognized key with the
+ same 422 instead of one writing-refusing and one silently dropping it
+ into the probe instance (pydantic ``extra="ignore"``).
+ """
+ allowed = set(cls.default_config()) | _MANAGER_OVERRIDE_KEYS
+ return sorted(key for key in patch if key not in allowed)
+
+
def _patch_of(name: str, body: dict[str, Any]) -> dict[str, Any]:
"""Filter a body patch: an empty string on a secret key keeps the stored value."""
return {
@@ -313,11 +325,7 @@ async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[
cls, instance = _build_ephemeral(name, merged)
- unknown = sorted(
- key
- for key in patch
- if key not in set(cls.default_config()) and key not in _MANAGER_OVERRIDE_KEYS
- )
+ unknown = _unknown_keys(cls, patch)
if unknown:
raise _reject_validation(unknown)
@@ -359,7 +367,8 @@ async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[
async def _run_test(name: str, body: dict[str, Any] | None, clears: list[str]) -> dict[str, Any]:
"""Probe credentials on an ephemeral instance; never persists anything."""
stored = _stored_section(name)
- merged = {**stored, **_patch_of(name, body or {})}
+ patch = _patch_of(name, body or {})
+ merged = {**stored, **patch}
for key in clears:
merged.pop(key, None)
tested_saved_config = not body
@@ -382,6 +391,10 @@ async def _run_test(name: str, body: dict[str, Any] | None, clears: list[str]) -
# Nothing network-facing is constructed for an unsupported channel.
return _result(False, "unsupported", "", sdk_fallback)
+ unknown = _unknown_keys(cls, patch)
+ if unknown:
+ raise _reject_validation(unknown)
+
try:
instance = cls(merged, MessageBus())
except ValidationError as exc:
diff --git a/agent/src/channels/config_meta.py b/agent/src/channels/config_meta.py
index 19ca76069..a5df3e5d0 100644
--- a/agent/src/channels/config_meta.py
+++ b/agent/src/channels/config_meta.py
@@ -131,6 +131,14 @@ def _derive_hints(name: str) -> list[FieldHint]:
for key, value in config.items():
if key in _EXCLUDED_KEYS:
continue
+ if isinstance(value, dict):
+ # The generic form edits text/password/bool/list widgets only;
+ # a dict-valued field cannot be represented and would render as
+ # "[object Object]". Such fields stay file-configured (their
+ # values still travel in GET ``values``, the form just omits
+ # them). Secret masking is unaffected: derived hints only mark
+ # what SECRET_KEY_RE already catches unconditionally.
+ continue
secret = bool(SECRET_KEY_RE.search(key))
hints.append(
{
diff --git a/agent/tests/test_channel_config_meta.py b/agent/tests/test_channel_config_meta.py
index 76b0d37b1..f9e63bc7d 100644
--- a/agent/tests/test_channel_config_meta.py
+++ b/agent/tests/test_channel_config_meta.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import pytest
+from src.channels import config_meta as _config_meta
from src.channels.config_meta import (
SECRET_KEY_RE,
channel_field_hints,
@@ -188,6 +189,9 @@ def test_fallback_derives_types_and_secret_flags(name: str) -> None:
for key, value in config.items():
if key == "enabled":
continue
+ if isinstance(value, dict):
+ assert key not in by_key
+ continue
hint = by_key[key]
assert hint["required"] is False
assert hint["help_key"] is None
@@ -204,6 +208,59 @@ def test_fallback_derives_types_and_secret_flags(name: str) -> None:
assert hint["type"] == "text"
+def test_dict_valued_defaults_are_excluded_from_derived_hints(monkeypatch) -> None:
+ """Dict-valued fields stay out of derived hints (hermetic stub pin).
+
+ The generic form edits text/password/bool/list widgets only; a dict
+ field derived as ``text`` rendered as "[object Object]" once the GET
+ defaults backfill reached pristine forms. Excluded from hints, still
+ present in ``values``, secret masking untouched.
+ """
+
+ class _Stub:
+ @staticmethod
+ def default_config() -> dict:
+ return {
+ "enabled": False,
+ "bot_token": "",
+ "dm": {},
+ "policies": {"mention": {}},
+ "name": "",
+ }
+
+ monkeypatch.setattr(_config_meta, "load_channel_class", lambda name: _Stub)
+
+ hints = channel_field_hints("stub_dict_channel")
+ assert {hint["key"] for hint in hints} == {"bot_token", "name"}
+ by_key = {hint["key"]: hint for hint in hints}
+ assert by_key["bot_token"]["type"] == "password"
+ assert by_key["bot_token"]["secret"] is True
+
+ values, secrets = split_values_secrets("stub_dict_channel", _Stub.default_config())
+ assert {"dm", "policies"} <= set(values)
+ assert "bot_token" in secrets
+
+
+def test_dict_valued_defaults_are_excluded_for_real_adapters() -> None:
+ """Same rule against a real adapter shape (signal's dm/group policy maps).
+
+ whatsapp ``lid_mappings``, napcat ``group_policy_overrides`` and mochat
+ ``mention``/``groups`` are the same class; signal is the loadable
+ representative here.
+ """
+ config = _section_for("signal")
+ if config is None:
+ pytest.skip("signal adapter unloadable in this environment")
+ dict_keys = {key for key, value in config.items() if isinstance(value, dict)}
+ assert dict_keys, "signal should expose dict-valued defaults"
+
+ hint_keys = {hint["key"] for hint in channel_field_hints("signal")}
+ assert not (dict_keys & hint_keys)
+
+ values, _ = split_values_secrets("signal", config)
+ assert dict_keys <= set(values)
+
+
def test_unloadable_adapter_is_handled_gracefully() -> None:
"""Adapters whose SDK is missing yield no hints instead of raising."""
for name in ADAPTER_NAMES:
diff --git a/agent/tests/test_channels_config_api.py b/agent/tests/test_channels_config_api.py
index 4163e433b..cbb98db30 100644
--- a/agent/tests/test_channels_config_api.py
+++ b/agent/tests/test_channels_config_api.py
@@ -756,6 +756,32 @@ def test_post_test_non_object_json_200_returns_envelope_not_500(
assert STORED_SECRET not in response.text
+def test_post_test_rejects_unknown_config_keys(tmp_path: Path, monkeypatch) -> None:
+ """POST /test shares PUT's unknown-key rejection instead of silently
+ dropping the keys through pydantic ``extra="ignore"`` into the probe."""
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover
+ raise AssertionError("an unknown key must be rejected before any probe")
+
+ requests = _inject_mock_transport(monkeypatch, handler)
+
+ response = client.post(
+ "/channels/dingtalk/test",
+ json={"config": {"definitely_unknown_key": 1, "__proto__": 1}},
+ )
+
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert detail["code"] == "validation_error"
+ assert {"definitely_unknown_key", "__proto__"} <= set(detail["fields"])
+ assert requests == []
+ assert path.read_bytes() == before
+
+
def test_post_test_honors_pending_secret_clear(tmp_path: Path, monkeypatch) -> None:
client, path = _client(
tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}