: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(invites): keep pending invites above the inviter's grant (#122926)
Tom Piccirellod92bd37d4803
diff --git a/posthog/api/organization_invite.py b/posthog/api/organization_invite.pyindex b7a44ab6f02c..d83215346b98 100644--- a/posthog/api/organization_invite.py+++ b/posthog/api/organization_invite.py@@ -1,4 +1,5 @@import concurrent.futures+from collections.abc import Iterablefrom datetime import timedeltafrom typing import Any, Optional, castfrom uuid import UUID@@ -67,18 +68,9 @@ _DELEGATION_FLAG_MAX_QUEUE = _DELEGATION_FLAG_MAX_WORKERS * 2class OrganizationInviteManager:@staticmethod- def combine_invites(- organization_id: UUID | str, validated_data: dict[str, Any], combine_pending_invites: bool = True- ) -> dict[str, Any]:- """Combines multiple pending invites for the same email address."""- if not combine_pending_invites:- return validated_data-- existing_invites = OrganizationInviteManager._get_invites_for_user_org(- organization_id=organization_id, target_email=validated_data["target_email"]- )-- if not existing_invites.exists():+ def combine_invites(validated_data: dict[str, Any], existing_invites: list[OrganizationInvite]) -> dict[str, Any]:+ """Combines the given pending invites for the same email address into the new invite."""+ if not existing_invites:return validated_datavalidated_data["level"] = OrganizationInviteManager._get_highest_level(@@ -107,13 +99,13 @@ class OrganizationInviteManager:return OrganizationInvite.objects.filter(**filters).order_by("-created_at")@staticmethod- def _get_highest_level(existing_invites: QuerySet, new_level: int) -> int:+ def _get_highest_level(existing_invites: Iterable[OrganizationInvite], new_level: int) -> int:levels = [invite.level for invite in existing_invites]levels.append(new_level)return max(levels)@staticmethod- def _combine_project_access(existing_invites: QuerySet, new_access: list[dict]) -> list[dict]:+ def _combine_project_access(existing_invites: Iterable[OrganizationInvite], new_access: list[dict]) -> list[dict]:combined_access: dict[int, int] = {}# Add new access first@@ -133,13 +125,19 @@ class OrganizationInviteManager:return [{"id": project_id, "level": level} for project_id, level in combined_access.items()]@staticmethod- def delete_existing_invites(organization_id: UUID | str, target_email: str) -> None:- """Deletes all existing invites for a given email in an organization."""- OrganizationInviteManager._get_invites_for_user_org(- organization_id=organization_id, target_email=target_email, include_expired=True+ def delete_invites(organization_id: UUID | str, invites: list[OrganizationInvite]) -> None:+ OrganizationInvite.objects.filter(+ organization_id=organization_id, id__in=[invite.id for invite in invites]).delete()+def _project_access_level_exceeds(*, requested_level: str, granted_level: Optional[str]) -> bool:+ levels: list[str] = [*ordered_access_levels("project")]+ granted_rank = levels.index(granted_level) if granted_level in levels else 0+ requested_rank = levels.index(requested_level) if requested_level in levels else 0+ return requested_rank > granted_rank++def first_bulk_invite_error(errors: list[Any]) -> exceptions.ValidationError:"""A many=True error is a list of per-row dicts the exception handler can't flatten — clients would@@ -281,39 +279,67 @@ class OrganizationInviteSerializer(serializers.ModelSerializer):# User is not an org admin/ownerpass- user_access_control = UserAccessControl(user=self.context["request"].user, team=team)- access_level = user_access_control.access_level_for_object(team)+ access_level = self._inviter_project_access_level(team)if access_level == "none":raise exceptions.ValidationError(team_error)# Check if user is trying to invite with a higher level than their own- levels = ordered_access_levels("project")- user_level_rank = levels.index(access_level) if access_level in levels else 0- requested_level_rank = levels.index(level) if level in levels else 0-- if requested_level_rank > user_level_rank:+ if _project_access_level_exceeds(requested_level=level, granted_level=access_level):raise exceptions.ValidationError("You cannot invite to a restricted project with a higher level than your own.")return private_project_access+ def _inviter_project_access_level(self, team: Team) -> Optional[str]:+ user_access_control = UserAccessControl(user=self.context["request"].user, team=team)+ return user_access_control.access_level_for_object(team)++ def _inviter_can_grant(self, invite: OrganizationInvite, inviter_membership: OrganizationMembership) -> bool:+ # Combining or replacing a pending invite carries its grants into the new invite, or removes them.+ # The field validators check only the request, so the inviter may only combine or replace an invite+ # whose level and project access they could have granted themselves.+ if invite.level > inviter_membership.level:+ return False+ if inviter_membership.level >= OrganizationMembership.Level.ADMIN:+ return True+ for item in invite.private_project_access or []:+ team = Team.objects.filter(organization_id=self.context["organization_id"], id=item["id"]).first()+ if team is None:+ return False+ access_level = self._inviter_project_access_level(team)+ if access_level == "none" or _project_access_level_exceeds(+ requested_level=item["level"], granted_level=access_level+ ):+ return False+ return True+def create(self, validated_data: dict[str, Any], *args: Any, **kwargs: Any) -> OrganizationInvite:combine_pending_invites = validated_data.pop("combine_pending_invites", False)send_email = validated_data.pop("send_email", True)+ inviter_membership = OrganizationMembership.objects.get(+ organization_id=self.context["organization_id"], user=self.context["request"].user+ )++ replaceable_invites = [+ invite+ for invite in OrganizationInviteManager._get_invites_for_user_org(+ organization_id=self.context["organization_id"],+ target_email=validated_data["target_email"],+ include_expired=True,+ )+ if self._inviter_can_grant(invite, inviter_membership)+ ]# Handle invite combination if requestedif combine_pending_invites:validated_data = OrganizationInviteManager.combine_invites(- organization_id=self.context["organization_id"],validated_data=validated_data,- combine_pending_invites=True,+ existing_invites=[invite for invite in replaceable_invites if not invite.is_expired()],)# Delete existing invites for this email- OrganizationInviteManager.delete_existing_invites(- organization_id=self.context["organization_id"], target_email=validated_data["target_email"]- )+ OrganizationInviteManager.delete_invites(self.context["organization_id"], replaceable_invites)# Create new inviteinvite: OrganizationInvite = OrganizationInvite.objects.create(diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 0975483c647c..dfd38182b88a 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -922,9 +922,15 @@ def lookup_invite_for_saml(email: str, saml_relay_state: str) -> Optional[Organiorganization_id=config.organization_id, user__email__iexact=email).exists():return None+ # An email can hold more than one pending invite in an organization, so use the unexpired one with the+ # highest level. An expired invite fails the same validation as a duplicate membership above.return (- OrganizationInvite.objects.filter(target_email__iexact=email, organization_id=config.organization_id)- .order_by("-created_at")+ OrganizationInvite.objects.filter(+ target_email__iexact=email,+ organization_id=config.organization_id,+ created_at__gt=timezone.now() - timedelta(days=INVITE_DAYS_VALIDITY),+ )+ .order_by("-level", "-created_at").first())@@ -1045,9 +1051,19 @@ def process_social_domain_jit_provisioning_signup(_refuse_blocked_sso_join(strategy, backend, email, user)if not user:try:- invite: OrganizationInvite = OrganizationInvite.objects.get(- target_email__iexact=email, organization=domain_instance.organization+ # An email can hold more than one pending invite in an organization, so accept+ # the one with the highest level.+ invite = (+ OrganizationInvite.objects.filter(+ target_email__iexact=email,+ organization=domain_instance.organization,+ created_at__gt=timezone.now() - timedelta(days=INVITE_DAYS_VALIDITY),+ )+ .order_by("-level", "-created_at")+ .first())+ if invite is None:+ raise OrganizationInvite.DoesNotExist()invite.validate(user=None, email=email)# Capture before invite.use() deletes the invite row.is_delegation = bool(getattr(invite, "is_setup_delegation", False))diff --git a/posthog/api/test/test_organization_invites.py b/posthog/api/test/test_organization_invites.pyindex 9e4204bb9796..3f23588e51fd 100644--- a/posthog/api/test/test_organization_invites.py+++ b/posthog/api/test/test_organization_invites.py@@ -952,6 +952,50 @@ class TestOrganizationInvitesAPI(APIBaseTest):# Check that new invite uses its own levelself.assertEqual(new_invite["level"], OrganizationMembership.Level.MEMBER)+ @parameterized.expand(+ [+ ("combine_above_level", True, OrganizationMembership.Level.ADMIN, False),+ ("combine_above_project_access", True, OrganizationMembership.Level.MEMBER, True),+ ("replace_above_level", False, OrganizationMembership.Level.ADMIN, False),+ ("replace_above_project_access", False, OrganizationMembership.Level.MEMBER, True),+ ]+ )+ def test_member_reinvite_keeps_pending_invite_above_their_grant(+ self, _name: str, combine: bool, existing_level: OrganizationMembership.Level, with_private_access: bool+ ) -> None:+ owner = self._create_user("[email protected]", level=OrganizationMembership.Level.OWNER)+ member = self._create_user("[email protected]")+ email = "[email protected]"+ private_access: list[dict[str, int | str]] = []+ if with_private_access:+ private_team = Team.objects.create(organization=self.organization, name="Private Team")+ AccessControl.objects.create(+ team=private_team, access_level="none", resource="project", resource_id=str(private_team.id)+ )+ private_access = [{"id": private_team.id, "level": "admin"}]+ existing_invite = OrganizationInvite.objects.create(+ organization=self.organization,+ target_email=email,+ level=existing_level,+ private_project_access=private_access,+ created_by=owner,+ )+ self.client.force_login(member)++ response = self.client.post(+ "/api/organizations/@current/invites/",+ {"target_email": email, "level": OrganizationMembership.Level.MEMBER, "combine_pending_invites": combine},+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["level"], OrganizationMembership.Level.MEMBER)+ self.assertEqual(response.json()["private_project_access"], [])+ self.assertTrue(+ OrganizationInvite.objects.filter(+ id=existing_invite.id, level=existing_level, private_project_access=private_access, created_by=owner+ ).exists()+ )+def test_member_cannot_invite_admin(self):# Create a member usermember_user = self._create_user("[email protected]")diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 8153ba1d8f08..f4d35575d677 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -920,7 +920,11 @@ class TestSignupAPI(APIBaseTest):use_invite: bool = False,expired_invite: bool = False,asserted_email: str = "[email protected]",+ newer_member_invite: bool = False,):+ expected_level = (+ OrganizationMembership.Level.ADMIN if newer_member_invite else OrganizationMembership.Level.MEMBER+ )# Make sure Google Auth is valid for this test instancemock_sso_providers.return_value = {"google-oauth2": True}@@ -939,9 +943,15 @@ class TestSignupAPI(APIBaseTest):target_email="[email protected]",organization=new_org,first_name="Jane",- level=OrganizationMembership.Level.MEMBER,+ level=expected_level,private_project_access=[{"id": private_project.id, "level": "admin"}],)+ if newer_member_invite:+ OrganizationInvite.objects.create(+ target_email="[email protected]",+ organization=new_org,+ level=OrganizationMembership.Level.MEMBER,+ )if expired_invite:invite.created_at = timezone.now() - timedelta(days=30) # Set invite to 30 days oldinvite.save()@@ -972,7 +982,7 @@ class TestSignupAPI(APIBaseTest):self.assertEqual(user.organization_memberships.count(), 1)self.assertEqual(cast(OrganizationMembership, user.organization_memberships.first()).level,- OrganizationMembership.Level.MEMBER,+ expected_level,)signup_calls = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user signed up"]assert signup_calls, "expected a 'user signed up' capture call"@@ -1011,16 +1021,27 @@ class TestSignupAPI(APIBaseTest):def test_social_signup_with_allowed_domain_on_self_hosted(self, mock_sso_providers, mock_request, mock_capture):self.run_test_for_allowed_domain(mock_sso_providers, mock_request, mock_capture)- @parameterized.expand(["[email protected]", "[email protected]"])+ @parameterized.expand(+ [+ ("[email protected]", False),+ ("[email protected]", False),+ ("[email protected]", True),+ ]+ )@patch("posthoganalytics.capture")@mock.patch("social_core.backends.base.BaseAuth.request")@mock.patch("posthog.api.authentication.get_instance_available_sso_providers")@pytest.mark.eedef test_social_signup_with_allowed_domain_uses_invite(- self, asserted_email, mock_sso_providers, mock_request, mock_capture+ self, asserted_email, newer_member_invite, mock_sso_providers, mock_request, mock_capture):self.run_test_for_allowed_domain(- mock_sso_providers, mock_request, mock_capture, use_invite=True, asserted_email=asserted_email+ mock_sso_providers,+ mock_request,+ mock_capture,+ use_invite=True,+ asserted_email=asserted_email,+ newer_member_invite=newer_member_invite,)@mock.patch("social_core.backends.base.BaseAuth.request")@@ -3627,17 +3648,40 @@ class TestSAMLInviteLookup(APIBaseTest):assert config.saml_relay_state is not Nonereturn config.saml_relay_state- @parameterized.expand(["[email protected]", "[email protected]"])- def test_finds_the_invite_for_the_config_that_signed_the_assertion(self, asserted_email):+ @parameterized.expand(+ [+ ("[email protected]", False, False),+ ("[email protected]", False, False),+ ("[email protected]", True, False),+ ("[email protected]", True, True),+ ]+ )+ def test_finds_the_invite_for_the_config_that_signed_the_assertion(+ self, asserted_email, newer_member_invite, admin_invite_expired+ ):identifier = self._saml_identifier_for("saml-invite.example.com")- invite = OrganizationInvite.objects.create(- organization=self.organization, target_email="[email protected]"- )+ admin_invite = OrganizationInvite.objects.create(+ organization=self.organization,+ target_email="[email protected]",+ level=OrganizationMembership.Level.ADMIN,+ )+ if admin_invite_expired:+ admin_invite.created_at = timezone.now() - timedelta(days=INVITE_DAYS_VALIDITY + 5)+ admin_invite.save()+ member_invite = None+ if newer_member_invite:+ member_invite = OrganizationInvite.objects.create(+ organization=self.organization,+ target_email="[email protected]",+ level=OrganizationMembership.Level.MEMBER,+ )found = lookup_invite_for_saml(asserted_email, identifier)+ expected_invite = member_invite if admin_invite_expired else admin_inviteassert found is not None- assert found.id == invite.id+ assert expected_invite is not None+ assert found.id == expected_invite.iddef test_finds_it_when_the_identifier_no_longer_matches_a_domain(self):# The identifier holds a domain id on configs created before it moved onto the config, and