: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): only accept claude plan runs from posthog desktop (#105218)
Alessandro Pogliaghi0ba8330d0aaf
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex bca1bff56728..d76e2a60c1a3 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -14,14 +14,17 @@ import posthoganalyticsfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field, extend_schema_serializerfrom rest_framework import serializers+from rest_framework.request import Requestfrom rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.event_usage import groupsfrom posthog.models.integration import Integrationfrom posthog.models.user_integration import UserIntegration+from posthog.oauth_provenance import get_oauth_client_id, is_interactive_desktop_grantfrom posthog.object_tags.kinds import OBJECT_KINDSfrom posthog.security.url_validation import is_url_allowed, resolve_url_hosts_ips+from posthog.temporal.oauth import POSTHOG_CODE_OAUTH_APP_CLIENT_IDSfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.api import CHANNEL_INSTRUCTIONS_MAX_BYTES@@ -103,6 +106,10 @@ def _is_pi_task_run_request(context: dict[str, Any]) -> bool:return task_runtime == tasks_facade.TaskRuntime.PI+def _is_desktop_app_grant(request: Request) -> bool:+ return get_oauth_client_id(request) in POSTHOG_CODE_OAUTH_APP_CLIENT_IDS and is_interactive_desktop_grant(request)++def _validate_subscription_caller(attrs: dict[str, Any], context: dict[str, Any]) -> None:request = context.get("request")if request is None:@@ -119,8 +126,15 @@ def _validate_subscription_caller(attrs: dict[str, Any], context: dict[str, Any]raise serializers.ValidationError({"claude_model_access": "Open PostHog Desktop to resume this run with your Claude plan."})- if access == "own-subscription" and is_sandbox_oauth_request(request):- raise serializers.ValidationError({"claude_model_access": "Only a user can select a Claude subscription."})+ if access == "own-subscription" and not _is_desktop_app_grant(request):+ raise serializers.ValidationError(+ {+ "claude_model_access": (+ "Only PostHog Desktop can start a run on your Claude plan. "+ "Start the task from Desktop, or drop this setting to use PostHog credits."+ )+ }+ )def request_distinct_id(context: dict[str, Any]) -> str | None:@@ -3340,8 +3354,9 @@ class TaskRunPreferencesFieldMixin(serializers.Serializer):help_text=("How the Claude runtime pays for model use. 'own-subscription' makes the sandbox ""request a Claude token from the creating PostHog Desktop at run start; the token is "- "sent in flight and never stored on PostHog servers. If omitted or null, resumed runs "- "keep their billing choice and new runs use the PostHog gateway."+ "sent in flight and never stored on PostHog servers. Only PostHog Desktop can select "+ "'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep "+ "their billing choice and new runs use the PostHog gateway."),)diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 5dce1f7fe408..a5c98ceb16a7 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -4167,7 +4167,7 @@ class TestTaskAPI(BaseTaskAPITest):def test_run_endpoint_persists_agent_toggle(self, field, value, mock_workflow):task = self.create_task()- response = self.client.post(+ response = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV).post(f"/api/projects/@current/tasks/{task.id}/run/",{field: value},format="json",@@ -4178,6 +4178,30 @@ class TestTaskAPI(BaseTaskAPITest):assert task_run.state[field] == valuemock_workflow.assert_called_once()+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_rejects_claude_plan_from_personal_api_key(self, mock_workflow):+ task = self.create_task()+ api_key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="Task script",+ secure_value=hash_key_value(api_key_value),+ scopes=["task:write"],+ )+ client = APIClient()+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {api_key_value}")++ response = client.post(+ f"/api/projects/@current/tasks/{task.id}/run/",+ {"claude_model_access": "own-subscription"},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "claude_model_access"+ assert not task.runs.exists()+ mock_workflow.assert_not_called()+@parameterized.expand([("rtk_enabled",), ("benjamin_enabled",), ("claude_model_access",)])@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_omits_agent_toggle_when_not_set(self, field, mock_workflow):@@ -4968,7 +4992,9 @@ class TestTaskAPI(BaseTaskAPITest):if requested is not None:payload["claude_model_access"] = requested- response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/", payload, format="json")+ response = self._oauth_client(ARRAY_APP_CLIENT_ID_DEV).post(+ f"/api/projects/@current/tasks/{task.id}/run/", payload, format="json"+ )if expected is None:assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/products/tasks/backend/tests/test_presentation_serializers.py b/products/tasks/backend/tests/test_presentation_serializers.pyindex a4eedecaf4bc..0f5824a348ec 100644--- a/products/tasks/backend/tests/test_presentation_serializers.py+++ b/products/tasks/backend/tests/test_presentation_serializers.py@@ -9,7 +9,11 @@ from parameterized import parameterizedfrom posthog.auth import OAuthAccessTokenAuthenticationfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication-from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_EU, ARRAY_APP_CLIENT_ID_US+from posthog.temporal.oauth import (+ ARRAY_APP_CLIENT_ID_EU,+ ARRAY_APP_CLIENT_ID_US,+ POSTHOG_DESKTOP_MOBILE_APP_CLIENT_ID_US,+)from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.presentation.serializers import (@@ -121,22 +125,29 @@ class TestTaskRunCreateRequestSerializer(SimpleTestCase):@parameterized.expand([- (serializer_class, resume, client_id, sandbox)+ (serializer_class, resume, caller)for serializer_class, resume in [(TaskRunCreateRequestSerializer, False),(TaskRunBootstrapCreateRequestSerializer, False),(TaskRunCreateRequestSerializer, True),]- for client_id in [ARRAY_APP_CLIENT_ID_US, ARRAY_APP_CLIENT_ID_EU]- for sandbox in [False, True]+ for caller in ["desktop_us", "desktop_eu", "mobile", "sandbox", "session"]])- def test_subscription_checks_oauth_origin(self, serializer_class, resume, client_id, sandbox) -> None:- authenticator = OAuthAccessTokenAuthentication()- authenticator.access_token = OAuthAccessToken(- application=OAuthApplication(client_id=client_id),- scope="task:write internal_run:read" if sandbox else "task:write",- )+ def test_subscription_checks_oauth_origin(self, serializer_class, resume, caller) -> None:+ authenticator = None+ if caller != "session":+ authenticator = OAuthAccessTokenAuthentication()+ authenticator.access_token = OAuthAccessToken(+ application=OAuthApplication(+ client_id={+ "desktop_eu": ARRAY_APP_CLIENT_ID_EU,+ "mobile": POSTHOG_DESKTOP_MOBILE_APP_CLIENT_ID_US,+ }.get(caller, ARRAY_APP_CLIENT_ID_US)+ ),+ scope="task:write internal_run:read" if caller == "sandbox" else "task:write",+ source_refresh_token_id="00000000-0000-0000-0000-000000000002",+ )serializer = serializer_class(data={"resume_from_run_id": "00000000-0000-0000-0000-000000000001"}if resume@@ -147,13 +158,14 @@ class TestTaskRunCreateRequestSerializer(SimpleTestCase):"team": SimpleNamespace(id=1),},)+ accepted = caller.startswith("desktop") and not resumewith patch.object(tasks_facade,"get_task_run_claude_model_access",return_value="own-subscription",):- assert serializer.is_valid() is (not sandbox and not resume), serializer.errors- if sandbox or resume:+ assert serializer.is_valid() is accepted, serializer.errors+ if not accepted:assert "claude_model_access" in serializer.errors@patch(diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.tsindex 34f76546f22f..b1a57531a2d4 100644--- a/products/tasks/frontend/generated/api.schemas.ts+++ b/products/tasks/frontend/generated/api.schemas.ts@@ -2877,7 +2877,7 @@ export interface ClaudeTaskRunCreateSchemaApi {* @nullable*/benjamin_enabled?: boolean | null- /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */@@ -3010,7 +3010,7 @@ export interface CodexTaskRunCreateSchemaApi {* @nullable*/benjamin_enabled?: boolean | null- /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */@@ -3461,7 +3461,7 @@ export interface TaskRunBootstrapCreateRequestApi {* @nullable*/benjamin_enabled?: boolean | null- /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.tsindex d5d012f55297..de86a5e18ab8 100644--- a/products/tasks/frontend/generated/api.zod.ts+++ b/products/tasks/frontend/generated/api.zod.ts@@ -1881,7 +1881,7 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([]).optional().describe(- "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),mode: zod.enum(['interactive', 'background'])@@ -2045,7 +2045,7 @@ export const TasksRunCreateBody = /* @__PURE__ */ zod.union([]).optional().describe(- "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),mode: zod.enum(['interactive', 'background'])@@ -2509,7 +2509,7 @@ export const TasksRunsCreateBody = /* @__PURE__ */ zod]).optional().describe(- "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),environment: zod.enum(['local', 'cloud'])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e2eab2475ed1..b0e2272b93c5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19946,7 +19946,7 @@ export namespace Schemas {* @nullable*/benjamin_enabled?: boolean | null;- /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */@@ -20363,7 +20363,7 @@ export namespace Schemas {* @nullable*/benjamin_enabled?: boolean | null;- /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */@@ -96026,7 +96026,7 @@ export namespace Schemas {* @nullable*/benjamin_enabled?: boolean | null;- /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.+ /** How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.** * `posthog-gateway` - posthog-gateway* * `own-subscription` - own-subscription */diff --git a/services/mcp/src/generated/tasks/api.ts b/services/mcp/src/generated/tasks/api.tsindex 35bbc185d9b3..d1fb2cd149ba 100644--- a/services/mcp/src/generated/tasks/api.ts+++ b/services/mcp/src/generated/tasks/api.ts@@ -1341,7 +1341,7 @@ export const TasksRunCreateBody = () => zod.union([]).optional().describe(- "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),mode: zod.enum(['interactive', 'background'])@@ -1505,7 +1505,7 @@ export const TasksRunCreateBody = () => zod.union([]).optional().describe(- "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"+ "How the Claude runtime pays for model use. 'own-subscription' makes the sandbox request a Claude token from the creating PostHog Desktop at run start; the token is sent in flight and never stored on PostHog servers. Only PostHog Desktop can select 'own-subscription'; other callers get a 400. If omitted or null, resumed runs keep their billing choice and new runs use the PostHog gateway.\n\n\* `posthog-gateway` - posthog-gateway\n\* `own-subscription` - own-subscription"),mode: zod.enum(['interactive', 'background'])