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): enforce Code access for cloud runs (#70757)

Peter Kirkhamadc039d2df34
diff --git a/products/tasks/backend/automation_service.py b/products/tasks/backend/automation_service.py
index c51bc4fcd832..37beeb887291 100644
--- a/products/tasks/backend/automation_service.py
+++ b/products/tasks/backend/automation_service.py
@@ -1,6 +1,7 @@
import logging
from django.conf import settings
+from django.core.exceptions import PermissionDenied
from django.db import transaction
from temporalio.client import Schedule, ScheduleActionStartWorkflow, ScheduleSpec, ScheduleState
@@ -15,6 +16,7 @@ from posthog.temporal.common.schedule import (
update_schedule,
)
+from .access import has_tasks_access
from .models import Task, TaskAutomation, TaskRun
logger = logging.getLogger(__name__)
@@ -65,6 +67,9 @@ def run_task_automation(automation_id: str, trigger_workflow_id: str | None = No
automation = TaskAutomation.objects.select_for_update(of=("self",)).select_related("task").get(id=automation_id)
task = automation.task
+ if task.created_by is not None and not has_tasks_access(task.created_by):
+ raise PermissionDenied("PostHog Code access is required to run task automations")
+
if trigger_workflow_id:
existing_task_run_query = TaskRun.objects.select_related("task").filter(
task__team_id=task.team_id,
diff --git a/products/tasks/backend/facade/access.py b/products/tasks/backend/facade/access.py
index 8cc984ba4e62..d96c8ed36491 100644
--- a/products/tasks/backend/facade/access.py
+++ b/products/tasks/backend/facade/access.py
@@ -2,13 +2,15 @@
Facade re-exports for tasks access / usage gating.
``has_tasks_access`` gates whether a user may use the tasks/code product.
-``cloud_usage_limit_response`` returns a structured 429 ``Response`` when the team is over
-its posthog_code usage limit (or ``None`` to proceed) — it is HTTP-layer Response wiring the
-``run``/``start`` endpoints call directly. Presentation imports both from here rather than
-reaching the internal ``access`` / ``logic.services.code_usage_gate`` modules directly.
+``code_access_required_response`` and ``cloud_usage_limit_response`` provide the HTTP-layer
+responses used by user-triggered cloud execution paths. Presentation imports them from here rather
+than reaching the internal ``access`` / ``logic.services.code_usage_gate`` modules directly.
"""
from products.tasks.backend.access import has_tasks_access
-from products.tasks.backend.logic.services.code_usage_gate import cloud_usage_limit_response
+from products.tasks.backend.logic.services.code_usage_gate import (
+ cloud_usage_limit_response,
+ code_access_required_response,
+)
-__all__ = ["cloud_usage_limit_response", "has_tasks_access"]
+__all__ = ["cloud_usage_limit_response", "code_access_required_response", "has_tasks_access"]
diff --git a/products/tasks/backend/logic/services/code_usage_gate.py b/products/tasks/backend/logic/services/code_usage_gate.py
index 88d5354c4ad5..c49734dda855 100644
--- a/products/tasks/backend/logic/services/code_usage_gate.py
+++ b/products/tasks/backend/logic/services/code_usage_gate.py
@@ -12,6 +12,7 @@ from posthog.models import OAuthAccessToken
from posthog.temporal.oauth import create_oauth_access_token_for_user
from posthog.utils import get_instance_region
+from products.tasks.backend.access import has_tasks_access
from products.tasks.backend.presentation.serializers import TaskRunErrorResponseSerializer
logger = logging.getLogger(__name__)
@@ -135,11 +136,29 @@ def rate_limit_error_payload(usage: CodeUsageStatus) -> dict[str, Any]:
return payload
+def code_access_required_response(user) -> Response | None:
+ if has_tasks_access(user):
+ return None
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "type": "permission_denied",
+ "code": "code_access_required",
+ "error": "PostHog Code access is required to run tasks in the cloud.",
+ }
+ ).data,
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+
def cloud_usage_limit_response(user, team_id: int) -> Response | None:
- """Return a structured 429 Response when the team is over its posthog_code usage limit, else None.
+ """Return a blocking response when Code access or usage limits deny a cloud run, else None.
- Fails open: if the gateway can't be reached, returns None and the run proceeds.
+ Entitlement checks fail closed. Usage checks fail open when the gateway can't be reached.
"""
+ if response := code_access_required_response(user):
+ return response
+
usage = get_posthog_code_usage(user, team_id)
if usage is None or not usage.is_rate_limited:
return None
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 6c8016c87ad6..04d09856f6b2 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -39,7 +39,7 @@ from products.tasks.backend.facade import (
cancellation as tasks_cancellation,
contracts as tasks_contracts,
)
-from products.tasks.backend.facade.access import cloud_usage_limit_response
+from products.tasks.backend.facade.access import cloud_usage_limit_response, code_access_required_response
from products.tasks.backend.facade.metrics import (
StreamConnectionOutcome,
observe_stream_connection_closed,
@@ -583,6 +583,9 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if not self._warm_enabled():
return Response(status=status.HTTP_200_OK)
+ if access_response := code_access_required_response(request.user):
+ return access_response
+
user_id = self._user_id()
if user_id is None:
return Response(status=status.HTTP_200_OK)
@@ -699,6 +702,8 @@ class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(request=TaskAutomationWriteSerializer, responses={201: TaskAutomationSerializer})
def create(self, request, **kwargs):
+ if access_response := code_access_required_response(request.user):
+ return access_response
serializer = self._write_serializer(request.data)
automation = tasks_facade.create_task_automation(
self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data)
@@ -708,6 +713,9 @@ class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(request=TaskAutomationWriteSerializer, responses={200: TaskAutomationSerializer})
def partial_update(self, request, pk=None, **kwargs):
serializer = self._write_serializer(request.data, partial=True)
+ if serializer.validated_data.get("enabled") is True:
+ if access_response := code_access_required_response(request.user):
+ return access_response
automation = tasks_facade.update_task_automation(
pk, self.team_id, getattr(request.user, "id", None), **self._facade_kwargs(serializer.validated_data)
)
@@ -724,6 +732,8 @@ class TaskAutomationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@extend_schema(request=None, responses={200: TaskAutomationSerializer})
@action(detail=True, methods=["post"], url_path="run", required_scopes=["task:write"])
def run(self, request, pk=None, **kwargs):
+ if access_response := code_access_required_response(request.user):
+ return access_response
automation = tasks_facade.run_task_automation_now(pk, self.team_id, getattr(request.user, "id", None))
if automation is None:
raise NotFound()
@@ -1445,6 +1455,8 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
params = request.validated_data.get("params")
if method == "user_message":
+ if access_response := code_access_required_response(request.user):
+ return access_response
command_params = dict(params or {})
artifact_ids = command_params.pop("artifact_ids", [])
if artifact_ids:
diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.md
index 1be224e3536d..11d240154357 100644
--- a/products/tasks/backend/temporal/process_task/README.md
+++ b/products/tasks/backend/temporal/process_task/README.md
@@ -52,7 +52,7 @@ User ─────────────────────────
### PostHog API
-`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.
+`backend/presentation/views/api.py` (thin viewsets) over `backend/facade/api.py` (behavior) — every user-triggered cloud launch path, including prewarming and task automations, checks server-side PostHog Code access before provisioning or activating a run. Scheduled automations repeat the entitlement check at execution time so revoked access cannot launch later. `TaskViewSet.run` creates a `TaskRun` (status=QUEUED) and starts the Temporal workflow. `TaskRunViewSet.partial_update` handles status transitions and signals the Temporal workflow on terminal statuses via `signal_workflow_completion`. `TaskRunViewSet.cancel` (`POST .../runs/{id}/cancel/`) is the user-facing kill switch: `cancel_task_run` interrupts the in-flight agent turn, signals `complete_task("cancelled")` so the workflow snapshots the session and tears down the sandbox, and falls back to finalizing the run directly when no workflow is running.
### Temporal workflow
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 02f00b5fc4e7..4a5446b13828 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -13,7 +13,7 @@ from unittest.mock import ANY, AsyncMock, MagicMock, call, patch
from django.conf import settings
from django.db import connection
from django.http import StreamingHttpResponse
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone as django_timezone
@@ -34,6 +34,8 @@ from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.logic.services.code_usage_gate import (
CodeUsageStatus,
_gateway_usage_url,
+ cloud_usage_limit_response,
+ code_access_required_response,
get_posthog_code_usage,
)
from products.tasks.backend.logic.services.connection_token import (
@@ -3342,6 +3344,27 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
self.assertEqual(automation.cron_expression, "0 9 * * *")
mock_sync_schedule.assert_called_once_with(automation)
+ @patch("products.tasks.backend.automation_service.sync_automation_schedule")
+ def test_create_automation_requires_code_access(self, mock_sync_schedule):
+ self.set_tasks_feature_flag(False)
+
+ response = self.client.post(
+ "/api/projects/@current/task_automations/",
+ {
+ "name": "Daily PRs",
+ "prompt": "Check my GitHub PRs",
+ "repository": "posthog/posthog",
+ "cron_expression": "0 9 * * *",
+ "timezone": "Europe/London",
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertFalse(TaskAutomation.objects.exists())
+ mock_sync_schedule.assert_not_called()
+
def test_list_automations(self):
automation = self.create_automation()
@@ -3454,6 +3477,25 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
self.assertFalse(automation.enabled)
mock_sync_schedule.assert_called_once_with(automation)
+ @patch("products.tasks.backend.automation_service.sync_automation_schedule")
+ def test_enable_automation_requires_code_access(self, mock_sync_schedule):
+ automation = self.create_automation()
+ automation.enabled = False
+ automation.save(update_fields=["enabled", "updated_at"])
+ self.set_tasks_feature_flag(False)
+
+ response = self.client.patch(
+ f"/api/projects/@current/task_automations/{automation.id}/",
+ {"enabled": True},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ automation.refresh_from_db()
+ self.assertFalse(automation.enabled)
+ mock_sync_schedule.assert_not_called()
+
@patch("products.tasks.backend.facade.api._sync_automation_schedule")
def test_update_automation_rolls_back_automation_when_task_update_fails(self, mock_sync_schedule):
automation = self.create_automation()
@@ -3492,6 +3534,17 @@ class TestTaskAutomationAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
mock_run_task_automation.assert_called_once_with(str(automation.id))
+ @patch("products.tasks.backend.automation_service.run_task_automation")
+ def test_run_requires_code_access(self, mock_run_task_automation):
+ self.set_tasks_feature_flag(False)
+ automation = self.create_automation()
+
+ response = self.client.post(f"/api/projects/@current/task_automations/{automation.id}/run/")
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ mock_run_task_automation.assert_not_called()
+
class TestTaskRunAPI(BaseTaskAPITest):
def _create_run_for_origin(self, origin_product: Task.OriginProduct) -> tuple[Task, TaskRun]:
@@ -7325,6 +7378,22 @@ class TestTaskRunCommandAPI(BaseTaskAPITest):
mock_signal_followup.assert_called_once_with(run.workflow_id, "Hello agent", [])
+ @patch("products.tasks.backend.temporal.client.signal_task_followup_message")
+ def test_command_user_message_requires_code_access(self, mock_signal_followup):
+ self.set_tasks_feature_flag(False)
+ task = self.create_task()
+ run = self._create_run_with_sandbox(task)
+
+ response = self.client.post(
+ self._command_url(task, run),
+ self._make_user_message(),
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ mock_signal_followup.assert_not_called()
+
@patch("products.tasks.backend.temporal.client.signal_task_followup_message")
def test_command_signals_user_message_without_active_sandbox(self, mock_signal_followup):
task = self.create_task()
@@ -8451,6 +8520,39 @@ class TestCloudUsageGate(BaseTaskAPITest):
status=status_value,
)
+ @patch("products.tasks.backend.facade.api.warm_task_sandbox")
+ @patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)
+ def test_warm_without_code_access_returns_403_before_provisioning(self, _mock_warm_enabled, mock_warm):
+ self.set_tasks_feature_flag(False)
+
+ response = self.client.post(
+ "/api/projects/@current/tasks/warm/",
+ {"repository": "posthog/posthog", "github_integration": 123},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ mock_warm.assert_not_called()
+
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ def test_run_without_code_access_returns_403_before_usage_check(self, mock_gate, mock_workflow):
+ self.set_tasks_feature_flag(False)
+ task = self.create_task()
+
+ response = self.client.post(
+ f"/api/projects/@current/tasks/{task.id}/run/",
+ {"mode": "background"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.json()["code"], "code_access_required")
+ self.assertFalse(TaskRun.objects.filter(task=task).exists())
+ mock_gate.assert_not_called()
+ mock_workflow.assert_not_called()
+
@patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
def test_run_over_limit_returns_429_and_creates_no_run(self, mock_gate):
mock_gate.return_value = self.OVER_LIMIT
@@ -8634,6 +8736,28 @@ class TestGetPosthogCodeUsage(TestCase):
mock_token.assert_not_called()
+class TestCloudUsageGateResponse(SimpleTestCase):
+ @patch("products.tasks.backend.logic.services.code_usage_gate.get_posthog_code_usage")
+ @patch("products.tasks.backend.logic.services.code_usage_gate.has_tasks_access")
+ def test_missing_code_access_returns_403_before_usage_check(self, mock_access, mock_usage):
+ mock_access.return_value = False
+
+ response = cloud_usage_limit_response(MagicMock(), 1)
+
+ assert response is not None
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.data["code"], "code_access_required")
+ mock_usage.assert_not_called()
+
+ @patch("products.tasks.backend.logic.services.code_usage_gate.has_tasks_access", return_value=False)
+ def test_code_access_required_response_is_structured(self, _mock_access):
+ response = code_access_required_response(MagicMock())
+
+ assert response is not None
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertEqual(response.data["code"], "code_access_required")
+
+
def _make_custom_image(*, team: Team, user: User, **kwargs) -> SandboxCustomImage:
image = SandboxCustomImage(team=team, created_by=user, **kwargs)
image.save()
diff --git a/products/tasks/backend/tests/test_automation_service.py b/products/tasks/backend/tests/test_automation_service.py
index 8c9aee4daac2..4ff18074f121 100644
--- a/products/tasks/backend/tests/test_automation_service.py
+++ b/products/tasks/backend/tests/test_automation_service.py
@@ -1,5 +1,6 @@
from unittest.mock import patch
+from django.core.exceptions import PermissionDenied
from django.test import TestCase
from posthog.models import Organization, Team, User
@@ -13,6 +14,9 @@ class TestAutomationService(TestCase):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
self.user = User.objects.create_user(email="[email protected]", first_name="Test", password="password")
+ access_patcher = patch("products.tasks.backend.automation_service.has_tasks_access", return_value=True)
+ access_patcher.start()
+ self.addCleanup(access_patcher.stop)
def create_automation(self) -> TaskAutomation:
task = Task.objects.create(
@@ -98,6 +102,17 @@ class TestAutomationService(TestCase):
self.assertEqual(TaskRun.objects.filter(task=first_task).count(), 2)
self.assertEqual(mock_execute_workflow.call_count, 2)
+ @patch("products.tasks.backend.automation_service.has_tasks_access", return_value=False)
+ @patch("products.tasks.backend.automation_service.execute_task_processing_workflow_for_automation")
+ def test_run_task_automation_requires_code_access(self, mock_execute_workflow, _mock_access):
+ automation = self.create_automation()
+
+ with self.assertRaises(PermissionDenied):
+ run_task_automation(str(automation.id))
+
+ self.assertFalse(TaskRun.objects.filter(task=automation.task).exists())
+ mock_execute_workflow.assert_not_called()
+
def test_automation_last_run_properties_come_from_last_task_run(self):
automation = self.create_automation()
task_run = automation.task.create_run(mode="background", extra_state={"automation_id": str(automation.id)})