Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(im): close Discord SOCKS auth bypass and redact proxy URLs in logs

cyh434b108860a2
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 3e86f3f03..5ed340506 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -5,7 +5,6 @@ import logging
import os
import time
from typing import Dict, Any, Optional, Callable, List
-from urllib.parse import urlsplit
import aiohttp
import discord
@@ -315,7 +314,7 @@ class DiscordBot(BaseIMClient):
self._loop = asyncio.get_running_loop()
# Inject proxy connector inside the event loop (required by
# aiohttp). Must happen before login() creates the session.
- from vibe.proxy import resolve_proxy
+ from vibe.proxy import redact_proxy_url, resolve_proxy
proxy_url = resolve_proxy(self.config.proxy_url)
if proxy_url:
@@ -323,7 +322,7 @@ class DiscordBot(BaseIMClient):
from aiohttp_socks import ProxyConnector
self.client.http.connector = ProxyConnector.from_url(proxy_url, rdns=True)
- logger.info("Discord using proxy: %s", self._redact_proxy_url(proxy_url))
+ logger.info("Discord using proxy: %s", redact_proxy_url(proxy_url))
except ImportError:
logger.warning("Proxy configured but aiohttp_socks not installed")
@@ -344,22 +343,6 @@ class DiscordBot(BaseIMClient):
except Exception:
logger.exception("Failed to stop Discord client")
- @staticmethod
- def _redact_proxy_url(proxy_url: str) -> str:
- """Return a proxy URL safe for logs (credentials stripped)."""
- try:
- parts = urlsplit(proxy_url)
- if parts.scheme and parts.hostname:
- host = parts.hostname
- if ":" in host and not host.startswith("["):
- host = f"[{host}]"
- if parts.port:
- return f"{parts.scheme}://{host}:{parts.port}"
- return f"{parts.scheme}://{host}"
- except Exception:
- pass
- return "<configured>"
-
async def shutdown(self) -> None:
loop = getattr(self, "_loop", None)
current_loop = asyncio.get_running_loop()
diff --git a/tests/test_im_proxy_unification.py b/tests/test_im_proxy_unification.py
index 83185a30a..0c252a132 100644
--- a/tests/test_im_proxy_unification.py
+++ b/tests/test_im_proxy_unification.py
@@ -1,9 +1,13 @@
-"""Unified tests for the IM proxy_url field and resolve_proxy() precedence.
+"""Unified tests for the IM proxy_url field, resolve_proxy() precedence,
+redact_proxy_url() credential stripping, and the Discord auth_test SOCKS path.
Covers:
- proxy_url is inherited by every IM config dataclass.
- resolve_proxy() honors explicit config first, then falls back to the
system SOCKS proxy, otherwise returns None.
+ - redact_proxy_url() strips userinfo so logs cannot leak credentials.
+ - _discord_api_get_via_aiohttp surfaces non-2xx responses as exceptions
+ so discord_auth_test correctly rejects invalid tokens via SOCKS.
"""
from __future__ import annotations
@@ -24,7 +28,7 @@ from config.v2_config import (
WeChatConfig,
)
from vibe import proxy as proxy_module
-from vibe.proxy import resolve_proxy
+from vibe.proxy import redact_proxy_url, resolve_proxy
CONFIG_FACTORIES = [
@@ -121,3 +125,108 @@ def test_resolve_proxy_returns_none_when_neither_configured() -> None:
assert resolve_proxy(None) is None
assert resolve_proxy("") is None
assert resolve_proxy(" ") is None
+
+
+# ---------------------------------------------------------------------------
+# redact_proxy_url() credential stripping
+# ---------------------------------------------------------------------------
+
+
+ "url,expected",
+ [
+ ("socks5://user:[email protected]:1080", "socks5://127.0.0.1:1080"),
+ ("socks5://user@host:1080", "socks5://host:1080"),
+ ("socks5://127.0.0.1:1080", "socks5://127.0.0.1:1080"),
+ ("http://proxy.local:8080", "http://proxy.local:8080"),
+ ("https://u:[email protected]", "https://proxy.local"),
+ ("socks5://u:p@[2001:db8::1]:1080", "socks5://[2001:db8::1]:1080"),
+ ],
+)
+def test_redact_proxy_url_strips_userinfo(url, expected) -> None:
+ assert redact_proxy_url(url) == expected
+
+
[email protected]("value", [None, ""])
+def test_redact_proxy_url_handles_empty(value) -> None:
+ assert redact_proxy_url(value) == "<unset>"
+
+
+def test_redact_proxy_url_handles_garbage() -> None:
+ """Unparseable input returns a generic placeholder, never the raw value."""
+ assert redact_proxy_url("not a url") == "<configured>"
+
+
+# ---------------------------------------------------------------------------
+# Discord auth_test SOCKS path: non-2xx must raise (regression for P1 review)
+# ---------------------------------------------------------------------------
+
+
+def test_discord_auth_test_socks_rejects_401() -> None:
+ """A 401 from Discord over SOCKS must surface as ok=False, not ok=True.
+
+ Before the fix, _discord_api_get_via_aiohttp returned the JSON body for
+ any status, so discord_auth_test wrapped Discord's error payload as a
+ successful response and let invalid tokens through the wizard.
+ """
+ import aiohttp
+
+ from vibe import api as vibe_api
+
+ async def raise_401(url, headers, proxy):
+ raise aiohttp.ClientResponseError(
+ request_info=aiohttp.RequestInfo(url=url, method="GET", headers={}, real_url=url),
+ history=(),
+ status=401,
+ message="Unauthorized",
+ )
+
+ with patch.object(vibe_api, "_discord_api_get_via_aiohttp", new=raise_401):
+ result = vibe_api.discord_auth_test("invalid", proxy_url="socks5://127.0.0.1:1080")
+
+ assert result["ok"] is False
+ assert "401" in result["error"] or "Unauthorized" in result["error"]
+
+
+def test_discord_api_get_via_aiohttp_raises_for_status() -> None:
+ """Direct unit test: the helper must call resp.raise_for_status().
+
+ Pinning this prevents future regressions: even if the auth_test wrapper
+ were rewritten, this contract keeps the SOCKS path consistent with the
+ urllib path (which raises HTTPError on non-2xx).
+ """
+ import asyncio
+
+ from unittest.mock import AsyncMock, MagicMock
+
+ from vibe.api import _discord_api_get_via_aiohttp
+
+ raise_for_status = MagicMock(side_effect=RuntimeError("would raise"))
+ fake_resp = MagicMock()
+ fake_resp.raise_for_status = raise_for_status
+ fake_resp.json = AsyncMock(return_value={"id": "should-not-see"})
+
+ fake_resp_cm = MagicMock()
+ fake_resp_cm.__aenter__ = AsyncMock(return_value=fake_resp)
+ fake_resp_cm.__aexit__ = AsyncMock(return_value=None)
+
+ fake_session = MagicMock()
+ fake_session.get = MagicMock(return_value=fake_resp_cm)
+
+ fake_session_cm = MagicMock()
+ fake_session_cm.__aenter__ = AsyncMock(return_value=fake_session)
+ fake_session_cm.__aexit__ = AsyncMock(return_value=None)
+
+ with patch("aiohttp.ClientSession", return_value=fake_session_cm), patch(
+ "aiohttp_socks.ProxyConnector.from_url", return_value=MagicMock()
+ ):
+ with pytest.raises(RuntimeError, match="would raise"):
+ asyncio.run(
+ _discord_api_get_via_aiohttp(
+ "https://discord.com/api/v10/users/@me",
+ {"Authorization": "Bot x"},
+ "socks5://127.0.0.1:1080",
+ )
+ )
+
+ raise_for_status.assert_called_once()
diff --git a/vibe/api.py b/vibe/api.py
index 9aefc49da..c64b709a6 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -766,6 +766,10 @@ async def _discord_api_get_via_aiohttp(url: str, headers: dict, proxy: str) -> d
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
async with session.get(url, headers=headers) as resp:
+ # urllib.urlopen raises HTTPError on non-2xx; mirror that here so
+ # callers like discord_auth_test correctly treat 401 as a failure
+ # instead of returning Discord's error JSON as a successful payload.
+ resp.raise_for_status()
return await resp.json()
@@ -1593,10 +1597,12 @@ def lark_auth_test(
log once when a value is provided so users understand the gap.
"""
if proxy_url and proxy_url.strip():
+ from vibe.proxy import redact_proxy_url
+
logger.warning(
"Feishu/Lark auth_test received proxy_url=%s but lark-oapi has no "
"proxy hook; the request will bypass the configured proxy.",
- proxy_url,
+ redact_proxy_url(proxy_url),
)
try:
token = _lark_tenant_token(app_id, app_secret, domain)
diff --git a/vibe/proxy.py b/vibe/proxy.py
index d4af9ed90..fe5b385a8 100644
--- a/vibe/proxy.py
+++ b/vibe/proxy.py
@@ -8,10 +8,35 @@ import logging
import os
import subprocess
from typing import Optional
+from urllib.parse import urlsplit
logger = logging.getLogger(__name__)
+def redact_proxy_url(proxy_url: Optional[str]) -> str:
+ """Return a proxy URL safe for logs (userinfo stripped).
+
+ Proxy URLs commonly include ``user:password@`` credentials. Logging them
+ verbatim leaks secrets into ``~/.vibe_remote/logs/``. This helper keeps
+ scheme, host, and port so operators can still identify the target, but
+ drops anything that could contain a credential.
+ """
+ if not proxy_url:
+ return "<unset>"
+ try:
+ parts = urlsplit(proxy_url)
+ if parts.scheme and parts.hostname:
+ host = parts.hostname
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ if parts.port:
+ return f"{parts.scheme}://{host}:{parts.port}"
+ return f"{parts.scheme}://{host}"
+ except Exception:
+ pass
+ return "<configured>"
+
+
def resolve_proxy(config_proxy: Optional[str]) -> Optional[str]:
"""Resolve the effective proxy URL for an IM adapter.