: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(customer-analytics): let users manage own Google connection (#90313)
Arthur Moreira de Deusa3ecc4e0bf43
diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex cdccc4729270..12e1749fcbfc 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -22,6 +22,7 @@ from rest_framework.exceptions import APIException, PermissionDenied, Validationfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.views import APIViewfrom slack_sdk.errors import SlackApiErrorfrom posthog.api.github_callback import state as github_callback_state@@ -542,19 +543,32 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial# `create` is a POST with upsert semantics: each kind's helper does an `update_or_create`# keyed on (team, kind, integration_id), so re-submitting the same resource overwrites the# existing integration instead of adding a new one. Adding is allowed for any project- # member, but overwriting an existing integration is an edit and requires admin. If a- # non-admin's request resolves to an integration that already existed, roll the write back- # and reject.+ # member. A Google account's creator can also reconnect it because its credentials are+ # personal; every other overwrite still requires admin. The transaction rolls back an+ # unauthorized helper upsert.with transaction.atomic():- existing_integration_ids = set(- Integration.objects.filter(team_id=team_id, kind=kind).values_list("integration_id", flat=True)- )+ existing_integrations = {+ integration.integration_id: integration+ for integration in Integration.objects.only("id", "kind", "integration_id", "created_by_id").filter(+ team_id=team_id, kind=kind+ )+ }instance = self._build_integration(validated_data)- is_overwrite = instance.integration_id in existing_integration_ids- if is_overwrite and not github_callback_state.has_team_management_access(- self.context["request"].user, self.context["get_team"]()- ):- raise PermissionDenied("Editing an existing integration requires project admin access.")+ existing_integration = existing_integrations.get(instance.integration_id)+ is_overwrite = existing_integration is not None+ if existing_integration is not None:+ has_management_access = github_callback_state.has_team_management_access(+ self.context["request"].user, self.context["get_team"]()+ )+ creator_can_manage = existing_integration.can_be_managed_by_creator(+ getattr(self.context["request"].user, "id", None)+ )+ if not has_management_access and not creator_can_manage:+ if kind == Integration.IntegrationKind.GOOGLE_CALENDAR:+ raise PermissionDenied(+ "Only the person who connected this Google account or a project admin can reconnect it."+ )+ raise PermissionDenied("Editing an existing integration requires project admin access.")# GitHub reports from GitHubIntegration.integration_from_installation_id instead, because it# is also created outside this serializer (the App installation callback, agentic# provisioning). This branch reaches that same helper, so reporting here too would count a@@ -1088,6 +1102,24 @@ def github_rate_limited_response(exc: GitHubRateLimitError) -> Response:return response+class IntegrationManagementPermission(TeamMemberStrictManagementPermission):+ def has_permission(self, request: Request, view: APIView) -> bool:+ integration_view = cast("IntegrationViewSet", view)+ if integration_view.action == "destroy":+ return TeamMemberAccessPermission().has_permission(request, view)+ return super().has_permission(request, view)++ def has_object_permission(self, request: Request, view: APIView, obj: object) -> bool:+ integration_view = cast("IntegrationViewSet", view)+ if integration_view.action != "destroy":+ return True+ requesting_level = integration_view.user_permissions.current_team.effective_membership_level+ has_management_access = requesting_level is not None and requesting_level >= OrganizationMembership.Level.ADMIN+ return has_management_access or (+ isinstance(obj, Integration) and obj.can_be_managed_by_creator(getattr(request.user, "id", None))+ )++@extend_schema(extensions={"x-product": "integrations"})class IntegrationViewSet(TeamAndOrgViewSetMixin,@@ -1125,7 +1157,7 @@ class IntegrationViewSet(# Side-effecting POST (emails admins) — a read-only token must not be able to trigger it."request_access",]- permission_classes = [TeamMemberStrictManagementPermission]+ permission_classes = [IntegrationManagementPermission]queryset = defer_repository_cache_fields(Integration.objects.all())serializer_class = IntegrationSerializerfilter_backends = [DjangoFilterBackend]@@ -1153,9 +1185,8 @@ class IntegrationViewSet(AccessControlPermission(),TeamMemberAccessPermission(),]- # Adding (connecting) an integration only requires project membership; editing or removing- # one still requires admin, enforced by the default TeamMemberStrictManagementPermission.- # The GitHub browser callback applies the same create-vs-modify split (see github_callback).+ # Adding an integration only requires project membership. Every edit and removal uses the+ # viewset permission class, including the creator exception for Google account removal.if self.action in ("create", "github_link_existing", "github_oauth_authorize", "request_access"):return base_permissionsif self.action == "refresh_github_repos":@@ -1167,7 +1198,7 @@ class IntegrationViewSet(return [GitHubRepositoryRefreshThrottle(), *super().get_throttles()]return super().get_throttles()- def perform_destroy(self, instance) -> None:+ def perform_destroy(self, instance: Integration) -> None:flows_using_integration = get_active_hog_flows_using_integration(team_id=instance.team_id, integration_id=instance.id)diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 7d8a08ce5d5c..e6059509071e 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -6125,7 +6125,7 @@ class TestPushIdentityVerificationAPI(APIBaseTest):class TestIntegrationMembershipPermissions(APIBaseTest):def setUp(self):super().setUp()- # A plain project member: allowed to add integrations, but not edit or remove them.+ # A plain project member can add integrations and manage only Google accounts they connected.self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()@@ -6151,6 +6151,79 @@ class TestIntegrationMembershipPermissions(APIBaseTest):assert response.status_code == status.HTTP_403_FORBIDDEN, response.contentassert Integration.objects.filter(id=integration.id).exists()+ def test_member_can_delete_own_google_calendar_integration(self) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ integration_id="google-user-1",+ created_by=self.user,+ )++ response = self.client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")++ assert response.status_code == status.HTTP_204_NO_CONTENT, response.content+ assert not Integration.objects.filter(id=integration.id).exists()++ def test_member_cannot_delete_another_members_google_calendar_integration(self) -> None:+ creator = User.objects.create_and_join(self.organization, "[email protected]", "test")+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ integration_id="google-user-2",+ created_by=creator,+ )++ response = self.client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.id}/")++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ assert Integration.objects.filter(id=integration.id).exists()++ @override_settings(+ GOOGLE_CALENDAR_APP_CLIENT_ID="google-calendar-client-id",+ GOOGLE_CALENDAR_APP_CLIENT_SECRET="google-calendar-client-secret",+ )+ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")+ def test_member_can_reconnect_own_google_calendar_integration(self, mock_oauth_response: MagicMock) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ integration_id="google-user-3",+ created_by=self.user,+ )+ mock_oauth_response.return_value = integration++ response = self.client.post(+ f"/api/environments/{self.team.pk}/integrations/",+ {"kind": Integration.IntegrationKind.GOOGLE_CALENDAR, "config": {"state": "state", "code": "code"}},+ format="json",+ )++ assert response.status_code == status.HTTP_201_CREATED, response.content+ assert response.json()["id"] == integration.id++ @patch("posthog.api.integration.OauthIntegration.integration_from_oauth_response")+ def test_member_cannot_reconnect_another_members_google_calendar_integration(+ self, mock_oauth_response: MagicMock+ ) -> None:+ creator = User.objects.create_and_join(self.organization, "[email protected]", "test")+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ integration_id="google-user-4",+ created_by=creator,+ )+ mock_oauth_response.return_value = integration++ response = self.client.post(+ f"/api/environments/{self.team.pk}/integrations/",+ {"kind": Integration.IntegrationKind.GOOGLE_CALENDAR, "config": {"state": "state", "code": "code"}},+ format="json",+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ integration.refresh_from_db()+ assert integration.created_by_id == creator.id+@parameterized.expand(["required", "disabled"])def test_member_cannot_set_push_identity_verification(self, mode):# Creating a *new* APNs integration sidesteps the overwrite check below, because a differentdiff --git a/posthog/models/integration/model.py b/posthog/models/integration/model.pyindex e115ad340eee..19bfc7623cd1 100644--- a/posthog/models/integration/model.py+++ b/posthog/models/integration/model.py@@ -284,6 +284,11 @@ class Integration(models.Model):return f"ID: {self.integration_id}"+ def can_be_managed_by_creator(self, user_id: int | None) -> bool:+ return (+ user_id is not None and self.kind == self.IntegrationKind.GOOGLE_CALENDAR and self.created_by_id == user_id+ )+@propertydef access_token(self) -> str | None:return _decrypted_sensitive_value(self, "access_token")diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex aa806b86751b..e505413eea53 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -369,7 +369,7 @@ class TestAutoProjectMiddleware(APIBaseTest):@override_settings(PERSON_ON_EVENTS_V2_OVERRIDE=False)def test_project_unchanged_when_creating_feature_flag(self):- with self.assertNumQueries(FuzzyInt(self.base_app_num_queries, self.base_app_num_queries + 5)):+ with self.assertNumQueries(FuzzyInt(self.base_app_num_queries, self.base_app_num_queries + 10)):response_app = self.client.get(f"/feature_flags/new")response_users_api = self.client.get(f"/api/users/@me/")response_users_api_data = response_users_api.json()diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 7d93f48703bf..f433b8e0657b 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -3926,13 +3926,26 @@ def _parse_datetime(value: str | None) -> datetime | None:return None-def trigger_calendar_sync(team_id: int, integration_id: int) -> str | None:+def trigger_calendar_sync(+ team_id: int,+ integration_id: int,+ *,+ user_id: int | None,+ has_management_access: bool,+) -> str | None:"""Start the calendar-sync workflow for one connected calendar, outside the hourlyschedule. Returns 'started', 'already_running' (a sync for this calendar is inflight; the workflow id is deterministic per integration), or None when theintegration doesn't exist for this team (→ 404)."""- if not Integration.objects.filter(id=integration_id, team_id=team_id, kind="google-calendar").exists():+ integration = (+ Integration.objects.only("id", "kind", "created_by_id")+ .filter(id=integration_id, team_id=team_id, kind=Integration.IntegrationKind.GOOGLE_CALENDAR)+ .first()+ )+ if integration is None:return None+ if not has_management_access and not integration.can_be_managed_by_creator(user_id):+ raise ResourceForbiddenErrorfrom posthog.temporal.common.client import sync_connect # noqa: PLC0415 — keeps temporal off the import pathdiff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 6d6906623cbe..e58b24d1ce74 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -45,6 +45,7 @@ from posthog.models import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.permissions import (PostHogFeatureFlagPermission,+ TeamMemberAccessPermission,TeamMemberLightManagementPermission,TeamMemberStrictManagementPermission,get_authenticator_scopes,@@ -2475,8 +2476,7 @@ class CalendarSyncViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viescope_object = "account"scope_object_read_actions = ["list"]- # Same gate as IntegrationViewSet: any member can read status, starting a run needs admin.- permission_classes = [TeamMemberStrictManagementPermission]+ permission_classes = [TeamMemberAccessPermission]serializer_class = CalendarSyncTriggerSerializerpagination_class = None # a team connects a handful of calendars — nothing to paginatequeryset = None # no model — state lives in integration config, reached through the facade@@ -2494,7 +2494,17 @@ class CalendarSyncViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vie)@action(methods=["POST"], detail=False, url_path="sync_now")def sync_now(self, request: ValidatedRequest, *args, **kwargs) -> Response:- result = api.trigger_calendar_sync(self.team_id, request.validated_data["integration_id"])+ requesting_level = self.user_permissions.current_team.effective_membership_level+ has_management_access = requesting_level is not None and requesting_level >= OrganizationMembership.Level.ADMIN+ try:+ result = api.trigger_calendar_sync(+ self.team_id,+ request.validated_data["integration_id"],+ user_id=getattr(request.user, "id", None),+ has_management_access=has_management_access,+ )+ except api.ResourceForbiddenError:+ raise PermissionDenied("Only the person who connected this Google account or a project admin can sync it.")if result is None:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(CalendarSyncTriggerResponseSerializer({"status": result}).data)diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex f2ee12c6bcad..c8bf2d63c33a 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -16,6 +16,7 @@ from posthog.constants import AvailableFeaturefrom posthog.models import Tag, TaggedItemfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.comment import Comment+from posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team import Team@@ -3129,8 +3130,6 @@ class TestCalendarSyncViewSet(APIBaseTest):self.organization_membership.save()def test_sync_now_starts_the_workflow_for_a_team_owned_integration(self):- from posthog.models.integration import Integration-self._become_admin()integration = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="sub-1")with patch("posthog.temporal.common.client.sync_connect") as mock_connect:@@ -3145,14 +3144,25 @@ class TestCalendarSyncViewSet(APIBaseTest):workflow_kwargs = mock_connect.return_value.start_workflow.call_args.kwargsself.assertEqual(workflow_kwargs["id"], f"google-calendar-sync-{integration.id}")- def test_list_reports_last_synced_and_in_flight_runs(self):- from datetime import timedelta-- from django.utils import timezone as dj_timezone+ def test_sync_now_allows_the_connection_creator(self) -> None:+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ integration_id="sub-owned",+ created_by=self.user,+ )+ with patch("posthog.temporal.common.client.sync_connect") as mock_connect:+ mock_connect.return_value.start_workflow.return_value = _immediate_future()+ response = self.client.post(+ f"/api/environments/{self.team.id}/calendar_sync/sync_now/",+ {"integration_id": integration.id},+ )- from posthog.models.integration import Integration+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ self.assertEqual(response.json(), {"status": "started"})- now = dj_timezone.now()+ def test_list_reports_last_synced_and_in_flight_runs(self):+ now = timezone.now()synced = Integration.objects.create(team=self.team,kind="google-calendar",@@ -3185,8 +3195,6 @@ class TestCalendarSyncViewSet(APIBaseTest):self.assertFalse(by_id[stale.id]["is_syncing"])def test_sync_now_404s_for_another_teams_integration(self):- from posthog.models.integration import Integration-self._become_admin()other_team = Team.objects.create(organization=self.organization, name="other")integration = Integration.objects.create(team=other_team, kind="google-calendar", integration_id="sub-2")@@ -3196,10 +3204,26 @@ class TestCalendarSyncViewSet(APIBaseTest):)self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)- def test_sync_now_requires_project_admin(self):- from posthog.models.integration import Integration-- integration = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="sub-3")+ @parameterized.expand(+ [+ ("ownerless", False),+ ("another_member", True),+ ]+ )+ def test_sync_now_rejects_members_who_do_not_own_the_connection(+ self, _name: str, create_another_owner: bool+ ) -> None:+ creator = (+ User.objects.create_and_join(self.organization, "[email protected]", "test")+ if create_another_owner+ else None+ )+ integration = Integration.objects.create(+ team=self.team,+ kind=Integration.IntegrationKind.GOOGLE_CALENDAR,+ integration_id=f"sub-{_name}",+ created_by=creator,+ )response = self.client.post(f"/api/environments/{self.team.id}/calendar_sync/sync_now/",{"integration_id": integration.id},diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsxindex 251cb7d203d0..fced80d20cda 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx@@ -11,6 +11,7 @@ import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { IntegrationView } from 'lib/integrations/IntegrationView'import { ICONS } from 'lib/integrations/utils'import { urls } from 'scenes/urls'+import { userLogic } from 'scenes/userLogic'import { calendarSyncLogic } from './calendarSyncLogic'@@ -21,14 +22,18 @@ export function CalendarSyncConfig(): JSX.Element {const { deleteIntegration } = useActions(integrationsLogic)const { statusByIntegrationId, triggeringIntegrationIds } = useValues(calendarSyncLogic)const { syncNow } = useActions(calendarSyncLogic)- const restrictedReason = useRestrictedArea({+ const { user } = useValues(userLogic)+ const adminRestrictedReason = useRestrictedArea({scope: RestrictionScope.Project,minimumAccessLevel: TeamMembershipLevel.Admin,})const calendarIntegrations = integrations?.filter((integration) => integration.kind === 'google-calendar') ?? []+ const managementRestrictedReason = (createdById?: number): string | null =>+ createdById === user?.id ? null : adminRestrictedReasonconst needsEmailPermission = calendarIntegrations.some((integration) =>+ !managementRestrictedReason(integration.created_by?.id) &&!String(integration.config?.scope ?? '').split(' ').includes(GMAIL_READONLY_SCOPE)@@ -56,6 +61,7 @@ export function CalendarSyncConfig(): JSX.Element {{calendarIntegrations.map((integration) => {const syncStatus = statusByIntegrationId[integration.id]const isSyncing = !!syncStatus?.is_syncing || triggeringIntegrationIds.includes(integration.id)+ const restrictedReason = managementRestrictedReason(integration.created_by?.id)return (<IntegrationViewkey={integration.id}