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.

fix(persons): allow personal API key access to batch endpoints (#66689)

Christiaan Hendriksen3f107f526ac8
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 378f18efd61c..d51c8375a014 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -1546,7 +1546,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
return response.Response(status=202)
- @action(methods=["POST"], detail=False, url_path="batch_by_distinct_ids")
+ @action(methods=["POST"], detail=False, url_path="batch_by_distinct_ids", required_scopes=["person:read"])
def batch_by_distinct_ids(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
distinct_ids = request.data.get("distinct_ids", [])
@@ -1577,13 +1577,14 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
for person in persons:
person._distinct_ids = ids
+ serializer_context = {**self.get_serializer_context(), "get_team": lambda: self.team}
results: dict[str, Any] = {
- distinct_id: MinimalPersonSerializer(person, context={"get_team": lambda: self.team}).data
+ distinct_id: MinimalPersonSerializer(person, context=serializer_context).data
for distinct_id, person in persons_by_distinct_id.items()
}
return response.Response({"results": results})
- @action(methods=["POST"], detail=False, url_path="batch_by_uuids")
+ @action(methods=["POST"], detail=False, url_path="batch_by_uuids", required_scopes=["person:read"])
def batch_by_uuids(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
uuids = request.data.get("uuids", [])
@@ -1602,9 +1603,10 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
with personhog_caller_tag("persons/batch-by-uuids"):
persons = get_persons_by_uuids(self.team_id, uuids, distinct_id_limit=10)
+ serializer_context = {**self.get_serializer_context(), "get_team": lambda: self.team}
results: dict[str, Any] = {}
for person in persons:
- results[str(person.uuid)] = MinimalPersonSerializer(person, context={"get_team": lambda: self.team}).data
+ results[str(person.uuid)] = MinimalPersonSerializer(person, context=serializer_context).data
return response.Response({"results": results})
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 744618ef952b..fec8b842be70 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -25,6 +25,7 @@ from rest_framework import status
import posthog.models.person.deletion
from posthog.clickhouse.client import sync_execute
+from posthog.constants import AvailableFeature
from posthog.models import Organization, Person, PropertyDefinition, Team
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person.missing_person import uuidFromDistinctId
@@ -39,6 +40,8 @@ from posthog.models.person.util import (
from posthog.personhog_client.fake_client import fake_personhog_client
from posthog.test.persons import add_distinct_id, create_person, delete_person
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
from products.cohorts.backend.models.cohort import Cohort
@@ -2093,3 +2096,51 @@ class TestPersonFromClickhouse(TestPerson):
response_include_total = self.client.get("/api/person/?limit=10&include_total").json()
self.assertEqual(response_include_total["count"], 19) # With `include_total`, the total count is returned too
+
+
+class TestPersonBatchRestrictedProperties(ClickhouseTestMixin, APIBaseTest):
+ # Regression: batch_by_distinct_ids / batch_by_uuids built MinimalPersonSerializer with a bare
+ # {"get_team": ...} context, skipping get_serializer_context() — so restricted_person_properties
+ # was never injected and field-level access control was bypassed. The single-person GET path
+ # strips restricted properties; the batch paths must too.
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ restricted = PropertyDefinition.objects.create(
+ team=self.team, name="ssn", property_type="String", type=PropertyDefinition.Type.PERSON
+ )
+ # A default rule (no member/role) restricts the property for the default test user, a plain MEMBER.
+ PropertyAccessControl.objects.create(
+ team=self.team, property_definition=restricted, access_level=PropertyAccessLevel.NONE.value
+ )
+
+ @parameterized.expand(["batch_by_distinct_ids", "batch_by_uuids"])
+ def test_batch_endpoint_strips_restricted_person_properties(self, action: str) -> None:
+ person = _create_person(
+ team=self.team,
+ distinct_ids=["restricted_user"],
+ properties={"email": "[email protected]", "ssn": "123-45-6789"},
+ immediate=True,
+ )
+ flush_persons_and_events()
+
+ if action == "batch_by_distinct_ids":
+ body: dict[str, list[str]] = {"distinct_ids": ["restricted_user"]}
+ result_key = "restricted_user"
+ else:
+ body = {"uuids": [str(person.uuid)]}
+ result_key = str(person.uuid)
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/persons/{action}/",
+ body,
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ properties = response.json()["results"][result_key]["properties"]
+ self.assertEqual(properties.get("email"), "[email protected]")
+ self.assertNotIn("ssn", properties)
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index 3cd25f9b8091..5d5f7d9a14da 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -777,6 +777,41 @@ class TestPersonalAPIKeysWithCommentScope(PersonalAPIKeysBaseTest):
assert response.json()["detail"] == "API key missing required scope 'comment:read'"
+class TestPersonalAPIKeysWithPersonScope(PersonalAPIKeysBaseTest):
+ # Regression: batch_by_distinct_ids and batch_by_uuids shipped without
+ # `required_scopes`, so APIScopePermission rejected every personal API key —
+ # even one scoped `*` — with "This action does not support personal API key
+ # access". Both are reads, so they must accept `person:read`.
+
+ @parameterized.expand(["batch_by_distinct_ids", "batch_by_uuids"])
+ def test_allows_batch_endpoint_with_person_read_scope(self, action):
+ self.key.scopes = ["person:read"]
+ self.key.save()
+ body: dict[str, list[str]] = {"distinct_ids": []} if action == "batch_by_distinct_ids" else {"uuids": []}
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/persons/{action}/",
+ body,
+ format="json",
+ headers={"authorization": f"Bearer {self.value}"},
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == {"results": {}}
+
+ @parameterized.expand(["batch_by_distinct_ids", "batch_by_uuids"])
+ def test_denies_batch_endpoint_without_person_scope(self, action):
+ self.key.scopes = ["feature_flag:read"]
+ self.key.save()
+ body: dict[str, list[str]] = {"distinct_ids": []} if action == "batch_by_distinct_ids" else {"uuids": []}
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/persons/{action}/",
+ body,
+ format="json",
+ headers={"authorization": f"Bearer {self.value}"},
+ )
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.json()["detail"] == "API key missing required scope 'person:read'"
+
+
class TestPersonalAPIKeysWithApprovalsScope(PersonalAPIKeysBaseTest):
def setUp(self):
super().setUp()