: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): enforce gated model access server-side (#80331)
Alessandro Pogliaghib31ce5c074d2
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 448cf429607a..4fe6f0e6716b 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -16,6 +16,26 @@ PI_CLOUD_RUNTIME_FEATURE_FLAG = "pi-harness"# Consumers read the stamp, so the decision stays stable for the run's whole lifetime.AGENT_OTEL_TELEMETRY_STATE_KEY = "agent_otel_telemetry_enabled"+# Models a caller may only select while the paired flag is enabled for them. The Desktop+# pickers already hide these client-side (`products/desktop/packages/shared/src/flags.ts`),+# but a picker is a convenience rather than a gate: a stored per-task model preference, an+# older client, or a direct API call all reach the write paths without consulting a flag, so+# entitlement is re-checked server-side. Keys are the model ids callers send.+MODEL_ACCESS_FLAGS: dict[str, str] = {+ "moonshotai/kimi-k3": "tasks-kimi-k3",+}+++def get_required_model_flag(model: str | None) -> str | None:+ """The feature flag a caller needs to select `model`, or None when it's generally available."""+ if not model:+ return None+ normalized = model.strip().lower()+ for gated_model, flag_key in MODEL_ACCESS_FLAGS.items():+ if gated_model.lower() == normalized:+ return flag_key+ return None+def _decode_vm_sandbox_payload(payload: object) -> object:"""Flag payloads may arrive JSON-encoded; decode strings, mapping bad JSON to None."""diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex e7528bbcb23a..7c8702bf53f3 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -48,9 +48,11 @@ from products.tasks.backend.constants import (PI_CLOUD_RUNTIME_FEATURE_FLAG,RESERVED_SANDBOX_ENVIRONMENT_VARIABLE_KEYS,TASK_SESSION_MAX_SIZE_BYTES,+ get_required_model_flag,is_blocked_sandbox_env_key,)from products.tasks.backend.error_telemetry import truncate_error_message+from products.tasks.backend.feature_flags import get_model_access_errorfrom products.tasks.backend.github_repository_access import (inaccessible_repositories_via_integration as _inaccessible_repositories_via_integration,)@@ -5388,6 +5390,20 @@ def run_task())+ # A resume inherits the previous run's model, so the serializer's check saw `None` and+ # passed. Re-check the model that will actually run. Only a gated model pays the lookup.+ if get_required_model_flag(model) is not None:+ actor_distinct_id = (+ User.objects.filter(pk=user_id).values_list("distinct_id", flat=True).first() if user_id else None+ )+ model_access_error = get_model_access_error(model, distinct_id=actor_distinct_id)+ if model_access_error is not None:+ return contracts.TaskRunResult(+ error=contracts.TaskValidationError(+ kind="validation_error", code="invalid_input", detail=model_access_error, attr="model"+ )+ )+pr_authorship_mode, validation_error = _resolve_cloud_pr_authorship_mode(task,pr_authorship_mode=pr_authorship_mode,diff --git a/products/tasks/backend/facade/run_config.py b/products/tasks/backend/facade/run_config.pyindex b8318e0c5262..32aef0178f12 100644--- a/products/tasks/backend/facade/run_config.py+++ b/products/tasks/backend/facade/run_config.py@@ -14,8 +14,11 @@ from products.tasks.backend.constants import (ALL_INITIAL_PERMISSION_MODE_CHOICES,CODEX_INITIAL_PERMISSION_MODE_CHOICES,INITIAL_PERMISSION_MODE_CHOICES,+ MODEL_ACCESS_FLAGS,InitialPermissionMode,+ get_required_model_flag,)+from products.tasks.backend.feature_flags import get_model_access_error# TaskArtifact's choice enums live on the model as Django ``TextChoices``; re-exported here# so presentation builds serializer choices without importing the ORM model directly.@@ -50,6 +53,7 @@ __all__ = ["CONTEXT_WINDOW_CHOICES","INITIAL_PERMISSION_MODE_CHOICES","InitialPermissionMode",+ "MODEL_ACCESS_FLAGS","PUBLIC_REASONING_EFFORTS","GitHubCredentialSource","LLMProvider",@@ -62,9 +66,11 @@ __all__ = ["TaskArtifactStatus","TaskArtifactType","get_default_model_for_runtime_adapter",+ "get_model_access_error","get_models_for_runtime_adapter","get_provider_for_runtime_adapter","get_reasoning_effort_error",+ "get_required_model_flag","get_runtime_adapter_for_model","get_supported_reasoning_efforts","parse_run_state",diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.pyindex 2647d2900bc9..aa0db1096557 100644--- a/products/tasks/backend/feature_flags.py+++ b/products/tasks/backend/feature_flags.py@@ -10,6 +10,7 @@ from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG,DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,+ get_required_model_flag,)logger = logging.getLogger(__name__)@@ -85,6 +86,39 @@ def is_agent_otel_telemetry_enabled(*, distinct_id: str, organization_id: str) -return False+def get_model_access_error(model: str | None, *, distinct_id: str | None) -> str | None:+ """Reject a gated model the caller isn't entitled to; `None` when the selection is allowed.++ Fail-closed on purpose. Only a model in `MODEL_ACCESS_FLAGS` reaches an evaluation at all,+ so an evaluation outage withholds a preview model from everyone rather than opening it to+ everyone — the opposite trade to the telemetry flags above, because this one decides spend.+ """+ flag_key = get_required_model_flag(model)+ if flag_key is None:+ return None++ # The analytics SDK is disabled in local dev, where every flag reads as off.+ if settings.DEBUG:+ return None++ not_available = f"'{model}' is not available for your account."+ if not distinct_id:+ return not_available++ try:+ enabled = posthoganalytics.feature_enabled(+ flag_key,+ distinct_id=distinct_id,+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception:+ logger.exception("model_access_flag_check_failed", extra={"flag": flag_key, "model": model})+ return not_available++ return None if enabled else not_available++def agent_otel_telemetry_enabled_for_state(state: dict | None) -> bool:"""Per-run telemetry decision, read from the flag value stamped into run state at dispatch.diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.pyindex 766a06a48c58..9c14672e8107 100644--- a/products/tasks/backend/presentation/serializers.py+++ b/products/tasks/backend/presentation/serializers.py@@ -55,6 +55,7 @@ from products.tasks.backend.facade.run_config import (TaskArtifactAdapter,TaskArtifactStatus,TaskArtifactType,+ get_model_access_error,get_reasoning_effort_error,)@@ -87,6 +88,14 @@ def _is_pi_task_run_request(context: dict[str, Any]) -> bool:return task_runtime == tasks_facade.TaskRuntime.PI+def request_distinct_id(context: dict[str, Any]) -> str | None:+ """The acting user's distinct id, for flag evaluation. `None` when there isn't one."""+ user = getattr(context.get("request"), "user", None)+ if user is None or not user.is_authenticated or not user.distinct_id:+ return None+ return str(user.distinct_id)++def _capture_rejected_reasoning_effort(context: dict[str, Any],*,@@ -735,6 +744,12 @@ class TaskWriteSerializer(serializers.Serializer):if "runtime" in self.initial_data and "runtime" not in self.fields:raise serializers.ValidationError({"runtime": "Runtime cannot be changed after task creation."})+ # Write-only and never persisted, but it selects which warm Run gets activated, so a+ # gated model here still runs one. Reject rather than silently cold-creating instead.+ model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))+ if model_access_error is not None:+ raise serializers.ValidationError({"model": model_access_error})+rel = attrs.get("signal_report_task_relationship")if rel is not None:if not attrs.get("signal_report"):@@ -2414,6 +2429,10 @@ class TaskRunCreateRequestSerializer(ImportedMcpServersFieldMixin, RelayedMcpSererror=reasoning_effort_error,)+ model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))+ if model_access_error is not None:+ errors["model"] = model_access_error+if errors:raise serializers.ValidationError(errors)@@ -2611,6 +2630,10 @@ class TaskRunBootstrapCreateRequestSerializer(error=reasoning_effort_error,)+ model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))+ if model_access_error is not None:+ errors["model"] = model_access_error+if errors:raise serializers.ValidationError(errors)@@ -2709,6 +2732,11 @@ class WarmTaskRequestSerializer(serializers.Serializer):raise serializers.ValidationError("Repository and GitHub integration must either both be provided or both be omitted.")++ # Warming starts the agent on this model, so it bills like a run and gates like one.+ model_access_error = get_model_access_error(attrs.get("model"), distinct_id=request_distinct_id(self.context))+ if model_access_error is not None:+ raise serializers.ValidationError({"model": model_access_error})return attrsdiff --git a/products/tasks/backend/presentation/serializers_loops.py b/products/tasks/backend/presentation/serializers_loops.pyindex 273fb4b67afc..835a72ec7b39 100644--- a/products/tasks/backend/presentation/serializers_loops.py+++ b/products/tasks/backend/presentation/serializers_loops.py@@ -27,12 +27,14 @@ from products.tasks.backend.facade.run_config import (PUBLIC_REASONING_EFFORTS,RuntimeAdapter,get_default_model_for_runtime_adapter,+ get_model_access_error,get_models_for_runtime_adapter,get_reasoning_effort_error,)from products.tasks.backend.presentation.serializers import (TASK_RUN_SKILL_BUNDLE_FORMAT_CHOICES,TASK_RUN_SKILL_SOURCE_CHOICES,+ request_distinct_id,)@@ -547,6 +549,10 @@ class LoopWriteSerializer(serializers.Serializer):{"model": f"'{model}' is not a supported model for runtime_adapter '{runtime_adapter}'."})+ model_access_error = get_model_access_error(model, distinct_id=request_distinct_id(self.context))+ if model_access_error is not None:+ raise serializers.ValidationError({"model": model_access_error})+reasoning_effort = attrs.get("reasoning_effort")if runtime_adapter is not None and reasoning_effort is not None:# A blank model means "PostHog picks at run time", so the effort isdiff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 29b24ef0375c..26afc5fe4ae6 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -853,6 +853,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"body when the feature flag is off, the warm pool is full, or the GitHub integration doesn't ""belong to the team."),+ include_serializer_context=True,)@action(detail=False, methods=["post"], url_path="warm", required_scopes=["task:write"])def warm(self, request, **kwargs):diff --git a/products/tasks/backend/presentation/views/loops.py b/products/tasks/backend/presentation/views/loops.pyindex f2880fb3d6cc..fcf3eb60ab07 100644--- a/products/tasks/backend/presentation/views/loops.py+++ b/products/tasks/backend/presentation/views/loops.py@@ -165,7 +165,13 @@ class LoopViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):serializer = LoopWriteSerializer(data=data,partial=partial,- context={"team": self.team, "team_id": self.team.id, "user_id": self._user_id()},+ context={+ "team": self.team,+ "team_id": self.team.id,+ "user_id": self._user_id(),+ # Model entitlement is evaluated per acting user, so the write path needs the request.+ "request": self.request,+ },)serializer.is_valid(raise_exception=True)return serializerdiff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 25702e161376..c5fe292be71e 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -3231,6 +3231,29 @@ class TestTaskAPI(BaseTaskAPITest):assert latest_run["reasoning_effort"] == reasoning_effortmock_workflow.assert_called_once()+ @override_settings(DEBUG=False)+ @patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_rejects_a_gated_model_the_caller_cannot_access(self, mock_workflow, mock_feature_enabled):+ # The Desktop picker hides gated models, but a stored preference or a direct API+ # call reaches this endpoint without one, so the entitlement is re-checked here.+ task = self.create_task()++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/run/",+ {+ "mode": "interactive",+ "runtime_adapter": "claude",+ "model": "moonshotai/kimi-k3",+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "model"+ assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"+ mock_workflow.assert_not_called()+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_run_endpoint_persists_context_window_and_fast_mode(self, mock_workflow):task = self.create_task()@@ -3840,6 +3863,31 @@ class TestTaskAPI(BaseTaskAPITest):}mock_workflow.assert_not_called()+ @override_settings(DEBUG=False)+ @patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_run_endpoint_resume_rejects_inherited_gated_model(self, mock_workflow, mock_feature_enabled):+ # A resume omits `model`, so the serializer sees None and passes. The inherited+ # model is the one that actually runs, so entitlement is re-checked after it lands.+ task = self.create_task()+ previous_run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={"runtime_adapter": "claude", "model": "moonshotai/kimi-k3"},+ )++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/run/",+ {"mode": "interactive", "resume_from_run_id": str(previous_run.id)},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "model"+ assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"+ mock_workflow.assert_not_called()+def test_run_endpoint_rejects_invalid_sandbox_environment_id(self):task = self.create_task()@@ -10967,6 +11015,46 @@ class TestCloudUsageGate(BaseTaskAPITest):self.assertEqual(response.json()["code"], "usage_limit_exceeded")mock_warm.assert_not_called()+ @override_settings(DEBUG=False)+ @patch("products.tasks.backend.facade.api.warm_task_sandbox")+ @patch("products.tasks.backend.presentation.views.api.TaskViewSet._warm_enabled", return_value=True)+ @patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)+ def test_warm_rejects_a_gated_model_the_caller_cannot_access(+ self, mock_feature_enabled, _mock_warm_enabled, mock_warm+ ):+ # Warming boots a sandbox and starts the agent on this model, so it bills like a run.+ response = self.client.post(+ "/api/projects/@current/tasks/warm/",+ {"runtime_adapter": "claude", "model": "moonshotai/kimi-k3"},+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "model"+ assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"+ mock_warm.assert_not_called()++ @override_settings(DEBUG=False)+ @patch("products.tasks.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)+ def test_create_rejects_a_gated_model_hint(self, mock_feature_enabled):+ # The create hint is write-only, but it is what selects a warm Run to activate,+ # so a gated value here would run the gated model without ever reaching run_task.+ response = self.client.post(+ "/api/projects/@current/tasks/",+ {+ "title": "Gated",+ "description": "Gated",+ "runtime_adapter": "claude",+ "model": "moonshotai/kimi-k3",+ },+ format="json",+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "model"+ assert mock_feature_enabled.call_args.args[0] == "tasks-kimi-k3"+ assert not Task.objects.filter(title="Gated").exists()+@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_still_runs(self, mock_gate, mock_workflow):diff --git a/products/tasks/backend/tests/test_feature_flags.py b/products/tasks/backend/tests/test_feature_flags.pyindex 6fab3f356de1..700f023552c7 100644--- a/products/tasks/backend/tests/test_feature_flags.py+++ b/products/tasks/backend/tests/test_feature_flags.py@@ -3,7 +3,7 @@ from unittest.mock import patchfrom django.test import override_settings-from products.tasks.backend.feature_flags import is_dev_stack_image_bake_enabled+from products.tasks.backend.feature_flags import get_model_access_error, is_dev_stack_image_bake_enabledclass TestIsDevStackImageBakeEnabled:@@ -47,3 +47,63 @@ class TestIsDevStackImageBakeEnabled:assert is_dev_stack_image_bake_enabled() is Falsefeature_enabled_mock.assert_not_called()+++class TestGetModelAccessError:+ @pytest.mark.parametrize(+ "model",+ ["claude-sonnet-5", "gpt-5.6-luna", "@cf/zai-org/glm-5.2", "", None],+ )+ def test_ungated_model_is_allowed_without_consulting_the_flag(self, model):+ with (+ override_settings(DEBUG=False),+ patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=False,+ ) as feature_enabled_mock,+ ):+ assert get_model_access_error(model, distinct_id="d-1") is None++ feature_enabled_mock.assert_not_called()++ @pytest.mark.parametrize("model", ["moonshotai/kimi-k3", " MoonshotAI/Kimi-K3 "])+ def test_gated_model_is_allowed_when_the_flag_is_on(self, model):+ with (+ override_settings(DEBUG=False),+ patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=True,+ ) as feature_enabled_mock,+ ):+ assert get_model_access_error(model, distinct_id="d-1") is None++ assert feature_enabled_mock.call_args.args[0] == "tasks-kimi-k3"+ assert feature_enabled_mock.call_args.kwargs["distinct_id"] == "d-1"++ @pytest.mark.parametrize(+ "flag_value, distinct_id",+ [(False, "d-1"), (None, "d-1"), (True, None), (True, "")],+ )+ def test_gated_model_is_rejected_without_entitlement(self, flag_value, distinct_id):+ with (+ override_settings(DEBUG=False),+ patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ return_value=flag_value,+ ),+ ):+ assert get_model_access_error("moonshotai/kimi-k3", distinct_id=distinct_id) == (+ "'moonshotai/kimi-k3' is not available for your account."+ )++ def test_fails_closed_on_flag_service_error(self):+ # This gate decides spend, so an evaluation outage withholds the preview model+ # rather than opening it to every caller.+ with (+ override_settings(DEBUG=False),+ patch(+ "products.tasks.backend.feature_flags.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flag service failed"),+ ),+ ):+ assert get_model_access_error("moonshotai/kimi-k3", distinct_id="d-1") is not None