:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(surveys): check target project access when duplicating (#105433)
Tom Piccirello83284eb7a23c
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex bfa47fa2829e..ecb2945e7402 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -60,8 +60,10 @@ from posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import UUIDT+from posthog.permissions import get_authenticator_scoped_team_idsfrom posthog.utils_cors import cors_response+from products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.access_control.backend.presentation.access_control import (AccessControlViewSetMixin,UserAccessControlSerializerMixin,@@ -3274,11 +3276,35 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControl})+ def _check_duplicate_target_access(+ self, request: request.Request, target_team: Team, access_control: UserAccessControl+ ) -> None:+ # The permission classes check only the source project in the URL. Apply the checks that+ # `POST /surveys/` in the target project applies: the key's project scope, project access,+ # and survey editor access.+ scoped_teams = get_authenticator_scoped_team_ids(getattr(request, "successful_authenticator", None))+ if scoped_teams is not None and target_team.id not in scoped_teams:+ raise exceptions.PermissionDenied(+ f"API key does not have access to the requested project: ID {target_team.id}."+ )++ if (+ self.user_permissions.team(target_team).effective_membership_level is None+ or not access_control.check_access_level_for_object(target_team, required_level="member")+ or not access_control.check_access_level_for_resource("survey", required_level="editor")+ ):+ raise exceptions.PermissionDenied(+ f"You don't have permission to create surveys in project {target_team.id}. "+ "Ask a project admin for access, or remove the project from the list."+ )+@action(methods=["POST"], detail=True, required_scopes=["survey:write"])def duplicate_to_projects(self, request: request.Request, **kwargs):"""Duplicate a survey to multiple projects in a single transaction.Accepts a list of target team IDs and creates a copy of the survey in each project.+ Every target project must be in the source project's organization, and the caller needs+ survey editor access in each one.Uses an all-or-nothing approach - if any duplication fails, all changes are rolled back."""if not request.user.is_authenticated:@@ -3296,15 +3322,22 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControlif not target_team_ids or not isinstance(target_team_ids, list):raise exceptions.ValidationError("target_team_ids must be a non-empty list of team IDs")- user_organization = user.organization- if not user_organization:- raise exceptions.ValidationError("User must belong to an organization")-- target_teams = Team.objects.filter(id__in=target_team_ids, organization_id=user_organization.id)+ organization_id = self.team.organization_id+ requested_teams = Team.objects.select_related("parent_team").filter(+ id__in=target_team_ids, organization_id=organization_id+ )+ # Surveys are project-scoped, so an environment resolves to its project, as RootTeamMixin.save does.+ # The checks below and bulk_create must see the project, because bulk_create skips that save.+ target_teams = list({team.id: team for team in (t.parent_team or t for t in requested_teams)}.values())+ # for_team_ids loads the teams again, so a team deleted between the two queries is missing from its result+ target_access_controls = self.user_access_control.for_team_ids(team.id for team in target_teams)- if len(target_teams) != len(target_team_ids):+ if len(requested_teams) != len(target_team_ids) or len(target_access_controls) != len(target_teams):raise exceptions.ValidationError("One or more target teams not found or you don't have access to them")+ for target_team in target_teams:+ self._check_duplicate_target_access(request, target_team, target_access_controls[target_team.id])+duplicate_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")created_surveys = []@@ -3398,7 +3431,7 @@ class SurveyViewSet(ApprovalHandlingMixin, TeamAndOrgViewSetMixin, AccessControl)log_activity(- organization_id=user_organization.id,+ organization_id=organization_id,team_id=created_survey.team_id,user=user,was_impersonated=is_impersonated(request),diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 1f54f9044926..75db56981547 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -27,7 +27,9 @@ from posthog.api.test.test_personal_api_keys import PersonalAPIKeysBaseTestfrom posthog.constants import AvailableFeaturefrom posthog.models import Teamfrom posthog.models.organization import Organization, OrganizationMembership+from posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.user import User+from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.test.persons import create_personfrom products.access_control.backend.models.access_control import AccessControl@@ -6802,6 +6804,100 @@ class TestSurveyBulkDuplication(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "not found" in str(response.json()).lower()+ @parameterized.expand([("private_project", "project"), ("no_survey_access", "survey")])+ def test_bulk_duplicate_requires_access_to_every_target(self, _name: str, resource: str) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ AccessControl.objects.create(+ team=self.team3,+ resource=resource,+ resource_id=str(self.team3.id) if resource == "project" else None,+ access_level="none",+ )+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)+ self.client.force_login(member)++ response = self.client.post(+ f"/api/projects/{self.team.project_id}/surveys/{self.source_survey.id}/duplicate_to_projects/",+ data={"target_team_ids": [self.team2.id, self.team3.id]},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert not Survey.objects.filter(team__in=[self.team2, self.team3]).exists()++ @parameterized.expand([("private_project", True, 403, 0), ("open_project", False, 201, 1)])+ def test_bulk_duplicate_resolves_an_environment_to_its_project(+ self, _name: str, project_private: bool, expected_status: int, expected_project_surveys: int+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ environment = Team.objects.create(organization=self.organization, name="Team 3 env", parent_team=self.team3)+ if project_private:+ AccessControl.objects.create(+ team=self.team3, resource="project", resource_id=str(self.team3.id), access_level="none"+ )+ member = self._create_user("[email protected]", level=OrganizationMembership.Level.MEMBER)+ self.client.force_login(member)++ response = self.client.post(+ f"/api/projects/{self.team.project_id}/surveys/{self.source_survey.id}/duplicate_to_projects/",+ data={"target_team_ids": [environment.id]},+ format="json",+ )++ assert response.status_code == expected_status, response.content+ assert Survey.objects.filter(team=self.team3).count() == expected_project_surveys+ assert not Survey.objects.filter(team=environment).exists()++ def test_bulk_duplicate_rejects_key_not_scoped_to_target(self) -> None:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="source-project-only",+ secure_value=hash_key_value(token),+ scopes=["survey:write"],+ scoped_teams=[self.team.id],+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.project_id}/surveys/{self.source_survey.id}/duplicate_to_projects/",+ data={"target_team_ids": [self.team2.id]},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert not Survey.objects.filter(team=self.team2).exists()++ def test_bulk_duplicate_only_targets_projects_in_the_source_organization(self) -> None:+ # bootstrap makes the new organization the user's current one, so it differs from the source organization+ _, _, other_org_team = Organization.objects.bootstrap(self.user)+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="source-org-only",+ secure_value=hash_key_value(token),+ scopes=["survey:write"],+ scoped_organizations=[str(self.organization.id)],+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.project_id}/surveys/{self.source_survey.id}/duplicate_to_projects/",+ data={"target_team_ids": [other_org_team.id]},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert not Survey.objects.filter(team=other_org_team).exists()+def test_bulk_duplicate_multiple_times_to_same_team(self):"""Test that multiple duplications to the same team create surveys with different timestamps"""with time_machine.travel("2024-01-01 00:00:00", tick=False) as frozen_time:diff --git a/products/surveys/frontend/generated/api.ts b/products/surveys/frontend/generated/api.tsindex 710903ce828b..946f8f52efc0 100644--- a/products/surveys/frontend/generated/api.ts+++ b/products/surveys/frontend/generated/api.ts@@ -309,6 +309,8 @@ export const getSurveysDuplicateToProjectsCreateUrl = (projectId: string, id: st* Duplicate a survey to multiple projects in a single transaction.** Accepts a list of target team IDs and creates a copy of the survey in each project.+ * Every target project must be in the source project's organization, and the caller needs+ * survey editor access in each one.* Uses an all-or-nothing approach - if any duplication fails, all changes are rolled back.*/export const surveysDuplicateToProjectsCreate = async (diff --git a/products/surveys/frontend/generated/api.zod.ts b/products/surveys/frontend/generated/api.zod.tsindex 285ca3b05bbe..a81225b9fd19 100644--- a/products/surveys/frontend/generated/api.zod.ts+++ b/products/surveys/frontend/generated/api.zod.ts@@ -2674,6 +2674,8 @@ export const SurveysPartialUpdateBody = /* @__PURE__ */ zod.object({* Duplicate a survey to multiple projects in a single transaction.** Accepts a list of target team IDs and creates a copy of the survey in each project.+ * Every target project must be in the source project's organization, and the caller needs+ * survey editor access in each one.* Uses an all-or-nothing approach - if any duplication fails, all changes are rolled back.*/export const surveysDuplicateToProjectsCreateBodyNameMax = 400