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(tasks): put the resolved mcp host on the sandbox egress allowlist (#109886)

Alessandro Pogliaghi5f6045d70177
diff --git a/products/tasks/backend/logic/services/agentsh.py b/products/tasks/backend/logic/services/agentsh.py
index 295e3a4afbc0..0075ad24b0be 100644
--- a/products/tasks/backend/logic/services/agentsh.py
+++ b/products/tasks/backend/logic/services/agentsh.py
@@ -11,6 +11,7 @@ from django.core.validators import DomainNameValidator
import yaml
from products.tasks.backend.constants import SANDBOX_AGENT_LAUNCH_UNSET_ENV_VARS
+from products.tasks.backend.logic.services.mcp_url import resolve_mcp_url
logger = logging.getLogger(__name__)
@@ -87,7 +88,6 @@ _SANDBOX_URL_SETTINGS = (
"SANDBOX_API_URL",
"SANDBOX_LLM_GATEWAY_URL",
"SANDBOX_AI_GATEWAY_URL",
- "SANDBOX_MCP_URL",
)
# Sandbox-host URLs that stay out of the enforced rule: telemetry export is not
@@ -134,6 +134,19 @@ def _is_loopback(hostname: str) -> bool:
return False
+def _sandbox_url_values(*, include_debug_only: bool = False) -> list[tuple[str, str | None]]:
+ setting_names = _SANDBOX_URL_SETTINGS + (_DEBUG_ONLY_URL_SETTINGS if include_debug_only else ())
+ values = [(setting_name, getattr(settings, setting_name, None)) for setting_name in setting_names]
+ sandbox_mcp_url = getattr(settings, "SANDBOX_MCP_URL", None)
+ mcp_server_url = getattr(settings, "MCP_SERVER_URL", None)
+ try:
+ mcp_url = resolve_mcp_url(sandbox_mcp_url=sandbox_mcp_url, mcp_server_url=mcp_server_url)
+ except ValueError:
+ mcp_url = sandbox_mcp_url or mcp_server_url
+ values.append(("SANDBOX_MCP_URL" if sandbox_mcp_url else "MCP_SERVER_URL", mcp_url))
+ return values
+
+
def sandbox_url_setting_domains() -> list[str]:
"""Hostnames parsed from the `SANDBOX_*_URL` settings that are usable on
the enforced allow rule. Loopback hosts are skipped silently (agentsh
@@ -143,8 +156,7 @@ def sandbox_url_setting_domains() -> list[str]:
this function exists to prevent.
"""
domains: list[str] = []
- for setting_name in _SANDBOX_URL_SETTINGS:
- value = getattr(settings, setting_name, None)
+ for setting_name, value in _sandbox_url_values():
if not value:
continue
hostname = _hostname_from_url(value)
@@ -190,8 +202,8 @@ def _get_debug_only_domains() -> list[str]:
the dev ports those services listen on.
"""
domains: list[str] = ["localhost", "host.docker.internal"]
- for setting_name in _SANDBOX_URL_SETTINGS + _DEBUG_ONLY_URL_SETTINGS:
- hostname = _hostname_from_url(getattr(settings, setting_name, None))
+ for _setting_name, value in _sandbox_url_values(include_debug_only=True):
+ hostname = _hostname_from_url(value)
if hostname and hostname not in domains:
domains.append(hostname)
return domains
@@ -206,8 +218,8 @@ def _get_debug_only_ports() -> list[int]:
syscall layer even when their hostname is allowed.
"""
ports: list[int] = [8000, 8010]
- for setting_name in _SANDBOX_URL_SETTINGS + _DEBUG_ONLY_URL_SETTINGS:
- port = _port_from_url(getattr(settings, setting_name, None))
+ for _setting_name, value in _sandbox_url_values(include_debug_only=True):
+ port = _port_from_url(value)
if port is not None and port not in ports:
ports.append(port)
return ports
diff --git a/products/tasks/backend/tests/test_agentsh.py b/products/tasks/backend/tests/test_agentsh.py
index f8dda51dd2d6..34b7d414a4c0 100644
--- a/products/tasks/backend/tests/test_agentsh.py
+++ b/products/tasks/backend/tests/test_agentsh.py
@@ -226,22 +226,47 @@ class TestGeneratePolicyYaml(TestCase):
allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
self.assertIn("ai-gateway.dev.posthog.dev", allow_rule["domains"])
- # One case per member of _SANDBOX_URL_SETTINGS: the enforced-rule path is
- # shared, so each entry needs its own tripping input or its deletion
- # merges green.
+ # One case per sandbox URL source: the enforced-rule path is shared, so
+ # each entry needs its own tripping input or its deletion merges green.
@parameterized.expand(
[
- ("SANDBOX_API_URL", "api.sandbox.example.dev"),
- ("SANDBOX_LLM_GATEWAY_URL", "llm-gw.sandbox.example.dev"),
- ("SANDBOX_AI_GATEWAY_URL", "ai-gw.sandbox.example.dev"),
- ("SANDBOX_MCP_URL", "mcp.sandbox.example.dev"),
+ ("api", {"SANDBOX_API_URL": "https://api.sandbox.example.dev"}, "api.sandbox.example.dev", None),
+ (
+ "llm_gateway",
+ {"SANDBOX_LLM_GATEWAY_URL": "https://llm-gw.sandbox.example.dev"},
+ "llm-gw.sandbox.example.dev",
+ None,
+ ),
+ (
+ "ai_gateway",
+ {"SANDBOX_AI_GATEWAY_URL": "https://ai-gw.sandbox.example.dev"},
+ "ai-gw.sandbox.example.dev",
+ None,
+ ),
+ (
+ "mcp_server_url_fallback",
+ {"SANDBOX_MCP_URL": None, "MCP_SERVER_URL": "https://mcp.us.posthog.com/mcp"},
+ "mcp.us.posthog.com",
+ None,
+ ),
+ (
+ "sandbox_mcp_url_wins",
+ {
+ "SANDBOX_MCP_URL": "https://mcp.sandbox.example.dev/mcp",
+ "MCP_SERVER_URL": "https://mcp.us.posthog.com/mcp",
+ },
+ "mcp.sandbox.example.dev",
+ "mcp.us.posthog.com",
+ ),
]
)
- def test_each_sandbox_url_setting_reaches_enforced_rule(self, setting_name, host):
- with override_settings(DEBUG=False, **{setting_name: f"https://{host}"}):
+ def test_each_sandbox_url_setting_reaches_enforced_rule(self, _name, overrides, host, absent_host):
+ with override_settings(DEBUG=False, **overrides):
policy = yaml.safe_load(generate_policy_yaml([]))
allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
self.assertIn(host, allow_rule["domains"])
+ if absent_host:
+ self.assertNotIn(absent_host, allow_rule["domains"])
@override_settings(DEBUG=False, SANDBOX_LLM_GATEWAY_URL="http://localhost:3308")
def test_loopback_sandbox_hosts_stay_off_prod_rule(self):
@@ -275,16 +300,32 @@ class TestGeneratePolicyYaml(TestCase):
allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
self.assertNotIn("10.0.5.3", allow_rule["domains"])
- @override_settings(DEBUG=False, SANDBOX_AI_GATEWAY_URL="ai-gateway.dev.posthog.dev")
- def test_schemeless_setting_warns_and_admits_nothing(self):
+ @parameterized.expand(
+ [
+ (
+ "schemeless",
+ {"SANDBOX_AI_GATEWAY_URL": "ai-gateway.dev.posthog.dev"},
+ "SANDBOX_AI_GATEWAY_URL",
+ "ai-gateway.dev.posthog.dev",
+ ),
+ (
+ "unparseable_mcp_server_url",
+ {"SANDBOX_MCP_URL": None, "MCP_SERVER_URL": "https://[broken/mcp"},
+ "MCP_SERVER_URL",
+ "broken",
+ ),
+ ]
+ )
+ def test_schemeless_setting_warns_and_admits_nothing(self, _name, overrides, setting_name, host_fragment):
# A scheme-less value passes the injection sites' truthiness gate but
# parses to no hostname, so the URL reaches the sandbox while its host
# is never admitted; the warning is the only backend-side signal.
- with self.assertLogs("products.tasks.backend.logic.services.agentsh", level="WARNING") as logs:
- policy = yaml.safe_load(generate_policy_yaml([]))
- self.assertTrue(any("SANDBOX_AI_GATEWAY_URL" in line for line in logs.output))
+ with override_settings(DEBUG=False, **overrides):
+ with self.assertLogs("products.tasks.backend.logic.services.agentsh", level="WARNING") as logs:
+ policy = yaml.safe_load(generate_policy_yaml([]))
+ self.assertTrue(any(setting_name in line for line in logs.output))
allow_rule = next(rule for rule in policy["network_rules"] if rule["name"] == "allow-domains")
- self.assertNotIn("ai-gateway.dev.posthog.dev", allow_rule["domains"])
+ self.assertFalse(any(host_fragment in domain for domain in allow_rule["domains"]))
@override_settings(DEBUG=False, SANDBOX_AI_GATEWAY_URL="https://ai-gw.example.dev:8443")
def test_non_cloud_port_outside_debug_warns_but_keeps_host(self):