Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mcp-store): connect upstream MCP fetches to the validated address (#102376)

Chris Volzerde63b1658f2c
diff --git a/ee/hogai/tools/call_mcp_server/test/test_tool.py b/ee/hogai/tools/call_mcp_server/test/test_tool.py
index fe2f8459fd34..2adabb9b3815 100644
--- a/ee/hogai/tools/call_mcp_server/test/test_tool.py
+++ b/ee/hogai/tools/call_mcp_server/test/test_tool.py
@@ -10,6 +10,8 @@ from asgiref.sync import sync_to_async
from langchain_core.runnables import RunnableConfig
from parameterized import parameterized
+from posthog.security.url_validation import PinnedUrlVerdict
+
from products.mcp_store.backend.models import (
MCPGatewayServer,
MCPServerInstallation,
@@ -37,8 +39,11 @@ class TestCallMCPServerTool(BaseTest):
self.context_manager = AssistantContextManager(self.team, self.user, {})
self.node_path = (NodePath(name="test_node", tool_call_id="test_call", message_id="test"),)
# Bypass SSRF DNS resolution for fake test domains
- patcher = patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- self.mock_is_url_allowed = patcher.start()
+ patcher = patch(
+ "products.mcp_store.backend.url_policy.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set()),
+ )
+ self.mock_validate_url = patcher.start()
self.addCleanup(patcher.stop)
def _install_server(
@@ -566,7 +571,9 @@ class TestIsTokenExpiring(TestCallMCPServerTool):
class TestSSRFProtection(TestCallMCPServerTool):
async def test_ssrf_blocked_url_raises_fatal_error(self):
- self.mock_is_url_allowed.return_value = (False, "Local/metadata host")
+ self.mock_validate_url.return_value = PinnedUrlVerdict(
+ allowed=False, reason="Local/metadata host", pinned_ips=set()
+ )
inst = {
"id": str(uuid.uuid4()),
"display_name": "Evil",
diff --git a/posthog/security/pinned_httpx.py b/posthog/security/pinned_httpx.py
new file mode 100644
index 000000000000..8028b9048ffa
--- /dev/null
+++ b/posthog/security/pinned_httpx.py
@@ -0,0 +1,117 @@
+"""SSRF-hardened httpx clients with DNS pinning.
+
+The ``requests`` counterpart is ``pinned_requests``. This module is for callers on ``httpx``,
+which resolves the host again when it opens the connection. A URL that passed validation can
+therefore still reach an internal address if its DNS record changes in between.
+
+``pinned_client`` returns an ``httpx.Client`` whose direct connections go to the validated
+address of the URL's host. The ``Host`` header and the TLS server name keep the host name, so
+the upstream server sees an ordinary request and the certificate check stays on the name.
+
+A proxy must appear in ``SSRF_TRUSTED_PROXY_URLS`` before it can receive a request.
+Operators must verify that each trusted proxy blocks sensitive destination addresses after
+DNS resolution. An environment proxy variable alone does not establish this trust.
+A connection through a trusted proxy is not pinned. The proxy resolves
+the name itself, and the CONNECT tunnel in httpcore uses the connect target as the TLS server
+name, so a pinned address there would fail certificate verification.
+
+Redirects are never followed automatically. A same-host redirect reuses the pin. Any other
+host is refused, because it was not validated.
+"""
+
+import ipaddress
+from collections.abc import Mapping
+from typing import Any
+
+from django.conf import settings
+
+import httpx
+
+from posthog.security.pinned_requests import SSRFBlockedError, select_pinned_ip
+from posthog.security.url_validation import ResolvedIPs
+
+IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
+
+
+def _pin_key(url: httpx.URL) -> str:
+ """The host form httpx connects to: lowercase punycode without the DNS root dot."""
+ return url.raw_host.decode("ascii").rstrip(".")
+
+
+class PinnedTransport(httpx.BaseTransport):
+ """Sends each request for a pinned host to the validated address.
+
+ Once anything is pinned, a request for another host is refused instead of falling back
+ to a fresh DNS lookup, because that lookup is the rebinding window pinning closes. An
+ empty pin map skips the host restriction for the dev bypass and internal endpoints.
+ Proxy trust checks still apply when no address is pinned.
+ """
+
+ def __init__(
+ self, inner: httpx.BaseTransport, pins: Mapping[str, IPAddress], *, proxy_url: httpx.URL | None = None
+ ) -> None:
+ self._inner = inner
+ self._pins = dict(pins)
+ self._proxy_url = proxy_url
+ self._trusted_proxy = proxy_url is None or proxy_url in {
+ httpx.URL(url) for url in settings.SSRF_TRUSTED_PROXY_URLS
+ }
+
+ def handle_request(self, request: httpx.Request) -> httpx.Response:
+ host = _pin_key(request.url)
+ ip = self._pins.get(host)
+ if self._pins and ip is None:
+ raise SSRFBlockedError(f"No validated address for host {host!r}; refusing to connect")
+ if not self._trusted_proxy:
+ raise SSRFBlockedError(
+ "Outbound proxy is not trusted. Ask an administrator to configure SSRF_TRUSTED_PROXY_URLS."
+ )
+ if self._proxy_url is not None or ip is None:
+ return self._inner.handle_request(request)
+
+ # The Host header was filled from the original URL when the request was built, and
+ # replacing the URL afterwards leaves it as it is.
+ original_url = request.url
+ try:
+ request.url = original_url.copy_with(host=str(ip))
+ if request.url.scheme == "https":
+ request.extensions["sni_hostname"] = host
+ return self._inner.handle_request(request)
+ finally:
+ request.url = original_url
+
+ def close(self) -> None:
+ self._inner.close()
+
+
+class PinnedClient(httpx.Client):
+ """An ``httpx.Client`` whose direct connections go to validated addresses.
+
+ httpx routes each request by its original URL, so ``HTTPS_PROXY`` and ``NO_PROXY`` keep
+ their meaning. Both direct and proxy transports enforce the host restriction. Trusted
+ proxies receive the host name; other proxies fail closed. Passing ``transport=`` to
+ ``httpx.Client`` would instead switch environment proxies off altogether.
+ """
+
+ def __init__(self, *, pins: Mapping[str, IPAddress], **kwargs: Any) -> None:
+ self._pins = dict(pins)
+ super().__init__(**kwargs)
+
+ def _init_transport(self, *args: Any, **kwargs: Any) -> httpx.BaseTransport:
+ return PinnedTransport(super()._init_transport(*args, **kwargs), self._pins)
+
+ def _init_proxy_transport(self, proxy: httpx.Proxy, *args: Any, **kwargs: Any) -> httpx.BaseTransport:
+ return PinnedTransport(super()._init_proxy_transport(proxy, *args, **kwargs), self._pins, proxy_url=proxy.url)
+
+
+def pinned_client(url: str, pinned_ips: ResolvedIPs, **kwargs: Any) -> httpx.Client:
+ """An httpx client for ``url`` that connects to one of its validated addresses.
+
+ ``pinned_ips`` is the set ``validate_url_and_pin_ips`` returned for ``url``. An empty set
+ pins nothing, which is what the validator returns under the dev bypass.
+ """
+ pins: dict[str, IPAddress] = {}
+ ip = select_pinned_ip(pinned_ips)
+ if ip is not None:
+ pins[_pin_key(httpx.URL(url))] = ip
+ return PinnedClient(pins=pins, **kwargs)
diff --git a/posthog/security/test/test_pinned_httpx.py b/posthog/security/test/test_pinned_httpx.py
new file mode 100644
index 000000000000..bd23bc9378f3
--- /dev/null
+++ b/posthog/security/test/test_pinned_httpx.py
@@ -0,0 +1,276 @@
+import os
+import ssl
+import socket
+import ipaddress
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+import httpx
+import httpcore
+
+from posthog.security.pinned_httpx import pinned_client
+from posthog.security.pinned_requests import SSRFBlockedError
+from posthog.security.url_validation import validate_url_and_pin_ips
+
+PUBLIC_IP = ipaddress.ip_address("93.184.216.34")
+
+
+def _capturing_transport(seen: list[httpx.Request]) -> httpx.MockTransport:
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(httpx.Request(request.method, request.url, headers=request.headers, extensions=request.extensions))
+ return httpx.Response(200)
+
+ return httpx.MockTransport(handler)
+
+
+def _without_environment_proxies() -> dict[str, str]:
+ return {key: "" for key in os.environ if key.lower().endswith("_proxy")}
+
+
+class TestPinnedTransport:
+ @pytest.mark.parametrize(
+ "url,ip,expected_url,expected_host_header,expected_sni",
+ [
+ (
+ "https://Example.com:8443/path?q=1",
+ "93.184.216.34",
+ "https://93.184.216.34:8443/path?q=1",
+ "example.com:8443",
+ "example.com",
+ ),
+ ("https://example.com/path", "2001:db8::1", "https://[2001:db8::1]/path", "example.com", "example.com"),
+ # httpx punycodes the host before the transport sees it, so the pin must match that form.
+ (
+ "https://éxample.com./path",
+ "93.184.216.34",
+ "https://93.184.216.34/path",
+ "xn--xample-9ua.com.",
+ "xn--xample-9ua.com",
+ ),
+ ("http://example.com/path", "93.184.216.34", "http://93.184.216.34/path", "example.com", None),
+ ],
+ )
+ def test_connects_to_the_pinned_address_and_keeps_the_host_name(
+ self, url, ip, expected_url, expected_host_header, expected_sni
+ ):
+ seen: list[httpx.Request] = []
+ client = pinned_client(url, {ipaddress.ip_address(ip)}, transport=_capturing_transport(seen), trust_env=False)
+
+ client.get(url)
+
+ [request] = seen
+ assert str(request.url) == expected_url
+ assert request.headers["Host"] == expected_host_header
+ assert request.extensions.get("sni_hostname") == expected_sni
+
+ def test_refuses_a_host_that_was_not_pinned(self):
+ seen: list[httpx.Request] = []
+ client = pinned_client(
+ "https://example.com/", {PUBLIC_IP}, transport=_capturing_transport(seen), trust_env=False
+ )
+
+ with pytest.raises(SSRFBlockedError):
+ client.get("https://other.example.com/")
+ assert seen == []
+
+ def test_nothing_pinned_passes_the_request_through(self):
+ seen: list[httpx.Request] = []
+ client = pinned_client("https://example.com/", set(), transport=_capturing_transport(seen), trust_env=False)
+
+ client.get("https://other.example.com/")
+
+ assert str(seen[0].url) == "https://other.example.com/"
+
+ @pytest.mark.parametrize("redirect", [False, True])
+ def test_preserves_host_only_cookies_across_requests_and_redirects(self, redirect: bool) -> None:
+ url = "https://example.com/mcp"
+ seen: list[httpx.Request] = []
+
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ seen.append(
+ httpx.Request(request.method, request.url, headers=request.headers, extensions=request.extensions)
+ )
+ if len(seen) == 1:
+ headers = {"Set-Cookie": "mcp_session=fake-session; Path=/; Secure"}
+ if redirect:
+ headers["Location"] = "/continued"
+ return httpx.Response(302 if redirect else 200, headers=headers)
+ return httpx.Response(200)
+
+ with pinned_client(url, {PUBLIC_IP}, transport=httpx.MockTransport(handle_request), trust_env=False) as client:
+ response = client.get(url, follow_redirects=True)
+ assert response.status_code == 200
+ assert response.url == httpx.URL("https://example.com/continued" if redirect else url)
+ assert [item.url for item in response.history] == ([httpx.URL(url)] if redirect else [])
+ assert [cookie.domain for cookie in client.cookies.jar] == ["example.com"]
+ assert client.get("https://example.com/continued").status_code == 200
+
+ assert len(seen) == (3 if redirect else 2)
+ assert {request.url.host for request in seen} == {str(PUBLIC_IP)}
+ assert {request.headers["Host"] for request in seen} == {"example.com"}
+ assert {request.extensions["sni_hostname"] for request in seen} == {"example.com"}
+ assert seen[0].headers.get("Cookie") is None
+ assert {request.headers.get("Cookie") for request in seen[1:]} == {"mcp_session=fake-session"}
+
+ @pytest.mark.parametrize("error_type", [httpx.ConnectError, httpx.ReadTimeout])
+ def test_restores_request_url_after_transport_error(self, error_type: type[httpx.RequestError]) -> None:
+ url = "https://example.com/mcp"
+
+ def handle_request(request: httpx.Request) -> httpx.Response:
+ assert request.url.host == str(PUBLIC_IP)
+ raise error_type("upstream failed", request=request)
+
+ with pinned_client(url, {PUBLIC_IP}, transport=httpx.MockTransport(handle_request), trust_env=False) as client:
+ request = client.build_request("GET", url)
+ with pytest.raises(error_type) as error:
+ client.send(request)
+ assert request.url == httpx.URL(url)
+ assert error.value.request.url == httpx.URL(url)
+
+
+class TestPinnedClientRouting:
+ @override_settings(SSRF_TRUSTED_PROXY_URLS=[])
+ @pytest.mark.parametrize("proxy_variable", ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"])
+ def test_refuses_untrusted_proxy_before_sending_credentials(self, proxy_variable: str) -> None:
+ scheme = "http" if proxy_variable == "HTTP_PROXY" else "https"
+ url = f"{scheme}://example.com/"
+ with (
+ patch.dict(os.environ, {**_without_environment_proxies(), proxy_variable: "http://egress.example:3128"}),
+ patch.object(httpx.HTTPTransport, "handle_request", return_value=httpx.Response(200)) as send,
+ pinned_client(url, {PUBLIC_IP}) as client,
+ ):
+ with pytest.raises(SSRFBlockedError, match="proxy"):
+ client.get(url, headers={"Authorization": "Bearer fake-test-token"})
+ send.assert_not_called()
+
+ @override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
+ @pytest.mark.parametrize(
+ "scheme,environment,expected_host",
+ [
+ ("https", {}, "93.184.216.34"),
+ ("https", {"HTTPS_PROXY": "http://egress.example:3128"}, "example.com"),
+ ("http", {"HTTP_PROXY": "http://egress.example:3128"}, "example.com"),
+ ("https", {"ALL_PROXY": "http://egress.example:3128"}, "example.com"),
+ ("https", {"HTTPS_PROXY": "http://untrusted.example:3128", "NO_PROXY": "example.com"}, "93.184.216.34"),
+ ("https", {"HTTPS_PROXY": "http://untrusted.example:3128", "NO_PROXY": "*"}, "93.184.216.34"),
+ ("https", {"HTTPS_PROXY": "http://egress.example:3128", "NO_PROXY": "other.example"}, "example.com"),
+ ],
+ )
+ def test_pins_direct_connections_only(self, scheme: str, environment: dict[str, str], expected_host: str) -> None:
+ seen: list[httpx.Request] = []
+
+ def handle_request(_transport: httpx.HTTPTransport, request: httpx.Request) -> httpx.Response:
+ seen.append(
+ httpx.Request(request.method, request.url, headers=request.headers, extensions=request.extensions)
+ )
+ return httpx.Response(200)
+
+ with (
+ patch.dict(os.environ, {**_without_environment_proxies(), **environment}),
+ patch.object(httpx.HTTPTransport, "handle_request", handle_request),
+ ):
+ url = f"{scheme}://example.com/"
+ with pinned_client(url, {PUBLIC_IP}, trust_env=True) as client:
+ client.get(url)
+
+ [request] = seen
+ assert request.url.host == expected_host
+
+ @override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
+ @pytest.mark.parametrize("target", ["https://other.example/", "http://169.254.169.254/"])
+ def test_trusted_proxy_refuses_redirect_to_unvalidated_host(self, target: str) -> None:
+ with (
+ patch.dict(os.environ, {**_without_environment_proxies(), "ALL_PROXY": "http://egress.example:3128"}),
+ patch.object(
+ httpx.HTTPTransport, "handle_request", return_value=httpx.Response(302, headers={"Location": target})
+ ) as send,
+ pinned_client("https://example.com/", {PUBLIC_IP}) as client,
+ ):
+ with pytest.raises(SSRFBlockedError, match="No validated address"):
+ client.get("https://example.com/", follow_redirects=True)
+ assert send.call_count == 1
+
+ @override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
+ @pytest.mark.parametrize("proxy", ["http://egress.example:3129", "http://other.example:3128"])
+ def test_explicit_proxy_requires_exact_trust_match(self, proxy: str) -> None:
+ with (
+ patch.object(httpx.HTTPTransport, "handle_request", return_value=httpx.Response(200)) as send,
+ pinned_client("https://example.com/", {PUBLIC_IP}, proxy=proxy, trust_env=False) as client,
+ ):
+ with pytest.raises(SSRFBlockedError, match="proxy"):
+ client.get("https://example.com/")
+ send.assert_not_called()
+
+ @override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
+ def test_proxy_rejection_does_not_fall_back_to_direct_connection(self) -> None:
+ stream = httpcore.MockStream([b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n"])
+ with (
+ patch.dict(os.environ, {**_without_environment_proxies(), "HTTPS_PROXY": "http://egress.example:3128"}),
+ patch("httpcore.SyncBackend.connect_tcp", return_value=stream) as connect,
+ pinned_client("https://example.com/", {PUBLIC_IP}) as client,
+ ):
+ with pytest.raises(httpx.ProxyError, match="403"):
+ client.get("https://example.com/")
+ assert connect.call_count == 1
+ assert connect.call_args.kwargs["host"] == "egress.example"
+
+ @override_settings(SSRF_TRUSTED_PROXY_URLS=["http://egress.example:3128"])
+ @pytest.mark.parametrize("proxied", [False, True])
+ @pytest.mark.parametrize("certificate_rejected", [False, True])
+ def test_tls_keeps_original_hostname_and_certificate_verification(
+ self, proxied: bool, certificate_rejected: bool
+ ) -> None:
+ responses = [b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"]
+ if proxied:
+ responses.insert(0, b"HTTP/1.1 200 Connection Established\r\n\r\n")
+ stream = httpcore.MockStream(responses)
+
+ def start_tls(ssl_context: ssl.SSLContext, server_hostname: str, timeout: float) -> httpcore.NetworkStream:
+ assert ssl_context.verify_mode == ssl.CERT_REQUIRED
+ assert ssl_context.check_hostname
+ assert server_hostname == "example.com"
+ if certificate_rejected:
+ raise httpcore.ConnectError("CERTIFICATE_VERIFY_FAILED")
+ return stream
+
+ environment = {"HTTPS_PROXY": "http://egress.example:3128"} if proxied else {}
+ with (
+ patch.dict(os.environ, {**_without_environment_proxies(), **environment}),
+ patch("httpcore.SyncBackend.connect_tcp", return_value=stream) as connect,
+ patch.object(stream, "start_tls", side_effect=start_tls) as tls,
+ pinned_client("https://example.com/", {PUBLIC_IP}) as client,
+ ):
+ if certificate_rejected:
+ with pytest.raises(httpx.ConnectError, match="CERTIFICATE_VERIFY_FAILED"):
+ client.get("https://example.com/")
+ else:
+ assert client.get("https://example.com/").status_code == 200
+ assert connect.call_args.kwargs["host"] == ("egress.example" if proxied else str(PUBLIC_IP))
+ tls.assert_called_once()
+
+ @override_settings(FORCE_URL_VALIDATION=True)
+ def test_direct_connection_cannot_rebind_after_validation(self) -> None:
+ url = "http://example.com/"
+ connection = MagicMock()
+ connection.fileno.return_value = -1
+ connection.recv.return_value = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"
+
+ def resolve_connection(
+ host: str, port: int, *args: object, **kwargs: object
+ ) -> list[tuple[int, int, int, str, tuple[str, int]]]:
+ address = "127.0.0.1" if host == "example.com" else host
+ return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", (address, port))]
+
+ with (
+ patch("posthog.security.url_validation.resolve_host_ips", return_value={PUBLIC_IP}),
+ patch("socket.getaddrinfo", side_effect=resolve_connection),
+ patch("socket.socket", return_value=connection),
+ ):
+ verdict = validate_url_and_pin_ips(url)
+ assert verdict.allowed
+ with pinned_client(url, verdict.pinned_ips, trust_env=False) as client:
+ assert client.get(url).status_code == 200
+ connection.connect.assert_called_once_with((str(PUBLIC_IP), 80))
diff --git a/posthog/settings/access.py b/posthog/settings/access.py
index 0c938f233dac..77fcd0c755c5 100644
--- a/posthog/settings/access.py
+++ b/posthog/settings/access.py
@@ -181,3 +181,5 @@ BLOCKED_GEOIP_REGIONS = get_list(os.getenv("BLOCKED_GEOIP_REGIONS", ""))
# development can reach localhost services. Set this to run the production validation path in dev —
# e.g. to reproduce or test SSRF fixes — without flipping DEBUG globally.
FORCE_URL_VALIDATION: bool = get_from_env("POSTHOG_FORCE_URL_VALIDATION", False, type_cast=str_to_bool)
+
+SSRF_TRUSTED_PROXY_URLS: list[str] = get_list(get_from_env("SSRF_TRUSTED_PROXY_URLS", ""))
diff --git a/products/mcp_store/backend/proxy.py b/products/mcp_store/backend/proxy.py
index 6d2bf2f37eeb..14de2816a4e1 100644
--- a/products/mcp_store/backend/proxy.py
+++ b/products/mcp_store/backend/proxy.py
@@ -11,6 +11,8 @@ import httpx
import structlog
from posthog.api.streaming import sse_streaming_response
+from posthog.security.pinned_httpx import pinned_client
+from posthog.security.pinned_requests import SSRFBlockedError
from posthog.security.url_validation import is_url_allowed
from posthog.settings import SERVER_GATEWAY_INTERFACE
@@ -19,7 +21,7 @@ from ee.hogai.utils.asgi import SyncIterableToAsync
from .models import MCPAuditEvent, MCPGatewayServer, MCPServerInstallation, MCPServerInstallationTool
from .oauth import TokenRefreshError, TokenRefreshRejectedError, is_token_expiring, refresh_installation_token
from .policy import GatewayCaller, PolicyContext
-from .url_policy import check_mcp_url_policy, trust_environment_proxy
+from .url_policy import resolve_mcp_url_policy, trust_environment_proxy
logger = structlog.get_logger(__name__)
@@ -469,11 +471,11 @@ def proxy_mcp_request(
rides, so the audit trail answers whose connection an agent used. Both are
empty for member calls, where the actor already is the credential owner.
"""
- allowed, error = check_mcp_url_policy(installation.url, installation.team_id)
- if not allowed:
- logger.warning("SSRF: blocked proxy request", url=installation.url, reason=error)
+ verdict = resolve_mcp_url_policy(installation.url, installation.team_id)
+ if not verdict.allowed:
+ logger.warning("SSRF: blocked proxy request", url=installation.url, reason=verdict.reason)
return HttpResponse(
- json.dumps({"error": f"URL not allowed: {error}"}),
+ json.dumps({"error": f"URL not allowed: {verdict.reason}"}),
content_type="application/json",
status=400,
)
@@ -543,7 +545,9 @@ def proxy_mcp_request(
if mcp_session_id:
headers["Mcp-Session-Id"] = mcp_session_id
- client = httpx.Client(
+ client = pinned_client(
+ installation.url,
+ verdict.pinned_ips,
timeout=UPSTREAM_TIMEOUT,
trust_env=trust_environment_proxy(installation.url, installation.team_id),
)
@@ -556,6 +560,14 @@ def proxy_mcp_request(
headers=headers,
stream=True,
)
+ except (SSRFBlockedError, httpx.ProxyError):
+ client.close()
+ logger.warning("Upstream MCP connection blocked by URL or proxy policy")
+ return HttpResponse(
+ '{"error": "Upstream MCP connection blocked. Ask an administrator to check the outbound proxy configuration."}',
+ content_type="application/json",
+ status=502,
+ )
except httpx.ConnectError:
client.close()
logger.warning("Upstream MCP server unreachable", url=installation.url)
diff --git a/products/mcp_store/backend/test/test_api.py b/products/mcp_store/backend/test/test_api.py
index 62cd9149e5f3..18678f2f397a 100644
--- a/products/mcp_store/backend/test/test_api.py
+++ b/products/mcp_store/backend/test/test_api.py
@@ -22,6 +22,7 @@ from posthog.models import Organization, Team, User
from posthog.models.instance_setting import override_instance_config
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import OrganizationMembership
+from posthog.security.url_validation import PinnedUrlVerdict
from products.mcp_store.backend.agents import create_gateway_agent_token, sync_built_in_agents
from products.mcp_store.backend.models import (
@@ -45,7 +46,8 @@ from products.mcp_store.backend.presentation.gateway_views import (
)
from products.mcp_store.backend.presentation.views import _is_valid_posthog_code_callback_url
-ALLOW_URL = patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
+ALLOWED_VERDICT = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())
+ALLOW_URL = patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
POLICY_REQUEST_SERIALIZER_CASES = [
("policy_upsert", GatewayPoliciesUpsertSerializer, {}),
@@ -2156,8 +2158,8 @@ class TestMCPServiceAccountAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
mock_proxy.assert_not_called()
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_agent_grant_enforces_agent_scope_policy(self, mock_http_client, _mock_is_url_allowed) -> None:
account = self._active_scout_account()
server = MCPGatewayServer.objects.for_team(self.team.id).create(
@@ -2779,7 +2781,10 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Private IP"))
+ @patch(
+ "products.mcp_store.backend.url_policy.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=False, reason="Private IP", pinned_ips=set()),
+ )
def test_install_custom_ssrf_blocked(self, _mock):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -2788,7 +2793,10 @@ class TestInstallCustomAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Local/metadata host"))
+ @patch(
+ "products.mcp_store.backend.url_policy.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=False, reason="Local/metadata host", pinned_ips=set()),
+ )
def test_install_custom_oauth_ssrf_blocked(self, _mock):
response = self.client.post(
f"/api/environments/{self.team.id}/mcp_server_installations/install_custom/",
@@ -4642,8 +4650,8 @@ class TestMCPInstallationScopeAccess(ClickhouseTestMixin, APIBaseTest, QueryMatc
other = User.objects.create_and_join(self.organization, "[email protected]", "password")
shared = self._create_installation(user=other, scope="shared", sensitive_configuration={"api_key": "k"})
- with mock_patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None)):
- with mock_patch("products.mcp_store.backend.proxy.httpx.Client") as mock_client_cls:
+ with mock_patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT):
+ with mock_patch("products.mcp_store.backend.proxy.pinned_client") as mock_client_cls:
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.headers = {"content-type": "application/json"}
diff --git a/products/mcp_store/backend/test/test_proxy.py b/products/mcp_store/backend/test/test_proxy.py
index f50122e3ad32..ebe2befc97f7 100644
--- a/products/mcp_store/backend/test/test_proxy.py
+++ b/products/mcp_store/backend/test/test_proxy.py
@@ -1,5 +1,7 @@
+import os
import time
import uuid
+import ipaddress
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, QueryMatchingTest
from unittest.mock import MagicMock, patch
@@ -14,6 +16,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.models import Organization, Team, User
+from posthog.security.url_validation import PinnedUrlVerdict
from products.mcp_store.backend.models import (
MCPAuditEvent,
@@ -25,17 +28,18 @@ from products.mcp_store.backend.models import (
from products.mcp_store.backend.oauth import TokenRefreshRejectedError
from products.mcp_store.backend.proxy import _build_sse_response
+ALLOWED_VERDICT = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())
+
class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
def setUp(self):
super().setUp()
- # Policy checks now flow through url_policy (check_mcp_url_policy);
+ # Policy checks flow through url_policy (resolve_mcp_url_policy);
# proxy.is_url_allowed still guards same-origin redirect targets.
- for target in (
- "products.mcp_store.backend.url_policy.is_url_allowed",
- "products.mcp_store.backend.proxy.is_url_allowed",
+ for patcher in (
+ patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT),
+ patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None)),
):
- patcher = patch(target, return_value=(True, None))
patcher.start()
self.addCleanup(patcher.stop)
@@ -88,7 +92,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
mock_client_cls.return_value = mock_client
return mock_client
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_forwards_json_rpc_with_api_key(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -109,7 +113,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
_, kwargs = mock_client.build_request.call_args
assert kwargs["headers"]["Authorization"] == "Bearer sk-test-key"
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_forwards_json_rpc_with_oauth_token(self, mock_client_cls):
installation = self._create_oauth_installation()
mock_response = MagicMock()
@@ -128,7 +132,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
_, kwargs = mock_client.build_request.call_args
assert kwargs["headers"]["Authorization"] == "Bearer oauth-token-123"
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_streams_sse_response_in_chunks(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -153,7 +157,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert content == b"event: message\ndata: {}\n\n"
mock_response.iter_bytes.assert_called_once_with(4096)
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_passes_mcp_session_id_both_ways(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -179,7 +183,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
_, kwargs = mock_client.build_request.call_args
assert kwargs["headers"]["Mcp-Session-Id"] == "client-session-xyz"
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_forwards_posthog_namespace_headers(self, mock_client_cls):
# Required for PostHog MCP installs through the Store: without
# `x-posthog-mcp-consumer` reaching the upstream, single-exec mode
@@ -223,7 +227,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert "x-not-posthog-namespace" not in forwarded
@patch("products.mcp_store.backend.oauth.refresh_oauth_token")
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_refreshes_expired_oauth_token(self, mock_client_cls, mock_refresh):
installation = self._create_oauth_installation(
sensitive_configuration={
@@ -337,7 +341,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json()["error"] == "Installation needs re-authentication"
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_sends_no_auth_header_for_none_auth_type(self, mock_client_cls):
installation = self._create_installation(auth_type="none")
mock_response = MagicMock()
@@ -362,7 +366,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
("timeout", httpx.TimeoutException("Timed out"), 502, "Upstream MCP server timed out"),
]
)
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_upstream_errors(self, _name, side_effect, expected_status, expected_error, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -394,7 +398,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == 400
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_passes_through_upstream_error_status(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -413,7 +417,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == 404
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_follows_same_origin_mcp_redirect(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -447,7 +451,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert mock_client.build_request.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer sk-test-key"
redirect_response.close.assert_called_once()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_does_not_follow_cross_origin_redirect_with_credentials(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -473,7 +477,7 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
mock_client.send.assert_called_once()
assert mock_client.build_request.call_args_list[0].kwargs["headers"]["Authorization"] == "Bearer sk-test-key"
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_does_not_follow_malformed_redirect_with_credentials(self, mock_client_cls):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -536,9 +540,11 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
assert response.json()["error"] == "No credentials configured"
- @patch("products.mcp_store.backend.url_policy.is_url_allowed")
- def test_proxy_rejects_ssrf_private_ips(self, mock_is_url_allowed):
- mock_is_url_allowed.return_value = (False, "Private IP address not allowed")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips")
+ def test_proxy_rejects_ssrf_private_ips(self, mock_validate):
+ mock_validate.return_value = PinnedUrlVerdict(
+ allowed=False, reason="Private IP address not allowed", pinned_ips=set()
+ )
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
)
@@ -552,6 +558,50 @@ class TestMCPProxyEndpoint(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
assert response.status_code == 400
assert "Private IP" in response.json()["error"]
+ @parameterized.expand([("direct",), ("trusted",), ("untrusted",), ("denied",)])
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips")
+ def test_proxy_connects_to_the_validated_address(self, route: str, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = PinnedUrlVerdict(
+ allowed=True, reason=None, pinned_ips={ipaddress.ip_address("93.184.216.34")}
+ )
+ installation = self._create_installation(sensitive_configuration={"api_key": "sk-test-key"})
+ seen: list[httpx.Request] = []
+
+ def handle_request(_transport: httpx.HTTPTransport, request: httpx.Request) -> httpx.Response:
+ if route == "denied":
+ raise httpx.ProxyError("403 Forbidden")
+ seen.append(
+ httpx.Request(request.method, request.url, headers=request.headers, extensions=request.extensions)
+ )
+ return httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})
+
+ no_proxies = {key: "" for key in os.environ if key.lower().endswith("_proxy")}
+ environment = {} if route == "direct" else {"HTTPS_PROXY": "http://egress.example:3128"}
+ trusted_proxies = ["http://egress.example:3128"] if route in {"trusted", "denied"} else []
+ with (
+ override_settings(SSRF_TRUSTED_PROXY_URLS=trusted_proxies),
+ patch.dict(os.environ, {**no_proxies, **environment}),
+ patch.object(httpx.HTTPTransport, "handle_request", handle_request),
+ ):
+ response = self.client.post(
+ self._proxy_url(installation.id),
+ data={"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
+ format="json",
+ )
+
+ if route in {"untrusted", "denied"}:
+ assert response.status_code == 502
+ assert "outbound proxy configuration" in response.json()["error"]
+ assert seen == []
+ return
+
+ assert response.status_code == 200
+ [request] = seen
+ assert request.url.host == ("93.184.216.34" if route == "direct" else "mcp.example.com")
+ assert request.headers["Host"] == "mcp.example.com"
+ assert request.extensions.get("sni_hostname") == ("mcp.example.com" if route == "direct" else None)
+ assert request.headers["Authorization"] == "Bearer sk-test-key"
+
def test_proxy_rejects_body_over_1mb(self):
installation = self._create_installation(
sensitive_configuration={"api_key": "sk-test-key"},
@@ -573,13 +623,12 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
def setUp(self):
super().setUp()
- # Policy checks now flow through url_policy (check_mcp_url_policy);
+ # Policy checks flow through url_policy (resolve_mcp_url_policy);
# proxy.is_url_allowed still guards same-origin redirect targets.
- for target in (
- "products.mcp_store.backend.url_policy.is_url_allowed",
- "products.mcp_store.backend.proxy.is_url_allowed",
+ for patcher in (
+ patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT),
+ patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None)),
):
- patcher = patch(target, return_value=(True, None))
patcher.start()
self.addCleanup(patcher.stop)
@@ -605,7 +654,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
removed_at=removed_at,
)
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_approved_tool_call_reaches_upstream(self, mock_client_cls):
installation = self._installation()
self._tool(installation, "search", "approved")
@@ -628,7 +677,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert response.status_code == 200
mock_client.send.assert_called_once()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_needs_approval_tool_call_blocked_with_jsonrpc_error(self, mock_client_cls):
installation = self._installation()
self._tool(installation, "search", "needs_approval")
@@ -646,7 +695,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert "approval" in body["error"]["message"].lower()
mock_client_cls.assert_not_called()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_do_not_use_tool_call_blocked_with_distinct_error_code(self, mock_client_cls):
installation = self._installation()
self._tool(installation, "delete", "do_not_use")
@@ -661,7 +710,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert body["error"]["code"] == -32002
mock_client_cls.assert_not_called()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_unknown_tool_returns_method_not_found(self, mock_client_cls):
installation = self._installation()
@@ -675,7 +724,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert body["error"]["code"] == -32601
mock_client_cls.assert_not_called()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_removed_tool_is_not_callable(self, mock_client_cls):
installation = self._installation()
self._tool(installation, "legacy", "approved", removed_at=timezone.now())
@@ -690,7 +739,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert body["error"]["code"] == -32601
mock_client_cls.assert_not_called()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_non_tools_call_methods_pass_through(self, mock_client_cls):
installation = self._installation()
# No tools registered — but tools/list must still reach upstream.
@@ -712,7 +761,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert response.status_code == 200
mock_client.send.assert_called_once()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_batch_all_approved_passes_through(self, mock_client_cls):
installation = self._installation()
self._tool(installation, "a", "approved")
@@ -738,7 +787,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert response.status_code == 200
mock_client.send.assert_called_once()
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_batch_all_blocked_returns_jsonrpc_error_list(self, mock_client_cls):
installation = self._installation()
self._tool(installation, "a", "needs_approval")
@@ -805,7 +854,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
assert len(batch_call_queries.captured_queries) == len(single_call_queries.captured_queries)
assert MCPAuditEvent.objects.for_team(self.team.id).count() == 6
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_mixed_batch_rejects_whole_request_with_batch_code(self, mock_client_cls):
server = MCPGatewayServer.objects.for_team(self.team.id).create(
team=self.team,
@@ -860,7 +909,7 @@ class TestMCPProxyToolApproval(ClickhouseTestMixin, APIBaseTest, QueryMatchingTe
installation.refresh_from_db()
assert installation.last_used_at is None
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_mixed_batch_with_tools_list_sibling_uses_batch_code(self, mock_client_cls):
"""A passthrough sibling like tools/list must not get TOOL_NEEDS_APPROVAL_CODE."""
installation = self._installation()
@@ -891,13 +940,12 @@ class TestMCPProxyAccessControl(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
def setUp(self):
super().setUp()
- # Policy checks now flow through url_policy (check_mcp_url_policy);
+ # Policy checks flow through url_policy (resolve_mcp_url_policy);
# proxy.is_url_allowed still guards same-origin redirect targets.
- for target in (
- "products.mcp_store.backend.url_policy.is_url_allowed",
- "products.mcp_store.backend.proxy.is_url_allowed",
+ for patcher in (
+ patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT),
+ patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None)),
):
- patcher = patch(target, return_value=(True, None))
patcher.start()
self.addCleanup(patcher.stop)
@@ -971,7 +1019,7 @@ class TestMCPProxyAccessControl(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
assert response.status_code == status.HTTP_404_NOT_FOUND
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_does_not_leak_other_users_credentials(self, mock_client_cls):
"""Even if the installation UUID is known, another user's secret must not be forwarded."""
other_user = User.objects.create_and_join(self.organization, "[email protected]", "password")
@@ -998,7 +1046,7 @@ class TestMCPProxyAccessControl(ClickhouseTestMixin, APIBaseTest, QueryMatchingT
mock_client_cls.return_value = mock_client
return mock_client
- @patch("products.mcp_store.backend.proxy.httpx.Client")
+ @patch("products.mcp_store.backend.proxy.pinned_client")
def test_proxy_scopes_to_authenticated_user_not_installation_owner(self, mock_client_cls):
"""The requesting user's identity gates access, not the installation's user field."""
installation = self._create_installation(self.team, self.user)
diff --git a/products/mcp_store/backend/test/test_tools.py b/products/mcp_store/backend/test/test_tools.py
index 26046979f258..e48451fe22cf 100644
--- a/products/mcp_store/backend/test/test_tools.py
+++ b/products/mcp_store/backend/test/test_tools.py
@@ -1,15 +1,20 @@
+import os
import json
import uuid
+import ipaddress
import pytest
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
+from django.test import override_settings
from django.utils import timezone
import httpx
from parameterized import parameterized
+from posthog.security.url_validation import PinnedUrlVerdict
+
from products.mcp_store.backend.models import MCPServerInstallation, MCPServerInstallationTool
from products.mcp_store.backend.tools import (
CALL_TIMEOUT,
@@ -21,6 +26,8 @@ from products.mcp_store.backend.tools import (
sync_installation_tools,
)
+ALLOWED_VERDICT = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())
+
def _build_response(
*, status: int = 200, body: str = "", content_type: str = "application/json", session_id: str | None = None
@@ -74,8 +81,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
defaults.update(overrides)
return MCPServerInstallation.objects.create(**defaults)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_uses_handshake_timeout(self, mock_client_cls, _allow):
# The handshake must not inherit the proxy's 180s budget — that would let a
# slow upstream hold a Django worker for minutes.
@@ -88,8 +95,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert mock_client_cls.call_args.kwargs["timeout"] == HANDSHAKE_TIMEOUT
assert HANDSHAKE_TIMEOUT <= 30 # guard against accidental regression
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_parses_result(self, mock_client_cls, _allow):
installation = self._installation()
tools_body = json.dumps(
@@ -125,8 +132,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert client.delete.call_args.kwargs["headers"]["Mcp-Session-Id"] == "sess-1"
@patch("products.mcp_store.backend.proxy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_follows_same_origin_initialize_redirect(
self, mock_client_cls, _allow_tools, _allow_proxy
):
@@ -155,8 +162,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert client.post.call_args_list[3].args[0] == "https://mcp.example.com/mcp/"
assert client.delete.call_args.args[0] == "https://mcp.example.com/mcp/"
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_parses_sse_tools_list(self, mock_client_cls, _allow):
# Some MCP servers reply to tools/list over SSE even though initialize
# came back as JSON. Make sure we still extract the tool array.
@@ -170,8 +177,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
tools = fetch_upstream_tools(installation)
assert [t["name"] for t in tools] == ["alpha"]
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_works_without_session_id(self, mock_client_cls, _allow):
# Servers that don't require a session simply omit Mcp-Session-Id on the
# initialize response. We should still complete the handshake and not
@@ -193,14 +200,84 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
assert [t["name"] for t in tools] == ["alpha"]
assert not client.delete.called
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Private IP"))
+ @parameterized.expand(
+ [
+ ("direct", "fetch"),
+ ("trusted", "fetch"),
+ ("untrusted", "fetch"),
+ ("untrusted", "call"),
+ ("denied", "fetch"),
+ ("denied", "call"),
+ ]
+ )
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips")
+ def test_fetch_upstream_tools_connects_to_the_validated_address(
+ self, route: str, operation: str, mock_validate: MagicMock
+ ) -> None:
+ mock_validate.return_value = PinnedUrlVerdict(
+ allowed=True, reason=None, pinned_ips={ipaddress.ip_address("93.184.216.34")}
+ )
+ installation = self._installation(url="https://mcp.example.com/mcp")
+ seen: list[httpx.Request] = []
+
+ def handle_request(_transport: httpx.HTTPTransport, request: httpx.Request) -> httpx.Response:
+ if route == "denied":
+ raise httpx.ProxyError("403 Forbidden")
+ seen.append(
+ httpx.Request(request.method, request.url, headers=request.headers, extensions=request.extensions)
+ )
+ if request.method == "DELETE":
+ return httpx.Response(200)
+ request_id = json.loads(request.content).get("id")
+ if request_id == 1:
+ return httpx.Response(
+ 200,
+ json={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05"}},
+ headers={"mcp-session-id": "sess-1", "Set-Cookie": "mcp_session=fake-session; Path=/; Secure"},
+ )
+ if request_id == 2:
+ return httpx.Response(200, json={"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "alpha"}]}})
+ return httpx.Response(202)
+
+ no_proxies = {key: "" for key in os.environ if key.lower().endswith("_proxy")}
+ environment = {} if route == "direct" else {"HTTPS_PROXY": "http://egress.example:3128"}
+ trusted_proxies = ["http://egress.example:3128"] if route in {"trusted", "denied"} else []
+ with (
+ override_settings(SSRF_TRUSTED_PROXY_URLS=trusted_proxies),
+ patch.dict(os.environ, {**no_proxies, **environment}),
+ patch.object(httpx.HTTPTransport, "handle_request", handle_request),
+ ):
+ if route in {"untrusted", "denied"}:
+ error_type = ToolsFetchError if operation == "fetch" else ToolCallError
+ with pytest.raises(error_type, match="outbound proxy configuration"):
+ if operation == "fetch":
+ fetch_upstream_tools(installation)
+ else:
+ call_upstream_tool(installation, "alpha", {})
+ assert seen == []
+ return
+ tools = fetch_upstream_tools(installation)
+
+ assert [tool["name"] for tool in tools] == ["alpha"]
+ assert len(seen) == 4
+ assert {request.headers.get("Cookie") for request in seen[1:]} == {"mcp_session=fake-session"}
+ assert {request.url.host for request in seen} == {"93.184.216.34" if route == "direct" else "mcp.example.com"}
+ assert {request.headers["Host"] for request in seen} == {"mcp.example.com"}
+ assert {request.extensions.get("sni_hostname") for request in seen} == {
+ "mcp.example.com" if route == "direct" else None
+ }
+
+ @patch(
+ "products.mcp_store.backend.url_policy.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=False, reason="Private IP", pinned_ips=set()),
+ )
def test_fetch_upstream_tools_raises_on_blocked_url(self, _allow):
installation = self._installation()
with pytest.raises(ToolsFetchError, match="URL not allowed"):
fetch_upstream_tools(installation)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_raises_on_connect_error(self, mock_client_cls, _allow):
installation = self._installation()
client = MagicMock()
@@ -210,8 +287,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ToolsFetchError, match="unreachable"):
fetch_upstream_tools(installation)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_raises_on_initialize_error(self, mock_client_cls, _allow):
installation = self._installation()
client = MagicMock()
@@ -221,8 +298,8 @@ class TestFetchUpstreamTools(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ToolsFetchError, match="initialize returned status 401"):
fetch_upstream_tools(installation)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_fetch_upstream_tools_raises_when_result_missing(self, mock_client_cls, _allow):
installation = self._installation()
tools_body = json.dumps({"jsonrpc": "2.0", "id": 2, "result": {}})
@@ -243,8 +320,8 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
sensitive_configuration={"api_key": "sk-test"},
)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_call_carries_the_session_from_initialize(self, mock_client_cls, _allow):
# Most servers reject tools/call without the Mcp-Session-Id they handed out on
# initialize, so losing the session header would break every real call while
@@ -282,8 +359,8 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
),
]
)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_call_parses_both_response_framings(self, _name, body, content_type, mock_client_cls, _allow):
installation = self._installation()
_install_handshake_mock(
@@ -292,8 +369,8 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
assert call_upstream_tool(installation, "create_issue", {})["content"] == [{"type": "text", "text": "ok"}]
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_call_returns_tool_reported_errors_instead_of_raising(self, mock_client_cls, _allow):
# `isError` is the tool telling the model it failed (bad arguments, not found).
# Raising here would hide the reason the agent needs in order to retry.
@@ -322,8 +399,8 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
("missing_result", json.dumps({"jsonrpc": "2.0", "id": 3}), "missing 'result'"),
]
)
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(True, None))
- @patch("products.mcp_store.backend.tools.httpx.Client")
+ @patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=ALLOWED_VERDICT)
+ @patch("products.mcp_store.backend.tools.pinned_client")
def test_call_raises_on_protocol_failures(self, _name, body, expected_message, mock_client_cls, _allow):
installation = self._installation()
_install_handshake_mock(mock_client_cls, tools_list_response=_build_response(body=body))
@@ -331,7 +408,10 @@ class TestCallUpstreamTool(ClickhouseTestMixin, APIBaseTest):
with pytest.raises(ToolCallError, match=expected_message):
call_upstream_tool(installation, "create_issue", {})
- @patch("products.mcp_store.backend.url_policy.is_url_allowed", return_value=(False, "Private IP"))
+ @patch(
+ "products.mcp_store.backend.url_policy.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=False, reason="Private IP", pinned_ips=set()),
+ )
def test_call_refuses_a_blocked_url(self, _allow):
installation = self._installation()
with pytest.raises(ToolCallError, match="URL not allowed"):
diff --git a/products/mcp_store/backend/test/test_url_policy.py b/products/mcp_store/backend/test/test_url_policy.py
index 5f32d0b4b52a..5479c20de9d8 100644
--- a/products/mcp_store/backend/test/test_url_policy.py
+++ b/products/mcp_store/backend/test/test_url_policy.py
@@ -1,9 +1,15 @@
+import ipaddress
+
+from unittest.mock import patch
+
from django.test import override_settings
+from posthog.security.url_validation import PinnedUrlVerdict
+
from products.mcp_store.backend.url_policy import (
- allow_internal_mcp_url,
check_mcp_url_policy,
is_internal_mcp_url,
+ resolve_mcp_url_policy,
trust_environment_proxy,
)
@@ -25,15 +31,18 @@ def test_internal_mcp_url_requires_an_exact_match() -> None:
@override_settings(
MCP_STORE_INTERNAL_ALLOWED_URLS_BY_TEAM={"42": ["http://grafana-mcp.monitoring.svc.cluster.local/mcp"]}
)
-def test_internal_mcp_url_can_override_a_failed_public_ssrf_check() -> None:
- configured = "http://grafana-mcp.monitoring.svc.cluster.local/mcp"
+def test_resolve_mcp_url_policy_pins_public_hosts_and_names_internal_ones() -> None:
+ public = PinnedUrlVerdict(allowed=True, reason=None, pinned_ips={ipaddress.ip_address("93.184.216.34")})
+ with patch("products.mcp_store.backend.url_policy.validate_url_and_pin_ips", return_value=public):
+ assert resolve_mcp_url_policy("https://mcp.example.com/mcp", 42) == public
- assert allow_internal_mcp_url(configured, 42, False, "Internal domain") == (True, None)
- assert allow_internal_mcp_url(configured, 43, False, "Internal domain") == (False, "Internal domain")
- assert allow_internal_mcp_url("http://other.svc.cluster.local/mcp", 42, False, "Internal domain") == (
- False,
- "Internal domain",
- )
+ # The real SSRF check rejects cluster-local hosts on the internal-domain
+ # pattern (no DNS involved), so the override path runs end to end.
+ configured = "http://grafana-mcp.monitoring.svc.cluster.local/mcp"
+ internal = resolve_mcp_url_policy(configured, 42)
+ assert internal == PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())
+ assert not resolve_mcp_url_policy(configured, 43).allowed
+ assert not resolve_mcp_url_policy("http://other.svc.cluster.local/mcp", 42).allowed
@override_settings(
diff --git a/products/mcp_store/backend/tools.py b/products/mcp_store/backend/tools.py
index 05d04fe0a057..201258a01a58 100644
--- a/products/mcp_store/backend/tools.py
+++ b/products/mcp_store/backend/tools.py
@@ -13,11 +13,14 @@ from django.utils import timezone
import httpx
import structlog
+from posthog.security.pinned_httpx import pinned_client
+from posthog.security.pinned_requests import SSRFBlockedError
+
from .models import MCPServerInstallation, MCPServerInstallationTool
from .oauth import TokenRefreshError, is_token_expiring, refresh_installation_token
from .policy import SYNC_DEFAULT_APPROVAL_STATE
from .proxy import build_upstream_auth_headers, validated_same_origin_redirect_url
-from .url_policy import check_mcp_url_policy, trust_environment_proxy
+from .url_policy import resolve_mcp_url_policy, trust_environment_proxy
logger = structlog.get_logger(__name__)
@@ -77,9 +80,9 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,
Shares the proxy's SSRF guard + timeout + auth-header builder so behavior stays
consistent between proxy traffic and sync traffic.
"""
- allowed, reason = check_mcp_url_policy(installation.url, installation.team_id)
- if not allowed:
- raise ToolsFetchError(f"URL not allowed: {reason}")
+ verdict = resolve_mcp_url_policy(installation.url, installation.team_id)
+ if not verdict.allowed:
+ raise ToolsFetchError(f"URL not allowed: {verdict.reason}")
_ensure_valid_token_for_fetch(installation)
@@ -91,7 +94,9 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,
}
try:
- with httpx.Client(
+ with pinned_client(
+ installation.url,
+ verdict.pinned_ips,
timeout=HANDSHAKE_TIMEOUT,
trust_env=trust_environment_proxy(installation.url, installation.team_id),
) as client:
@@ -108,6 +113,10 @@ def fetch_upstream_tools(installation: MCPServerInstallation) -> list[dict[str,
# here are purely janitorial and must not mask real errors above.
if session_id:
_mcp_terminate_session(client, upstream_url, session_headers)
+ except (SSRFBlockedError, httpx.ProxyError) as exc:
+ raise ToolsFetchError(
+ "Upstream MCP connection blocked. Ask an administrator to check the outbound proxy configuration."
+ ) from exc
except httpx.ConnectError as exc:
raise ToolsFetchError("Upstream MCP server unreachable") from exc
except httpx.TimeoutException as exc:
@@ -129,9 +138,9 @@ def call_upstream_tool(
the gateway's policy engine first (see ``enforce_tool_approval``), so this stays
a transport concern.
"""
- allowed, reason = check_mcp_url_policy(installation.url, installation.team_id)
- if not allowed:
- raise ToolCallError(f"URL not allowed: {reason}")
+ verdict = resolve_mcp_url_policy(installation.url, installation.team_id)
+ if not verdict.allowed:
+ raise ToolCallError(f"URL not allowed: {verdict.reason}")
_ensure_valid_token_for_fetch(installation)
@@ -143,7 +152,9 @@ def call_upstream_tool(
}
try:
- with httpx.Client(
+ with pinned_client(
+ installation.url,
+ verdict.pinned_ips,
timeout=CALL_TIMEOUT,
trust_env=trust_environment_proxy(installation.url, installation.team_id),
) as client:
@@ -158,6 +169,10 @@ def call_upstream_tool(
finally:
if session_id:
_mcp_terminate_session(client, upstream_url, session_headers)
+ except (SSRFBlockedError, httpx.ProxyError) as exc:
+ raise ToolCallError(
+ "Upstream MCP connection blocked. Ask an administrator to check the outbound proxy configuration."
+ ) from exc
except httpx.ConnectError as exc:
raise ToolCallError("Upstream MCP server unreachable") from exc
except httpx.TimeoutException as exc:
diff --git a/products/mcp_store/backend/url_policy.py b/products/mcp_store/backend/url_policy.py
index 9d046fc3efbe..a2a7c3e5215c 100644
--- a/products/mcp_store/backend/url_policy.py
+++ b/products/mcp_store/backend/url_policy.py
@@ -9,7 +9,7 @@ sibling paths or grant another team access.
from django.conf import settings
-from posthog.security.url_validation import is_url_allowed
+from posthog.security.url_validation import PinnedUrlVerdict, validate_url_and_pin_ips
def is_internal_mcp_url(url: str, team_id: int | None) -> bool:
@@ -19,24 +19,37 @@ def is_internal_mcp_url(url: str, team_id: int | None) -> bool:
return isinstance(urls, list) and url in urls
-def check_mcp_url_policy(url: str, team_id: int | None) -> tuple[bool, str | None]:
+def resolve_mcp_url_policy(url: str, team_id: int | None) -> PinnedUrlVerdict:
"""The single entry point for MCP URL policy: shared SSRF validation,
overridden only by an exact team-scoped internal-allowlist match.
- Call sites must use this rather than composing ``is_url_allowed`` with
- ``allow_internal_mcp_url`` themselves — a caller that forgets one half (or
- reorders the splatted positional results) silently drops the policy.
+ Call sites must use this rather than composing the SSRF validator with
+ ``is_internal_mcp_url`` themselves, because a caller that forgets one half
+ silently drops the policy.
+
+ A caller that opens a connection to the URL must connect to ``pinned_ips``
+ (see ``posthog.security.pinned_httpx``), or use an explicitly trusted proxy
+ that validates the address it connects to. Other proxies must fail closed.
+ An internal endpoint is reached by name inside the cluster, so its verdict
+ pins nothing.
"""
- return allow_internal_mcp_url(url, team_id, *is_url_allowed(url))
+ verdict = validate_url_and_pin_ips(url)
+ if verdict.allowed or not is_internal_mcp_url(url, team_id):
+ return verdict
+ return PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set())
-def allow_internal_mcp_url(url: str, team_id: int | None, allowed: bool, reason: str | None) -> tuple[bool, str | None]:
- if not allowed and is_internal_mcp_url(url, team_id):
- return True, None
- return allowed, reason
+def check_mcp_url_policy(url: str, team_id: int | None) -> tuple[bool, str | None]:
+ """``resolve_mcp_url_policy`` for callers that only need the decision."""
+ verdict = resolve_mcp_url_policy(url, team_id)
+ return verdict.allowed, verdict.reason
def trust_environment_proxy(url: str, team_id: int | None) -> bool:
- """Internal Services must be reached directly instead of via HTTP_PROXY."""
+ """Allow proxy routing for public URLs, not proxy trust.
+
+ The pinned client separately enforces ``SSRF_TRUSTED_PROXY_URLS``.
+ Internal services must be reached directly instead of via HTTP_PROXY.
+ """
return not is_internal_mcp_url(url, team_id)