: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): unblock run commands to hogland sandboxes from the API (#107389)
Tom Owers0a05c966f4a8
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 172825a2e91d..7c446f63eb3a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -5297,6 +5297,21 @@ def resolve_task_run_preview_redirect()+def is_hogland_sandbox_url(sandbox_url: str | None) -> bool:+ """Whether ``sandbox_url`` is the configured hogland control-plane origin.++ Thin facade wrapper: presentation may not import ``logic`` directly (see+ products/architecture.md § Presentation Layer), so both the sandbox-URL allowlist gate+ and the request-transport decision in the command relay view go through this one edge+ instead of reaching into ``logic.services.agent_command`` themselves.+ """+ from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import path+ is_hogland_sandbox_url as _is_hogland_sandbox_url,+ )++ return _is_hogland_sandbox_url(sandbox_url)++# Relay control verbs whose outcome PostHog AI funnels track. Captured here (gated on# origin_product) so the generic relay stays product-agnostic while the conversation layer stops# firing them as the renderer drives permission/cancel through `runs/{run}/command/`.diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 3dd11f86089d..fda7d73878b9 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -58,6 +58,7 @@ from posthog.permissions import (from posthog.rate_limit import TaskRunChartRenderThrottlefrom posthog.renderers import ServerSentEventRendererfrom posthog.schema_migrations.upgrade import upgrade+from posthog.security.outbound_proxy import internal_requests_sessionfrom posthog.temporal.oauth import SANDBOX_OAUTH_APP_CLIENT_IDS, TASK_AGENT_OAUTH_APP_CLIENT_IDSfrom posthog.utils import absolute_uri@@ -3333,7 +3334,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)if not self._is_valid_sandbox_url(connection.sandbox_url):- logger.warning(f"Blocked request to disallowed sandbox URL for task run {pk}")+ # The URL is in the log line on purpose: it is what the allowlist judged, and+ # without it a block cannot be diagnosed from logs. It carries no credential —+ # sandbox auth travels separately, attached per request.+ logger.warning(f"Blocked request to disallowed sandbox URL for task run {pk}: {connection.sandbox_url}")return Response(TaskRunErrorResponseSerializer({"error": "Invalid sandbox URL"}).data,status=status.HTTP_400_BAD_REQUEST,@@ -3438,7 +3442,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):- http://127.0.0.1:{port} (Docker sandboxes)- https://*.modal.run (Modal sandboxes)- https://*.modal.host (Modal connect token sandboxes)- - the exact host of settings.HOGLAND_API_URL (hogland box proxy)+ - the exact https origin of settings.HOGLAND_API_URL (hogland box proxy)"""from urllib.parse import urlparse@@ -3457,11 +3461,12 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):):return True- hogland_host = urlparse(settings.HOGLAND_API_URL).hostname if settings.HOGLAND_API_URL else None- if parsed.scheme == "https" and hogland_host and parsed.hostname == hogland_host:- return True-- return False+ # Hogland is one configured origin, so delegate to the same exact-origin gate+ # (https + host + port) that authorizes attaching the hogland bearer. One gate+ # for both decisions means a URL this allowlist admits as hogland is always a+ # URL the bearer may travel to, and vice versa — the previous inline check+ # compared the hostname only, so it was slightly wider than the bearer gate.+ return tasks_facade.is_hogland_sandbox_url(url)@staticmethoddef _proxy_command_to_agent_server(@@ -3486,14 +3491,26 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if sandbox_connect_token:params[sandbox_token_param] = sandbox_connect_token- return http_requests.post(- command_url,- json=payload,- headers=headers,- params=params,- timeout=5 if payload.get("method") == "credential_response" else 600,- allow_redirects=payload.get("method") != "credential_response",- )+ request_kwargs: dict[str, Any] = {+ "json": payload,+ "headers": headers,+ "params": params,+ "timeout": 5 if payload.get("method") == "credential_response" else 600,+ "allow_redirects": payload.get("method") != "credential_response",+ }++ if tasks_facade.is_hogland_sandbox_url(sandbox_url):+ # In-cluster DNS answers for the hogland host with a private address, and the+ # egress proxy answers 407 for it — so bypass HTTP(S)_PROXY for this one+ # exact origin, the same way agent_command.send_agent_command does. Redirects are+ # disabled outright (rather than validated against the allowlist) because this+ # transport already skips the egress proxy that would otherwise constrain where a+ # followed redirect could reach from the web pod.+ request_kwargs["allow_redirects"] = False+ with internal_requests_session() as session:+ return session.post(command_url, **request_kwargs)++ return http_requests.post(command_url, **request_kwargs)@validated_request(query_serializer=TaskRunSessionLogsQuerySerializer,diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 613db9965c8b..ff4358ea3e72 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -14290,6 +14290,80 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):self.assertEqual(response.status_code, status.HTTP_200_OK)+ @override_settings(+ SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY,+ HOGLAND_API_URL="https://hogland.prod-us.posthog.dev",+ )+ @patch("products.tasks.backend.presentation.views.api.internal_requests_session")+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")+ def test_command_to_hogland_sandbox_bypasses_egress_proxy(self, mock_post, mock_session_factory):+ # A hogland box-proxy URL resolves in-cluster to a private address the egress+ # proxy refuses (407), so the command must ride the proxy-bypassing session —+ # never the env-proxied module-level post.+ reset_sandbox_jwt_key_cache()+ session = mock_session_factory.return_value.__enter__.return_value+ self._mock_agent_response(session.post, {"jsonrpc": "2.0", "result": {}})++ task = self.create_task()+ run = self._create_run_with_sandbox(+ task, sandbox_url="https://hogland.prod-us.posthog.dev/v1/hogboxes/box-1/proxy/8080"+ )++ response = self.client.post(+ self._command_url(task, run),+ self._make_cancel(),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_post.assert_not_called()+ session.post.assert_called_once()+ self.assertEqual(+ session.post.call_args[0][0],+ "https://hogland.prod-us.posthog.dev/v1/hogboxes/box-1/proxy/8080/command",+ )++ def test_command_blocks_hogland_sandbox_url_when_unconfigured(self):+ # Regression: on a pod without HOGLAND_API_URL, a hogland box-proxy URL matches+ # no allowlist entry, so the command must be refused instead of proxied. This is+ # the exact failure that killed every own-subscription run on hogland sandboxes+ # (the credential_response died here with "Invalid sandbox URL").+ task = self.create_task()+ run = self._create_run_with_sandbox(+ task, sandbox_url="https://hogland.prod-us.posthog.dev/v1/hogboxes/box-1/proxy/8080"+ )++ with override_settings(HOGLAND_API_URL=None):+ response = self.client.post(+ self._command_url(task, run),+ self._make_cancel(),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("Invalid sandbox URL", response.json()["error"])++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ @patch("products.tasks.backend.presentation.views.api.internal_requests_session")+ @patch("products.tasks.backend.presentation.views.api.http_requests.post")+ def test_command_to_modal_sandbox_keeps_env_proxied_post(self, mock_post, mock_session_factory):+ # Modal tunnel hosts are public: they keep the default (env-proxied) transport.+ reset_sandbox_jwt_key_cache()+ self._mock_agent_response(mock_post, {"jsonrpc": "2.0", "result": {}})++ task = self.create_task()+ run = self._create_run_with_sandbox(task, sandbox_url="https://sb-abc123.modal.run")++ response = self.client.post(+ self._command_url(task, run),+ self._make_cancel(),+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ mock_session_factory.assert_not_called()+ mock_post.assert_called_once()+def test_command_with_empty_state(self):task = self.create_task()run = TaskRun.objects.create(diff --git a/products/tasks/backend/tests/test_sandbox_url_validation.py b/products/tasks/backend/tests/test_sandbox_url_validation.pyindex b15e35bf24a7..9953ee8aef73 100644--- a/products/tasks/backend/tests/test_sandbox_url_validation.py+++ b/products/tasks/backend/tests/test_sandbox_url_validation.py@@ -12,10 +12,14 @@ class TestIsValidSandboxUrl:("https://abc123.modal.host/command", True),("https://abc.modal.run/events", True),("https://hogland.prod-us.posthog.dev/v1/hogboxes/hb-1/proxy/8080/command", True),+ # The real box-proxy URL shape from production (box ids, port path segment).+ ("https://hogland.prod-us.posthog.dev/v1/hogboxes/box-2e04766e124b/proxy/8080/command", True),# An attacker-shaped lookalike host must not pass the exact-host check.("https://hogland.prod-us.posthog.dev.evil.example/command", False),("https://evil.example/command", False),("http://hogland.prod-us.posthog.dev/command", False),+ # The hogland entry is an exact origin: a different port is a different origin.+ ("https://hogland.prod-us.posthog.dev:8443/command", False),],)@override_settings(HOGLAND_API_URL="https://hogland.prod-us.posthog.dev")@@ -27,3 +31,15 @@ class TestIsValidSandboxUrl:assert not TaskRunViewSet._is_valid_sandbox_url("https://hogland.prod-us.posthog.dev/v1/hogboxes/hb-1/proxy/8080/command")++ @pytest.mark.parametrize(+ "url,expected",+ [+ ("https://hogland.prod-us.posthog.dev:8443/command", True),+ # Portless is a different origin when the configured URL pins a port.+ ("https://hogland.prod-us.posthog.dev/command", False),+ ],+ )+ @override_settings(HOGLAND_API_URL="https://hogland.prod-us.posthog.dev:8443")+ def test_hogland_origin_match_includes_port(self, url, expected):+ assert TaskRunViewSet._is_valid_sandbox_url(url) is expected