: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(workflows): Add Get account customer analytics workflow action (#63835)
Arthur Moreira de Deus041bbc70751b
diff --git a/nodejs/src/cdp/async-functions/customer_analytics.ts b/nodejs/src/cdp/async-functions/customer_analytics.tsnew file mode 100644index 000000000000..3e0703f0f4f9--- /dev/null+++ b/nodejs/src/cdp/async-functions/customer_analytics.ts@@ -0,0 +1,67 @@+import { DateTime } from 'luxon'++import { CyclotronInvocationQueueParametersFetchSchema } from '~/schema/cyclotron'++import { registerAsyncFunction } from '../async-function-registry'++registerAsyncFunction('postHogGetAccount', {+ execute: async (args, context, result) => {+ const [opts] = args as [Record<string, any> | undefined]+ const externalId = opts?.external_id++ if (!externalId || typeof externalId !== 'string') {+ throw new Error("[HogFunction] - postHogGetAccount call missing 'external_id' property")+ }++ const team = await context.teamManager.getTeam(context.invocation.teamId)+ if (!team) {+ throw new Error(`Team ${context.invocation.teamId} not found`)+ }+ if (!team.secret_api_token) {+ throw new Error(`Team ${context.invocation.teamId} has no secret API token configured`)+ }++ result.invocation.queueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({+ type: 'fetch',+ url: `${context.siteUrl}/api/customer_analytics/external/account?external_id=${encodeURIComponent(+ externalId+ )}`,+ method: 'GET',+ headers: { Authorization: `Bearer ${team.secret_api_token}` },+ })+ },++ mock: (args, logs) => {+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `Async function 'postHogGetAccount' was mocked with arguments:`,+ })+ logs.push({+ level: 'info',+ timestamp: DateTime.now(),+ message: `postHogGetAccount(${JSON.stringify(args[0], null, 2)})`,+ })++ return {+ status: 200,+ body: {+ id: 'mock-account-id',+ external_id: args[0]?.external_id ?? 'mock-external-id',+ name: 'Mock Account',+ properties: {+ csm: null,+ account_executive: null,+ account_owner: null,+ stripe_customer_id: null,+ hubspot_deal_id: null,+ billing_id: null,+ sfdc_id: null,+ zendesk_id: null,+ slack_channel_id: null,+ usage_dashboard_link: null,+ },+ },+ }+ },+})diff --git a/nodejs/src/cdp/async-functions/index.ts b/nodejs/src/cdp/async-functions/index.tsindex 3fb1ab5bfd8d..99ebba277d03 100644--- a/nodejs/src/cdp/async-functions/index.ts+++ b/nodejs/src/cdp/async-functions/index.ts@@ -1,4 +1,5 @@import './conversations'+import './customer_analytics'import './fetch-handler'import './send-email'import './warehouse-webhooks'diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.tsindex e28683e15a4d..8aa7428a3782 100644--- a/nodejs/src/cdp/services/hog-executor.service.test.ts+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts@@ -916,6 +916,83 @@ describe('Hog Executor', () => {})})+ describe('postHogGetAccount', () => {+ const mockExecHogForAsyncFunction = (asyncFunctionName: string, asyncFunctionArgs: any[]) => {+ const hogExecModule = require('../utils/hog-exec')+ jest.spyOn(hogExecModule, 'execHog').mockResolvedValue({+ execResult: {+ finished: false,+ asyncFunctionName,+ asyncFunctionArgs,+ state: { syncDuration: 1, maxMemUsed: 100, ops: 10, stack: [] },+ },+ error: undefined,+ durationMs: 1,+ })+ }++ const createAccountInvocation = () =>+ createExampleInvocation(+ createHogFunction({+ ...HOG_EXAMPLES.simple_fetch,+ ...HOG_INPUTS_EXAMPLES.simple_fetch,+ ...HOG_FILTERS_EXAMPLES.no_filters,+ }),+ { inputs: {} }+ )++ it('postHogGetAccount queues internal fetch with the external_id query param', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)++ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme corp/1' }])++ const result = await executor.execute(createAccountInvocation())++ expect(result.invocation.queueParameters).toEqual({+ type: 'fetch',+ url: `${hub.SITE_URL}/api/customer_analytics/external/account?external_id=acme%20corp%2F1`,+ method: 'GET',+ headers: { Authorization: 'Bearer test-secret-token' },+ })+ })++ it('postHogGetAccount errors when external_id is missing', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: 'test-secret-token',+ } as any)++ mockExecHogForAsyncFunction('postHogGetAccount', [{}])++ const result = await executor.execute(createAccountInvocation())+ expect(result.error).toContain("missing 'external_id'")+ })++ it('postHogGetAccount errors when team is not found', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue(null)++ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])++ const result = await executor.execute(createAccountInvocation())+ expect(result.error).toContain('Team 1 not found')+ })++ it('postHogGetAccount errors when the team has no secret API token', async () => {+ jest.spyOn(hub.teamManager, 'getTeam').mockResolvedValue({+ id: 1,+ secret_api_token: null,+ } as any)++ mockExecHogForAsyncFunction('postHogGetAccount', [{ external_id: 'acme-1' }])++ const result = await executor.execute(createAccountInvocation())+ expect(result.error).toContain('has no secret API token configured')+ })+ })+describe('produceToWarehouseWebhooks', () => {const buildInvocation = async (code: string): Promise<CyclotronJobInvocationHogFunction> => {const bytecode = await compileHog(code)diff --git a/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.tsnew file mode 100644index 000000000000..bc1d83f92205--- /dev/null+++ b/nodejs/src/cdp/templates/_destinations/posthog_customer_analytics/posthog-get-account.template.ts@@ -0,0 +1,41 @@+import { HogFunctionTemplate } from '~/cdp/types'++export const template: HogFunctionTemplate = {+ free: true,+ status: 'hidden',+ type: 'destination',+ id: 'template-posthog-get-account',+ name: 'Get account',+ description: 'Fetch a Customer analytics account into a workflow variable.',+ icon_url: '/static/posthog-icon.svg',+ category: ['Custom'],+ code_language: 'hog',+ code: `+if (empty(inputs.external_id)) {+ throw Error('Account external ID is required')+}++let response := postHogGetAccount({'external_id': inputs.external_id})++if (response.status == 404) {+ throw Error(f'Account not found: {inputs.external_id}')+}++if (response.status != 200) {+ throw Error(f'Failed to fetch account: {response.status}')+}++return response.body+`,+ inputs_schema: [+ {+ key: 'external_id',+ type: 'string',+ label: 'Account external ID',+ secret: false,+ required: true,+ description:+ 'The external ID of the account to fetch — the group key the account is linked to. Available from trigger event or group properties.',+ },+ ],+}diff --git a/nodejs/src/cdp/templates/index.ts b/nodejs/src/cdp/templates/index.tsindex 11222ebaf499..3043c318baef 100644--- a/nodejs/src/cdp/templates/index.ts+++ b/nodejs/src/cdp/templates/index.ts@@ -21,6 +21,7 @@ import { template as posthogGroupIdentifyTemplate } from './_destinations/posthoimport { template as posthogUpdatePersonPropertiesTemplate } from './_destinations/posthog_capture/posthog-update-person-properties.template'import { template as posthogGetTicketTemplate } from './_destinations/posthog_conversations/posthog-get-ticket.template'import { template as posthogUpdateTicketTemplate } from './_destinations/posthog_conversations/posthog-update-ticket.template'+import { template as posthogGetAccountTemplate } from './_destinations/posthog_customer_analytics/posthog-get-account.template'import { template as posthogSetHogflowVariableTemplate } from './_destinations/posthog_workflows/posthog-set-variable.template'import { template as redditAdsTemplate } from './_destinations/reddit_ads/reddit.template'import { template as snapchatAdsTemplate } from './_destinations/snapchat_ads/snapchat.template'@@ -70,6 +71,7 @@ export const HOG_FUNCTION_TEMPLATES_DESTINATIONS: HogFunctionTemplate[] = [posthogSetHogflowVariableTemplate,posthogGetTicketTemplate,posthogUpdateTicketTemplate,+ posthogGetAccountTemplate,hubspotCompanyTemplate,accoilTemplate,klimeTemplate,diff --git a/posthog/cdp/validation.py b/posthog/cdp/validation.pyindex 6d704cd5578e..bbf62c59ad4d 100644--- a/posthog/cdp/validation.py+++ b/posthog/cdp/validation.py@@ -37,6 +37,7 @@ def register_supported_function(name: str) -> None:register_supported_function("postHogGetTicket")register_supported_function("postHogUpdateTicket")+register_supported_function("postHogGetAccount")# Globals that the realtime transformer actually populates at runtime.diff --git a/posthog/urls.py b/posthog/urls.pyindex d6d5e3e6698a..335d7dd94504 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -279,6 +279,7 @@ urlpatterns = [),path("api/sdk_health/", sdk_health),path("api/conversations/", include("products.conversations.backend.api.urls")),+ path("api/customer_analytics/", include("products.customer_analytics.backend.api.urls")),path("api/environments/<int:parent_lookup_team_id>/mcp_analytics/",include("products.mcp_analytics.backend.presentation.urls"),diff --git a/products/customer_analytics/backend/api/external.py b/products/customer_analytics/backend/api/external.pynew file mode 100644index 000000000000..e70245a261fb--- /dev/null+++ b/products/customer_analytics/backend/api/external.py@@ -0,0 +1,130 @@+"""+External API endpoints for the Customer analytics product.++These endpoints are used by the CDP worker for workflow actions. Authenticated+via the team secret API token passed as a Bearer token in the Authorization header.+"""++import hashlib+from typing import Any++from django.db.models import Q++import structlog+import posthoganalytics+from rest_framework import status+from rest_framework.permissions import AllowAny+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.throttling import SimpleRateThrottle+from rest_framework.views import APIView++from posthog.models import Team++from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAG+from products.customer_analytics.backend.models import Account++logger = structlog.get_logger(__name__)+++class _ExternalAccountThrottle(SimpleRateThrottle):+ """Rate limit by Bearer token (team secret_api_token)."""++ def get_cache_key(self, request: Request, view: APIView) -> str:+ auth_header = request.headers.get("Authorization", "")+ token = auth_header[7:].strip() if auth_header.startswith("Bearer ") else ""+ ident = hashlib.sha256(token.encode()).hexdigest() if token else self.get_ident(request)+ return self.cache_format % {"scope": self.scope, "ident": ident}+++class ExternalAccountBurstThrottle(_ExternalAccountThrottle):+ scope = "external_account_burst"+ rate = "60/minute"+++class ExternalAccountSustainedThrottle(_ExternalAccountThrottle):+ scope = "external_account_sustained"+ rate = "600/hour"+++def _customer_analytics_enabled(team: Team) -> bool:+ organization_id = str(team.organization_id)+ return bool(+ posthoganalytics.feature_enabled(+ CUSTOMER_ANALYTICS_CSP_FLAG,+ organization_id,+ groups={"organization": organization_id},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ )+++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", "")+ if not auth_header.startswith("Bearer "):+ return None, Response({"error": "Missing or invalid Authorization header"}, status=status.HTTP_401_UNAUTHORIZED)++ api_key = auth_header[7:].strip()+ if not api_key:+ return None, Response({"error": "Empty API key"}, status=status.HTTP_401_UNAUTHORIZED)++ # Authenticate against secret_api_token (not api_token) because api_token+ # is the public project key embedded in client-side JS and visible to anyone.+ try:+ team = Team.objects.get(Q(secret_api_token=api_key) | Q(secret_api_token_backup=api_key))+ except (Team.DoesNotExist, Team.MultipleObjectsReturned):+ return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)++ # Same 401 as an unknown token: a valid secret token for a team without customer+ # analytics enabled must not be usable to read account data.+ if not _customer_analytics_enabled(team):+ return None, Response({"error": "Invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)++ return team, None+++def _serialize_account(account: Account) -> dict[str, Any]:+ return {+ "id": str(account.id),+ "external_id": account.external_id,+ "name": account.name,+ "properties": account.properties.model_dump(mode="json"),+ }+++def _get_account_by_external_id(team: Team, external_id: str) -> Account | None:+ try:+ return Account.objects.for_team(team.id).get(external_id=external_id)+ except Account.DoesNotExist:+ return None+++class ExternalAccountView(APIView):+ """+ GET /api/customer_analytics/external/account?external_id=<external_id> — Fetch account data++ Authenticated via Bearer token (team secret_api_token) in Authorization header.+ """++ authentication_classes: list = []+ permission_classes = [AllowAny]+ throttle_classes = [ExternalAccountBurstThrottle, ExternalAccountSustainedThrottle]++ def get(self, request: Request) -> Response:+ team, error = _authenticate_team(request)+ if error:+ return error++ assert team is not None++ 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 = _get_account_by_external_id(team, external_id)+ if account is None:+ return Response({"error": "Account not found"}, status=status.HTTP_404_NOT_FOUND)++ return Response(_serialize_account(account))diff --git a/products/customer_analytics/backend/api/test_external.py b/products/customer_analytics/backend/api/test_external.pynew file mode 100644index 000000000000..f3a6058bc966--- /dev/null+++ b/products/customer_analytics/backend/api/test_external.py@@ -0,0 +1,110 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from parameterized import parameterized+from rest_framework import status+from rest_framework.test import APIClient++from posthog.models import Team+from posthog.models.utils import generate_random_token_secret++from products.customer_analytics.backend.models.account import AccountAssignment, AccountProperties+from products.customer_analytics.backend.test.factories import create_account+++class TestExternalAccountAPI(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.team.secret_api_token = generate_random_token_secret()+ self.team.save(update_fields=["secret_api_token"])+ # Fresh client so requests are unauthenticated unless they carry the Bearer token.+ self.client = APIClient()+ self.account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-1")+ self.url = "/api/customer_analytics/external/account"+ csp_enabled = patch(+ "products.customer_analytics.backend.api.external.posthoganalytics.feature_enabled",+ return_value=True,+ )+ self.mock_csp_enabled = csp_enabled.start()+ self.addCleanup(csp_enabled.stop)++ def _auth_headers(self, token=None):+ return {"HTTP_AUTHORIZATION": f"Bearer {token or self.team.secret_api_token}"}++ def _get(self, external_id="acme-1", token=None):+ return self.client.get(self.url, data={"external_id": external_id}, **self._auth_headers(token))++ # -- Authentication ---------------------------------------------------++ def test_get_requires_auth(self):+ response = self.client.get(self.url, data={"external_id": "acme-1"})+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ @parameterized.expand(+ [+ ("no_header", ""),+ ("bad_scheme", "Basic abc123"),+ ("empty_bearer", "Bearer "),+ ("wrong_token", "Bearer phs_wrong_token"),+ ]+ )+ def test_get_rejects_invalid_auth(self, _name, auth_value):+ headers = {"HTTP_AUTHORIZATION": auth_value} if auth_value else {}+ response = self.client.get(self.url, data={"external_id": "acme-1"}, **headers)+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_rejects_public_api_token(self):+ response = self._get(token=self.team.api_token)+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_accepts_backup_token(self):+ backup_token = generate_random_token_secret()+ self.team.secret_api_token_backup = backup_token+ self.team.save(update_fields=["secret_api_token_backup"])+ response = self._get(token=backup_token)+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ def test_rejects_team_without_customer_analytics_enabled(self):+ self.mock_csp_enabled.return_value = False+ response = self._get()+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ # -- GET account ------------------------------------------------------++ def test_get_requires_external_id(self):+ response = self.client.get(self.url, **self._auth_headers())+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_get_account_not_found(self):+ response = self._get(external_id="does-not-exist")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_get_account_returns_fields(self):+ response = self._get()+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["id"], str(self.account.id))+ self.assertEqual(data["external_id"], "acme-1")+ self.assertEqual(data["name"], "Acme Corp")+ self.assertIn("properties", data)+ self.assertIsNone(data["properties"]["csm"])++ def test_get_account_returns_role_properties(self):+ self.account.properties = AccountProperties(+ csm=AccountAssignment(id=self.user.id, email=self.user.email),+ )+ self.account.save(update_fields=["_properties"])++ response = self._get()+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ csm = response.json()["properties"]["csm"]+ self.assertEqual(csm["id"], self.user.id)+ self.assertEqual(csm["email"], self.user.email)++ def test_does_not_leak_accounts_from_other_team(self):+ other_team = Team.objects.create(organization=self.organization, name="Other")+ other_team.secret_api_token = generate_random_token_secret()+ other_team.save(update_fields=["secret_api_token"])++ response = self._get(token=other_team.secret_api_token)+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)diff --git a/products/customer_analytics/backend/api/urls.py b/products/customer_analytics/backend/api/urls.pynew file mode 100644index 000000000000..8091b369a470--- /dev/null+++ b/products/customer_analytics/backend/api/urls.py@@ -0,0 +1,9 @@+"""URL configuration for the Customer analytics external API."""++from django.urls import path++from .external import ExternalAccountView++urlpatterns = [+ path("external/account", ExternalAccountView.as_view(), name="external-account"),+]diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.tsnew file mode 100644index 000000000000..93c8353feecb--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.test.ts@@ -0,0 +1,32 @@+import './customer_analytics'++import { FEATURE_FLAGS } from 'lib/constants'++import { getRegisteredActionNodeCategories } from './actionNodeRegistry'++describe('customer analytics action registry', () => {+ const getCategory = (): ReturnType<typeof getRegisteredActionNodeCategories>[number] => {+ const category = getRegisteredActionNodeCategories().find((c) => c.label === 'Customer analytics')+ if (!category) {+ throw new Error('Customer analytics action category not registered')+ }+ return category+ }++ it('gates the category behind the customer analytics CSP feature flag', () => {+ expect(getCategory().featureFlag).toBe(FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP)+ })++ it('wires the Get account node to its hog function template', () => {+ const node = getCategory().nodes.find((n) => n.name === 'Get account')+ expect(node).toMatchObject({+ type: 'function',+ config: { template_id: 'template-posthog-get-account' },+ })+ })++ it('stores the account in a single variable without spreading', () => {+ const node = getCategory().nodes.find((n) => n.name === 'Get account')+ expect(node?.output_variable).toEqual({ key: 'account', result_path: null })+ })+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.tsnew file mode 100644index 000000000000..20a2bf3cb79b--- /dev/null+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/customer_analytics.ts@@ -0,0 +1,19 @@+import { FEATURE_FLAGS } from 'lib/constants'++import { registerActionNodeCategory } from 'products/workflows/frontend/Workflows/hogflows/registry/actions/actionNodeRegistry'++registerActionNodeCategory({+ label: 'Customer analytics',+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,+ nodes: [+ {+ type: 'function',+ name: 'Get account',+ description: 'Fetch a Customer analytics account into a workflow variable.',+ config: { template_id: 'template-posthog-get-account', inputs: {} },+ // No `spread`: the editor's spread helper (hogFlowEditorLogic) hardcodes ticket field+ // names, so it can't flatten an account. Store the whole object in one variable instead.+ output_variable: { key: 'account', result_path: null },+ },+ ],+})diff --git a/products/workflows/frontend/Workflows/hogflows/registry/actions/index.ts b/products/workflows/frontend/Workflows/hogflows/registry/actions/index.tsindex 13cdfd461c5e..38da7fbfee1e 100644--- a/products/workflows/frontend/Workflows/hogflows/registry/actions/index.ts+++ b/products/workflows/frontend/Workflows/hogflows/registry/actions/index.ts@@ -1 +1,2 @@import './conversations'+import './customer_analytics'