: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(projects): log a project org move for the losing organization (#92042)
posthog[bot]390d0720fe22
diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 34e86a3e52dc..0915081efd17 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -1965,63 +1965,109 @@ class ProjectViewSet(user = cast(User, request.user)target_organization_id = request.data.get("organization_id")- current_organization = project.organization- try:- target_organization = Organization.objects.get(pk=target_organization_id)- current_organization_membership = OrganizationMembership.objects.get(- user=user, organization=current_organization- )- target_organization_membership = OrganizationMembership.objects.get(- user=user, organization=target_organization- )+ with transaction.atomic():+ # Lock the project row so concurrent moves serialize: each request re-reads the+ # organization and teams only after the previous move has committed, so snapshots+ # never go stale and no departure is recorded twice.+ try:+ project = Project.objects.select_for_update().get(pk=project.pk)+ except Project.DoesNotExist:+ raise exceptions.NotFound("Project not found.")- if (- current_organization_membership.level < OrganizationMembership.Level.ADMIN- or target_organization_membership.level < OrganizationMembership.Level.ADMIN- ):- raise exceptions.ValidationError(- "You must be an admin of both the source and target organizations to move a project."- )+ current_organization = project.organization- except (OrganizationMembership.DoesNotExist, Organization.DoesNotExist):- raise exceptions.ValidationError("You must be a member of the target organization to move a project.")+ try:+ target_organization = Organization.objects.get(pk=target_organization_id)+ current_organization_membership = OrganizationMembership.objects.get(+ user=user, organization=current_organization+ )+ target_organization_membership = OrganizationMembership.objects.get(+ user=user, organization=target_organization+ )- if project.organization_id == target_organization_id:- raise exceptions.ValidationError("Project is already in the target organization.")+ if (+ current_organization_membership.level < OrganizationMembership.Level.ADMIN+ or target_organization_membership.level < OrganizationMembership.Level.ADMIN+ ):+ raise exceptions.ValidationError(+ "You must be an admin of both the source and target organizations to move a project."+ )- teams = list(project.teams.all())+ except (OrganizationMembership.DoesNotExist, Organization.DoesNotExist):+ raise exceptions.ValidationError("You must be a member of the target organization to move a project.")++ # Compare resolved UUIDs: target_organization_id comes off the request body as a string, so+ # comparing it to the UUID organization_id never matches and would let a same-org request through.+ if project.organization_id == target_organization.id:+ raise exceptions.ValidationError("Project is already in the target organization.")++ teams = list(project.teams.all())+ was_impersonated = is_impersonated(request)+ project_change = Change(+ type="Project",+ action="changed",+ field="organization_id",+ before=str(current_organization.id),+ after=str(target_organization.id),+ )- with transaction.atomic():- project.organization_id = target_organization_id+ project.organization_id = target_organization.idproject.save()+ # Record the arrival for the receiving organization.log_activity(organization_id=cast(UUIDT, target_organization_id),team_id=project.pk,user=user,- was_impersonated=is_impersonated(request),+ was_impersonated=was_impersonated,scope="Project",item_id=project.pk,activity="updated",- detail=Detail(- name="moved to another organization",- changes=[- Change(- type="Project",- action="changed",- field="organization_id",- before=str(current_organization.id),- after=str(target_organization.id),- )- ],- ),+ detail=Detail(name="moved to another organization", changes=[project_change]),+ )++ # Record the departure for the losing organization. Its members can no longer reach the+ # project, so this org-scoped entry is their only readable record of who moved it and where.+ log_activity(+ organization_id=current_organization.id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ scope="Project",+ item_id=project.pk,+ activity="updated",+ # Name the project itself; the losing org can no longer resolve it any other way.+ detail=Detail(name=str(project.name), changes=[project_change]),)for team in teams:- team.organization_id = target_organization_id+ team.organization_id = target_organization.idteam.save()+ # One departure entry per environment, so the losing org sees which ones left.+ log_activity(+ organization_id=current_organization.id,+ team_id=None,+ user=user,+ was_impersonated=was_impersonated,+ scope="Team",+ item_id=team.pk,+ activity="updated",+ detail=Detail(+ name=str(team.name),+ changes=[+ Change(+ type="Team",+ action="changed",+ field="organization_id",+ before=str(current_organization.id),+ after=str(target_organization.id),+ )+ ],+ ),+ )+self._reconcile_current_project_of_affected_users(teams, target_organization)report_user_action(diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 8b95e41137d8..47a613d7bb80 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -1,3 +1,4 @@+import threadingfrom datetime import UTC, datetime, timedeltafrom typing import Any@@ -9,13 +10,13 @@ from unittest.mock import ANY, MagicMock, call, patchfrom django.core.cache import cachefrom django.db import OperationalErrorfrom django.http import HttpResponse-from django.test import SimpleTestCase, override_settings+from django.test import SimpleTestCase, TransactionTestCase, override_settingsfrom django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status, test-from posthog.api.project import ProjectBackwardCompatSerializer+from posthog.api.project import ProjectBackwardCompatSerializer, log_activityfrom posthog.api.team import (TEAM_CONFIG_FIELDS_SET,TEAM_CONFIG_MEMBER_FIELDS_SET,@@ -24,6 +25,7 @@ from posthog.api.team import (_reset_default_data_color_theme_id_cache,)from posthog.constants import AvailableFeature+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.event_ingestion_restriction_config import EventIngestionRestrictionConfig, RestrictionTypefrom posthog.models.group_type_mapping import (GROUP_TYPES_CACHE_KEY_PREFIX,@@ -1550,6 +1552,54 @@ def team_api_test_factory():outsider.refresh_from_db()assert outsider.current_team_id is None and outsider.current_organization_id is None+ def test_change_organization_logs_departure_for_source_organization(self):+ source_org = self.organization+ other_org, _ = self._create_other_org_and_team(OrganizationMembership.Level.ADMIN)+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ res = self.client.post(+ f"/api/projects/{self.team.project.id}/change_organization/", {"organization_id": other_org.id}+ )+ assert res.status_code == status.HTTP_200_OK, res.json()++ # The losing organization keeps a readable record even though it can no longer reach the project+ source_project_logs = ActivityLog.objects.filter(+ organization_id=source_org.id, scope="Project", item_id=str(self.project.pk)+ )+ assert source_project_logs.count() == 1+ source_project_log = source_project_logs.get()+ assert source_project_log.detail is not None+ # The row names the project that left, not action text, so the losing org can read it+ assert source_project_log.detail["name"] == self.project.name++ # And one entry per environment that left, so the source org sees which ones moved+ source_team_logs = ActivityLog.objects.filter(+ organization_id=source_org.id, scope="Team", item_id=str(self.team.pk)+ )+ assert source_team_logs.count() == 1++ # The receiving organization still gets its arrival entry+ assert ActivityLog.objects.filter(organization_id=other_org.id, scope="Project").count() == 1++ def test_change_organization_to_same_organization_is_rejected(self):+ # organization_id arrives from the request body as a string, so a same-org request must+ # still be caught by the guard, or it writes false move entries in the activity log.+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ logs_before = ActivityLog.objects.count()++ res = self.client.post(+ f"/api/projects/{self.team.project.id}/change_organization/",+ {"organization_id": str(self.organization.id)},+ )++ assert res.status_code == status.HTTP_400_BAD_REQUEST, res.json()+ assert res.json()["detail"] == "Project is already in the target organization."+ # A no-op move must not write audit rows+ assert ActivityLog.objects.count() == logs_before+def _assert_replay_config_is(self, expected: dict[str, Any] | None) -> HttpResponse:return self._assert_config_is("session_replay_config", expected)@@ -3103,6 +3153,118 @@ class TestTeamAPI(team_api_test_factory()): # type: ignore)+class TestChangeOrganizationConcurrency(TransactionTestCase):+ """Two moves of the same project must serialize on the project row lock.++ Without the lock, both requests read the pre-move organization before either+ commits, and both record a departure from it.+ """++ LOCK_WAIT_TIMEOUT = 15++ def setUp(self):+ self.org_a = Organization.objects.create(name="Org A")+ # A previous failed run can leave this user behind: the test database survives between runs.+ User.objects.filter(email="[email protected]").delete()+ self.user = User.objects.create_and_join(+ organization=self.org_a, email="[email protected]", password=None, level=OrganizationMembership.Level.ADMIN+ )+ self.org_b = Organization.objects.create(name="Org B")+ self.org_c = Organization.objects.create(name="Org C")+ for org in (self.org_b, self.org_c):+ OrganizationMembership.objects.create(+ user=self.user, organization=org, level=OrganizationMembership.Level.ADMIN+ )+ self.project, self.team = Project.objects.create_with_team(+ name="Concurrent", organization=self.org_a, initiating_user=self.user+ )++ def _move(self, target_org: Organization, results: dict, errors: list) -> None:+ try:+ client = test.APIClient()+ client.force_authenticate(user=self.user)+ res = client.post(+ f"/api/projects/{self.project.pk}/change_organization/",+ {"organization_id": str(target_org.id)},+ format="json",+ )+ results[str(target_org.id)] = res.status_code+ except Exception as error:+ errors.append(error)+ finally:+ from django.db import connections++ connections.close_all()++ def test_concurrent_moves_serialize_on_the_project_lock(self):+ errors: list[Exception] = []+ results: dict[str, int] = {}+ counter_lock = threading.Lock()+ select_calls = [0]+ log_calls = [0]+ first_request_locked = threading.Event()+ second_request_at_lock = threading.Event()+ release_first_request = threading.Event()++ real_select_for_update = Project.objects.select_for_update+ real_log_activity = log_activity++ def traced_select_for_update(*args: Any, **kwargs: Any):+ with counter_lock:+ select_calls[0] += 1+ call_number = select_calls[0]+ if call_number == 2:+ # The second request has built its locking queryset; its get() now blocks on the+ # row lock the first request still holds.+ second_request_at_lock.set()+ return real_select_for_update(*args, **kwargs)++ def traced_log_activity(**kwargs: Any):+ with counter_lock:+ log_calls[0] += 1+ call_number = log_calls[0]+ result = real_log_activity(**kwargs)+ if call_number == 1:+ # The first request signals once it holds the project row lock and has started+ # writing, and keeps its transaction open until the second request has reached+ # the lock, so both reads provably overlap.+ first_request_locked.set()+ if not release_first_request.wait(self.LOCK_WAIT_TIMEOUT):+ errors.append(AssertionError("Second request never reached the project lock"))+ return result++ with (+ patch.object(Project.objects, "select_for_update", traced_select_for_update),+ patch("posthog.api.project.log_activity", traced_log_activity),+ ):+ first = threading.Thread(target=self._move, args=(self.org_b, results, errors))+ first.start()+ assert first_request_locked.wait(self.LOCK_WAIT_TIMEOUT), "First request never acquired the project lock"++ second = threading.Thread(target=self._move, args=(self.org_c, results, errors))+ second.start()+ assert second_request_at_lock.wait(self.LOCK_WAIT_TIMEOUT), "Second request never reached the project lock"++ release_first_request.set()+ first.join(self.LOCK_WAIT_TIMEOUT)+ second.join(self.LOCK_WAIT_TIMEOUT)++ assert errors == []+ assert results == {str(self.org_b.id): 200, str(self.org_c.id): 200}++ self.project.refresh_from_db()+ assert self.project.organization_id == self.org_c.id++ # Each losing organization recorded exactly one departure, and the second one read the+ # organization the first move had committed: before == B, not the stale A.+ org_a_departure = ActivityLog.objects.get(organization_id=self.org_a.id, scope="Project", team_id=None)+ assert org_a_departure.detail is not None+ assert org_a_departure.detail["changes"][0]["before"] == str(self.org_a.id)+ org_b_departure = ActivityLog.objects.get(organization_id=self.org_b.id, scope="Project", team_id=None)+ assert org_b_departure.detail is not None+ assert org_b_departure.detail["changes"][0]["before"] == str(self.org_b.id)++class TestTeamSerializerHomeViewWins(APIBaseTest):def setUp(self):super().setUp()