: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
feat(customer-analytics): add JWT-only internal account routes (#90899)
Patricio12a4650c2815
diff --git a/posthog/jwt.py b/posthog/jwt.pyindex 201d14f554ca..b96932c727b5 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -26,6 +26,7 @@ class PosthogJwtAudience(Enum):INTEGRATION_SERVICE = "posthog:integration_service"TASKS_CREATE = "posthog:tasks:create"CONVERSATIONS_TICKETS = "posthog:conversations:tickets"+ CUSTOMER_ANALYTICS_ACCOUNTS = "posthog:customer_analytics:accounts"def signing_key_fingerprint(key: str) -> str:diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.pyindex 678207633a47..c7f7f2e4ee3a 100644--- a/posthog/settings/data_stores.py+++ b/posthog/settings/data_stores.py@@ -592,6 +592,17 @@ CONVERSATIONS_TICKETS_JWT_SECRETS = get_list(get_from_env("CONVERSATIONS_TICKETS_JWT_SECRET", "local-dev-conversations-tickets-jwt" if DEBUG or TEST else ""))+# Verifies the scoped JWTs the CDP worker's customer analytics account actions send to the+# internal account routes (the worker mints, Django verifies;+# products/customer_analytics/backend/presentation/views/internal.py). Comma-separated,+# newest first. Empty outside dev/test, so the internal routes reject every request until+# the secret is provisioned and the worker stays on its legacy auth path (#82564).+CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS = get_list(+ get_from_env(+ "CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRET", "local-dev-customer-analytics-accounts-jwt" if DEBUG or TEST else ""+ )+)+EMBEDDING_API_URL = get_from_env("EMBEDDING_API_URL", "")# Used to generate embeddings on the fly, for use with the document embeddings tablediff --git a/posthog/urls.py b/posthog/urls.pyindex 5bd1c35e39b5..e2fd7c1e0812 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -53,6 +53,10 @@ from products.ai_observability.backend.api.personal_spend import PersonalSpendEUfrom products.canvas.backend.artifacts import canvas_artifactfrom products.cdp.backend.api import hog_function_templatefrom products.conversations.backend.api.internal import InternalTicketView as ConversationsInternalTicketView+from products.customer_analytics.backend.presentation.views.internal import (+ InternalAccountCustomPropertiesView as CustomerAnalyticsInternalAccountCustomPropertiesView,+ InternalAccountView as CustomerAnalyticsInternalAccountView,+)from products.demo.backend.facade.api import demo_routefrom products.early_access_features.backend.api import early_access_featuresfrom products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook@@ -632,6 +636,15 @@ urlpatterns = ["api/projects/<str:team_id>/internal/conversations/tickets/<uuid:ticket_id>",csrf_exempt(ConversationsInternalTicketView.as_view()),),+ # Account routes for the CDP worker's workflow actions (auth: scoped service JWT)+ path(+ "api/projects/<str:team_id>/internal/customer_analytics/account",+ csrf_exempt(CustomerAnalyticsInternalAccountView.as_view()),+ ),+ path(+ "api/projects/<str:team_id>/internal/customer_analytics/account/custom_property_values",+ csrf_exempt(CustomerAnalyticsInternalAccountCustomPropertiesView.as_view()),+ ),# Test setup endpoint (only available in TEST mode)path("api/setup_test/<str:test_name>/", csrf_exempt(playwright_setup.setup_test)),opt_slash_path(diff --git a/products/customer_analytics/backend/metrics.py b/products/customer_analytics/backend/metrics.pyindex 89cc24f05e50..acd761ebfa74 100644--- a/products/customer_analytics/backend/metrics.py+++ b/products/customer_analytics/backend/metrics.py@@ -138,3 +138,8 @@ def record_account_track_rule_coordinator(_otel.record_gauge_twin(_ACCOUNT_TRACK_RULE_ENABLED_TEAMS, enabled_teams)_otel.record_gauge_twin(_ACCOUNT_TRACK_RULE_OVERDUE_TEAMS, overdue_teams)_otel.record_gauge_twin(_ACCOUNT_TRACK_RULE_OLDEST_SUCCESS_AGE_SECONDS, oldest_success_age_seconds)+++# Cutover observability for #82564: the CDP worker's account actions move from+# secret_api_token on the external routes to scoped JWTs on the internal routes.+# The legacy worker path can be removed once auth_method="secret_api_token" stays at zero.diff --git a/products/customer_analytics/backend/presentation/views/account_actions.py b/products/customer_analytics/backend/presentation/views/account_actions.pynew file mode 100644index 000000000000..42e5e51726d5--- /dev/null+++ b/products/customer_analytics/backend/presentation/views/account_actions.py@@ -0,0 +1,303 @@+"""+Shared handler logic for the single-account endpoints called by the CDP worker's+workflow actions. Two routes delegate here: the legacy external route in+``external.py`` (team secret API token) and the JWT-only internal route in+``internal.py`` (#82564). The functions hold request validation and the mapping of+facade results to responses; auth stays in each route.+"""++import uuid+from typing import Any++from drf_spectacular.utils import extend_schema_field+from prometheus_client import Counter+from rest_framework import serializers, status+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.models import Team++from products.customer_analytics.backend.facade import (+ api as facade,+ contracts,+)++ACCOUNT_ACTION_AUTH_COUNTER = Counter(+ "posthog_customer_analytics_account_action_auth_total",+ "Successful authentications on the account routes called by CDP workflow actions, by auth method",+ labelnames=["auth_method", "http_method"], # auth_method: secret_api_token | scoped_jwt+)+++HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"+++def _workflow_id_from_request(request: Request) -> str | None:+ """The originating HogFlow workflow id, when the request comes from a workflow step.++ The header is caller-supplied, so only a well-formed UUID is accepted; worst case is a+ token holder attributing a write to another workflow id within its own team.+ """+ hog_flow_id = request.headers.get(HOG_FLOW_ID_HEADER)+ if not hog_flow_id:+ return None+ try:+ uuid.UUID(hog_flow_id)+ except (ValueError, TypeError):+ return None+ return hog_flow_id+++def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]:+ return {+ "id": account.id,+ "external_id": account.external_id,+ "name": account.name,+ "churned_at": account.churned_at,+ "ignored_at": account.ignored_at,+ "properties": account.properties,+ "tags": account.tags,+ "relationships": account.relationships,+ "custom_properties": account.custom_properties,+ }+++_UPDATE_ERROR_RESPONSES = {+ contracts.ExternalAccountUpdateError.NOT_FOUND: ("Account not found", status.HTTP_404_NOT_FOUND),+ contracts.ExternalAccountUpdateError.INVALID_PROPERTIES: (+ "Invalid account properties",+ status.HTTP_400_BAD_REQUEST,+ ),+ # A server fault (the facade's blanket except), not a client error: 500 keeps the CDP+ # fetch layer retrying instead of failing the workflow permanently.+ contracts.ExternalAccountUpdateError.UPDATE_FAILED: (+ "Failed to update account",+ status.HTTP_500_INTERNAL_SERVER_ERROR,+ ),+}+++def _update_error_response(result: contracts.ExternalAccountUpdateResult) -> Response:+ if result.error == contracts.ExternalAccountUpdateError.USER_NOT_IN_ORGANIZATION:+ return Response(+ {"error": f"{result.error_field}: user is not a member of this organization"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if result.error == contracts.ExternalAccountUpdateError.RELATIONSHIP_DEFINITION_NOT_FOUND:+ return Response(+ {"error": f"{result.error_field}: no relationship definition with this ID"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ assert result.error is not None+ message, code = _UPDATE_ERROR_RESPONSES[result.error]+ return Response({"error": message}, status=code)+++class ExternalAccountUpdateSerializer(serializers.Serializer):+ external_id = serializers.CharField(max_length=400, help_text="External ID (group key) of the account to update.")+ # Each value accepts a `posthog_assignee` object `{type, id}`, or `null` to end the+ # active assignment. Roles (RBAC) are rejected — accounts assign users only.+ # `validate` normalizes a provided assignment down to the user id; the facade resolves+ # it against an org membership so assignees are always trusted.+ relationships = serializers.DictField(+ child=serializers.JSONField(allow_null=True),+ required=False,+ help_text=(+ "Relationship assignments keyed by definition UUID. Each value is an assignee object "+ "`{type: 'user', id}` or null to end the active assignment. Only the supplied "+ "definitions are changed."+ ),+ )+ tags = serializers.ListField(+ child=serializers.CharField(max_length=200),+ required=False,+ max_length=100,+ help_text="Tag names to apply, per tags_mode.",+ )+ tags_mode = serializers.ChoiceField(+ choices=["add", "set", "remove"],+ required=False,+ default="add",+ help_text="How to apply tags: add to, replace, or remove from the existing set.",+ )+ churned_at = serializers.DateTimeField(+ required=False,+ allow_null=True,+ help_text="When the account churned. Set to null to mark it as active again.",+ )++ def validate_relationships(self, value: dict[str, Any]) -> dict[str, int | None]:+ return {name: self._normalize_assignee(name, assignee) for name, assignee in value.items()}++ def _normalize_assignee(self, field: str, value: Any) -> int | None:+ if value is None:+ return None+ if not isinstance(value, dict):+ raise serializers.ValidationError({field: "Must be an assignee object or null"})+ if value.get("type") != "user":+ raise serializers.ValidationError({field: "Accounts can only be assigned to users, not roles"})+ raw_id = value.get("id")+ if not isinstance(raw_id, (int, str)):+ raise serializers.ValidationError({field: "Assignee id must be a user id"})+ try:+ return int(raw_id)+ except (TypeError, ValueError):+ raise serializers.ValidationError({field: "Assignee id must be a user id"})+++class ExternalAccountCreateSerializer(serializers.Serializer):+ external_id = serializers.CharField(+ max_length=400,+ help_text=(+ "External ID (group key) for the account. An account with this ID already existing is a no-op. "+ "The account name is derived from the matching group's `name` property, falling back to this ID."+ ),+ )+++@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}]})+class _CustomPropertyScalarField(serializers.Field):+ """A custom property value sent over the external API — a JSON scalar.++ Objects, arrays, and null are rejected here; the concrete type each property accepts is set by+ its definition and validated server-side when the value is coerced.+ """++ def to_internal_value(self, data: Any) -> Any:+ if data is None or isinstance(data, dict | list):+ raise serializers.ValidationError("Value must be a string, number, or boolean.")+ return data+++class ExternalAccountCustomPropertiesSerializer(serializers.Serializer):+ external_id = serializers.CharField(+ max_length=400,+ help_text="External ID of the account whose custom property values to set — the group key it is linked to.",+ )+ properties = serializers.DictField(+ child=_CustomPropertyScalarField(),+ help_text="Map of custom property definition UUID to the value to set for this account.",+ )+++_CUSTOM_PROPERTIES_ERROR_RESPONSES = {+ contracts.ExternalAccountCustomPropertiesError.ACCOUNT_NOT_FOUND: ("Account not found", status.HTTP_404_NOT_FOUND),+ contracts.ExternalAccountCustomPropertiesError.DEFINITION_NOT_FOUND: (+ "Custom property definition not found",+ status.HTTP_400_BAD_REQUEST,+ ),+ contracts.ExternalAccountCustomPropertiesError.INVALID_VALUE: (+ "Invalid custom property value",+ status.HTTP_400_BAD_REQUEST,+ ),+ contracts.ExternalAccountCustomPropertiesError.CONFLICT: (+ "A concurrent write set this property — retry",+ status.HTTP_409_CONFLICT,+ ),+ contracts.ExternalAccountCustomPropertiesError.UPDATE_FAILED: (+ "Failed to update custom properties",+ status.HTTP_500_INTERNAL_SERVER_ERROR,+ ),+ contracts.ExternalAccountCustomPropertiesError.SOURCE_MANAGED: (+ "This custom property is managed by a data warehouse source and can't be set manually",+ status.HTTP_400_BAD_REQUEST,+ ),+}+++def _custom_properties_error_response(result: contracts.ExternalAccountCustomPropertiesResult) -> Response:+ assert result.error is not None+ message, code = _CUSTOM_PROPERTIES_ERROR_RESPONSES[result.error]+ if result.error_field:+ message = f"{result.error_field}: {message}"+ return Response({"error": message}, status=code)+++def handle_account_get(team: Team, external_id: str) -> Response:+ account = facade.get_external_account(team.id, external_id)+ if account is None:+ return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)++ return Response(_external_account_body(account))+++def handle_account_create(request: Request, team: Team) -> Response:+ serializer = ExternalAccountCreateSerializer(data=request.data)+ if not serializer.is_valid():+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)+ data = serializer.validated_data++ external_id = data["external_id"].strip()+ if not external_id:+ return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)++ try:+ account, created = facade.create_external_account(+ team,+ external_id=external_id,+ workflow_id=_workflow_id_from_request(request),+ )+ except facade.AccountConflictError:+ # Lost a concurrent-create race; the account exists now, so honor no-op semantics.+ existing = facade.get_external_account(team.id, external_id)+ if existing is None:+ return Response({"error": "Failed to create account"}, status=status.HTTP_400_BAD_REQUEST)+ account, created = existing, False++ return Response(+ _external_account_body(account),+ status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,+ )+++def handle_account_update(request: Request, team: Team) -> Response:+ serializer = ExternalAccountUpdateSerializer(data=request.data)+ if not serializer.is_valid():+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)+ data = serializer.validated_data++ external_id = data["external_id"].strip()+ if not external_id:+ return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)++ result = facade.update_external_account(+ team.id,+ external_id,+ relationship_assignments=data.get("relationships") or {},+ tags=data["tags"] if "tags" in data else None,+ tags_mode=data.get("tags_mode", "add"),+ churned_at=data.get("churned_at"),+ churned_at_provided="churned_at" in data,+ workflow_id=_workflow_id_from_request(request),+ )+ if result.account is None:+ return _update_error_response(result)++ return Response(_external_account_body(result.account))+++def handle_account_set_properties(request: Request, team: Team) -> Response:+ serializer = ExternalAccountCustomPropertiesSerializer(data=request.data)+ if not serializer.is_valid():+ return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)+ data = serializer.validated_data++ external_id = data["external_id"].strip()+ if not external_id:+ return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)++ result = facade.set_external_account_custom_properties(+ team.id, external_id, properties=data["properties"], workflow_id=_workflow_id_from_request(request)+ )+ if result.values is None:+ return _custom_properties_error_response(result)++ # Hand-built payload, deliberately: neither wrapping route is in the OpenAPI spec (plain+ # APIViews without scope_object), so the schema-drift risk behind the rule cannot occur,+ # and the wire shape must stay identical while the worker migrates between the routes.+ return Response( # nosemgrep: api-response-must-match-schema+ {+ "external_id": external_id,+ "values": [{"definition_id": str(v.definition_id), "value": v.value} for v in result.values],+ }+ )diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.pyindex 78acef433b94..3592a898be1f 100644--- a/products/customer_analytics/backend/presentation/views/external.py+++ b/products/customer_analytics/backend/presentation/views/external.py@@ -21,7 +21,6 @@ transactional write, org-membership resolution, tag application, and exceptioncapture live behind ``facade.api``."""-import uuidimport hashlibfrom typing import Any, castfrom uuid import UUID@@ -32,7 +31,7 @@ from django.http import HttpRequestimport structlogimport posthoganalyticsfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializers, statusfrom rest_framework.permissions import AllowAnyfrom rest_framework.request import Request@@ -46,11 +45,17 @@ from posthog.models import Teamfrom posthog.permissions import get_authenticator_scopes, is_authenticated_via_project_secret_api_keyfrom posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle-from products.customer_analytics.backend.facade import (- api as facade,- contracts,-)+from products.customer_analytics.backend.facade import api as facadefrom products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_CSP_FLAG+from products.customer_analytics.backend.presentation.views.account_actions import (+ ACCOUNT_ACTION_AUTH_COUNTER,+ ExternalAccountCreateSerializer,+ ExternalAccountCustomPropertiesSerializer,+ handle_account_create,+ handle_account_get,+ handle_account_set_properties,+ handle_account_update,+)logger = structlog.get_logger(__name__)@@ -119,25 +124,6 @@ class ExternalAccountListAuthentication(ProjectSecretAPIKeyAuthentication):return result-HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"---def _workflow_id_from_request(request: Request) -> str | None:- """The originating HogFlow workflow id, when the request comes from a workflow step.-- The header is caller-supplied, so only a well-formed UUID is accepted; worst case is a- token holder attributing a write to another workflow id within its own team.- """- hog_flow_id = request.headers.get(HOG_FLOW_ID_HEADER)- if not hog_flow_id:- return None- try:- uuid.UUID(hog_flow_id)- except (ValueError, TypeError):- return None- return hog_flow_id--def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:"""Extract Bearer token from Authorization header and validate against a team."""auth_header = request.headers.get("Authorization", "")@@ -185,108 +171,6 @@ def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None,return psak.team, None-def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]:- return {- "id": account.id,- "external_id": account.external_id,- "name": account.name,- "churned_at": account.churned_at,- "ignored_at": account.ignored_at,- "properties": account.properties,- "tags": account.tags,- "relationships": account.relationships,- "custom_properties": account.custom_properties,- }---_UPDATE_ERROR_RESPONSES = {- contracts.ExternalAccountUpdateError.NOT_FOUND: ("Account not found", status.HTTP_404_NOT_FOUND),- contracts.ExternalAccountUpdateError.INVALID_PROPERTIES: (- "Invalid account properties",- status.HTTP_400_BAD_REQUEST,- ),- contracts.ExternalAccountUpdateError.UPDATE_FAILED: ("Failed to update account", status.HTTP_400_BAD_REQUEST),-}---def _update_error_response(result: contracts.ExternalAccountUpdateResult) -> Response:- if result.error == contracts.ExternalAccountUpdateError.USER_NOT_IN_ORGANIZATION:- return Response(- {"error": f"{result.error_field}: user is not a member of this organization"},- status=status.HTTP_400_BAD_REQUEST,- )- if result.error == contracts.ExternalAccountUpdateError.RELATIONSHIP_DEFINITION_NOT_FOUND:- return Response(- {"error": f"{result.error_field}: no relationship definition with this ID"},- status=status.HTTP_400_BAD_REQUEST,- )- assert result.error is not None- message, code = _UPDATE_ERROR_RESPONSES[result.error]- return Response({"error": message}, status=code)---class ExternalAccountUpdateSerializer(serializers.Serializer):- external_id = serializers.CharField(max_length=400, help_text="External ID (group key) of the account to update.")- # Each value accepts a `posthog_assignee` object `{type, id}`, or `null` to end the- # active assignment. Roles (RBAC) are rejected — accounts assign users only.- # `validate` normalizes a provided assignment down to the user id; the facade resolves- # it against an org membership so assignees are always trusted.- relationships = serializers.DictField(- child=serializers.JSONField(allow_null=True),- required=False,- help_text=(- "Relationship assignments keyed by definition UUID. Each value is an assignee object "- "`{type: 'user', id}` or null to end the active assignment. Only the supplied "- "definitions are changed."- ),- )- tags = serializers.ListField(- child=serializers.CharField(max_length=200),- required=False,- max_length=100,- help_text="Tag names to apply, per tags_mode.",- )- tags_mode = serializers.ChoiceField(- choices=["add", "set", "remove"],- required=False,- default="add",- help_text="How to apply tags: add to, replace, or remove from the existing set.",- )- churned_at = serializers.DateTimeField(- required=False,- allow_null=True,- help_text="When the account churned. Set to null to mark it as active again.",- )-- def validate_relationships(self, value: dict[str, Any]) -> dict[str, int | None]:- return {name: self._normalize_assignee(name, assignee) for name, assignee in value.items()}-- def _normalize_assignee(self, field: str, value: Any) -> int | None:- if value is None:- return None- if not isinstance(value, dict):- raise serializers.ValidationError({field: "Must be an assignee object or null"})- if value.get("type") != "user":- raise serializers.ValidationError({field: "Accounts can only be assigned to users, not roles"})- raw_id = value.get("id")- if not isinstance(raw_id, (int, str)):- raise serializers.ValidationError({field: "Assignee id must be a user id"})- try:- return int(raw_id)- except (TypeError, ValueError):- raise serializers.ValidationError({field: "Assignee id must be a user id"})---class ExternalAccountCreateSerializer(serializers.Serializer):- external_id = serializers.CharField(- max_length=400,- help_text=(- "External ID (group key) for the account. An account with this ID already existing is a no-op. "- "The account name is derived from the matching group's `name` property, falling back to this ID."- ),- )--class ExternalAccountAssignmentSerializer(serializers.Serializer):user_id = serializers.IntegerField(help_text="PostHog user id of the assigned user.")email = serializers.CharField(help_text="Email address of the assigned user.")@@ -349,16 +233,13 @@ class ExternalAccountView(APIView):return errorassert team is not None+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method="get").inc()external_id = request.query_params.get("external_id", "").strip()if not external_id:return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)- account = facade.get_external_account(team.id, external_id)- if account is None:- return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)-- return Response(_external_account_body(account))+ return handle_account_get(team, external_id)@extend_schema(request=ExternalAccountCreateSerializer,@@ -379,33 +260,8 @@ class ExternalAccountView(APIView):return errorassert team is not None-- serializer = ExternalAccountCreateSerializer(data=request.data)- if not serializer.is_valid():- return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)- data = serializer.validated_data-- external_id = data["external_id"].strip()- if not external_id:- return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)-- try:- account, created = facade.create_external_account(- team,- external_id=external_id,- workflow_id=_workflow_id_from_request(request),- )- except facade.AccountConflictError:- # Lost a concurrent-create race; the account exists now, so honor no-op semantics.- existing = facade.get_external_account(team.id, external_id)- if existing is None:- return Response({"error": "Failed to create account"}, status=status.HTTP_400_BAD_REQUEST)- account, created = existing, False-- return Response(- _external_account_body(account),- status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,- )+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method="post").inc()+ return handle_account_create(request, team)def patch(self, request: Request) -> Response:team, error = _authenticate_team(request)@@ -413,30 +269,8 @@ class ExternalAccountView(APIView):return errorassert team is not None-- serializer = ExternalAccountUpdateSerializer(data=request.data)- if not serializer.is_valid():- return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)- data = serializer.validated_data-- external_id = data["external_id"].strip()- if not external_id:- return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)-- result = facade.update_external_account(- team.id,- external_id,- relationship_assignments=data.get("relationships") or {},- tags=data["tags"] if "tags" in data else None,- tags_mode=data.get("tags_mode", "add"),- churned_at=data.get("churned_at"),- churned_at_provided="churned_at" in data,- workflow_id=_workflow_id_from_request(request),- )- if result.account is None:- return _update_error_response(result)-- return Response(_external_account_body(result.account))+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method="patch").inc()+ return handle_account_update(request, team)class ExternalAccountListQuerySerializer(serializers.Serializer):@@ -596,64 +430,6 @@ class ExternalAccountListView(APIView):return Response(ExternalAccountListPageSerializer(page).data)-@extend_schema_field({"oneOf": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}]})-class _CustomPropertyScalarField(serializers.Field):- """A custom property value sent over the external API — a JSON scalar.-- Objects, arrays, and null are rejected here; the concrete type each property accepts is set by- its definition and validated server-side when the value is coerced.- """-- def to_internal_value(self, data: Any) -> Any:- if data is None or isinstance(data, dict | list):- raise serializers.ValidationError("Value must be a string, number, or boolean.")- return data---class ExternalAccountCustomPropertiesSerializer(serializers.Serializer):- external_id = serializers.CharField(- max_length=400,- help_text="External ID of the account whose custom property values to set — the group key it is linked to.",- )- properties = serializers.DictField(- child=_CustomPropertyScalarField(),- help_text="Map of custom property definition UUID to the value to set for this account.",- )---_CUSTOM_PROPERTIES_ERROR_RESPONSES = {- contracts.ExternalAccountCustomPropertiesError.ACCOUNT_NOT_FOUND: ("Account not found", status.HTTP_404_NOT_FOUND),- contracts.ExternalAccountCustomPropertiesError.DEFINITION_NOT_FOUND: (- "Custom property definition not found",- status.HTTP_400_BAD_REQUEST,- ),- contracts.ExternalAccountCustomPropertiesError.INVALID_VALUE: (- "Invalid custom property value",- status.HTTP_400_BAD_REQUEST,- ),- contracts.ExternalAccountCustomPropertiesError.CONFLICT: (- "A concurrent write set this property — retry",- status.HTTP_409_CONFLICT,- ),- contracts.ExternalAccountCustomPropertiesError.UPDATE_FAILED: (- "Failed to update custom properties",- status.HTTP_500_INTERNAL_SERVER_ERROR,- ),- contracts.ExternalAccountCustomPropertiesError.SOURCE_MANAGED: (- "This custom property is managed by a data warehouse source and can't be set manually",- status.HTTP_400_BAD_REQUEST,- ),-}---def _custom_properties_error_response(result: contracts.ExternalAccountCustomPropertiesResult) -> Response:- assert result.error is not None- message, code = _CUSTOM_PROPERTIES_ERROR_RESPONSES[result.error]- if result.error_field:- message = f"{result.error_field}: {message}"- return Response({"error": message}, status=code)--class ExternalAccountCustomPropertiesView(APIView):"""PATCH /api/customer_analytics/external/account/custom_property_values — Set an account's custom@@ -673,25 +449,5 @@ class ExternalAccountCustomPropertiesView(APIView):return errorassert team is not None-- serializer = ExternalAccountCustomPropertiesSerializer(data=request.data)- if not serializer.is_valid():- return Response({"error": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)- data = serializer.validated_data-- external_id = data["external_id"].strip()- if not external_id:- return Response({"error": "external_id is required"}, status=status.HTTP_400_BAD_REQUEST)-- result = facade.set_external_account_custom_properties(- team.id, external_id, properties=data["properties"], workflow_id=_workflow_id_from_request(request)- )- if result.values is None:- return _custom_properties_error_response(result)-- return Response(- {- "external_id": external_id,- "values": [{"definition_id": str(v.definition_id), "value": v.value} for v in result.values],- }- )+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="secret_api_token", http_method="patch").inc()+ return handle_account_set_properties(request, team)diff --git a/products/customer_analytics/backend/presentation/views/internal.py b/products/customer_analytics/backend/presentation/views/internal.pynew file mode 100644index 000000000000..2c8f466adcaa--- /dev/null+++ b/products/customer_analytics/backend/presentation/views/internal.py@@ -0,0 +1,138 @@+"""+Internal account endpoints for the Customer analytics product.++The service-to-service surface the CDP worker's account workflow actions call. Callers+authenticate with a short-lived scoped service JWT pinned to one team and one account+external_id (#82564 tracks retiring the legacy secret_api_token routes in external.py).+Mounted under /api/projects/<team_id>/internal/ in posthog/urls.py, a namespace Contour+ingress does not expose, so the routes are unreachable from the public internet.+"""++from typing import Any, cast++from rest_framework import status+from rest_framework.permissions import IsAuthenticated+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.views import APIView++from posthog.auth import ScopedServiceJWTAuthentication+from posthog.jwt import PosthogJwtAudience+from posthog.models import Team+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose++from products.customer_analytics.backend.presentation.views.account_actions import (+ ACCOUNT_ACTION_AUTH_COUNTER,+ handle_account_create,+ handle_account_get,+ handle_account_set_properties,+ handle_account_update,+)+from products.customer_analytics.backend.presentation.views.external import _customer_analytics_enabled++CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.CUSTOMER_ANALYTICS_ACCOUNTS,+ settings_name="CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS",+)+++class CustomerAnalyticsAccountJWTAuthentication(ScopedServiceJWTAuthentication):+ purpose = CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE+++class InternalAccountView(APIView):+ """+ GET /api/projects/<team_id>/internal/customer_analytics/account?external_id=<id> — Fetch account data+ POST /api/projects/<team_id>/internal/customer_analytics/account — Create an account (no-op if it exists)+ PATCH /api/projects/<team_id>/internal/customer_analytics/account — Update relationships, tags, churn state++ JWT-only from birth: there is no legacy-token fallback here, so these routes never+ accept secret_api_token. The auth class binds the request to the token's team and+ rejects tokens whose team differs from the URL's.+ """++ authentication_classes = [CustomerAnalyticsAccountJWTAuthentication]+ permission_classes = [IsAuthenticated]++ def get(self, request: Request, team_id: str) -> Response:+ external_id = request.query_params.get("external_id", "").strip()+ team, error = _check_account_access(request, external_id)+ if error:+ return error+ assert team is not None+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="get").inc()+ return handle_account_get(team, external_id)++ def post(self, request: Request, team_id: str) -> Response:+ team, error = _check_account_access(request, _external_id_from_body(request))+ if error:+ return error+ assert team is not None+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="post").inc()+ return handle_account_create(request, team)++ def patch(self, request: Request, team_id: str) -> Response:+ team, error = _check_account_access(request, _external_id_from_body(request))+ if error:+ return error+ assert team is not None+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="patch").inc()+ return handle_account_update(request, team)+++class InternalAccountCustomPropertiesView(APIView):+ """+ PATCH /api/projects/<team_id>/internal/customer_analytics/account/custom_property_values — Set an+ account's custom property values. Same auth model as InternalAccountView.+ """++ authentication_classes = [CustomerAnalyticsAccountJWTAuthentication]+ permission_classes = [IsAuthenticated]++ def patch(self, request: Request, team_id: str) -> Response:+ team, error = _check_account_access(request, _external_id_from_body(request))+ if error:+ return error+ assert team is not None+ ACCOUNT_ACTION_AUTH_COUNTER.labels(auth_method="scoped_jwt", http_method="patch").inc()+ return handle_account_set_properties(request, team)+++def _external_id_from_body(request: Request) -> str:+ external_id = request.data.get("external_id") if isinstance(request.data, dict) else None+ return external_id.strip() if isinstance(external_id, str) else ""+++def _check_account_access(request: Request, external_id: str) -> tuple[Team, None] | tuple[None, Response]:+ """Enforce the per-entity claim and the product gate after JWT authentication.++ The worker mints each token for one specific account external_id (create pins the id+ being created), so a token replayed with a different external_id is refused even within+ its own team. Missing claim or empty request id fails closed.+ """+ claims = cast(dict[str, Any], request.auth or {})+ # No str() on the claim: a missing claim would stringify to "None" and match an account+ # literally named "None" — only a real string passes, keeping an absent claim failing+ # closed. Stripped to mirror the request-side normalization, so a padded id behaves the+ # same here as on the legacy route.+ claim_external_id = claims.get("external_id")+ if not isinstance(claim_external_id, str):+ claim_external_id = None+ if not external_id or claim_external_id is None or claim_external_id.strip() != external_id:+ return None, Response(+ {"error": "Service token does not grant access to this account"}, status=status.HTTP_403_FORBIDDEN+ )++ # The auth class already verified the team claim exists, matches the URL, and names a real+ # team; fetch the full row because the handlers need organization access for assignments.+ # The team can still vanish between the two reads, so a clean 404 beats an unhandled 500.+ try:+ team = Team.objects.get(id=claims["team_id"])+ except Team.DoesNotExist:+ return None, Response({"error": "Team not found"}, status=status.HTTP_404_NOT_FOUND)+ if not _customer_analytics_enabled(team):+ return None, Response(+ {"error": "Customer analytics is not enabled for this team"}, status=status.HTTP_403_FORBIDDEN+ )++ return team, Nonediff --git a/products/customer_analytics/backend/test/test_external.py b/products/customer_analytics/backend/test/test_external.pyindex 01cb6ee465d9..7170a6848612 100644--- a/products/customer_analytics/backend/test/test_external.py+++ b/products/customer_analytics/backend/test/test_external.py@@ -318,7 +318,7 @@ class TestExternalAccountAPI(APIBaseTest):"tags": ["enterprise"],})- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)self.assertEqual(self._active_csm_user_ids(), [])def test_patch_cannot_change_external_id_or_name(self):diff --git a/products/customer_analytics/backend/test/test_internal.py b/products/customer_analytics/backend/test/test_internal.pynew file mode 100644index 000000000000..9a2d05e6d905--- /dev/null+++ b/products/customer_analytics/backend/test/test_internal.py@@ -0,0 +1,190 @@+from datetime import timedelta++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized+from prometheus_client import REGISTRY+from rest_framework import status+from rest_framework.test import APIClient++from posthog.jwt import PosthogJwtAudience+from posthog.models.utils import generate_random_token_secret+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose++from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.models import CustomPropertyValue+from products.customer_analytics.backend.presentation.views.internal import CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition++# Signed with this route's key but carrying another surface's audience — a token minted for a+# different purpose must never authenticate here even when the signing key checks out.+OTHER_AUDIENCE_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.CONVERSATIONS_TICKETS,+ settings_name="CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS",+)+++class TestInternalAccountAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.secret_api_token = generate_random_token_secret()+ self.team.save(update_fields=["secret_api_token"])+ self.client = APIClient()+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ self.url = f"/api/projects/{self.team.id}/internal/customer_analytics/account"+ csp_enabled = patch(+ "products.customer_analytics.backend.presentation.views.external.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.mock_csp_enabled = csp_enabled.start()+ self.addCleanup(csp_enabled.stop)++ def _claims(self, external_id: str = "acme-1") -> dict:+ return {"team_id": self.team.id, "external_id": external_id}++ def _headers(self, claims: dict | None = None) -> dict:+ return self._bearer(CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE.mint(claims if claims is not None else self._claims()))++ @staticmethod+ def _bearer(token: str) -> dict:+ return {"HTTP_AUTHORIZATION": f"Bearer {token}"}++ def test_get_returns_account_for_minted_token(self):+ response = self.client.get(self.url, data={"external_id": "acme-1"}, **self._headers())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["external_id"], "acme-1")++ def test_post_creates_account_pinned_to_the_claim(self):+ response = self.client.post(+ self.url,+ {"external_id": "acme-new"},+ format="json",+ **self._headers(self._claims("acme-new")),+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["external_id"], "acme-new")++ def test_patch_updates_account(self):+ response = self.client.patch(+ self.url,+ {"external_id": "acme-1", "tags": ["vip"]},+ format="json",+ **self._headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["tags"], ["vip"])++ def test_patch_sets_custom_property_values(self):+ definition = create_custom_property_definition(team_id=self.team.id, name="Tier")+ response = self.client.patch(+ f"{self.url}/custom_property_values",+ {"external_id": "acme-1", "properties": {str(definition.id): "gold"}},+ format="json",+ **self._headers(),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ values = CustomPropertyValue.objects.for_team(self.team.id).filter(account=self.account, is_deleted=False)+ self.assertEqual([v.value_str for v in values], ["gold"])++ @parameterized.expand(+ [+ (+ "token_for_another_team",+ lambda self: self._headers({"team_id": self.team.id + 1, "external_id": "acme-1"}),+ status.HTTP_401_UNAUTHORIZED,+ ),+ (+ "legacy_secret_api_token",+ lambda self: {"HTTP_AUTHORIZATION": f"Bearer {self.team.secret_api_token}"},+ status.HTTP_401_UNAUTHORIZED,+ ),+ (+ "expired_token",+ lambda self: self._bearer(+ CUSTOMER_ANALYTICS_ACCOUNTS_PURPOSE.mint(self._claims(), ttl=timedelta(minutes=-1))+ ),+ status.HTTP_401_UNAUTHORIZED,+ ),+ (+ "token_for_another_purpose",+ lambda self: self._bearer(OTHER_AUDIENCE_PURPOSE.mint(self._claims())),+ status.HTTP_401_UNAUTHORIZED,+ ),+ (+ "missing_external_id_claim",+ lambda self: self._headers({"team_id": self.team.id}),+ status.HTTP_403_FORBIDDEN,+ ),+ (+ "token_for_another_account",+ lambda self: self._headers(self._claims("someone-else")),+ status.HTTP_403_FORBIDDEN,+ ),+ ("no_credentials", lambda self: {}, status.HTTP_401_UNAUTHORIZED),+ ]+ )+ def test_rejected_credentials(self, _name, make_headers, expected_status):+ headers = make_headers(self)+ get_response = self.client.get(self.url, data={"external_id": "acme-1"}, **headers)+ self.assertEqual(get_response.status_code, expected_status)+ patch_response = self.client.patch(+ self.url, {"external_id": "acme-1", "tags": ["vip"]}, format="json", **headers+ )+ self.assertEqual(patch_response.status_code, expected_status)+ self.assertEqual(self.account.tagged_items.count(), 0)++ def test_missing_claim_does_not_match_an_account_named_none(self):+ # A missing claim stringified would read "None"; it must never authorize an account+ # whose external_id is literally that.+ create_account(team_id=self.team.id, name="Edge", external_id="None")+ response = self.client.get(self.url, data={"external_id": "None"}, **self._headers({"team_id": self.team.id}))+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_whitespace_padded_claim_matches_like_the_legacy_route(self):+ # The request id is stripped before comparison; the claim must be stripped the same+ # way or a padded id would 403 here while succeeding on the legacy route.+ response = self.client.get(+ self.url,+ data={"external_id": " acme-1 "},+ **self._headers({"team_id": self.team.id, "external_id": " acme-1 "}),+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_unexpected_update_failure_returns_500(self):+ # UPDATE_FAILED only comes from the facade's blanket except (server fault); a 400+ # would stop the CDP fetch layer from retrying a transient database error.+ failed = contracts.ExternalAccountUpdateResult(error=contracts.ExternalAccountUpdateError.UPDATE_FAILED)+ with patch(+ "products.customer_analytics.backend.presentation.views.account_actions.facade.update_external_account",+ return_value=failed,+ ):+ response = self.client.patch(+ self.url, {"external_id": "acme-1", "tags": ["vip"]}, format="json", **self._headers()+ )+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)++ def test_request_external_id_must_match_the_claim(self):+ # A token pinned to one account must not read or write another, even in the same team.+ response = self.client.get(self.url, data={"external_id": "someone-else"}, **self._headers())+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_unprovisioned_secret_rejects_even_a_well_formed_token(self):+ headers = self._headers()+ with override_settings(CUSTOMER_ANALYTICS_ACCOUNTS_JWT_SECRETS=[]):+ response = self.client.get(self.url, data={"external_id": "acme-1"}, **headers)+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_customer_analytics_disabled_is_rejected(self):+ self.mock_csp_enabled.return_value = False+ response = self.client.get(self.url, data={"external_id": "acme-1"}, **self._headers())+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_authenticated_get_increments_the_scoped_jwt_counter(self):+ labels = {"auth_method": "scoped_jwt", "http_method": "get"}+ before = REGISTRY.get_sample_value("posthog_customer_analytics_account_action_auth_total", labels) or 0+ self.client.get(self.url, data={"external_id": "acme-1"}, **self._headers())+ after = REGISTRY.get_sample_value("posthog_customer_analytics_account_action_auth_total", labels)+ self.assertEqual(after, before + 1)