feat(network): centralize proxy settings and add MCP routing (NAN-315) (#6372)
* feat(network): share proxy settings across features and MCP (NAN-315) * fix(network): address shared proxy review regressions * test(network): align rebased OAuth fixtures with runtime admission * fix(webui): configure shared proxy without leaving connection drafts * feat(webui): add optional shared proxy authentication editor * fix(webui): align proxy save tests and loading skeleton
This commit is contained in:
1 parent
872a83340d
commit
084b6bb394
181 files changed
+3740
-807
No files matched your search
@@ -10,6 +10,7 @@ from loguru import logger
|
||||
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.pairing import (
|
||||
PAIRING_CODE_META_KEY,
|
||||
format_pairing_reply,
|
||||
@@ -29,20 +30,26 @@ class BaseChannel(ABC):
|
||||
|
||||
name: str = "base"
|
||||
display_name: str = "Base"
|
||||
# Opt-in construction capability, not a channel configuration field.
|
||||
uses_shared_proxy: bool = False
|
||||
send_progress: bool = True
|
||||
send_tool_hints: bool = True
|
||||
show_reasoning: bool = True
|
||||
show_compaction_notices: bool = False
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize the channel.
|
||||
|
||||
Args:
|
||||
config: Channel-specific configuration.
|
||||
bus: The message bus for communication.
|
||||
network: Instance-scoped shared network settings.
|
||||
"""
|
||||
self.config = config
|
||||
self.network = network if network is not None else NetworkConfig()
|
||||
self.logger = logger.bind(channel=self.name)
|
||||
self.bus = bus
|
||||
self._running = False
|
||||
|
||||
@@ -6,9 +6,12 @@ import json
|
||||
from collections.abc import Iterable
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import field as dataclass_field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Literal, TypeGuard, cast
|
||||
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.channels.plugin import ChannelPlugin
|
||||
|
||||
@@ -21,6 +24,7 @@ class ChannelValidationContext:
|
||||
"""Host policy passed to package-owned setup validators."""
|
||||
|
||||
allow_local_service_access: bool = False
|
||||
network: NetworkConfig = dataclass_field(default_factory=NetworkConfig)
|
||||
|
||||
|
||||
# Keep callback contracts precise for static consumers. The public adapters below
|
||||
|
||||
@@ -8,9 +8,7 @@ from nanobot.channels.plugin import ChannelPlugin
|
||||
SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"token": field("secret"),
|
||||
"proxy": field(),
|
||||
"proxyUsername": field(),
|
||||
"proxyPassword": field("secret"),
|
||||
"useProxy": field("bool", default=False),
|
||||
"allowFrom": field("list", snapshot=False),
|
||||
"allowChannels": field("list"),
|
||||
"groupPolicy": field("enum", choices=DIRECT_GROUP_POLICIES, default="mention"),
|
||||
|
||||
@@ -19,6 +19,7 @@ from nanobot.bus.outbound_events import ContextCompactionEvent, ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.utils.helpers import safe_filename, split_message
|
||||
@@ -64,9 +65,7 @@ class DiscordConfig(Base):
|
||||
working_emoji_delay: float = 2.0
|
||||
streaming: bool = True
|
||||
reply_to_message: bool = False
|
||||
proxy: str | None = None
|
||||
proxy_username: str | None = None
|
||||
proxy_password: str | None = None
|
||||
use_proxy: bool = False
|
||||
|
||||
|
||||
if DISCORD_AVAILABLE:
|
||||
@@ -378,6 +377,7 @@ class DiscordChannel(BaseChannel):
|
||||
|
||||
name = "discord"
|
||||
display_name = "Discord"
|
||||
uses_shared_proxy = True
|
||||
_STREAM_EDIT_INTERVAL = 0.8
|
||||
|
||||
@classmethod
|
||||
@@ -443,11 +443,14 @@ class DiscordChannel(BaseChannel):
|
||||
partial = cast(Any, channel).get_partial_message(message_id)
|
||||
return partial.to_reference(fail_if_not_exists=fail_if_not_exists), mention_settings
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = DiscordConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: DiscordConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self._client: DiscordBotClient | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
self._bot_user_id: str | None = None
|
||||
@@ -478,30 +481,10 @@ class DiscordChannel(BaseChannel):
|
||||
intents = discord.Intents.none()
|
||||
intents.value = self.config.intents
|
||||
|
||||
proxy_auth = None
|
||||
has_user = bool(self.config.proxy_username)
|
||||
has_pass = bool(self.config.proxy_password)
|
||||
if has_user and has_pass:
|
||||
import aiohttp
|
||||
|
||||
proxy_auth = aiohttp.BasicAuth(
|
||||
login=cast(str, self.config.proxy_username),
|
||||
password=cast(str, self.config.proxy_password),
|
||||
)
|
||||
elif has_user != has_pass:
|
||||
self.logger.warning(
|
||||
"proxy auth incomplete: both proxy_username and "
|
||||
"proxy_password must be set; ignoring partial credentials",
|
||||
)
|
||||
|
||||
proxy = self.config.proxy
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
self._client = DiscordBotClient(
|
||||
self,
|
||||
intents=intents,
|
||||
proxy=proxy,
|
||||
proxy_auth=proxy_auth,
|
||||
proxy=self._proxy,
|
||||
)
|
||||
except Exception:
|
||||
self.logger.exception("Failed to initialize client")
|
||||
|
||||
@@ -22,6 +22,7 @@ from nanobot.channels.discord.runtime import (
|
||||
DiscordConfig,
|
||||
)
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
# Minimal Discord client test double used to control startup/readiness behavior.
|
||||
@@ -1566,25 +1567,20 @@ async def test_start_typing_uses_typing_context_when_trigger_typing_missing() ->
|
||||
assert channel._typing_tasks == {}
|
||||
|
||||
|
||||
def test_config_accepts_proxy_fields() -> None:
|
||||
config = DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_username="user",
|
||||
proxy_password="pass",
|
||||
)
|
||||
assert config.proxy == "http://127.0.0.1:7890"
|
||||
assert config.proxy_username == "user"
|
||||
assert config.proxy_password == "pass"
|
||||
def test_config_accepts_proxy_opt_in() -> None:
|
||||
config = DiscordConfig.model_validate({
|
||||
"enabled": True,
|
||||
"token": "token",
|
||||
"allowFrom": ["*"],
|
||||
"useProxy": True,
|
||||
})
|
||||
assert config.use_proxy is True
|
||||
assert config.model_dump(by_alias=True)["useProxy"] is True
|
||||
|
||||
|
||||
def test_config_proxy_defaults_to_none() -> None:
|
||||
def test_config_proxy_defaults_to_disabled() -> None:
|
||||
config = DiscordConfig(enabled=True, token="token", allow_from=["*"])
|
||||
assert config.proxy is None
|
||||
assert config.proxy_username is None
|
||||
assert config.proxy_password is None
|
||||
assert config.use_proxy is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1595,9 +1591,10 @@ async def test_start_passes_proxy_to_client(monkeypatch) -> None:
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
use_proxy=True,
|
||||
),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(proxy="http://127.0.0.1:7890"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
@@ -1610,19 +1607,15 @@ async def test_start_passes_proxy_to_client(monkeypatch) -> None:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_passes_proxy_auth_when_credentials_provided(monkeypatch) -> None:
|
||||
async def test_start_passes_shared_url_credentials_to_aiohttp(monkeypatch) -> None:
|
||||
aiohttp = pytest.importorskip("aiohttp")
|
||||
|
||||
_FakeDiscordClient.instances.clear()
|
||||
network = NetworkConfig(proxy="http://user:p%40ss@127.0.0.1:7890")
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_username="user",
|
||||
proxy_password="pass",
|
||||
),
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"], use_proxy=True),
|
||||
MessageBus(),
|
||||
network=network,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
@@ -1630,54 +1623,51 @@ async def test_start_passes_proxy_auth_when_credentials_provided(monkeypatch) ->
|
||||
|
||||
assert channel.is_running is False
|
||||
assert len(_FakeDiscordClient.instances) == 1
|
||||
assert _FakeDiscordClient.instances[0].proxy == "http://127.0.0.1:7890"
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth is not None
|
||||
assert isinstance(_FakeDiscordClient.instances[0].proxy_auth, aiohttp.BasicAuth)
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth.login == "user"
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth.password == "pass"
|
||||
client = _FakeDiscordClient.instances[0]
|
||||
assert client.proxy == network.proxy
|
||||
# aiohttp extracts URL credentials for the proxy connection, not the destination request.
|
||||
proxy_connection = AsyncMock(side_effect=RuntimeError("stop before opening proxy socket"))
|
||||
monkeypatch.setattr(aiohttp.TCPConnector, "_create_direct_connection", proxy_connection)
|
||||
async with aiohttp.ClientSession() as session:
|
||||
with pytest.raises(RuntimeError, match="stop before opening proxy socket"):
|
||||
await session.get(
|
||||
"https://discord.com/api/v10/users/@me",
|
||||
proxy=client.proxy, proxy_auth=client.proxy_auth,
|
||||
)
|
||||
|
||||
proxy_connection.assert_awaited_once()
|
||||
request = proxy_connection.await_args.args[0]
|
||||
assert request.url.host == "127.0.0.1"
|
||||
assert request.url.port == 7890
|
||||
auth = aiohttp.BasicAuth.decode(request.headers["Proxy-Authorization"])
|
||||
assert auth.login == "user"
|
||||
assert auth.password == "p@ss"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_no_proxy_auth_when_only_username(monkeypatch) -> None:
|
||||
async def test_start_without_opt_in_ignores_shared_proxy_credentials(monkeypatch) -> None:
|
||||
_FakeDiscordClient.instances.clear()
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_username="user",
|
||||
),
|
||||
DiscordConfig(enabled=True, token="token", allow_from=["*"], use_proxy=False),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(proxy="http://user:pass@127.0.0.1:7890"),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
await channel.start()
|
||||
|
||||
assert channel.is_running is False
|
||||
assert _FakeDiscordClient.instances[0].proxy is None
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_no_proxy_auth_when_only_password(monkeypatch) -> None:
|
||||
_FakeDiscordClient.instances.clear()
|
||||
channel = DiscordChannel(
|
||||
DiscordConfig(
|
||||
enabled=True,
|
||||
token="token",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
proxy_password="pass",
|
||||
),
|
||||
MessageBus(),
|
||||
)
|
||||
monkeypatch.setattr("nanobot.channels.discord.runtime.DiscordBotClient", _FakeDiscordClient)
|
||||
|
||||
await channel.start()
|
||||
|
||||
assert channel.is_running is False
|
||||
assert _FakeDiscordClient.instances[0].proxy == "http://127.0.0.1:7890"
|
||||
assert _FakeDiscordClient.instances[0].proxy_auth is None
|
||||
def test_proxy_opt_in_without_shared_address_fails_before_start() -> None:
|
||||
with pytest.raises(ValueError, match="Advanced"):
|
||||
DiscordChannel(
|
||||
DiscordConfig(enabled=True, token="token", use_proxy=True),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -10,15 +10,20 @@ from nanobot.channels.validation import (
|
||||
http_get,
|
||||
payload,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("discord", values)
|
||||
try:
|
||||
proxy = resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("discord", checks, missing)
|
||||
token = string_value(values.get("token"))
|
||||
proxy = string_value(values.get("proxy"))
|
||||
if token:
|
||||
try:
|
||||
data = http_get(
|
||||
@@ -61,9 +66,9 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
|
||||
f"Discord rejected the token: HTTP {exc.response.status_code}",
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception:
|
||||
checks.append(
|
||||
check("bot_token", "Bot token", "warn", f"Could not reach Discord now: {exc}")
|
||||
check("bot_token", "Bot token", "warn", "Could not reach Discord now. Try again later.")
|
||||
)
|
||||
return status_from_checks("discord", checks, missing)
|
||||
|
||||
|
||||
@@ -12,9 +12,7 @@ export default {
|
||||
docsUrl: chatAppGuideUrl("discord"),
|
||||
fields: [
|
||||
{ key: "channels.discord.token", section: "credentials" },
|
||||
{ key: "channels.discord.proxy", section: "connection" },
|
||||
{ key: "channels.discord.proxyUsername", section: "connection" },
|
||||
{ key: "channels.discord.proxyPassword", section: "connection" },
|
||||
{ key: "channels.discord.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.discord.allowFrom", section: "access" },
|
||||
{ key: "channels.discord.allowChannels", section: "access" },
|
||||
{ key: "channels.discord.groupPolicy", section: "behavior" },
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Allowed users",
|
||||
"placeholder": "User IDs, comma separated"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Proxy username"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Proxy password"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Gateway intents"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Usuarios permitidos",
|
||||
"placeholder": "ID de usuario separados por comas"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "proxy de red"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Usuario del proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Contraseña de proxy"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Intentos de puerta de enlace"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Utilisateurs autorisés",
|
||||
"placeholder": "ID utilisateur séparés par des virgules"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Mandataire réseau"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Utilisateur du proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Mot de passe proxy"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Intentions de passerelle"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Pengguna diizinkan",
|
||||
"placeholder": "ID pengguna, dipisahkan koma"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proksi jaringan"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Nama pengguna proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Kata sandi proksi"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Maksud gerbang"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "許可ユーザー",
|
||||
"placeholder": "ユーザー ID(カンマ区切り)"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "プロキシのユーザー名"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "プロキシパスワード"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
},
|
||||
"intents": {
|
||||
"label": "ゲートウェイの意図"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "허용 사용자",
|
||||
"placeholder": "사용자 ID, 쉼표로 구분"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "프록시 사용자 이름"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "프록시 비밀번호"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
},
|
||||
"intents": {
|
||||
"label": "게이트웨이 인텐트"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Usuários permitidos",
|
||||
"placeholder": "IDs de usuário separados por vírgulas"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Usuário do proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Senha proxy"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Intenções de gateway"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "Người dùng được phép",
|
||||
"placeholder": "ID người dùng, phân tách bằng dấu phẩy"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "Tên người dùng proxy"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "Mật khẩu proxy"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Ý định của cổng"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "允许用户",
|
||||
"placeholder": "用户 ID,用逗号分隔"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "代理账号"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "代理密码"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Gateway Intents"
|
||||
|
||||
@@ -23,14 +23,8 @@
|
||||
"label": "允許使用者",
|
||||
"placeholder": "使用者 ID,以逗號分隔"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理"
|
||||
},
|
||||
"proxyUsername": {
|
||||
"label": "代理賬號"
|
||||
},
|
||||
"proxyPassword": {
|
||||
"label": "代理密碼"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"intents": {
|
||||
"label": "Gateway Intents"
|
||||
|
||||
@@ -202,6 +202,8 @@ class ChannelManager:
|
||||
runtime_name: str | None = None,
|
||||
) -> BaseChannel:
|
||||
kwargs: dict[str, Any] = {}
|
||||
if cls.uses_shared_proxy:
|
||||
kwargs["network"] = self.config.network
|
||||
if cls.name == "websocket":
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.gateway_services import build_gateway_services
|
||||
|
||||
@@ -22,7 +22,7 @@ SETUP_SPEC = ChannelSetupSpec(
|
||||
"groupAllowFrom": field("list"),
|
||||
"allowRoomMentions": field("bool", default=False),
|
||||
"streaming": field("bool", default=False),
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
},
|
||||
required=(
|
||||
*required_fields("homeserver", "userId"),
|
||||
|
||||
@@ -63,6 +63,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_data_dir, get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -303,7 +304,7 @@ class MatrixConfig(Base):
|
||||
group_allow_from: list[str] = Field(default_factory=list)
|
||||
allow_room_mentions: bool = False
|
||||
streaming: bool = False
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
|
||||
|
||||
class MatrixChannel(BaseChannel):
|
||||
@@ -311,6 +312,7 @@ class MatrixChannel(BaseChannel):
|
||||
|
||||
name = "matrix"
|
||||
display_name = "Matrix"
|
||||
uses_shared_proxy = True
|
||||
_STREAM_EDIT_INTERVAL = 2 # min seconds between edit_message_text calls
|
||||
monotonic_time: Callable[[], float] = staticmethod(time.monotonic)
|
||||
|
||||
@@ -323,12 +325,15 @@ class MatrixChannel(BaseChannel):
|
||||
config: Any,
|
||||
bus: MessageBus,
|
||||
*,
|
||||
network: NetworkConfig | None = None,
|
||||
restrict_to_workspace: bool = False,
|
||||
workspace: str | Path | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = MatrixConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: MatrixConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self.client: AsyncClient | None = None
|
||||
self._sync_task: asyncio.Task[None] | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {}
|
||||
@@ -359,14 +364,11 @@ class MatrixChannel(BaseChannel):
|
||||
# Replace ':' with '_' to produce a Windows-safe filename
|
||||
safe_store_name = self.config.user_id.replace(":", "_") + f"_{self.config.device_id}.db"
|
||||
|
||||
proxy = self.config.proxy.strip() if self.config.proxy else ""
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
self.client = AsyncClient(
|
||||
homeserver=self.config.homeserver,
|
||||
user=self.config.user_id,
|
||||
store_path=str(self.store_path),
|
||||
proxy=proxy or None,
|
||||
proxy=self._proxy,
|
||||
config=AsyncClientConfig(
|
||||
store_sync_tokens=True,
|
||||
encryption_enabled=self.config.e2ee_enabled,
|
||||
|
||||
@@ -25,6 +25,7 @@ from nanobot.channels.matrix.runtime import (
|
||||
MatrixConfig,
|
||||
_build_matrix_text_content,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
_ROOM_SEND_UNSET = object()
|
||||
|
||||
@@ -328,8 +329,9 @@ async def test_start_skips_load_store_when_device_id_missing(
|
||||
)
|
||||
|
||||
channel = MatrixChannel(
|
||||
_make_config(device_id="", e2ee_enabled=True, proxy="127.0.0.1:7890"),
|
||||
_make_config(device_id="", e2ee_enabled=True, use_proxy=True),
|
||||
MessageBus(),
|
||||
network=NetworkConfig(proxy="127.0.0.1:7890"),
|
||||
)
|
||||
await channel.start()
|
||||
|
||||
|
||||
@@ -3,11 +3,22 @@
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
from nanobot.channels.validation import check, required_checks, status_from_checks, string_value
|
||||
from nanobot.channels.validation import (
|
||||
check,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("matrix", values)
|
||||
try:
|
||||
resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("matrix", checks, missing)
|
||||
password = string_value(values.get("password"))
|
||||
access_token = string_value(values.get("accessToken"))
|
||||
device_id = string_value(values.get("deviceId"))
|
||||
|
||||
@@ -12,6 +12,7 @@ export default {
|
||||
docsUrl: chatAppGuideUrl("matrix"),
|
||||
fields: [
|
||||
{ key: "channels.matrix.homeserver", section: "connection" },
|
||||
{ key: "channels.matrix.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.matrix.userId", section: "account" },
|
||||
{ key: "channels.matrix.password", section: "credentials" },
|
||||
{ key: "channels.matrix.accessToken", section: "credentials" },
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Off"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Apagado"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Désactivé"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Mati"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "オフ"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "끄기"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Desligado"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "Tắt"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "关闭"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,8 @@
|
||||
"false": "關閉"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ SETUP_SPEC = ChannelSetupSpec(
|
||||
"dm.enabled": field("bool", default=True),
|
||||
"dm.policy": field("enum", choices={"open", "allowlist"}, default="open"),
|
||||
"dm.allowFrom": field("list"),
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
},
|
||||
required=required_fields("appToken", "botToken"),
|
||||
official_url="https://api.slack.com/apps",
|
||||
|
||||
@@ -19,6 +19,7 @@ from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -84,7 +85,7 @@ class SlackConfig(Base):
|
||||
# instead of every message). No effect for "mention"/"open" policies.
|
||||
group_require_mention: bool = False
|
||||
dm: SlackDMConfig = Field(default_factory=SlackDMConfig)
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
|
||||
|
||||
SLACK_MAX_MESSAGE_LEN = 39_000 # Slack API allows ~40k; leave margin
|
||||
@@ -109,6 +110,7 @@ class SlackChannel(BaseChannel):
|
||||
|
||||
name = "slack"
|
||||
display_name = "Slack"
|
||||
uses_shared_proxy = True
|
||||
_SLACK_ID_RE = re.compile(r"^[CDGUW][A-Z0-9]{2,}$")
|
||||
_SLACK_CHANNEL_REF_RE = re.compile(r"^<#([A-Z0-9]+)(?:\|[^>]+)?>$")
|
||||
_SLACK_USER_REF_RE = re.compile(r"^<@([A-Z0-9]+)(?:\|[^>]+)?>$")
|
||||
@@ -119,11 +121,14 @@ class SlackChannel(BaseChannel):
|
||||
|
||||
_THREAD_CONTEXT_CACHE_LIMIT = 10_000
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = SlackConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: SlackConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self._web_client: AsyncWebClient | None = None
|
||||
self._socket_client: SocketModeClient | None = None
|
||||
self._bot_user_id: str | None = None
|
||||
@@ -148,10 +153,7 @@ class SlackChannel(BaseChannel):
|
||||
|
||||
self._running = True
|
||||
|
||||
proxy = self.config.proxy.strip() if self.config.proxy else ""
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
proxy = proxy or None
|
||||
proxy = self._proxy
|
||||
self._web_client = AsyncWebClient(token=self.config.bot_token, proxy=proxy)
|
||||
self._socket_client = SocketModeClient(
|
||||
app_token=self.config.app_token,
|
||||
@@ -592,14 +594,10 @@ class SlackChannel(BaseChannel):
|
||||
mounts=(
|
||||
{
|
||||
"all://": httpx.AsyncHTTPTransport(
|
||||
proxy=httpx.Proxy(
|
||||
self.config.proxy
|
||||
if "://" in self.config.proxy
|
||||
else f"http://{self.config.proxy}"
|
||||
)
|
||||
proxy=httpx.Proxy(self._proxy)
|
||||
)
|
||||
}
|
||||
if self.config.proxy
|
||||
if self._proxy
|
||||
else httpx_env_proxy_mounts()
|
||||
),
|
||||
event_hooks={"request": [_validate_slack_download_request]},
|
||||
|
||||
@@ -17,6 +17,7 @@ except ImportError:
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.slack.runtime import SLACK_MAX_MESSAGE_LEN, SlackChannel, SlackConfig
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
class _FakeAsyncWebClient:
|
||||
@@ -984,3 +985,74 @@ async def test_download_follows_safe_redirect(
|
||||
assert validated == [url, "https://cdn.example/file.bin"]
|
||||
assert requests[0].headers["Authorization"] == "Bearer xoxb-test"
|
||||
assert "Authorization" not in requests[1].headers
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_proxy", [True, False])
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_uses_shared_proxy_for_web_api_and_socket_mode(monkeypatch, use_proxy) -> None:
|
||||
network = NetworkConfig(proxy="http://127.0.0.1:7890")
|
||||
channel = SlackChannel(
|
||||
SlackConfig(bot_token="xoxb-test", app_token="xapp-test", use_proxy=use_proxy),
|
||||
MessageBus(),
|
||||
network=network,
|
||||
)
|
||||
captured = {}
|
||||
|
||||
def web_client(**kwargs):
|
||||
captured["web"] = kwargs
|
||||
return SimpleNamespace(auth_test=AsyncMock(return_value={"user_id": "U42"}))
|
||||
|
||||
async def connect():
|
||||
channel._running = False
|
||||
|
||||
def socket_client(**kwargs):
|
||||
captured["socket"] = kwargs
|
||||
return SimpleNamespace(socket_mode_request_listeners=[], connect=connect)
|
||||
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.AsyncWebClient", web_client)
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.SocketModeClient", socket_client)
|
||||
|
||||
await channel.start()
|
||||
|
||||
expected = network.proxy if use_proxy else None
|
||||
assert captured["web"] == {"token": "xoxb-test", "proxy": expected}
|
||||
assert captured["socket"]["proxy"] == expected
|
||||
assert captured["socket"]["web_client"] is channel._web_client
|
||||
assert channel._bot_user_id == "U42"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_download_uses_shared_proxy_and_keeps_redirect_validation(monkeypatch, tmp_path) -> None:
|
||||
proxies = []
|
||||
requests = []
|
||||
validated = []
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(302, headers={"location": "http://169.254.169.254/secret"})
|
||||
|
||||
def proxy_transport(*, proxy):
|
||||
proxies.append(proxy)
|
||||
return httpx.MockTransport(handler)
|
||||
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.httpx.AsyncHTTPTransport", proxy_transport)
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.PinnedDNSAsyncTransport", lambda: httpx.MockTransport(handler))
|
||||
monkeypatch.setattr("nanobot.channels.slack.runtime.get_media_dir", lambda _name: tmp_path)
|
||||
_patch_download_validation(monkeypatch, validated)
|
||||
channel = SlackChannel(
|
||||
SlackConfig(bot_token="xoxb-test", use_proxy=True), MessageBus(), network=network,
|
||||
)
|
||||
url = "https://files.slack.com/file.bin"
|
||||
|
||||
path, _marker = await channel._download_slack_file({
|
||||
"id": "F1", "name": "file.bin", "url_private_download": url,
|
||||
})
|
||||
|
||||
assert path is None
|
||||
assert len(proxies) == 1
|
||||
assert proxies[0].url == httpx.URL("http://127.0.0.1:7890")
|
||||
assert proxies[0].raw_auth == (b"user", b"pass")
|
||||
assert len(requests) == 1
|
||||
assert validated == [url, "http://169.254.169.254/secret"]
|
||||
assert requests[0].headers["Authorization"] == "Bearer xoxb-test"
|
||||
@@ -10,16 +10,21 @@ from nanobot.channels.validation import (
|
||||
official_action,
|
||||
payload,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("slack", values)
|
||||
try:
|
||||
proxy = resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("slack", checks, missing)
|
||||
app_token = string_value(values.get("appToken"))
|
||||
bot_token = string_value(values.get("botToken"))
|
||||
proxy = string_value(values.get("proxy"))
|
||||
if app_token:
|
||||
checks.append(
|
||||
check(
|
||||
@@ -76,13 +81,13 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
|
||||
message_from_response(data, "Slack rejected the bot token."),
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
except Exception:
|
||||
checks.append(
|
||||
check(
|
||||
"auth_test",
|
||||
"Workspace identity",
|
||||
"warn",
|
||||
f"Could not reach Slack now: {exc}",
|
||||
"Could not reach Slack now. Try again later.",
|
||||
)
|
||||
)
|
||||
return status_from_checks("slack", checks, missing)
|
||||
|
||||
@@ -56,6 +56,7 @@ export default {
|
||||
fields: [
|
||||
{ key: "channels.slack.appToken", section: "credentials" },
|
||||
{ key: "channels.slack.botToken", section: "credentials" },
|
||||
{ key: "channels.slack.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.slack.groupPolicy", section: "behavior" },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Allowed DM users"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Usuarios de DM permitidos"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Utilisateurs de DM autorisés"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Pengguna DM diizinkan"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "許可する DM ユーザー"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "허용 DM 사용자"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Usuários de DM permitidos"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "Người dùng DM được phép"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "私聊用户"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,9 +84,8 @@
|
||||
"dm_allowFrom": {
|
||||
"label": "私聊使用者"
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ from nanobot.channels.telegram.validation import validate
|
||||
SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"token": field("secret"),
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
"allowFrom": field("list"),
|
||||
"groupPolicy": field("enum", choices=GROUP_POLICIES, default="mention"),
|
||||
"mode": field("enum", choices={"polling", "webhook"}, default="polling"),
|
||||
|
||||
@@ -35,6 +35,7 @@ from nanobot.bus.outbound_events import ProgressEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.command.builtin import build_help_text
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -495,7 +496,7 @@ class TelegramConfig(Base):
|
||||
token: str = ""
|
||||
mode: Literal["polling", "webhook"] = "polling"
|
||||
allow_from: list[str] = Field(default_factory=list)
|
||||
proxy: str | None = None
|
||||
use_proxy: bool = False
|
||||
reply_to_message: bool = False
|
||||
react_emoji: str = "👀"
|
||||
group_policy: Literal["open", "mention"] = "mention"
|
||||
@@ -588,6 +589,7 @@ class TelegramChannel(BaseChannel):
|
||||
|
||||
name = "telegram"
|
||||
display_name = "Telegram"
|
||||
uses_shared_proxy = True
|
||||
|
||||
# Commands registered with Telegram's command menu
|
||||
BOT_COMMANDS: list[BotCommand] = [
|
||||
@@ -623,11 +625,14 @@ class TelegramChannel(BaseChannel):
|
||||
def default_config(cls) -> dict[str, Any]:
|
||||
return TelegramConfig().model_dump(by_alias=True)
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
if isinstance(config, dict):
|
||||
config = TelegramConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: TelegramConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
self._app: TelegramApplication | None = None
|
||||
self._typing_tasks: dict[str, asyncio.Task[None]] = {} # chat_id -> typing loop task
|
||||
self._media_group_buffers: dict[str, dict[str, Any]] = {}
|
||||
@@ -735,9 +740,7 @@ class TelegramChannel(BaseChannel):
|
||||
|
||||
async def _start_app(self) -> None:
|
||||
"""Build, initialize and start the Telegram application."""
|
||||
proxy = self.config.proxy or None
|
||||
if proxy and "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
proxy = self._proxy
|
||||
|
||||
# Separate pools so long-polling (getUpdates) never starves outbound sends.
|
||||
api_request = HTTPXRequest(
|
||||
|
||||
@@ -28,6 +28,7 @@ from nanobot.channels.telegram.runtime import (
|
||||
_StreamBuf,
|
||||
_telegram_command_text,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
|
||||
|
||||
@@ -349,10 +350,11 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:
|
||||
enabled=True,
|
||||
token="123:abc",
|
||||
allow_from=["*"],
|
||||
proxy="http://127.0.0.1:7890",
|
||||
use_proxy=True,
|
||||
)
|
||||
bus = MessageBus()
|
||||
channel = TelegramChannel(config, bus)
|
||||
network = NetworkConfig(proxy="http://127.0.0.1:7890")
|
||||
channel = TelegramChannel(config, bus, network=network)
|
||||
app = _FakeApp(lambda: setattr(channel, "_running", False))
|
||||
builder = _FakeBuilder(app)
|
||||
|
||||
@@ -366,8 +368,8 @@ async def test_start_creates_separate_pools_with_proxy(monkeypatch) -> None:
|
||||
|
||||
assert len(_FakeHTTPXRequest.instances) == 2
|
||||
api_req, poll_req = _FakeHTTPXRequest.instances
|
||||
assert api_req.kwargs["proxy"] == config.proxy
|
||||
assert poll_req.kwargs["proxy"] == config.proxy
|
||||
assert api_req.kwargs["proxy"] == network.proxy
|
||||
assert poll_req.kwargs["proxy"] == network.proxy
|
||||
assert api_req.kwargs["connection_pool_size"] == 32
|
||||
assert poll_req.kwargs["connection_pool_size"] == 4
|
||||
assert builder.request_value is api_req
|
||||
|
||||
@@ -10,11 +10,12 @@ from nanobot.config.loader import save_config
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
def test_telegram_setup_exposes_proxy_as_an_optional_field() -> None:
|
||||
proxy = SETUP_SPEC.fields["proxy"]
|
||||
def test_telegram_setup_exposes_proxy_opt_in_as_an_optional_field() -> None:
|
||||
use_proxy = SETUP_SPEC.fields["useProxy"]
|
||||
|
||||
assert proxy.kind == "string"
|
||||
assert "proxy" not in SETUP_SPEC.simple_required_fields
|
||||
assert use_proxy.kind == "bool"
|
||||
assert use_proxy.default is False
|
||||
assert "useProxy" not in SETUP_SPEC.simple_required_fields
|
||||
|
||||
|
||||
def test_get_me_builds_http_client_with_explicit_proxy(
|
||||
@@ -169,7 +170,7 @@ def test_validate_telegram_marks_proxy_transport_failures_without_exposing_proxy
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token, "proxy": proxy}}}
|
||||
{"network": {"proxy": proxy}, "channels": {"telegram": {"token": token, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -197,7 +198,7 @@ def test_validate_telegram_uses_saved_proxy_without_exposing_it(
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token, "proxy": proxy}}}
|
||||
{"network": {"proxy": proxy}, "channels": {"telegram": {"token": token, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -230,7 +231,7 @@ def test_validate_telegram_resolves_saved_secret_env_refs_without_exposing_them(
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token_ref, "proxy": proxy_ref}}}
|
||||
{"network": {"proxy": proxy_ref}, "channels": {"telegram": {"token": token_ref, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -263,7 +264,7 @@ def test_validate_telegram_rejects_unset_proxy_env_ref_without_connecting(
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(
|
||||
Config.model_validate(
|
||||
{"channels": {"telegram": {"token": token, "proxy": proxy_ref}}}
|
||||
{"network": {"proxy": proxy_ref}, "channels": {"telegram": {"token": token, "useProxy": True}}}
|
||||
),
|
||||
config_path,
|
||||
)
|
||||
@@ -279,17 +280,17 @@ def test_validate_telegram_rejects_unset_proxy_env_ref_without_connecting(
|
||||
assert result["status"] == "invalid"
|
||||
assert result["can_enable"] is False
|
||||
assert proxy_ref not in str(result)
|
||||
assert any(check["id"] == "proxy_env" for check in result["checks"])
|
||||
assert any(check["id"] == "network_proxy" for check in result["checks"])
|
||||
|
||||
|
||||
def test_validate_telegram_uses_proxy_submitted_with_new_token(
|
||||
def test_validate_telegram_uses_shared_proxy_when_opt_in_is_submitted_with_new_token(
|
||||
tmp_path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
token = "123456:abcdefghijklmnopqrstuvwxyz"
|
||||
proxy = "http://127.0.0.1:7890"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
save_config(Config.model_validate({"network": {"proxy": proxy}}), config_path)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
captured: dict[str, str | None] = {}
|
||||
|
||||
@@ -303,7 +304,7 @@ def test_validate_telegram_uses_proxy_submitted_with_new_token(
|
||||
"telegram",
|
||||
{
|
||||
"channels.telegram.token": token,
|
||||
"channels.telegram.proxy": proxy,
|
||||
"channels.telegram.useProxy": True,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -319,7 +320,10 @@ def test_validate_telegram_rejects_invalid_proxy_without_trying_token(
|
||||
) -> None:
|
||||
token = "123456:abcdefghijklmnopqrstuvwxyz"
|
||||
config_path = tmp_path / "config.json"
|
||||
save_config(Config(), config_path)
|
||||
monkeypatch.setenv("NETWORK_PROXY_TEST", proxy)
|
||||
save_config(
|
||||
Config.model_validate({"network": {"proxy": "${NETWORK_PROXY_TEST}"}}), config_path,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
|
||||
|
||||
def fail_get_me(*_args) -> dict:
|
||||
@@ -331,11 +335,11 @@ def test_validate_telegram_rejects_invalid_proxy_without_trying_token(
|
||||
"telegram",
|
||||
{
|
||||
"channels.telegram.token": token,
|
||||
"channels.telegram.proxy": proxy,
|
||||
"channels.telegram.useProxy": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert result["status"] == "invalid"
|
||||
assert result["can_enable"] is False
|
||||
assert proxy not in str(result)
|
||||
assert any(check["id"] == "proxy_format" for check in result["checks"])
|
||||
assert any(check["id"] == "network_proxy" for check in result["checks"])
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import re
|
||||
from typing import Any, cast
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -12,25 +11,13 @@ from nanobot.channels.validation import (
|
||||
message_from_response,
|
||||
payload,
|
||||
required_checks,
|
||||
resolve_proxy,
|
||||
status_from_checks,
|
||||
string_value,
|
||||
)
|
||||
from nanobot.config.loader import resolve_env_refs
|
||||
|
||||
_TIMEOUT_SECONDS = 4.0
|
||||
_SUPPORTED_PROXY_SCHEMES = {"http", "https", "socks5", "socks5h"}
|
||||
|
||||
|
||||
def _proxy_url_is_valid(proxy: str) -> bool:
|
||||
if "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
try:
|
||||
parsed = urlparse(proxy)
|
||||
hostname = parsed.hostname
|
||||
parsed.port
|
||||
except ValueError:
|
||||
return False
|
||||
return parsed.scheme.lower() in _SUPPORTED_PROXY_SCHEMES and bool(hostname)
|
||||
|
||||
|
||||
def _get_me(token: str, proxy: str | None) -> dict[str, Any]:
|
||||
@@ -46,12 +33,15 @@ def _get_me(token: str, proxy: str | None) -> dict[str, Any]:
|
||||
return cast(dict[str, Any], data) if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks, missing = required_checks("telegram", values)
|
||||
try:
|
||||
proxy = resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return status_from_checks("telegram", checks, missing)
|
||||
raw_token = string_value(values.get("token"))
|
||||
raw_proxy = string_value(values.get("proxy"))
|
||||
token = string_value(resolve_env_refs(raw_token))
|
||||
proxy = string_value(resolve_env_refs(raw_proxy))
|
||||
if raw_token and not token:
|
||||
checks.append(
|
||||
check(
|
||||
@@ -61,26 +51,7 @@ def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict
|
||||
"Set every environment variable referenced by the bot token.",
|
||||
)
|
||||
)
|
||||
if raw_proxy and not proxy:
|
||||
checks.append(
|
||||
check(
|
||||
"proxy_env",
|
||||
"Proxy environment variable",
|
||||
"fail",
|
||||
"Set every environment variable referenced by the network proxy.",
|
||||
)
|
||||
)
|
||||
if (raw_token and not token) or (raw_proxy and not proxy):
|
||||
return status_from_checks("telegram", checks, missing)
|
||||
if proxy and not _proxy_url_is_valid(proxy):
|
||||
checks.append(
|
||||
check(
|
||||
"proxy_format",
|
||||
"Network proxy",
|
||||
"fail",
|
||||
"Enter a valid HTTP or SOCKS proxy.",
|
||||
)
|
||||
)
|
||||
if raw_token and not token:
|
||||
return status_from_checks("telegram", checks, missing)
|
||||
if token:
|
||||
if not re.match(r"^\d+:[A-Za-z0-9_-]{20,}$", token):
|
||||
|
||||
@@ -12,7 +12,7 @@ export default {
|
||||
docsUrl: chatAppGuideUrl("telegram"),
|
||||
fields: [
|
||||
{ key: "channels.telegram.token", section: "credentials" },
|
||||
{ key: "channels.telegram.proxy", section: "connection" },
|
||||
{ key: "channels.telegram.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.telegram.allowFrom", section: "access" },
|
||||
{ key: "channels.telegram.groupPolicy", section: "behavior" },
|
||||
],
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Bot token",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Allowed users",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token del bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Usuarios permitidos",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Jeton du bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Utilisateurs autorisés",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Pengguna diizinkan",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "ボットトークン",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "許可ユーザー",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "봇 토큰",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "허용 사용자",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token do bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Usuários permitidos",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "Token bot",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "Người dùng được phép",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "机器人令牌",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "允许用户",
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"label": "機器人權杖",
|
||||
"placeholder": "123456:ABC..."
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
},
|
||||
"allowFrom": {
|
||||
"label": "允許使用者",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Cross-channel Python tests."""
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Shared proxy ownership at channel construction and setup boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
from nanobot.channels.manager import ChannelManager
|
||||
from nanobot.channels.registry import load_channel_plugin
|
||||
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
_CHANNEL_VALUES = {
|
||||
"telegram": {"token": "123456:abcdefghijklmnopqrstuvwxyz"},
|
||||
"discord": {"token": "discord-token"},
|
||||
"slack": {"appToken": "xapp-test", "botToken": "xoxb-test"},
|
||||
"matrix": {
|
||||
"homeserver": "https://matrix.example",
|
||||
"userId": "@bot:matrix.example",
|
||||
"password": "matrix-password",
|
||||
},
|
||||
"whatsapp": {"enabled": True},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", _CHANNEL_VALUES)
|
||||
def test_setup_refuses_proxy_opt_in_without_shared_address(name, monkeypatch) -> None:
|
||||
def fail_client(*_args, **_kwargs):
|
||||
pytest.fail("missing shared proxy must not fall back to a direct connection")
|
||||
|
||||
monkeypatch.setattr("httpx.Client", fail_client)
|
||||
validator = load_channel_plugin(name).setup.validator
|
||||
|
||||
result = validator(
|
||||
{**_CHANNEL_VALUES[name], "useProxy": True}, ChannelValidationContext(),
|
||||
)
|
||||
|
||||
assert result["status"] == "invalid"
|
||||
assert result["can_enable"] is False
|
||||
proxy_check = next(check for check in result["checks"] if check["id"] == "network_proxy")
|
||||
assert proxy_check["status"] == "fail"
|
||||
assert "Advanced" in proxy_check["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "request_method", "response"),
|
||||
[
|
||||
("telegram", "_get_me", {"ok": True, "result": {"id": 42}}),
|
||||
("discord", "http_get", {"id": "42", "username": "bot"}),
|
||||
("slack", "http_post", {"ok": True, "user_id": "U42"}),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("use_proxy", [True, False, "false"])
|
||||
def test_identity_validation_respects_shared_proxy_opt_in(
|
||||
name, request_method, response, use_proxy, monkeypatch,
|
||||
) -> None:
|
||||
module = importlib.import_module(f"nanobot.channels.{name}.validation")
|
||||
proxies = []
|
||||
|
||||
def request(_target, proxy=None, **_kwargs):
|
||||
proxies.append(proxy)
|
||||
return response
|
||||
|
||||
monkeypatch.setattr(module, request_method, request)
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
|
||||
result = module.validate(
|
||||
{**_CHANNEL_VALUES[name], "useProxy": use_proxy},
|
||||
ChannelValidationContext(network=network),
|
||||
)
|
||||
|
||||
assert result["status"] == "connected"
|
||||
assert proxies == [network.proxy if use_proxy is True else None]
|
||||
assert network.proxy not in str(result)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", _CHANNEL_VALUES)
|
||||
def test_runtime_refuses_proxy_opt_in_without_shared_address(name) -> None:
|
||||
pytest.importorskip(f"nanobot.channels.{name}.runtime", exc_type=ImportError)
|
||||
channel_cls = load_channel_plugin(name).load_channel_class()
|
||||
|
||||
with pytest.raises(ValueError, match="Advanced"):
|
||||
channel_cls({"useProxy": True}, MessageBus(), network=NetworkConfig())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", _CHANNEL_VALUES)
|
||||
@pytest.mark.parametrize("use_proxy", [True, False])
|
||||
def test_manager_constructs_proxy_capable_builtin_from_descriptor(
|
||||
name, use_proxy, monkeypatch, tmp_path,
|
||||
) -> None:
|
||||
pytest.importorskip(f"nanobot.channels.{name}.runtime", exc_type=ImportError)
|
||||
plugin = load_channel_plugin(name)
|
||||
monkeypatch.setattr("nanobot.channels.registry.discover_plugins", lambda: {name: plugin})
|
||||
monkeypatch.setattr("nanobot.optional_features.extra_installed", lambda *_args: True)
|
||||
config = Config.model_validate({
|
||||
"network": {"proxy": "http://127.0.0.1:7890"},
|
||||
"channels": {
|
||||
name: {**_CHANNEL_VALUES[name], "enabled": True, "useProxy": use_proxy},
|
||||
},
|
||||
})
|
||||
|
||||
manager = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")
|
||||
|
||||
channel = manager.channels[name]
|
||||
assert isinstance(channel, plugin.load_channel_class())
|
||||
assert channel.uses_shared_proxy is True
|
||||
assert channel.network is config.network
|
||||
assert channel._proxy == (config.network.proxy if use_proxy else None)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_manager_keeps_shared_proxy_instance_scoped(monkeypatch) -> None:
|
||||
class ProxySettings:
|
||||
def __init__(self, *, proxy_address: str) -> None:
|
||||
self.proxy_address = proxy_address
|
||||
|
||||
monkeypatch.setitem(sys.modules, "neonize._binder", SimpleNamespace(ProxySettings=ProxySettings))
|
||||
channels = []
|
||||
for address in ("http://127.0.0.1:7890", "http://127.0.0.1:7891"):
|
||||
manager = object.__new__(ChannelManager)
|
||||
manager.config = Config(network=NetworkConfig(proxy=address))
|
||||
manager.bus = MessageBus()
|
||||
channel = manager._build_channel("whatsapp", WhatsAppChannel, {"useProxy": True})
|
||||
assert channel.network is manager.config.network
|
||||
channels.append(channel)
|
||||
|
||||
for channel, address in zip(channels, ("http://127.0.0.1:7890", "http://127.0.0.1:7891")):
|
||||
client = SimpleNamespace(connect=AsyncMock())
|
||||
await channel._connect_client(client)
|
||||
assert client.connect.await_args.args[0].proxy_address == address
|
||||
assert channel.config.model_dump(by_alias=True)["useProxy"] is True
|
||||
assert "proxy" not in channel.config.model_dump(by_alias=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("name", "request_method"), [("discord", "http_get"), ("slack", "http_post")])
|
||||
def test_identity_validation_does_not_expose_shared_proxy_in_errors(name, request_method, monkeypatch) -> None:
|
||||
module = importlib.import_module(f"nanobot.channels.{name}.validation")
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
|
||||
def fail_request(*_args, **_kwargs):
|
||||
raise OSError(f"could not connect through {network.proxy}")
|
||||
|
||||
monkeypatch.setattr(module, request_method, fail_request)
|
||||
result = module.validate(
|
||||
{**_CHANNEL_VALUES[name], "useProxy": True}, ChannelValidationContext(network=network),
|
||||
)
|
||||
|
||||
assert result["status"] == "configured"
|
||||
assert result["can_enable"] is True
|
||||
assert any(check["status"] == "warn" for check in result["checks"])
|
||||
assert network.proxy not in str(result)
|
||||
assert "user:pass" not in str(result)
|
||||
@@ -74,6 +74,7 @@ def validate_channel_config(
|
||||
if setup_spec is not None and setup_spec.validator is not None:
|
||||
context = ChannelValidationContext(
|
||||
allow_local_service_access=config.tools.webui_allow_local_service_access,
|
||||
network=config.network,
|
||||
)
|
||||
custom_payload = setup_spec.validator(values, context)
|
||||
if cast(object, custom_payload) is not None:
|
||||
@@ -321,6 +322,11 @@ def _enabled(values: dict[str, Any]) -> bool:
|
||||
return _truthy(values.get("enabled"))
|
||||
|
||||
|
||||
def resolve_proxy(values: dict[str, Any], context: ChannelValidationContext) -> str | None:
|
||||
"""Resolve a channel's opt-in against the host's shared network settings."""
|
||||
return context.network.resolve_proxy(_truthy(channel_field_value(values, "useProxy")))
|
||||
|
||||
|
||||
def _label(field: str) -> str:
|
||||
words = re.sub(r"([a-z])([A-Z])", r"\1 \2", field).replace(".", " ").replace("_", " ")
|
||||
return words[:1].upper() + words[1:]
|
||||
@@ -424,6 +430,7 @@ __all__ = [
|
||||
"payload",
|
||||
"probe_tcp",
|
||||
"required_checks",
|
||||
"resolve_proxy",
|
||||
"status_from_checks",
|
||||
"string_value",
|
||||
"truthy",
|
||||
|
||||
@@ -331,14 +331,15 @@ class WhatsAppConnectStore:
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.whatsapp.runtime import WhatsAppChannel
|
||||
|
||||
section = getattr(load_config().channels, "whatsapp", None)
|
||||
root_config = load_config()
|
||||
section = getattr(root_config.channels, "whatsapp", None)
|
||||
if section is not None and hasattr(section, "model_dump"):
|
||||
config = section.model_dump(mode="json", by_alias=True)
|
||||
elif isinstance(section, dict):
|
||||
config = dict(cast(dict[str, Any], section))
|
||||
else:
|
||||
config = {}
|
||||
channel = WhatsAppChannel(config, MessageBus())
|
||||
channel = WhatsAppChannel(config, MessageBus(), network=root_config.network)
|
||||
return channel, channel.connect_database_path()
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -8,7 +8,7 @@ from nanobot.channels.whatsapp.validation import validate
|
||||
|
||||
SETUP_SPEC = ChannelSetupSpec(
|
||||
fields={
|
||||
"proxy": field(),
|
||||
"useProxy": field("bool", default=False),
|
||||
"allowFrom": field("list", snapshot=False),
|
||||
"groupPolicy": field(
|
||||
"enum",
|
||||
|
||||
@@ -22,6 +22,7 @@ from nanobot.bus.delivery import ChannelNotReadyError
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.channels.base import BaseChannel
|
||||
from nanobot.config.network import NetworkConfig
|
||||
from nanobot.config.paths import get_media_dir, get_runtime_subdir
|
||||
from nanobot.config_base import Base
|
||||
from nanobot.events import ContextCompactionEvent
|
||||
@@ -35,7 +36,7 @@ class WhatsAppConfig(Base):
|
||||
allow_from: list[str] = Field(default_factory=list)
|
||||
group_policy: Literal["open", "mention"] = "open"
|
||||
database_path: str = ""
|
||||
proxy: str = ""
|
||||
use_proxy: bool = False
|
||||
lid_mappings: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -299,19 +300,24 @@ class WhatsAppChannel(BaseChannel):
|
||||
|
||||
name = "whatsapp"
|
||||
display_name = "WhatsApp"
|
||||
uses_shared_proxy = True
|
||||
|
||||
@classmethod
|
||||
def default_config(cls) -> dict[str, Any]:
|
||||
return WhatsAppConfig().model_dump(by_alias=True)
|
||||
|
||||
def __init__(self, config: Any, bus: MessageBus):
|
||||
def __init__(
|
||||
self, config: Any, bus: MessageBus, *, network: NetworkConfig | None = None,
|
||||
):
|
||||
legacy_bridge_fields = (
|
||||
_legacy_bridge_config_fields(cast(dict[str, Any], config))
|
||||
if isinstance(config, dict) else []
|
||||
)
|
||||
if isinstance(config, dict):
|
||||
config = WhatsAppConfig.model_validate(config)
|
||||
super().__init__(config, bus)
|
||||
super().__init__(config, bus, network=network)
|
||||
self.config: WhatsAppConfig = config
|
||||
self._proxy = self.network.resolve_proxy(self.config.use_proxy)
|
||||
if legacy_bridge_fields:
|
||||
self.logger.warning(
|
||||
"Ignoring deprecated WhatsApp bridge config fields: {}. "
|
||||
@@ -348,11 +354,9 @@ class WhatsAppChannel(BaseChannel):
|
||||
return api.NewAClient(str(db_path))
|
||||
|
||||
async def _connect_client(self, client: Any) -> Any:
|
||||
proxy = self.config.proxy.strip()
|
||||
proxy = self._proxy
|
||||
if not proxy:
|
||||
return await client.connect()
|
||||
if "://" not in proxy:
|
||||
proxy = f"http://{proxy}"
|
||||
from neonize._binder import ProxySettings
|
||||
|
||||
return await client.connect(ProxySettings(proxy_address=proxy))
|
||||
@@ -513,8 +517,12 @@ class WhatsAppChannel(BaseChannel):
|
||||
|
||||
async def _fetch_remote_media(self, url: str) -> bytes:
|
||||
timeout = httpx.Timeout(_REMOTE_MEDIA_TIMEOUT_SECONDS, connect=10.0)
|
||||
transport = (
|
||||
PinnedDNSAsyncTransport(inner=httpx.AsyncHTTPTransport(proxy=self._proxy))
|
||||
if self._proxy else PinnedDNSAsyncTransport()
|
||||
)
|
||||
async with httpx.AsyncClient(
|
||||
transport=PinnedDNSAsyncTransport(),
|
||||
transport=transport,
|
||||
follow_redirects=True,
|
||||
max_redirects=_REMOTE_MEDIA_MAX_REDIRECTS,
|
||||
timeout=timeout,
|
||||
|
||||
@@ -10,6 +10,7 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
from nanobot.channels.whatsapp.connect import WhatsAppConnectStore
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
@@ -359,3 +360,18 @@ async def test_cancel_during_finalize_does_not_promote_login_database(
|
||||
assert target.read_bytes() == b"working-session"
|
||||
assert not Path(channel.config.database_path).exists()
|
||||
assert store.has_pending_work is False
|
||||
|
||||
|
||||
def test_connect_builds_channel_with_shared_network_settings(monkeypatch, tmp_path) -> None:
|
||||
database = tmp_path / "neonize.db"
|
||||
config = Config.model_validate({
|
||||
"network": {"proxy": "http://127.0.0.1:7890"},
|
||||
"channels": {"whatsapp": {"useProxy": True, "databasePath": str(database)}},
|
||||
})
|
||||
monkeypatch.setattr("nanobot.channels.whatsapp.connect.load_config", lambda: config)
|
||||
|
||||
channel, target = WhatsAppConnectStore._build_channel()
|
||||
|
||||
assert channel.network is config.network
|
||||
assert channel.config.use_proxy is True
|
||||
assert target == database
|
||||
@@ -18,6 +18,7 @@ from nanobot.channels.whatsapp.runtime import (
|
||||
_legacy_bridge_config_fields,
|
||||
_NeonizeAPI,
|
||||
)
|
||||
from nanobot.config.network import NetworkConfig
|
||||
|
||||
|
||||
class _Proto:
|
||||
@@ -139,7 +140,9 @@ async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) ->
|
||||
"neonize._binder",
|
||||
SimpleNamespace(ProxySettings=ProxySettings),
|
||||
)
|
||||
channel = _make_channel({"proxy": "127.0.0.1:23458"})
|
||||
channel = WhatsAppChannel(
|
||||
{"useProxy": True}, MessageBus(), network=NetworkConfig(proxy="127.0.0.1:23458"),
|
||||
)
|
||||
client = SimpleNamespace(connect=AsyncMock(return_value=None))
|
||||
|
||||
await channel._connect_client(client)
|
||||
@@ -150,7 +153,9 @@ async def test_connect_client_normalizes_proxy_without_a_scheme(monkeypatch) ->
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_connect_client_without_proxy_uses_default_connection() -> None:
|
||||
channel = _make_channel({"proxy": ""})
|
||||
channel = WhatsAppChannel(
|
||||
{"useProxy": False}, MessageBus(), network=NetworkConfig(proxy="127.0.0.1:23458"),
|
||||
)
|
||||
client = SimpleNamespace(connect=AsyncMock(return_value=None))
|
||||
|
||||
await channel._connect_client(client)
|
||||
@@ -828,3 +833,32 @@ def test_reset_database_removes_sqlite_sidecars(tmp_path) -> None:
|
||||
assert not db.exists()
|
||||
assert not wal.exists()
|
||||
assert not shm.exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remote_media_uses_shared_proxy_without_bypassing_url_guard(monkeypatch) -> None:
|
||||
network = NetworkConfig(proxy="http://user:pass@127.0.0.1:7890")
|
||||
proxies = []
|
||||
requests = []
|
||||
|
||||
def handler(request):
|
||||
requests.append(request)
|
||||
return httpx.Response(200, content=b"remote media")
|
||||
|
||||
def proxy_transport(*, proxy):
|
||||
proxies.append(proxy)
|
||||
return httpx.MockTransport(handler)
|
||||
|
||||
monkeypatch.setattr(whatsapp_module.httpx, "AsyncHTTPTransport", proxy_transport)
|
||||
channel = WhatsAppChannel({"useProxy": True}, MessageBus(), network=network)
|
||||
|
||||
with pytest.raises(httpx.RequestError, match="private/internal"):
|
||||
await channel._fetch_remote_media("http://127.0.0.1/media.wav")
|
||||
|
||||
assert proxies == [network.proxy]
|
||||
assert requests == []
|
||||
|
||||
public_url = "https://93.184.216.34/media.wav"
|
||||
assert await channel._fetch_remote_media(public_url) == b"remote media"
|
||||
assert proxies == [network.proxy, network.proxy]
|
||||
assert [str(request.url) for request in requests] == [public_url]
|
||||
@@ -3,11 +3,23 @@
|
||||
from typing import Any
|
||||
|
||||
from nanobot.channels.contracts import ChannelValidationContext
|
||||
from nanobot.channels.validation import check, enabled, official_action, payload, string_value
|
||||
from nanobot.channels.validation import (
|
||||
check,
|
||||
enabled,
|
||||
official_action,
|
||||
payload,
|
||||
resolve_proxy,
|
||||
string_value,
|
||||
)
|
||||
|
||||
|
||||
def validate(values: dict[str, Any], _context: ChannelValidationContext) -> dict[str, Any]:
|
||||
def validate(values: dict[str, Any], context: ChannelValidationContext) -> dict[str, Any]:
|
||||
checks: list[dict[str, Any]] = []
|
||||
try:
|
||||
resolve_proxy(values, context)
|
||||
except ValueError as exc:
|
||||
checks.append(check("network_proxy", "Network proxy", "fail", str(exc)))
|
||||
return payload("whatsapp", "invalid", checks, can_enable=False)
|
||||
if enabled(values) or string_value(values.get("databasePath")):
|
||||
checks.append(
|
||||
check("local_state", "Local login state", "pass", "Saved local login state was detected.")
|
||||
|
||||
@@ -16,7 +16,7 @@ export default {
|
||||
mode: "connect",
|
||||
docsUrl: chatAppGuideUrl("whatsapp"),
|
||||
manualFields: [
|
||||
{ key: "channels.whatsapp.proxy", section: "connection" },
|
||||
{ key: "channels.whatsapp.useProxy", section: "connection", control: "switch" },
|
||||
{ key: "channels.whatsapp.allowFrom", section: "access" },
|
||||
{ key: "channels.whatsapp.groupPolicy", section: "behavior" },
|
||||
],
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Allowlist"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Network proxy",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Use proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Lista de permitidos"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de red",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Liste d’autorisation"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy réseau",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Utiliser le proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Daftar izin"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy jaringan",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Gunakan proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "許可リスト"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "ネットワークプロキシ",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "プロキシを使う"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "허용 목록"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "네트워크 프록시",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "프록시 사용"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Lista de permissão"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy de rede",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Usar proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "Danh sách cho phép"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "Proxy mạng",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "Dùng proxy"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "白名单"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "网络代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -16,9 +16,8 @@
|
||||
"allowlist": "允許清單"
|
||||
}
|
||||
},
|
||||
"proxy": {
|
||||
"label": "網路代理",
|
||||
"placeholder": "http://127.0.0.1:7890"
|
||||
"useProxy": {
|
||||
"label": "使用代理"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user