Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(api): channel config routes with validate-on-save and hot apply

shadowinlife42f5f0794803
diff --git a/agent/api_server.py b/agent/api_server.py
index bb6757d7d..304b4164a 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -237,6 +237,8 @@ from src.api.uploads_routes import ( # noqa: F401, E402
# --- Channels ---
from src.api.channels_routes import register_channels_routes # noqa: E402
register_channels_routes(app)
+from src.api.channels_config_routes import register_channels_config_routes # noqa: E402
+register_channels_config_routes(app)
from src.api.qveris_routes import qveris_router # noqa: E402 # QVERIS-INTEGRATION
app.include_router(qveris_router) # QVERIS-INTEGRATION
diff --git a/agent/src/api/channels_config_routes.py b/agent/src/api/channels_config_routes.py
new file mode 100644
index 000000000..0a2ceb5a8
--- /dev/null
+++ b/agent/src/api/channels_config_routes.py
@@ -0,0 +1,396 @@
+"""IM channel configuration HTTP routes (web config forms + hot update).
+
+Mounted by ``agent/api_server.py`` via ``register_channels_config_routes(app, ...)``.
+Composes the delivered building blocks — the atomic writer
+(:func:`src.config.writer.update_channel_section`), the connection-test hook
+(:meth:`src.channels.base.BaseChannel.test_connection`), per-channel hot reload
+(:meth:`src.channels.manager.ChannelManager.reload_channel` +
+:func:`src.api.state.reset_channel_runtime`) and field metadata
+(:mod:`src.channels.config_meta`) — without reimplementing any of them.
+
+Security properties owned here: secret values never cross the wire (masked via
+``split_values_secrets``), and a section that fails validation or the
+enable-transition credential probe is rejected with 422 *before* anything is
+written to disk.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import sys as _sys
+from collections import defaultdict
+from typing import Any, Awaitable, Callable
+
+from fastapi import Depends, FastAPI, HTTPException, status
+from pydantic import BaseModel, ConfigDict, Field, ValidationError
+
+from src.api import state as _state
+from src.channels import config as _channels_config
+from src.channels.bus.queue import MessageBus
+from src.channels.config_meta import SECRET_KEY_RE, channel_field_hints, split_values_secrets
+from src.channels.registry import (
+ discover_channel_names,
+ inspect_channel,
+ inspect_channels,
+ load_channel_class,
+)
+from src.config import writer as _config_writer
+from src.config.paths import get_config_path
+
+logger = logging.getLogger(__name__)
+
+# Helper modules in src/channels/ that are not adapters; discovery enumerates them.
+_NON_CHANNEL_MODULES = frozenset({"targets", "config_meta"})
+
+_PROBE_CODES = frozenset({"ok", "invalid_credentials", "network", "unsupported"})
+_VERIFY_BLOCK_CODES = frozenset({"invalid_credentials", "network"})
+
+# Per-channel PUT/test serialization + one lock around runtime reset/rebuild.
+_channel_locks: defaultdict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
+_runtime_lock = asyncio.Lock()
+
+
+# ---------------------------------------------------------------------------
+# Pydantic models (defined locally -- NO shared modules, per maintainer rule)
+# ---------------------------------------------------------------------------
+
+
+class ChannelConfigUpdateRequest(BaseModel):
+ """Merge-patch body for one channel section.
+
+ ``clear_<field>: true`` flags arrive as extra keys and remove the stored
+ key (used for secrets the form never echoes back).
+ """
+
+ model_config = ConfigDict(extra="allow")
+
+ config: dict[str, Any] = Field(default_factory=dict)
+ skip_verify: bool = False
+
+
+class ChannelTestRequest(BaseModel):
+ """Optional unsaved partial config for an ephemeral connection test."""
+
+ config: dict[str, Any] | None = None
+
+
+# ---------------------------------------------------------------------------
+# Helpers (host state resolved via sys.modules, late-access for monkeypatch)
+# ---------------------------------------------------------------------------
+
+
+def _host():
+ """Return the ``api_server`` host module for late-access attribute reads."""
+ return _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+
+
+def _known_channel_names() -> set[str]:
+ """Return discovered channel adapter names, minus non-channel helpers."""
+ return set(discover_channel_names()) - _NON_CHANNEL_MODULES
+
+
+def _is_secret_key(name: str, key: str) -> bool:
+ """Return whether a config key must never cross the wire in clear."""
+ if SECRET_KEY_RE.search(key):
+ return True
+ return any(hint["key"] == key and hint["secret"] for hint in channel_field_hints(name))
+
+
+def _stored_section(name: str) -> dict[str, Any]:
+ """Return the channel's current on-disk config section."""
+ section = _channels_config.load_channels_config().get(name)
+ return dict(section) if isinstance(section, dict) else {}
+
+
+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 {
+ key: value
+ for key, value in body.items()
+ if not (_is_secret_key(name, key) and isinstance(value, str) and not value.strip())
+ }
+
+
+def _supports_connection_test(name: str) -> bool:
+ """Return whether the adapter class declares a standalone connection test."""
+ try:
+ return bool(load_channel_class(name).supports_connection_test)
+ except Exception: # noqa: BLE001 - an unloadable adapter has no test support
+ return False
+
+
+def _live_status(name: str) -> dict[str, Any]:
+ """Return the running manager's status entry for *name* ({} if no runtime)."""
+ runtime = getattr(_host(), "_channel_runtime", None)
+ if runtime is None:
+ return {}
+ live = (runtime.status().get("channels") or {}).get(name)
+ return dict(live) if isinstance(live, dict) else {}
+
+
+def _channel_entry(name: str, section: dict[str, Any], status_map: dict[str, Any]) -> dict[str, Any]:
+ """Build one channel's GET-shape entry; secrets are masked, never returned."""
+ values, secrets = split_values_secrets(name, section)
+ available = bool(status_map.get("available", False))
+ return {
+ "display_name": str(status_map.get("display_name") or name),
+ "available": available,
+ "loaded": bool(status_map.get("loaded", False)),
+ "install_hint": str(status_map.get("install_hint") or ""),
+ "error": str(status_map.get("error") or ""),
+ "supports_test": _supports_connection_test(name),
+ "sdk_available": bool(status_map.get("sdk_available", available)),
+ "fields": channel_field_hints(name),
+ "values": values,
+ "secrets": secrets,
+ }
+
+
+def _fresh_entry(name: str) -> dict[str, Any]:
+ """Build a channel entry from the current disk section + merged status."""
+ status_map = inspect_channel(name).to_dict()
+ status_map.update(_live_status(name))
+ return _channel_entry(name, _stored_section(name), status_map)
+
+
+def _scrub_detail(name: str, text: Any, section: dict[str, Any]) -> str:
+ """Mask every secret value of *section* found in *text* (defense in depth)."""
+ cleaned = str(text or "")
+ for key, value in section.items():
+ if _is_secret_key(name, key) and isinstance(value, str) and value:
+ cleaned = cleaned.replace(value, "***")
+ return cleaned
+
+
+def _validation_fields(exc: ValidationError) -> list[str]:
+ """Return error field locations from a ValidationError (never values)."""
+ fields: list[str] = []
+ for error in exc.errors():
+ loc = ".".join(str(part) for part in error.get("loc", ()))
+ fields.append(loc or str(error.get("type", "invalid")))
+ return fields
+
+
+def _reject_validation(fields: list[str]) -> HTTPException:
+ """Build the frozen 422 ``validation_error`` envelope."""
+ return HTTPException(
+ status_code=422, # literal per repo convention (the starlette constant is deprecated)
+ detail={"code": "validation_error", "fields": fields},
+ )
+
+
+def _build_ephemeral(name: str, section: dict[str, Any]) -> tuple[type, Any]:
+ """Construct a throwaway adapter instance to validate *section*.
+
+ Mirrors ``ChannelManager._build_channel`` construction. Raises the frozen
+ 422 ``validation_error`` envelope when the section cannot build; error
+ values (which may echo secrets) never leave this function.
+ """
+ try:
+ cls = load_channel_class(name)
+ except Exception as exc: # noqa: BLE001 - an unloadable adapter cannot validate
+ raise _reject_validation([type(exc).__name__]) from None
+ try:
+ return cls, cls(section, MessageBus())
+ except ValidationError as exc:
+ raise _reject_validation(_validation_fields(exc)) from None
+ except Exception as exc: # noqa: BLE001 - any construction error is a config error
+ raise _reject_validation([type(exc).__name__]) from None
+
+
+async def _hot_apply(name: str, section: dict[str, Any] | None) -> str:
+ """Apply a written section to the cached runtime; return the apply mode.
+
+ Running runtime → per-channel hot swap; built-but-stopped → drop the stale
+ singleton so the next explicit Start reads fresh config; never built →
+ no-op (the lazy build reads disk). A failed swap falls back to a full
+ reset + restart through the same path ``/channels/start`` uses.
+ """
+ host = _host()
+ runtime = getattr(host, "_channel_runtime", None)
+ if runtime is None:
+ return "deferred"
+ if not runtime.status().get("running"):
+ async with _runtime_lock:
+ _state.reset_channel_runtime()
+ return "reset"
+ try:
+ await runtime.manager.reload_channel(name, section)
+ return "hot_swapped"
+ except Exception: # noqa: BLE001 - a failed swap must not strand the runtime
+ logger.warning(
+ "Hot reload failed for channel %s; falling back to a runtime reset",
+ name,
+ exc_info=True,
+ )
+ async with _runtime_lock:
+ _state.reset_channel_runtime()
+ await host._get_channel_runtime().start(start_manager=True)
+ return "reset"
+
+
+async def _apply_update(name: str, payload: ChannelConfigUpdateRequest) -> dict[str, Any]:
+ """Validate → optional enable-transition probe → write → hot apply."""
+ stored = _stored_section(name)
+ patch = _patch_of(name, payload.config)
+ clears = [
+ key[len("clear_"):]
+ for key, value in (payload.model_extra or {}).items()
+ if key.startswith("clear_") and len(key) > len("clear_") and value
+ ]
+ merged = {**stored, **patch}
+ for key in clears:
+ merged.pop(key, None)
+
+ cls, instance = _build_ephemeral(name, merged)
+
+ enabling = bool(merged.get("enabled")) and not bool(stored.get("enabled"))
+ if enabling and cls.supports_connection_test and not payload.skip_verify:
+ probe = await instance.test_connection()
+ if not probe.get("ok"):
+ code = probe.get("code")
+ raise HTTPException(
+ status_code=422,
+ detail={"code": code if code in _VERIFY_BLOCK_CODES else "network", "fields": []},
+ )
+
+ try:
+ _config_writer.update_channel_section(name, patch, clears=clears)
+ except _config_writer.ConfigNotWritableError:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"code": "config_not_writable"},
+ ) from None
+
+ fresh = _stored_section(name)
+ applied = await _hot_apply(name, fresh or None)
+ return {"channel": _fresh_entry(name), "applied": applied}
+
+
+async def _run_test(name: str, body: dict[str, Any] | None) -> dict[str, Any]:
+ """Probe credentials on an ephemeral instance; never persists anything."""
+ stored = _stored_section(name)
+ merged = {**stored, **_patch_of(name, body or {})}
+ tested_saved_config = not body
+ sdk_fallback = bool(inspect_channel(name).to_dict().get("available", False))
+
+ def _result(ok: bool, code: str, detail: str, sdk_available: bool) -> dict[str, Any]:
+ return {
+ "ok": ok,
+ "code": code,
+ "detail": _scrub_detail(name, detail, merged),
+ "sdk_available": sdk_available,
+ "tested_saved_config": tested_saved_config,
+ }
+
+ try:
+ cls = load_channel_class(name)
+ except Exception: # noqa: BLE001 - an unloadable adapter cannot be probed
+ cls = None
+ if cls is None or not getattr(cls, "supports_connection_test", False):
+ # Nothing network-facing is constructed for an unsupported channel.
+ return _result(False, "unsupported", "", sdk_fallback)
+
+ try:
+ instance = cls(merged, MessageBus())
+ except ValidationError as exc:
+ detail = "validation_error: " + ", ".join(_validation_fields(exc))
+ return _result(False, "invalid_credentials", detail, sdk_fallback)
+ except Exception as exc: # noqa: BLE001 - a broken section cannot be probed
+ return _result(False, "invalid_credentials", f"validation_error: {type(exc).__name__}", sdk_fallback)
+
+ probe = await instance.test_connection()
+ code = probe.get("code")
+ sdk_available = probe.get("sdk_available")
+ return _result(
+ bool(probe.get("ok")),
+ code if code in _PROBE_CODES else "network",
+ probe.get("detail", ""),
+ bool(sdk_available) if sdk_available is not None else sdk_fallback,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Registration
+# ---------------------------------------------------------------------------
+
+AuthDep = Callable[..., Awaitable[Any] | Any]
+
+
+def register_channels_config_routes(
+ app: FastAPI,
+ require_auth: AuthDep | None = None,
+ require_settings_write_auth: AuthDep | None = None,
+) -> None:
+ """Mount the channel-config routes onto ``app``.
+
+ Resolves the auth dependencies from the host ``api_server`` module via
+ ``sys.modules`` when not passed explicitly (same idiom as
+ ``channels_routes`` / ``settings_routes``).
+ """
+ host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
+
+ if host is None:
+ raise RuntimeError(
+ "register_channels_config_routes: api_server module not in sys.modules; "
+ "ensure api_server is imported before calling this function"
+ )
+
+ if require_auth is None:
+ require_auth = host.require_auth
+ if require_settings_write_auth is None:
+ require_settings_write_auth = host.require_settings_write_auth
+
+ @app.get("/channels/config", dependencies=[Depends(require_auth)])
+ async def get_channels_config():
+ """Return every channel's config form data with masked secrets."""
+ availability = inspect_channels()
+ disk = _channels_config.load_channels_config()
+ runtime = getattr(host, "_channel_runtime", None)
+ running = False
+ live: dict[str, Any] = {}
+ if runtime is not None:
+ snapshot = runtime.status()
+ running = bool(snapshot.get("running"))
+ live = snapshot.get("channels") or {}
+
+ path = get_config_path()
+ channels: dict[str, Any] = {}
+ for name in sorted(set(availability) - _NON_CHANNEL_MODULES):
+ section = disk.get(name)
+ status_map = dict(availability[name])
+ live_entry = live.get(name)
+ if isinstance(live_entry, dict):
+ status_map.update(live_entry)
+ channels[name] = _channel_entry(
+ name, section if isinstance(section, dict) else {}, status_map
+ )
+ return {
+ "config_path": str(path),
+ "writable": path.suffix.lower() == ".json",
+ "runtime_running": running,
+ "channels": channels,
+ }
+
+ @app.put(
+ "/channels/config/{name}",
+ dependencies=[Depends(require_settings_write_auth)],
+ )
+ async def put_channel_config(name: str, payload: ChannelConfigUpdateRequest):
+ """Merge-patch one channel section with pre-write validation + hot apply."""
+ if name not in _known_channel_names():
+ raise HTTPException(status_code=404, detail=f"Unknown channel: {name}")
+ async with _channel_locks[name]:
+ return await _apply_update(name, payload)
+
+ @app.post(
+ "/channels/{name}/test",
+ dependencies=[Depends(require_settings_write_auth)],
+ )
+ async def post_channel_test(name: str, payload: ChannelTestRequest):
+ """Probe credentials ephemerally; never writes to the config file."""
+ if name not in _known_channel_names():
+ raise HTTPException(status_code=404, detail=f"Unknown channel: {name}")
+ async with _channel_locks[name]:
+ return await _run_test(name, payload.config)
diff --git a/agent/tests/test_channels_config_api.py b/agent/tests/test_channels_config_api.py
new file mode 100644
index 000000000..05848fe52
--- /dev/null
+++ b/agent/tests/test_channels_config_api.py
@@ -0,0 +1,612 @@
+"""API contracts for the web IM channel-config surface (Task 5).
+
+Covers the frozen contract from ``.omo/plans/im-channel-web-config.md``:
+``GET /channels/config``, ``PUT /channels/config/{name}`` and
+``POST /channels/{name}/test`` — secret masking, the 422-before-write ordering
+(bad credentials never reach disk), hot-apply modes (hot_swapped / reset /
+deferred), per-channel lock serialization, and the never-persist guarantee of
+the test endpoint. No secret value may appear in any response body.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+import yaml
+from fastapi.testclient import TestClient
+
+import api_server
+from src.api import channels_config_routes as routes
+from src.api import state as api_state
+from src.channels.dingtalk import DINGTALK_AVAILABLE
+
+CLIENT_ID = "ding-client-id-1234567890"
+STORED_SECRET = "stored-secret-abcdefghij"
+UNSAVED_SECRET = "unsaved-secret-xyz987654321"
+
+# Captured before any test monkeypatches httpx, so repeated injections in a
+# single test still wrap the real client (test_dingtalk_connection_test idiom).
+_REAL_ASYNC_CLIENT = httpx.AsyncClient
+
+
+class FakeSessionService:
+ """SessionService placeholder so a runtime build never touches real state."""
+
+
+class FakeManager:
+ """Records ``reload_channel`` calls; optional delay exposes lock overlap."""
+
+ def __init__(self, *, delay: float = 0.0, fail: bool = False) -> None:
+ self.reload_calls: list[tuple[str, dict | None]] = []
+ self.active = 0
+ self.max_active = 0
+ self._delay = delay
+ self._fail = fail
+
+ async def reload_channel(self, name: str, section: dict | None) -> dict[str, Any]:
+ if self._fail:
+ raise RuntimeError("reload boom")
+ self.reload_calls.append((name, section))
+ self.active += 1
+ self.max_active = max(self.max_active, self.active)
+ try:
+ if self._delay:
+ await asyncio.sleep(self._delay)
+ finally:
+ self.active -= 1
+ return {"loaded": bool(section and section.get("enabled"))}
+
+
+class FakeRuntime:
+ """Stands in for ChannelRuntime: an authoritative running flag + manager."""
+
+ def __init__(self, *, running: bool, manager: FakeManager | None = None) -> None:
+ self._running = running
+ self.manager = manager if manager is not None else FakeManager()
+ self.start_calls: list[bool] = []
+
+ def status(self) -> dict[str, Any]:
+ return {"running": self._running, "channels": {}}
+
+ async def start(self, *, start_manager: bool = True) -> None:
+ self.start_calls.append(start_manager)
+
+
+def _write_agent_config(
+ tmp_path: Path, channels: dict[str, Any], *, suffix: str = ".json"
+) -> Path:
+ path = tmp_path / f"agent{suffix}"
+ payload = {"channels": channels}
+ if suffix == ".json":
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ else:
+ path.write_text(yaml.safe_dump(payload), encoding="utf-8")
+ return path
+
+
+def _client(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ channels: dict[str, Any] | None = None,
+ runtime: Any = None,
+ suffix: str = ".json",
+) -> tuple[TestClient, Path]:
+ """Point the config root at *tmp_path* and mount the app test client."""
+ config_path = _write_agent_config(tmp_path, channels or {}, suffix=suffix)
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path))
+ monkeypatch.setattr(api_server, "_channel_runtime", runtime)
+ monkeypatch.setattr(api_server, "_channel_bus", None)
+ monkeypatch.setattr(api_server, "_channel_manager", None)
+ monkeypatch.setattr(api_server, "_get_session_service", lambda: FakeSessionService())
+ return TestClient(api_server.app, client=("127.0.0.1", 50000)), config_path
+
+
[email protected](autouse=True)
+def _fresh_locks():
+ """Give every test unbound locks (asyncio.Lock binds to a loop on contention)."""
+ routes._channel_locks.clear()
+ routes._runtime_lock = asyncio.Lock()
+ yield
+ routes._channel_locks.clear()
+ routes._runtime_lock = asyncio.Lock()
+
+
+def _dingtalk_section(**overrides: Any) -> dict[str, Any]:
+ section: dict[str, Any] = {
+ "enabled": False,
+ "client_id": CLIENT_ID,
+ "client_secret": STORED_SECRET,
+ "allow_from": ["*"],
+ }
+ section.update(overrides)
+ return section
+
+
+def _inject_mock_transport(
+ monkeypatch: pytest.MonkeyPatch, handler: Any
+) -> list[httpx.Request]:
+ """Route the probe's fresh ``httpx.AsyncClient`` through a MockTransport."""
+ 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
+
+
+# --------------------------------------------------------------------------- #
+# GET /channels/config
+# --------------------------------------------------------------------------- #
+
+
+def test_get_masks_secrets_and_reports_writable(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+
+ response = client.get("/channels/config")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["config_path"] == str(path)
+ assert payload["writable"] is True
+ assert payload["runtime_running"] is False
+
+ entry = payload["channels"]["dingtalk"]
+ assert entry["display_name"] == "DingTalk"
+ assert entry["supports_test"] is True
+ assert entry["sdk_available"] is DINGTALK_AVAILABLE
+ assert entry["values"]["client_id"] == CLIENT_ID
+ assert entry["values"]["enabled"] is False
+ assert "client_secret" not in entry["values"]
+ assert entry["secrets"]["client_secret"] == {"set": True, "masked": "****ghij"}
+ keys = {field["key"] for field in entry["fields"]}
+ assert keys >= {"client_id", "client_secret", "allow_from"}
+ assert "enabled" not in keys
+ client_id_hint = next(f for f in entry["fields"] if f["key"] == "client_id")
+ assert client_id_hint["help_key"] == "settings.channels.fields.dingtalk.client_id"
+ assert client_id_hint["secret"] is False
+
+ assert STORED_SECRET not in response.text
+ # GET is read-only: it must not build the runtime singleton.
+ assert api_server._channel_runtime is None
+
+
+def test_get_excludes_non_channel_helper_modules(tmp_path: Path, monkeypatch) -> None:
+ client, _ = _client(tmp_path, monkeypatch)
+
+ payload = client.get("/channels/config").json()
+
+ assert "targets" not in payload["channels"]
+ assert "config_meta" not in payload["channels"]
+ assert "dingtalk" in payload["channels"]
+
+
+def test_get_reports_not_writable_for_yaml_config(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path,
+ monkeypatch,
+ channels={"dingtalk": _dingtalk_section()},
+ suffix=".yaml",
+ )
+
+ response = client.get("/channels/config")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["writable"] is False
+ assert payload["config_path"] == str(path)
+ assert payload["channels"]["dingtalk"]["values"]["client_id"] == CLIENT_ID
+ assert STORED_SECRET not in response.text
+
+
+def test_get_reports_runtime_running_from_live_status(tmp_path: Path, monkeypatch) -> None:
+ client, _ = _client(
+ tmp_path,
+ monkeypatch,
+ channels={"dingtalk": _dingtalk_section()},
+ runtime=FakeRuntime(running=True),
+ )
+
+ payload = client.get("/channels/config").json()
+
+ assert payload["runtime_running"] is True
+
+
+# --------------------------------------------------------------------------- #
+# PUT /channels/config/{name}
+# --------------------------------------------------------------------------- #
+
+
+def test_put_writes_file_and_hot_swaps_running_runtime(tmp_path: Path, monkeypatch) -> None:
+ runtime = FakeRuntime(running=True)
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
+ )
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_id": "new-client-id"}}
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["applied"] == "hot_swapped"
+ assert body["channel"]["values"]["client_id"] == "new-client-id"
+ assert body["channel"]["secrets"]["client_secret"]["set"] is True
+
+ on_disk = json.loads(path.read_text(encoding="utf-8"))["channels"]["dingtalk"]
+ assert on_disk["client_id"] == "new-client-id"
+ # A secret absent from the patch keeps its stored value.
+ assert on_disk["client_secret"] == STORED_SECRET
+
+ assert runtime.manager.reload_calls == [
+ ("dingtalk", {**on_disk}),
+ ]
+ assert STORED_SECRET not in response.text
+
+
+def test_put_empty_secret_string_keeps_stored_value(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_secret": ""}}
+ )
+
+ assert response.status_code == 200
+ on_disk = json.loads(path.read_text(encoding="utf-8"))["channels"]["dingtalk"]
+ assert on_disk["client_secret"] == STORED_SECRET
+ assert STORED_SECRET not in response.text
+
+
+def test_put_enable_with_bad_credentials_is_blocked_before_write(
+ tmp_path: Path, monkeypatch
+) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, json={"message": "invalid appKey/appSecret"})
+
+ requests = _inject_mock_transport(monkeypatch, handler)
+
+ response = client.put("/channels/config/dingtalk", 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
+ # The security property: bad credentials never reach disk.
+ assert path.read_bytes() == before
+ assert api_server._channel_runtime is None
+ assert STORED_SECRET not in response.text
+
+
+def test_put_enable_skip_verify_writes_without_probe(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+
+ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover
+ raise AssertionError("probe must not run with skip_verify")
+
+ _inject_mock_transport(monkeypatch, handler)
+
+ response = client.put(
+ "/channels/config/dingtalk",
+ json={"config": {"enabled": True}, "skip_verify": True},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "deferred"
+ on_disk = json.loads(path.read_text(encoding="utf-8"))["channels"]["dingtalk"]
+ assert on_disk["enabled"] is True
+
+
+def test_put_validation_error_blocks_write(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"allow_from": "not-a-list"}}
+ )
+
+ assert response.status_code == 422
+ detail = response.json()["detail"]
+ assert detail["code"] == "validation_error"
+ assert "allow_from" in detail["fields"]
+ assert path.read_bytes() == before
+ assert STORED_SECRET not in response.text
+
+
+def test_put_clear_flag_removes_stored_secret(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {}, "clear_client_secret": True}
+ )
+
+ assert response.status_code == 200
+ on_disk = json.loads(path.read_text(encoding="utf-8"))["channels"]["dingtalk"]
+ assert "client_secret" not in on_disk
+ assert on_disk["client_id"] == CLIENT_ID
+ entry = response.json()["channel"]
+ assert entry["secrets"].get("client_secret", {"set": False})["set"] is False
+ assert STORED_SECRET not in response.text
+
+
+def test_put_yaml_config_returns_config_not_writable(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path,
+ monkeypatch,
+ channels={"dingtalk": _dingtalk_section()},
+ suffix=".yaml",
+ )
+ before = path.read_bytes()
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_id": "x"}}
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == {"code": "config_not_writable"}
+ assert path.read_bytes() == before
+
+
+def test_put_with_stopped_runtime_resets_singleton(tmp_path: Path, monkeypatch) -> None:
+ runtime = FakeRuntime(running=False)
+ client, _ = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
+ )
+ resets: list[bool] = []
+ monkeypatch.setattr(api_state, "reset_channel_runtime", lambda: resets.append(True))
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_id": "stopped-id"}}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "reset"
+ assert resets == [True]
+ assert runtime.manager.reload_calls == []
+
+
+def test_put_without_runtime_defers(tmp_path: Path, monkeypatch) -> None:
+ client, _ = _client(tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()})
+ resets: list[bool] = []
+ monkeypatch.setattr(api_state, "reset_channel_runtime", lambda: resets.append(True))
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_id": "deferred-id"}}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "deferred"
+ assert resets == []
+ assert api_server._channel_runtime is None
+
+
+def test_put_reload_failure_falls_back_to_reset_and_restart(
+ tmp_path: Path, monkeypatch
+) -> None:
+ runtime = FakeRuntime(running=True, manager=FakeManager(fail=True))
+ client, _ = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
+ )
+ resets: list[bool] = []
+ monkeypatch.setattr(api_state, "reset_channel_runtime", lambda: resets.append(True))
+
+ response = client.put(
+ "/channels/config/dingtalk", json={"config": {"client_id": "fallback-id"}}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["applied"] == "reset"
+ assert resets == [True]
+ # The fallback restarts through the same path /channels/start uses.
+ assert runtime.start_calls == [True]
+
+
+def test_concurrent_puts_serialize_per_channel(tmp_path: Path, monkeypatch) -> None:
+ runtime = FakeRuntime(running=True, manager=FakeManager(delay=0.05))
+ _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
+ )
+
+ async def scenario() -> list[httpx.Response]:
+ transport = httpx.ASGITransport(app=api_server.app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as ac:
+ return list(
+ await asyncio.gather(
+ ac.put("/channels/config/dingtalk", json={"config": {"client_id": "a"}}),
+ ac.put("/channels/config/dingtalk", json={"config": {"client_id": "b"}}),
+ )
+ )
+
+ responses = asyncio.run(scenario())
+
+ assert [r.status_code for r in responses] == [200, 200]
+ assert len(runtime.manager.reload_calls) == 2
+ # The per-channel lock kept the two hot swaps from overlapping.
+ assert runtime.manager.max_active == 1
+
+
+# --------------------------------------------------------------------------- #
+# POST /channels/{name}/test
+# --------------------------------------------------------------------------- #
+
+
+def test_post_test_uses_unsaved_creds_and_never_writes(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+ seen: list[dict[str, Any]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(json.loads(request.content.decode("utf-8")))
+ return httpx.Response(200, json={"accessToken": "token-do-not-leak"})
+
+ _inject_mock_transport(monkeypatch, handler)
+
+ response = client.post(
+ "/channels/dingtalk/test",
+ json={"config": {"client_id": "unsaved-id", "client_secret": UNSAVED_SECRET}},
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is True
+ assert body["code"] == "ok"
+ assert body["tested_saved_config"] is False
+ assert body["sdk_available"] is DINGTALK_AVAILABLE
+ assert seen == [{"appKey": "unsaved-id", "appSecret": UNSAVED_SECRET}]
+ # The test endpoint never persists anything.
+ assert path.read_bytes() == before
+ assert UNSAVED_SECRET not in response.text
+ assert STORED_SECRET not in response.text
+ assert "token-do-not-leak" not in response.text
+
+
+def test_post_test_without_body_uses_saved_config(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+ seen: list[dict[str, Any]] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(json.loads(request.content.decode("utf-8")))
+ return httpx.Response(200, json={"accessToken": "token-do-not-leak"})
+
+ _inject_mock_transport(monkeypatch, handler)
+
+ response = client.post("/channels/dingtalk/test", json={})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["tested_saved_config"] is True
+ assert body["ok"] is True
+ assert seen == [{"appKey": CLIENT_ID, "appSecret": STORED_SECRET}]
+ assert path.read_bytes() == before
+ assert STORED_SECRET not in response.text
+
+
+def test_post_test_reports_invalid_credentials(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, text=f"appSecret {STORED_SECRET} is invalid")
+
+ _inject_mock_transport(monkeypatch, handler)
+
+ response = client.post("/channels/dingtalk/test", json={})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is False
+ assert body["code"] == "invalid_credentials"
+ assert body["tested_saved_config"] is True
+ # The echoed secret is scrubbed (adapter layer + route defense in depth).
+ assert STORED_SECRET not in response.text
+ assert path.read_bytes() == before
+
+
+def test_post_test_unsupported_channel_short_circuits(tmp_path: Path, monkeypatch) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"email": {"enabled": False}}
+ )
+ before = path.read_bytes()
+
+ def handler(request: httpx.Request) -> httpx.Response: # pragma: no cover
+ raise AssertionError("no network call may happen for an unsupported channel")
+
+ requests = _inject_mock_transport(monkeypatch, handler)
+
+ response = client.post("/channels/email/test", json={})
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["ok"] is False
+ assert body["code"] == "unsupported"
+ assert body["tested_saved_config"] is True
+ assert isinstance(body["sdk_available"], bool)
+ assert requests == []
+ assert path.read_bytes() == before
+
+
+# --------------------------------------------------------------------------- #
+# Unknown channels / helper modules
+# --------------------------------------------------------------------------- #
+
+
[email protected]("name", ["nonexistent", "targets", "config_meta"])
+def test_put_and_test_404_unknown_and_helper_modules(
+ tmp_path: Path, monkeypatch, name: str
+) -> None:
+ client, path = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}
+ )
+ before = path.read_bytes()
+
+ put = client.put(f"/channels/config/{name}", json={"config": {}})
+ post = client.post(f"/channels/{name}/test", json={})
+
+ assert put.status_code == 404
+ assert post.status_code == 404
+ assert path.read_bytes() == before
+
+
+# --------------------------------------------------------------------------- #
+# Secret hygiene sweep
+# --------------------------------------------------------------------------- #
+
+
+def test_no_secret_value_in_any_response_body(tmp_path: Path, monkeypatch) -> None:
+ runtime = FakeRuntime(running=True)
+ client, _ = _client(
+ tmp_path, monkeypatch, channels={"dingtalk": _dingtalk_section()}, runtime=runtime
+ )
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(401, text=f"bad secret {STORED_SECRET}")
+
+ _inject_mock_transport(monkeypatch, handler)
+
+ responses = [
+ client.get("/channels/config"),
+ # Enable transition with a probe that echoes the secret in its 401 body.
+ client.put("/channels/config/dingtalk", json={"config": {"enabled": True}}),
+ client.post("/channels/dingtalk/test", json={}),
+ client.put("/channels/config/dingtalk", json={"config": {"client_id": "ok-id"}}),
+ ]
+
+ assert [r.status_code for r in responses] == [200, 422, 200, 200]
+ for response in responses:
+ assert STORED_SECRET not in response.text