Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): add external accounts list endpoint (#68925)

Abhischek950f10e89b00
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 89086ef283f9..006e93e2d46c 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -252,7 +252,11 @@ export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, strin
external_data_schema: 'Pending removal: covered by external_data_source; no viewset uses it.',
}
-export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = ['endpoint:read', 'feature_flag:read'] as const
+export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = [
+ 'endpoint:read',
+ 'feature_flag:read',
+ 'account:read',
+] as const
export type ProjectSecretAPIKeyAllowedScope = (typeof PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)[number]
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 2ce3a951fef6..8114988f15fa 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -181,6 +181,10 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS
# SDK local evaluation and remote config. The Rust feature-flags service already
# validates feature_flag:read PSAKs on the flag-definitions path; this makes them creatable.
("feature_flag", "read"),
+ # Customer analytics external account list, a bulk export for service integrations.
+ # Gated on a PSAK so the team-wide secret_api_token (readable by any project member)
+ # can't be used to sidestep per-user account access controls.
+ ("account", "read"),
]
# Server-side scope assignment string-set constants (see RFC: server-side scope
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index c14f303ffa56..0cb0515fc192 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -23,7 +23,7 @@ from uuid import UUID
from django.apps import apps
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
-from django.db.models import Prefetch, Q
+from django.db.models import Exists, OuterRef, Prefetch, Q
from celery import current_app
from pydantic import ValidationError as PydanticValidationError
@@ -328,6 +328,71 @@ def get_external_account(team_id: int, external_id: str) -> contracts.ExternalAc
return _to_external_account(account)
+def list_external_accounts(
+ team_id: int,
+ *,
+ organization_id: UUID,
+ cursor: str | None = None,
+ limit: int = 100,
+ assigned_only: bool = False,
+) -> contracts.ExternalAccountListPage:
+ """Page through the team's accounts for the external API, ordered by id.
+
+ Account ids are time-ordered UUIDs, so ``id__gt`` is a stable cursor.
+ Accounts without an external id are excluded — external consumers key on
+ it. Only active relationship assignments to current members of the team's
+ organization are exposed. With ``assigned_only``, only accounts holding at
+ least one such assignment are returned; a consumer reconciling by absence
+ still sees the complete assigned set. Assignments mirror the single-account
+ endpoint's ``relationships`` shape (keyed by definition name), with the
+ user's current display name added.
+ """
+ active_relationships = AccountRelationship.objects.for_team(team_id).filter(
+ ended_at__isnull=True,
+ user__isnull=False,
+ user__organization_membership__organization_id=organization_id,
+ )
+ queryset = (
+ Account.objects.for_team(team_id).filter(external_id__isnull=False).exclude(external_id="").order_by("id")
+ )
+ if assigned_only:
+ queryset = queryset.filter(Exists(active_relationships.filter(account=OuterRef("pk"))))
+ if cursor:
+ queryset = queryset.filter(id__gt=cursor)
+
+ page_accounts = list(queryset[: limit + 1])
+ accounts = page_accounts[:limit]
+
+ relationships_by_account: dict[UUID, dict[str, list[contracts.ExternalAccountAssignment]]] = {}
+ for relationship in (
+ active_relationships.filter(account__in=accounts)
+ .select_related("definition", "user")
+ .order_by("definition__name", "user__email")
+ ):
+ user = relationship.user
+ assert user is not None
+ relationships_by_account.setdefault(relationship.account_id, {}).setdefault(
+ relationship.definition.name, []
+ ).append(
+ contracts.ExternalAccountAssignment(
+ user_id=user.id,
+ email=user.email,
+ name=f"{user.first_name} {user.last_name}".strip() or None,
+ )
+ )
+
+ results = [
+ contracts.ExternalAccountListItem(
+ external_id=cast(str, account.external_id),
+ name=account.name,
+ relationships=relationships_by_account.get(account.id, {}),
+ )
+ for account in accounts
+ ]
+ next_cursor = str(accounts[-1].id) if accounts and len(page_accounts) > limit else None
+ return contracts.ExternalAccountListPage(results=results, next_cursor=next_cursor)
+
+
def _apply_external_tags(account: Account, tags: list[str], mode: str, workflow_id: str | None = None) -> None:
normalized = list({tagify(t) for t in tags})
if mode == "remove":
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index bbf510dfa4fd..3c5167b396d6 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -155,6 +155,39 @@ class ExternalAccount:
custom_properties: dict[str, float | bool | str | None] = field(default_factory=dict)
+@dataclass(frozen=True)
+class ExternalAccountAssignment:
+ """An active relationship assignment on the external list wire shape.
+
+ Carries the assigned user's id and current email plus their display name so
+ external consumers (the billing service's ownership sync) don't need a
+ second lookup. ``name`` is None when the user has no name set.
+ """
+
+ user_id: int
+ email: str
+ name: str | None = None
+
+
+@dataclass(frozen=True)
+class ExternalAccountListItem:
+ """One account row on the external list wire shape, with active relationship
+ assignments to current organization members keyed by definition name."""
+
+ external_id: str
+ name: str
+ relationships: dict[str, list[ExternalAccountAssignment]] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class ExternalAccountListPage:
+ """A page of external account rows. ``next_cursor`` is the last account id
+ of a full page, or None when the listing is exhausted."""
+
+ results: list[ExternalAccountListItem] = field(default_factory=list)
+ next_cursor: str | None = None
+
+
class ExternalAccountUpdateError(Enum):
"""Failure modes of the external account write, each mapping to a distinct
HTTP response in the view."""
diff --git a/products/customer_analytics/backend/presentation/views/external.py b/products/customer_analytics/backend/presentation/views/external.py
index 2c2237df6d4a..b226358f28dc 100644
--- a/products/customer_analytics/backend/presentation/views/external.py
+++ b/products/customer_analytics/backend/presentation/views/external.py
@@ -1,8 +1,11 @@
"""
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.
+The single-account endpoints are used by the CDP worker for workflow actions and
+authenticate via the team secret API token passed as a Bearer token in the
+Authorization header. The bulk account list instead authenticates via a project
+secret API key carrying the ``account:read`` scope, because the team token is
+readable by every project member and must not unlock a team-wide account export.
The view holds only HTTP concerns — Bearer auth, throttles, the feature-flag gate,
request validation, and mapping facade results to responses. Data access, the
@@ -12,14 +15,16 @@ capture live behind ``facade.api``.
import uuid
import hashlib
-from typing import Any
+from typing import Any, cast
+from uuid import UUID
from django.db.models import Q
+from django.http import HttpRequest
import structlog
import posthoganalytics
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import extend_schema, extend_schema_field
+from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import serializers, status
from rest_framework.permissions import AllowAny
from rest_framework.request import Request
@@ -27,7 +32,11 @@ from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView
+from posthog.api.utils import ErrorResponseSerializer
+from posthog.auth import ProjectSecretAPIKeyAuthentication
from posthog.models import Team
+from posthog.permissions import get_authenticator_scopes, is_authenticated_via_project_secret_api_key
+from posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle
from products.customer_analytics.backend.facade import (
api as facade,
@@ -37,6 +46,9 @@ from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYT
logger = structlog.get_logger(__name__)
+EXTERNAL_ACCOUNT_LIST_MAX_LIMIT = 100
+EXTERNAL_ACCOUNT_LIST_REQUIRED_SCOPE = "account:read"
+
class _ExternalAccountThrottle(SimpleRateThrottle):
"""Rate limit by Bearer token (team secret_api_token)."""
@@ -58,6 +70,26 @@ class ExternalAccountSustainedThrottle(_ExternalAccountThrottle):
rate = "600/hour"
+class ExternalAccountListBurstThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "external_account_list_burst"
+ rate = ExternalAccountBurstThrottle.rate
+
+
+class ExternalAccountListSustainedThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "external_account_list_sustained"
+ rate = ExternalAccountSustainedThrottle.rate
+
+
+class ExternalAccountListTeamBurstThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ scope = "external_account_list_psak_team_burst"
+ rate = ExternalAccountBurstThrottle.rate
+
+
+class ExternalAccountListTeamSustainedThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ scope = "external_account_list_psak_team_sustained"
+ rate = ExternalAccountSustainedThrottle.rate
+
+
def _customer_analytics_enabled(team: Team) -> bool:
organization_id = str(team.organization_id)
return bool(
@@ -71,6 +103,14 @@ def _customer_analytics_enabled(team: Team) -> bool:
)
+class ExternalAccountListAuthentication(ProjectSecretAPIKeyAuthentication):
+ def authenticate(self, request: HttpRequest | Request) -> tuple[Any, None] | None:
+ result = super().authenticate(request)
+ if result is None or not _customer_analytics_enabled(self.project_secret_api_key.team):
+ return None
+ return result
+
+
HOG_FLOW_ID_HEADER = "X-PostHog-Hog-Flow-Id"
@@ -115,6 +155,28 @@ def _authenticate_team(request: Request) -> tuple[Team, None] | tuple[None, Resp
return team, None
+def _authenticate_psak_team(request: Request) -> tuple[Team, None] | tuple[None, Response]:
+ """Resolve the team from a project secret API key with the ``account:read`` scope."""
+ if not is_authenticated_via_project_secret_api_key(request):
+ return None, Response({"error": "Missing or invalid API key"}, status=status.HTTP_401_UNAUTHORIZED)
+
+ authenticator = cast(ProjectSecretAPIKeyAuthentication, request.successful_authenticator)
+ psak = authenticator.project_secret_api_key
+
+ key_scopes = set(get_authenticator_scopes(authenticator) or [])
+ valid_scopes = {
+ EXTERNAL_ACCOUNT_LIST_REQUIRED_SCOPE,
+ EXTERNAL_ACCOUNT_LIST_REQUIRED_SCOPE.replace(":read", ":write"),
+ }
+ if "*" not in key_scopes and key_scopes.isdisjoint(valid_scopes):
+ return None, Response(
+ {"error": f"API key missing required scope '{EXTERNAL_ACCOUNT_LIST_REQUIRED_SCOPE}'"},
+ status=status.HTTP_403_FORBIDDEN,
+ )
+
+ return psak.team, None
+
+
def _external_account_body(account: contracts.ExternalAccount) -> dict[str, Any]:
return {
"id": account.id,
@@ -259,6 +321,148 @@ class ExternalAccountView(APIView):
return Response(_external_account_body(result.account))
+class ExternalAccountListQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ required=False,
+ default=EXTERNAL_ACCOUNT_LIST_MAX_LIMIT,
+ help_text=(
+ "Maximum number of accounts to return. Values below 1 are clamped to 1; values above 100 are clamped to 100."
+ ),
+ )
+ cursor = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ trim_whitespace=True,
+ help_text="Account UUID from `next_cursor` to continue listing from. Omit for the first page.",
+ )
+ assigned_only = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "When true, return only accounts with at least one active relationship assignment "
+ "to a current member of the project's organization."
+ ),
+ )
+
+ def validate_limit(self, value: int) -> int:
+ return max(1, min(value, EXTERNAL_ACCOUNT_LIST_MAX_LIMIT))
+
+ def validate_cursor(self, value: str) -> str | None:
+ if not value:
+ return None
+ try:
+ UUID(value)
+ except ValueError:
+ raise serializers.ValidationError("Must be a valid account id.")
+ return value
+
+
+class ExternalAccountListAssignmentSerializer(serializers.Serializer):
+ user_id = serializers.IntegerField(help_text="PostHog user id of the assigned user.")
+ email = serializers.CharField(help_text="Current email address of the assigned user.")
+ name = serializers.CharField(
+ allow_null=True,
+ help_text="Current display name of the assigned user, or null when the user has no name set.",
+ )
+
+
+class ExternalAccountListItemSerializer(serializers.Serializer):
+ external_id = serializers.CharField(help_text="External account key used by downstream systems.")
+ name = serializers.CharField(help_text="Human-readable account name.")
+ relationships = serializers.DictField(
+ child=ExternalAccountListAssignmentSerializer(many=True),
+ help_text=(
+ "Active relationship assignments to current organization members, keyed by relationship definition name "
+ "(e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted."
+ ),
+ )
+
+
+class ExternalAccountListPageSerializer(serializers.Serializer):
+ results = ExternalAccountListItemSerializer(
+ many=True,
+ help_text="Accounts in this page, ordered by account id.",
+ )
+ next_cursor = serializers.CharField(
+ allow_null=True,
+ help_text="Account UUID to pass as `cursor` for the next page, or null when the list is exhausted.",
+ )
+
+
+class ExternalAccountListValidationErrorSerializer(serializers.Serializer):
+ error = serializers.DictField(
+ child=serializers.ListField(child=serializers.CharField()),
+ help_text="Validation errors keyed by query parameter.",
+ )
+
+
+class ExternalAccountListView(APIView):
+ """
+ GET /api/customer_analytics/external/accounts — List accounts with their relationship assignments
+
+ Cursor-paginated by account id. ``assigned_only=true`` restricts the listing
+ to accounts with at least one active relationship assignment, which is what
+ the billing service's ownership sync consumes.
+
+ Authenticated via a project secret API key (Bearer ``phs_...``) carrying the
+ ``account:read`` scope, not the team secret_api_token the sibling views
+ accept. The team token is readable by any project member, so it must not
+ grant this team-wide export; a PSAK is a service credential minted with an
+ explicit scope.
+ """
+
+ authentication_classes = [ExternalAccountListAuthentication]
+ permission_classes = [AllowAny]
+ throttle_classes = [
+ ExternalAccountListBurstThrottle,
+ ExternalAccountListSustainedThrottle,
+ ExternalAccountListTeamBurstThrottle,
+ ExternalAccountListTeamSustainedThrottle,
+ ]
+ scope_object = "account"
+
+ @extend_schema(
+ parameters=[ExternalAccountListQuerySerializer],
+ responses={
+ 200: OpenApiResponse(response=ExternalAccountListPageSerializer, description="Page of external accounts."),
+ 400: OpenApiResponse(
+ response=ExternalAccountListValidationErrorSerializer,
+ description="Invalid query parameters.",
+ ),
+ 401: OpenApiResponse(response=ErrorResponseSerializer, description="Authentication failed."),
+ 403: OpenApiResponse(
+ response=ErrorResponseSerializer,
+ description="API key does not carry the account:read scope.",
+ ),
+ },
+ summary="List external customer analytics accounts",
+ description=(
+ "List accounts with external IDs and their active relationship assignments. "
+ "Requires a project secret API key with the `account:read` scope."
+ ),
+ )
+ def get(self, request: Request) -> Response:
+ team, error = _authenticate_psak_team(request)
+ if error:
+ return error
+
+ assert team is not None
+
+ query_serializer = ExternalAccountListQuerySerializer(data=request.query_params)
+ if not query_serializer.is_valid():
+ return Response({"error": query_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
+ query_data = query_serializer.validated_data
+
+ page = facade.list_external_accounts(
+ team.id,
+ organization_id=team.organization_id,
+ cursor=query_data.get("cursor"),
+ limit=query_data["limit"],
+ assigned_only=query_data["assigned_only"],
+ )
+ 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.
diff --git a/products/customer_analytics/backend/presentation/views/urls.py b/products/customer_analytics/backend/presentation/views/urls.py
index 9cf7bebc9973..c803098b4d4e 100644
--- a/products/customer_analytics/backend/presentation/views/urls.py
+++ b/products/customer_analytics/backend/presentation/views/urls.py
@@ -4,11 +4,13 @@ from django.urls import path
from products.customer_analytics.backend.presentation.views.external import (
ExternalAccountCustomPropertiesView,
+ ExternalAccountListView,
ExternalAccountView,
)
urlpatterns = [
path("external/account", ExternalAccountView.as_view(), name="external-account"),
+ path("external/accounts", ExternalAccountListView.as_view(), name="external-account-list"),
path(
"external/account/custom_property_values",
ExternalAccountCustomPropertiesView.as_view(),
diff --git a/products/customer_analytics/backend/test/test_external_list.py b/products/customer_analytics/backend/test/test_external_list.py
new file mode 100644
index 000000000000..62b31810d298
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_external_list.py
@@ -0,0 +1,337 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from datetime import UTC, datetime
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.project_secret_api_key import ProjectSecretAPIKey
+from posthog.models.utils import generate_random_token_secret, hash_key_value, mask_key_value
+
+from products.customer_analytics.backend.models import AccountRelationship, AccountRelationshipDefinition
+from products.customer_analytics.backend.test.factories import create_account
+
+ENDED_AT = datetime(2026, 1, 1, tzinfo=UTC)
+
+
+class TestExternalAccountListAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.psak_token = self._create_psak_token(scopes=["account:read"])
+ # Fresh client so requests are unauthenticated unless they carry the Bearer token.
+ self.client = APIClient()
+ self.url = "/api/customer_analytics/external/accounts"
+ self.csm_definition = self._create_definition("CSM")
+ csp_enabled = patch(
+ "products.customer_analytics.backend.presentation.views.external._customer_analytics_enabled",
+ return_value=True,
+ )
+ self.mock_csp_enabled = csp_enabled.start()
+ self.addCleanup(csp_enabled.stop)
+
+ def _create_psak_token(self, scopes, label="external-list"):
+ token = generate_random_token_secret()
+ ProjectSecretAPIKey.objects.create(
+ team=self.team,
+ label=label,
+ mask_value=mask_key_value(token),
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ )
+ return token
+
+ def _create_definition(self, name, **kwargs):
+ return AccountRelationshipDefinition.objects.for_team(self.team.id).create(
+ team_id=self.team.id, name=name, **kwargs
+ )
+
+ def _assign(self, account, user, definition=None, ended_at=None):
+ return AccountRelationship.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ account=account,
+ definition=definition or self.csm_definition,
+ user=user,
+ ended_at=ended_at,
+ )
+
+ def _auth_headers(self, token=None):
+ return {"HTTP_AUTHORIZATION": f"Bearer {token or self.psak_token}"}
+
+ def _get(self, params=None, token=None):
+ return self.client.get(self.url, data=params or {}, **self._auth_headers(token))
+
+ @contextmanager
+ def _rate_limits(self, *, key_rate: str, team_rate: str) -> Iterator[None]:
+ with (
+ patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True),
+ patch(
+ "products.customer_analytics.backend.presentation.views.external.ExternalAccountListBurstThrottle.rate",
+ key_rate,
+ ),
+ patch(
+ "products.customer_analytics.backend.presentation.views.external.ExternalAccountListSustainedThrottle.rate",
+ key_rate,
+ ),
+ patch(
+ "products.customer_analytics.backend.presentation.views.external.ExternalAccountListTeamBurstThrottle.rate",
+ team_rate,
+ ),
+ patch(
+ "products.customer_analytics.backend.presentation.views.external.ExternalAccountListTeamSustainedThrottle.rate",
+ team_rate,
+ ),
+ ):
+ yield
+
+ # -- Authentication ---------------------------------------------------
+
+ def test_requires_auth(self):
+ response = self.client.get(self.url)
+ 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_rejects_team_secret_api_token(self):
+ # The team-wide secret token is readable by any project member, so it must
+ # not unlock this bulk export; only a scoped project secret API key may.
+ self.team.secret_api_token = generate_random_token_secret()
+ self.team.save(update_fields=["secret_api_token"])
+
+ response = self._get(token=self.team.secret_api_token)
+
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
+ def test_rejects_key_without_account_read_scope(self):
+ token = self._create_psak_token(scopes=["endpoint:read"], label="wrong-scope")
+
+ response = self._get(token=token)
+
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_disabled_feature_does_not_reveal_key_validity_or_scopes(self):
+ wrong_scope_token = self._create_psak_token(scopes=["endpoint:read"], label="wrong-scope-disabled")
+ self.mock_csp_enabled.return_value = False
+
+ for token in [self.psak_token, wrong_scope_token, generate_random_token_secret()]:
+ with self.subTest(token=token):
+ response = self._get(token=token)
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.json(), {"error": "Missing or invalid API key"})
+
+ def test_rate_limit_is_shared_across_project_secret_api_keys(self):
+ cache.clear()
+ self.addCleanup(cache.clear)
+ second_token = self._create_psak_token(scopes=["account:read"], label="second-key")
+
+ with self._rate_limits(key_rate="100/minute", team_rate="1/minute"):
+ self.assertEqual(self._get().status_code, status.HTTP_200_OK)
+ self.assertEqual(self._get(token=second_token).status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_invalid_tokens_share_ip_rate_limit(self):
+ cache.clear()
+ self.addCleanup(cache.clear)
+
+ with self._rate_limits(key_rate="1/minute", team_rate="100/minute"):
+ self.assertEqual(
+ self._get(token=generate_random_token_secret()).status_code,
+ status.HTTP_401_UNAUTHORIZED,
+ )
+ self.assertEqual(
+ self._get(token=generate_random_token_secret()).status_code,
+ status.HTTP_429_TOO_MANY_REQUESTS,
+ )
+
+ def test_disabled_feature_uses_invalid_token_rate_bucket(self):
+ cache.clear()
+ self.addCleanup(cache.clear)
+ self.mock_csp_enabled.return_value = False
+
+ with self._rate_limits(key_rate="1/minute", team_rate="100/minute"):
+ self.assertEqual(self._get().status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(
+ self._get(token=generate_random_token_secret()).status_code,
+ status.HTTP_429_TOO_MANY_REQUESTS,
+ )
+
+ # -- Listing ----------------------------------------------------------
+
+ def test_lists_accounts_with_relationship_assignments(self):
+ self.user.first_name = "Anna"
+ self.user.last_name = "Exec"
+ self.user.save(update_fields=["first_name", "last_name"])
+ colleague = User.objects.create_and_join(self.organization, "[email protected]", None)
+ ae_definition = self._create_definition("Account executive", is_single_holder=False)
+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-1")
+ self._assign(account, self.user)
+ self._assign(account, self.user, definition=ae_definition)
+ self._assign(account, colleague, definition=ae_definition)
+
+ response = self._get()
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ data = response.json()
+ self.assertIsNone(data["next_cursor"])
+ self.assertEqual(len(data["results"]), 1)
+ row = data["results"][0]
+ self.assertEqual(row["external_id"], "org-1")
+ self.assertEqual(row["name"], "Acme")
+ self.assertEqual(
+ row["relationships"],
+ {
+ "Account executive": [
+ {"user_id": colleague.id, "email": "[email protected]", "name": None},
+ {"user_id": self.user.id, "email": self.user.email, "name": "Anna Exec"},
+ ],
+ "CSM": [{"user_id": self.user.id, "email": self.user.email, "name": "Anna Exec"}],
+ },
+ )
+
+ @parameterized.expand(
+ [
+ ("membership_removed",),
+ ("other_organization_only",),
+ ]
+ )
+ def test_omits_relationship_users_without_current_org_membership(self, membership_state: str) -> None:
+ if membership_state == "membership_removed":
+ relationship_user = User.objects.create_and_join(self.organization, "[email protected]", None)
+ OrganizationMembership.objects.filter(
+ organization=self.organization,
+ user=relationship_user,
+ ).delete()
+ else:
+ other_organization = Organization.objects.create(name="Other organization")
+ relationship_user = User.objects.create_and_join(other_organization, "[email protected]", None)
+
+ relationship_user.first_name = "Former"
+ relationship_user.last_name = "Member"
+ relationship_user.save(update_fields=["first_name", "last_name"])
+
+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-1")
+ self._assign(account, relationship_user)
+
+ response = self._get()
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json()["results"],
+ [
+ {
+ "external_id": "org-1",
+ "name": "Acme",
+ "relationships": {},
+ }
+ ],
+ )
+
+ def test_omits_ended_and_userless_assignments(self):
+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-1")
+ self._assign(account, self.user, ended_at=ENDED_AT)
+ ghost = User.objects.create_user(email="[email protected]", password=None, first_name="Ghost")
+ self._assign(account, ghost, definition=self._create_definition("Account executive"))
+ # Deleting the user SET_NULLs the relationship's user; the row must not surface.
+ ghost.delete()
+
+ response = self._get()
+
+ row = response.json()["results"][0]
+ self.assertEqual(row["relationships"], {})
+
+ def test_excludes_accounts_without_external_id(self):
+ no_external = create_account(team_id=self.team.id, name="No external id")
+ self._assign(no_external, self.user)
+ blank_external = create_account(team_id=self.team.id, name="Blank external id", external_id="")
+ self._assign(blank_external, self.user)
+ create_account(team_id=self.team.id, name="Listed", external_id="org-1")
+
+ response = self._get()
+
+ names = [row["name"] for row in response.json()["results"]]
+ self.assertEqual(names, ["Listed"])
+
+ def test_assigned_only_filters_to_accounts_with_an_active_assignment(self):
+ assigned = create_account(team_id=self.team.id, name="Assigned", external_id="org-1")
+ self._assign(assigned, self.user)
+ ended = create_account(team_id=self.team.id, name="Ended", external_id="org-2")
+ self._assign(ended, self.user, ended_at=ENDED_AT)
+ create_account(team_id=self.team.id, name="Never assigned", external_id="org-3")
+
+ response = self._get({"assigned_only": "true"})
+
+ names = [row["name"] for row in response.json()["results"]]
+ self.assertEqual(names, ["Assigned"])
+
+ response = self._get()
+ self.assertEqual(len(response.json()["results"]), 3)
+
+ def test_assigned_only_excludes_accounts_assigned_only_to_another_organization_member(self) -> None:
+ other_organization = Organization.objects.create(name="Other organization")
+ relationship_user = User.objects.create_and_join(other_organization, "[email protected]", None)
+ account = create_account(team_id=self.team.id, name="Acme", external_id="org-1")
+ self._assign(account, relationship_user)
+
+ response = self._get({"assigned_only": "true"})
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_paginates_with_cursor(self):
+ for i in range(3):
+ account = create_account(team_id=self.team.id, name=f"Account {i}", external_id=f"org-{i}")
+ self._assign(account, self.user)
+
+ page_one = self._get({"limit": 2}).json()
+ self.assertEqual(len(page_one["results"]), 2)
+ self.assertIsNotNone(page_one["next_cursor"])
+
+ page_two = self._get({"limit": 2, "cursor": page_one["next_cursor"]}).json()
+ self.assertEqual(len(page_two["results"]), 1)
+ self.assertIsNone(page_two["next_cursor"])
+
+ all_names = [row["name"] for row in page_one["results"] + page_two["results"]]
+ self.assertEqual(sorted(all_names), ["Account 0", "Account 1", "Account 2"])
+
+ def test_does_not_leak_accounts_from_other_team(self):
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ create_account(team_id=other_team.id, name="Other team account", external_id="org-other")
+ create_account(team_id=self.team.id, name="Mine", external_id="org-1")
+
+ response = self._get()
+
+ names = [row["name"] for row in response.json()["results"]]
+ self.assertEqual(names, ["Mine"])
+
+ # -- Validation -------------------------------------------------------
+
+ @parameterized.expand(
+ [
+ ("invalid_cursor", {"cursor": "not-a-uuid"}),
+ ("non_integer_limit", {"limit": "abc"}),
+ ("invalid_assigned_only", {"assigned_only": "banana"}),
+ ]
+ )
+ def test_rejects_invalid_query_param(self, _name, params):
+ response = self._get(params)
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(set(response.json()), {"error"})
+ self.assertIn(next(iter(params)), response.json()["error"])
+
+ def test_clamps_limit(self):
+ for i in range(2):
+ create_account(team_id=self.team.id, name=f"Account {i}", external_id=f"org-{i}")
+
+ response = self._get({"limit": "1000"})
+ self.assertEqual(len(response.json()["results"]), 2)
+
+ response = self._get({"limit": "0"})
+ self.assertEqual(len(response.json()["results"]), 1)
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index e436f3ff6454..79b722053b95 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -7,6 +7,57 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface ExternalAccountListAssignmentApi {
+ /** PostHog user id of the assigned user. */
+ user_id: number
+ /** Current email address of the assigned user. */
+ email: string
+ /**
+ * Current display name of the assigned user, or null when the user has no name set.
+ * @nullable
+ */
+ name: string | null
+}
+
+/**
+ * Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted.
+ */
+export type ExternalAccountListItemApiRelationships = { [key: string]: ExternalAccountListAssignmentApi[] }
+
+export interface ExternalAccountListItemApi {
+ /** External account key used by downstream systems. */
+ external_id: string
+ /** Human-readable account name. */
+ name: string
+ /** Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted. */
+ relationships: ExternalAccountListItemApiRelationships
+}
+
+export interface ExternalAccountListPageApi {
+ /** Accounts in this page, ordered by account id. */
+ results: ExternalAccountListItemApi[]
+ /**
+ * Account UUID to pass as `cursor` for the next page, or null when the list is exhausted.
+ * @nullable
+ */
+ next_cursor: string | null
+}
+
+/**
+ * Validation errors keyed by query parameter.
+ */
+export type ExternalAccountListValidationErrorApiError = { [key: string]: string[] }
+
+export interface ExternalAccountListValidationErrorApi {
+ /** Validation errors keyed by query parameter. */
+ error: ExternalAccountListValidationErrorApiError
+}
+
+export interface ErrorResponseApi {
+ /** Error message */
+ error: string
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -950,6 +1001,21 @@ export interface PatchedGroupUsageMetricApi {
math_property?: string | null
}
+export type CustomerAnalyticsExternalAccountsRetrieveParams = {
+ /**
+ * When true, return only accounts with at least one active relationship assignment to a current member of the project's organization.
+ */
+ assigned_only?: boolean
+ /**
+ * Account UUID from `next_cursor` to continue listing from. Omit for the first page.
+ */
+ cursor?: string
+ /**
+ * Maximum number of accounts to return. Values below 1 are clamped to 1; values above 100 are clamped to 100.
+ */
+ limit?: number
+}
+
export type AccountNotesListParams = {
/**
* Only return notes linked to this account.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 735ea4805350..46f6fc0498e2 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -28,10 +28,12 @@ import type {
CustomPropertyValueApi,
CustomPropertyValueSuggestionsResponseApi,
CustomPropertyValueWriteApi,
+ CustomerAnalyticsExternalAccountsRetrieveParams,
CustomerJourneyApi,
CustomerJourneysListParams,
CustomerProfileConfigApi,
CustomerProfileConfigsListParams,
+ ExternalAccountListPageApi,
GroupUsageMetricApi,
GroupsTypesMetricsListParams,
PaginatedAccountListApi,
@@ -69,6 +71,38 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getCustomerAnalyticsExternalAccountsRetrieveUrl = (
+ params?: CustomerAnalyticsExternalAccountsRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/customer_analytics/external/accounts?${stringifiedParams}`
+ : `/api/customer_analytics/external/accounts`
+}
+
+/**
+ * List accounts with external IDs and their active relationship assignments. Requires a project secret API key with the `account:read` scope.
+ * @summary List external customer analytics accounts
+ */
+export const customerAnalyticsExternalAccountsRetrieve = async (
+ params?: CustomerAnalyticsExternalAccountsRetrieveParams,
+ options?: RequestInit
+): Promise<ExternalAccountListPageApi> => {
+ return apiMutator<ExternalAccountListPageApi>(getCustomerAnalyticsExternalAccountsRetrieveUrl(params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getAccountNotesListUrl = (projectId: string, params?: AccountNotesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 0c385735a003..3c8062b6f9ce 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -473,6 +473,9 @@ tools:
custom-property-sources-update:
operation: custom_property_sources_update
enabled: false
+ customer-analytics-external-accounts-retrieve:
+ operation: customer_analytics_external_accounts_retrieve
+ enabled: false
customer-journeys-create:
operation: customer_journeys_create
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7f7ad046f96f..79eabc6d719f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -25877,6 +25877,52 @@ export namespace Schemas {
readonly user_access_level: string | null;
}
+ export interface ExternalAccountListAssignment {
+ /** PostHog user id of the assigned user. */
+ user_id: number;
+ /** Current email address of the assigned user. */
+ email: string;
+ /**
+ * Current display name of the assigned user, or null when the user has no name set.
+ * @nullable
+ */
+ name: string | null;
+ }
+
+ /**
+ * Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted.
+ */
+ export type ExternalAccountListItemRelationships = {[key: string]: ExternalAccountListAssignment[]};
+
+ export interface ExternalAccountListItem {
+ /** External account key used by downstream systems. */
+ external_id: string;
+ /** Human-readable account name. */
+ name: string;
+ /** Active relationship assignments to current organization members, keyed by relationship definition name (e.g. 'CSM', 'Account executive'). Definitions with no active assignment are omitted. */
+ relationships: ExternalAccountListItemRelationships;
+ }
+
+ export interface ExternalAccountListPage {
+ /** Accounts in this page, ordered by account id. */
+ results: ExternalAccountListItem[];
+ /**
+ * Account UUID to pass as `cursor` for the next page, or null when the list is exhausted.
+ * @nullable
+ */
+ next_cursor: string | null;
+ }
+
+ /**
+ * Validation errors keyed by query parameter.
+ */
+ export type ExternalAccountListValidationErrorError = {[key: string]: string[]};
+
+ export interface ExternalAccountListValidationError {
+ /** Validation errors keyed by query parameter. */
+ error: ExternalAccountListValidationErrorError;
+ }
+
/**
* @nullable
*/
@@ -65610,6 +65656,21 @@ export namespace Schemas {
query: _TracingTreeQueryBody;
}
+ export type CustomerAnalyticsExternalAccountsRetrieveParams = {
+ /**
+ * When true, return only accounts with at least one active relationship assignment to a current member of the project's organization.
+ */
+ assigned_only?: boolean;
+ /**
+ * Account UUID from `next_cursor` to continue listing from. Omit for the first page.
+ */
+ cursor?: string;
+ /**
+ * Maximum number of accounts to return. Values below 1 are clamped to 1; values above 100 are clamped to 100.
+ */
+ limit?: number;
+ };
+
export type EnvironmentsAccountsListParams = {
/**
* Filter by account executive. Use 'unassigned' or an integer user id.