Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: isolate invalid Partner channel configs (#827)

Bingxi Zhao1cc27028f69e
diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.py
index 8b36016af..a90f1001b 100644
--- a/deeptutor/api/routers/partners.py
+++ b/deeptutor/api/routers/partners.py
@@ -229,6 +229,25 @@ def _validate_channels_payload(channels: dict) -> None:
detail=f"{t('api.invalid_channels_config')}: {exc}",
) from None
+ empty_allow_lists = sorted(
+ name
+ for name, section in channels.items()
+ if isinstance(section, dict)
+ and section.get("enabled") is True
+ and section.get("allow_from", section.get("allowFrom")) == []
+ )
+ if empty_allow_lists:
+ raise HTTPException(
+ status_code=422,
+ detail={
+ "message": (
+ "Enabled channels require at least one allowed sender: "
+ + ", ".join(empty_allow_lists)
+ ),
+ "channels": empty_allow_lists,
+ },
+ )
+
# Inline avatars are client-resized to ~128px before upload; this cap is a
# server-side backstop so config.yaml can't be bloated with raw photos.
diff --git a/deeptutor/partners/channels/manager.py b/deeptutor/partners/channels/manager.py
index 2efc7e735..2d256c50e 100644
--- a/deeptutor/partners/channels/manager.py
+++ b/deeptutor/partners/channels/manager.py
@@ -83,13 +83,17 @@ class ChannelManager:
channel.send_tool_hints = self._resolve_bool_override(
section, "send_tool_hints", default=True
)
+ if getattr(channel.config, "allow_from", None) == []:
+ _logger().warning(
+ 'Skipping channel "{}": allowFrom is empty (denies all)',
+ name,
+ )
+ continue
self.channels[name] = channel
_logger().info("{} channel enabled", cls.display_name)
except Exception as e:
_logger().warning("{} channel not available: {}", name, e)
- self._validate_allow_from()
-
@staticmethod
def _resolve_bool_override(section: Any, key: str, *, default: bool) -> bool:
"""Return *key* from *section* if it is a bool, otherwise *default*.
@@ -108,14 +112,6 @@ class ChannelManager:
value = getattr(section, key, None)
return value if isinstance(value, bool) else default
- def _validate_allow_from(self) -> None:
- for name, ch in self.channels.items():
- if getattr(ch.config, "allow_from", None) == []:
- raise SystemExit(
- f'Error: "{name}" has empty allowFrom (denies all). '
- f'Set ["*"] to allow everyone, or add specific user IDs.'
- )
-
async def _start_channel(self, name: str, channel: BaseChannel) -> None:
try:
await channel.start()
diff --git a/tests/api/test_partners_channel_schema.py b/tests/api/test_partners_channel_schema.py
index e8f37fbb3..9b7ffcd8c 100644
--- a/tests/api/test_partners_channel_schema.py
+++ b/tests/api/test_partners_channel_schema.py
@@ -11,6 +11,7 @@ Covers:
from __future__ import annotations
+from fastapi import HTTPException
from fastapi.testclient import TestClient
import pytest
@@ -21,6 +22,19 @@ from deeptutor.api.routers._partners_channel_schema import (
inline_refs,
resolve_config_model,
)
+from deeptutor.api.routers.partners import _validate_channels_payload
+
+
+class TestChannelPayloadValidation:
+ def test_rejects_enabled_channel_with_empty_allow_list(self) -> None:
+ with pytest.raises(HTTPException) as exc_info:
+ _validate_channels_payload({"weixin": {"enabled": True, "allow_from": [], "token": ""}})
+
+ assert exc_info.value.status_code == 422
+ assert exc_info.value.detail["channels"] == ["weixin"]
+
+ def test_allows_disabled_channel_with_empty_allow_list(self) -> None:
+ _validate_channels_payload({"weixin": {"enabled": False, "allow_from": []}})
class TestResolveConfigModel:
diff --git a/tests/services/partners/test_channel_manager.py b/tests/services/partners/test_channel_manager.py
index 0b35caf62..561f7bd93 100644
--- a/tests/services/partners/test_channel_manager.py
+++ b/tests/services/partners/test_channel_manager.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
@@ -12,6 +13,27 @@ from deeptutor.partners.channels.manager import ChannelManager
from deeptutor.partners.config.schema import ChannelsConfig
+def test_empty_allow_list_skips_only_misconfigured_channel(monkeypatch):
+ class _Channel:
+ display_name = "Test"
+
+ def __init__(self, config, _bus):
+ self.config = SimpleNamespace(allow_from=config["allow_from"])
+
+ monkeypatch.setattr(
+ "deeptutor.partners.channels.registry.discover_all",
+ lambda: {"invalid": _Channel, "valid": _Channel},
+ )
+ config = ChannelsConfig(
+ invalid={"enabled": True, "allow_from": []},
+ valid={"enabled": True, "allow_from": ["user-1"]},
+ )
+
+ manager = ChannelManager(config, _MultiShotBus([])) # type: ignore[arg-type]
+
+ assert list(manager.channels) == ["valid"]
+
+
class _OneShotBus:
def __init__(self, msg: OutboundMessage):
self._msg = msg