Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(providers): re-check custom endpoints on every connection

Haozhe Wu065d571686a7
diff --git a/agent/src/api/custom_provider_routes.py b/agent/src/api/custom_provider_routes.py
index 3d2573b8d..961882584 100644
--- a/agent/src/api/custom_provider_routes.py
+++ b/agent/src/api/custom_provider_routes.py
@@ -16,6 +16,7 @@ from pydantic import BaseModel, Field
from src.api.settings_routes import activate_custom_provider
from src.providers.custom_profiles import CustomProviderStore, STORE_LOCK
+from src.providers.endpoint_guard import is_non_public_address, proxy_applies, public_only_async_client
AuthDep = Callable[..., Awaitable[Any] | Any]
_TEST_TTL_S = 300.0
@@ -43,26 +44,6 @@ class CustomProviderActivateRequest(BaseModel):
confirm: bool = False
-def _is_non_public_address(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
- """Return whether a provider endpoint address is outside the public internet.
-
- ``is_private`` misses the shared address space 100.64.0.0/10, which holds
- Alibaba Cloud's metadata service (100.100.100.200); ``is_global`` covers it
- together with loopback, link-local, reserved and documentation ranges. An
- IPv4-mapped IPv6 address is judged by the IPv4 address it carries.
-
- Args:
- address: The literal or resolved endpoint address.
-
- Returns:
- True when the address must not be used as a provider endpoint.
- """
- mapped = getattr(address, "ipv4_mapped", None)
- if mapped is not None:
- address = mapped
- return not address.is_global or address.is_multicast
-
-
def _validate_custom_base_url(value: str) -> str:
normalized = value.strip().rstrip("/")
parsed = urlsplit(normalized)
@@ -82,7 +63,7 @@ def _validate_custom_base_url(value: str) -> str:
address = ipaddress.ip_address(hostname)
except ValueError:
address = None
- if address is not None and _is_non_public_address(address):
+ if address is not None and is_non_public_address(address):
raise ValueError("Provider base URL cannot target local or private network addresses")
if normalized.endswith("/chat/completions"):
normalized = normalized[:-len("/chat/completions")]
@@ -99,7 +80,7 @@ def _reject_private_dns_targets(base_url: str) -> None:
raise ValueError("Provider hostname could not be resolved") from exc
for result in results:
address = ipaddress.ip_address(result[4][0])
- if _is_non_public_address(address):
+ if is_non_public_address(address, resolved=True):
raise ValueError("Provider hostname resolves to a local or private network address")
@@ -110,6 +91,20 @@ def _completion_url(base_url: str) -> str:
return f"{url}/chat/completions"
+def _provider_async_client(base_url: str) -> httpx.AsyncClient:
+ """Client for the provider test: every direct connection is re-checked.
+
+ The name is resolved again when the request connects, and only to public
+ addresses, so a host that re-resolves after the check above (DNS
+ rebinding) or redirects is still refused. Through a proxy the proxy
+ resolves the name, so the default client is used.
+ """
+ kwargs = {"timeout": _PROVIDER_REQUEST_TIMEOUT_S, "follow_redirects": False}
+ if proxy_applies(base_url):
+ return httpx.AsyncClient(**kwargs)
+ return public_only_async_client(**kwargs)
+
+
async def _perform_completion_test(*, base_url: str, model: str, api_key: str) -> dict[str, Any]:
started = time.perf_counter()
normalized_base_url = _validate_custom_base_url(base_url)
@@ -124,12 +119,14 @@ async def _perform_completion_test(*, base_url: str, model: str, api_key: str) -
"temperature": 0,
}
try:
- async with httpx.AsyncClient(timeout=_PROVIDER_REQUEST_TIMEOUT_S, follow_redirects=False) as client:
+ async with _provider_async_client(normalized_base_url) as client:
response = await client.post(_completion_url(normalized_base_url), headers=headers, json=body)
response.raise_for_status()
payload = response.json()
except httpx.HTTPStatusError as exc:
raise ValueError(f"Provider returned HTTP {exc.response.status_code}") from exc
+ except httpx.ConnectError as exc:
+ raise ValueError(f"Provider test failed: {exc}") from exc
except (httpx.HTTPError, ValueError) as exc:
raise ValueError("Provider test failed: endpoint did not return valid JSON") from exc
try:
diff --git a/agent/src/providers/endpoint_guard.py b/agent/src/providers/endpoint_guard.py
new file mode 100644
index 000000000..23372339e
--- /dev/null
+++ b/agent/src/providers/endpoint_guard.py
@@ -0,0 +1,190 @@
+"""Keep a user-supplied model endpoint on the public internet at connect time.
+
+A custom OpenAI-compatible provider is checked when it is tested and saved,
+but a host name can re-resolve later (DNS rebinding) and point the saved
+profile at a private address. The clients built here resolve every direct
+connection once, refuse it unless every address is public, and connect to the
+address they checked, so there is no second lookup to rebind. TLS still
+verifies the certificate against the original host name.
+
+When a proxy applies to the endpoint, the proxy resolves the name and no
+local check can see the address it reaches; those clients are not built and
+the caller keeps its default transport.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import socket
+import urllib.request
+from typing import Any
+from urllib.parse import urlsplit
+
+import anyio
+import httpcore
+import httpx
+
+
+# Fake-IP proxies (Clash, Surge, sing-box in TUN mode) answer every lookup
+# from the RFC 2544 benchmarking range and resolve the real name themselves,
+# the way an HTTP proxy does; refusing it refused every endpoint on such hosts.
+_FAKE_IP_RANGE = ipaddress.ip_network("198.18.0.0/15")
+
+
+def is_non_public_address(
+ address: ipaddress.IPv4Address | ipaddress.IPv6Address, *, resolved: bool = False
+) -> bool:
+ """Return whether an endpoint address is outside the public internet.
+
+ ``is_private`` misses the shared address space 100.64.0.0/10, which holds
+ Alibaba Cloud's metadata service (100.100.100.200); ``is_global`` covers it
+ together with loopback, link-local, reserved and documentation ranges. An
+ IPv4-mapped IPv6 address is judged by the IPv4 address it carries.
+
+ Args:
+ address: The literal or resolved endpoint address.
+ resolved: True when the address came from a DNS lookup. A looked-up
+ address in 198.18.0.0/15 is a local fake-IP proxy's answer and is
+ allowed; the same address written into a URL is not.
+
+ Returns:
+ True when the address must not be used as a provider endpoint.
+ """
+ mapped = getattr(address, "ipv4_mapped", None)
+ if mapped is not None:
+ address = mapped
+ if resolved and address in _FAKE_IP_RANGE:
+ return False
+ return not address.is_global or address.is_multicast
+
+
+def proxy_applies(url: str) -> bool:
+ """Return whether the process proxy settings route ``url`` through a proxy.
+
+ Args:
+ url: The endpoint URL.
+
+ Returns:
+ True when a proxy from the environment would carry the request.
+ """
+ parts = urlsplit(url)
+ host = parts.hostname or ""
+ proxies = urllib.request.getproxies()
+ if not (proxies.get(parts.scheme) or proxies.get("all")):
+ return False
+ return not urllib.request.proxy_bypass(host)
+
+
+def _checked_address(host: str, port: int) -> str:
+ """Resolve ``host`` and return one address, refusing any non-public one.
+
+ Raises:
+ httpcore.ConnectError: If the name does not resolve or any of its
+ addresses is not public.
+ """
+ try:
+ infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
+ except socket.gaierror as exc:
+ raise httpcore.ConnectError(f"Provider host {host!r} could not be resolved") from exc
+ addresses = [ipaddress.ip_address(info[4][0]) for info in infos]
+ if not addresses or any(is_non_public_address(address, resolved=True) for address in addresses):
+ raise httpcore.ConnectError(
+ f"Provider host {host!r} resolves to a local or private network address"
+ )
+ return str(addresses[0])
+
+
+class _PublicOnlyBackend(httpcore.NetworkBackend):
+ """Sync network backend that connects only to checked public addresses."""
+
+ def __init__(self, inner: httpcore.NetworkBackend) -> None:
+ self._inner = inner
+
+ def connect_tcp(self, host: str, port: int, timeout: float | None = None,
+ local_address: str | None = None, socket_options: Any = None) -> httpcore.NetworkStream:
+ return self._inner.connect_tcp(
+ _checked_address(host, port), port, timeout=timeout,
+ local_address=local_address, socket_options=socket_options,
+ )
+
+ def connect_unix_socket(self, path: str, timeout: float | None = None,
+ socket_options: Any = None) -> httpcore.NetworkStream:
+ raise httpcore.ConnectError("Unix sockets are not provider endpoints")
+
+ def sleep(self, seconds: float) -> None:
+ self._inner.sleep(seconds)
+
+
+class _AsyncPublicOnlyBackend(httpcore.AsyncNetworkBackend):
+ """Async network backend that connects only to checked public addresses."""
+
+ def __init__(self, inner: httpcore.AsyncNetworkBackend) -> None:
+ self._inner = inner
+
+ async def connect_tcp(self, host: str, port: int, timeout: float | None = None,
+ local_address: str | None = None, socket_options: Any = None) -> httpcore.AsyncNetworkStream:
+ address = await anyio.to_thread.run_sync(_checked_address, host, port)
+ return await self._inner.connect_tcp(
+ address, port, timeout=timeout,
+ local_address=local_address, socket_options=socket_options,
+ )
+
+ async def connect_unix_socket(self, path: str, timeout: float | None = None,
+ socket_options: Any = None) -> httpcore.AsyncNetworkStream:
+ raise httpcore.ConnectError("Unix sockets are not provider endpoints")
+
+ async def sleep(self, seconds: float) -> None:
+ await self._inner.sleep(seconds)
+
+
+def _guard_pool(transport: httpx.HTTPTransport | httpx.AsyncHTTPTransport) -> None:
+ """Wrap the transport's connection pool backend in the public-only check.
+
+ Raises:
+ RuntimeError: If the installed httpx no longer exposes the pool's
+ network backend, so the guard cannot be installed.
+ """
+ pool = getattr(transport, "_pool", None)
+ inner = getattr(pool, "_network_backend", None)
+ if inner is None:
+ raise RuntimeError("httpx transport layout changed; cannot install the endpoint guard")
+ wrapper = _AsyncPublicOnlyBackend if isinstance(transport, httpx.AsyncHTTPTransport) else _PublicOnlyBackend
+ pool._network_backend = wrapper(inner)
+
+
+def public_only_async_client(**client_kwargs: Any) -> httpx.AsyncClient:
+ """Build an async client whose every direct connection is checked.
+
+ The transport is explicit, so environment proxies are not mounted; call
+ this only when :func:`proxy_applies` is false for the endpoint.
+
+ Args:
+ **client_kwargs: Extra keyword arguments for the client.
+
+ Returns:
+ The guarded async client.
+ """
+ transport = httpx.AsyncHTTPTransport(proxy=None, trust_env=True)
+ _guard_pool(transport)
+ return httpx.AsyncClient(transport=transport, **client_kwargs)
+
+
+def build_public_only_clients(**client_kwargs: Any) -> tuple[httpx.Client, httpx.AsyncClient]:
+ """Build sync and async clients whose every direct connection is checked.
+
+ The transports are explicit, so environment proxies are not mounted; call
+ this only when :func:`proxy_applies` is false for the endpoint.
+
+ Args:
+ **client_kwargs: Extra keyword arguments for both clients (timeouts,
+ redirect policy).
+
+ Returns:
+ A ``(sync_client, async_client)`` pair.
+ """
+ sync_transport = httpx.HTTPTransport(proxy=None, trust_env=True)
+ _guard_pool(sync_transport)
+ return (
+ httpx.Client(transport=sync_transport, **client_kwargs),
+ public_only_async_client(**client_kwargs),
+ )
diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.py
index 65f0df99a..c08c9ca66 100644
--- a/agent/src/providers/llm.py
+++ b/agent/src/providers/llm.py
@@ -18,6 +18,7 @@ from urllib.parse import urlsplit
from pydantic import PrivateAttr
from src.config.accessor import get_env_config, reset_env_config
+from src.providers.endpoint_guard import build_public_only_clients, proxy_applies
from src.providers.session_context import current_llm_session_id
from src.providers.capabilities import (
ProviderCapabilities,
@@ -1776,7 +1777,15 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Any
headers["User-Agent"] = custom_ua
_validate_explicit_headers(headers, source=f"{caps.name} provider configuration")
kwargs["default_headers"] = headers
- if get_env_config().llm.vibe_trading_disable_http_proxy:
+ disable_proxy = get_env_config().llm.vibe_trading_disable_http_proxy
+ if provider == "custom" and (disable_proxy or not proxy_applies(creds["base_url"])):
+ # A saved custom endpoint is re-checked on every connection, so a
+ # host that re-resolves to a private address later is refused.
+ sync_client, async_client = build_public_only_clients()
+ kwargs["http_client"] = sync_client
+ kwargs["http_async_client"] = async_client
+ kwargs["vibe_owned_http_clients"] = (sync_client, async_client)
+ elif disable_proxy:
sync_client, async_client = _build_proxy_free_http_clients()
kwargs["http_client"] = sync_client
kwargs["http_async_client"] = async_client
diff --git a/agent/tests/test_custom_provider_routes.py b/agent/tests/test_custom_provider_routes.py
index e8975ea93..febe2551e 100644
--- a/agent/tests/test_custom_provider_routes.py
+++ b/agent/tests/test_custom_provider_routes.py
@@ -271,7 +271,7 @@ def test_real_completion_transport_redacts_key_and_sends_expected_request(monkey
seen.append(request)
return httpx.Response(200, json={"choices": [{"message": {"content": "OK synthetic-secret"}}]})
monkeypatch.setattr(custom_provider_routes, "_reject_private_dns_targets", lambda _: None)
- monkeypatch.setattr(custom_provider_routes.httpx, "AsyncClient", lambda **kw: actual_client(transport=httpx.MockTransport(handle), **kw))
+ monkeypatch.setattr(custom_provider_routes, "_provider_async_client", lambda _url: actual_client(transport=httpx.MockTransport(handle)))
result = asyncio.run(custom_provider_routes._perform_completion_test(base_url="https://example.test/v1", model="demo", api_key="synthetic-secret"))
assert result["response_preview"] == "OK [redacted]"
assert str(seen[0].url) == "https://example.test/v1/chat/completions"
diff --git a/agent/tests/test_provider_endpoint_guard.py b/agent/tests/test_provider_endpoint_guard.py
new file mode 100644
index 000000000..c017e592b
--- /dev/null
+++ b/agent/tests/test_provider_endpoint_guard.py
@@ -0,0 +1,160 @@
+"""A custom provider endpoint is re-checked when each connection is made.
+
+Saving a profile checks the host once; without a connect-time check a name
+that later re-resolves to a private address (DNS rebinding) would reach it.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import httpcore
+import httpx
+import pytest
+
+from src.providers import endpoint_guard
+
+
+_PROXY_VARS = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy")
+
+
+def _no_proxy(monkeypatch: pytest.MonkeyPatch) -> None:
+ for name in _PROXY_VARS:
+ monkeypatch.delenv(name, raising=False)
+
+
+def _resolve_to(monkeypatch: pytest.MonkeyPatch, *addresses: str) -> None:
+ monkeypatch.setattr(
+ endpoint_guard.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [(None, None, None, "", (address, 0)) for address in addresses],
+ )
+
+
+class _RecordingAsyncBackend(httpcore.AsyncNetworkBackend):
+ def __init__(self) -> None:
+ self.hosts: list[str] = []
+
+ async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
+ self.hosts.append(host)
+ raise httpcore.ConnectError("recorded, not connected")
+
+ async def connect_unix_socket(self, path, timeout=None, socket_options=None):
+ raise NotImplementedError
+
+ async def sleep(self, seconds):
+ return None
+
+
+class _RecordingSyncBackend(httpcore.NetworkBackend):
+ def __init__(self) -> None:
+ self.hosts: list[str] = []
+
+ def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
+ self.hosts.append(host)
+ raise httpcore.ConnectError("recorded, not connected")
+
+ def connect_unix_socket(self, path, timeout=None, socket_options=None):
+ raise NotImplementedError
+
+ def sleep(self, seconds):
+ return None
+
+
[email protected]("resolved", [("10.0.0.5",), ("100.100.100.200",), ("8.8.8.8", "127.0.0.1"), ("::ffff:169.254.169.254",)])
+def test_guarded_client_refuses_a_name_that_resolves_to_a_private_address(
+ monkeypatch: pytest.MonkeyPatch, resolved: tuple[str, ...]
+) -> None:
+ _resolve_to(monkeypatch, *resolved)
+
+ async def run() -> None:
+ async with endpoint_guard.public_only_async_client() as client:
+ await client.get("https://provider.example/v1/models")
+
+ with pytest.raises(httpx.ConnectError, match="local or private network address"):
+ asyncio.run(run())
+
+
+def test_guarded_backends_connect_to_the_address_they_checked(monkeypatch: pytest.MonkeyPatch) -> None:
+ _resolve_to(monkeypatch, "93.184.216.34")
+ async_inner, sync_inner = _RecordingAsyncBackend(), _RecordingSyncBackend()
+
+ with pytest.raises(httpcore.ConnectError, match="recorded"):
+ asyncio.run(endpoint_guard._AsyncPublicOnlyBackend(async_inner).connect_tcp("provider.example", 443))
+ with pytest.raises(httpcore.ConnectError, match="recorded"):
+ endpoint_guard._PublicOnlyBackend(sync_inner).connect_tcp("provider.example", 443)
+
+ # No second lookup by name: the inner backend dials the checked address.
+ assert async_inner.hosts == ["93.184.216.34"]
+ assert sync_inner.hosts == ["93.184.216.34"]
+
+
+def test_guard_is_installed_on_both_clients() -> None:
+ sync_client, async_client = endpoint_guard.build_public_only_clients()
+ try:
+ assert isinstance(sync_client._transport._pool._network_backend, endpoint_guard._PublicOnlyBackend)
+ assert isinstance(async_client._transport._pool._network_backend, endpoint_guard._AsyncPublicOnlyBackend)
+ finally:
+ sync_client.close()
+ asyncio.run(async_client.aclose())
+
+
+def test_proxy_applies_follows_the_process_proxy_settings(monkeypatch: pytest.MonkeyPatch) -> None:
+ _no_proxy(monkeypatch)
+ assert not endpoint_guard.proxy_applies("https://provider.example/v1")
+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:7890")
+ assert endpoint_guard.proxy_applies("https://provider.example/v1")
+ monkeypatch.setenv("NO_PROXY", "provider.example")
+ assert not endpoint_guard.proxy_applies("https://provider.example/v1")
+
+
+def test_custom_model_uses_guarded_clients_unless_a_proxy_resolves_the_name(monkeypatch: pytest.MonkeyPatch) -> None:
+ from src.providers import llm
+
+ monkeypatch.setattr(llm, "_ensure_dotenv", lambda: None)
+ monkeypatch.setattr(
+ llm,
+ "get_llm_credentials",
+ lambda provider, model: {"provider": "custom", "model": "m", "base_url": "https://provider.example/v1", "api_key": "k"},
+ )
+ monkeypatch.setenv("LANGCHAIN_PROVIDER", "custom")
+ monkeypatch.setenv("LANGCHAIN_MODEL_NAME", "m")
+ monkeypatch.delenv("VIBE_TRADING_DISABLE_HTTP_PROXY", raising=False)
+ llm.reset_env_config()
+
+ _no_proxy(monkeypatch)
+ direct = llm.build_llm()
+ assert isinstance(direct.http_async_client._transport._pool._network_backend, endpoint_guard._AsyncPublicOnlyBackend)
+
+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:7890")
+ proxied = llm.build_llm()
+ assert proxied.http_async_client is None
+
+
+def test_a_fake_ip_proxy_answer_is_allowed_but_a_written_fake_ip_is_not(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Clash / Surge TUN answer every lookup from 198.18.0.0/15 (2026-10-21:
+ every custom provider was refused on such a host at save time)."""
+ import ipaddress
+
+ from src.api import custom_provider_routes
+
+ fake = ipaddress.ip_address("198.18.0.4")
+ assert endpoint_guard.is_non_public_address(fake)
+ assert not endpoint_guard.is_non_public_address(fake, resolved=True)
+ assert endpoint_guard.is_non_public_address(ipaddress.ip_address("198.20.0.1"), resolved=True) is False
+ assert endpoint_guard.is_non_public_address(ipaddress.ip_address("10.0.0.5"), resolved=True)
+
+ _resolve_to(monkeypatch, "198.18.0.4")
+ inner = _RecordingAsyncBackend()
+ with pytest.raises(httpcore.ConnectError, match="recorded"):
+ asyncio.run(endpoint_guard._AsyncPublicOnlyBackend(inner).connect_tcp("provider.example", 443))
+ assert inner.hosts == ["198.18.0.4"]
+
+ monkeypatch.setattr(
+ custom_provider_routes.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [(None, None, None, "", ("198.18.0.4", 0))],
+ )
+ custom_provider_routes._reject_private_dns_targets("https://provider.example/v1")
+ with pytest.raises(ValueError, match="local or private"):
+ custom_provider_routes._validate_custom_base_url("http://198.18.0.4/v1")