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
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user