π OpenHands: AI-Driven Development
feat: accept pending invitations by verified-email match at sign-in (#14759)
Alona121509ebc59f
diff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.pyindex 28a72b7ccb..55e5fa61c9 100644--- a/enterprise/server/routes/auth.py+++ b/enterprise/server/routes/auth.py@@ -582,6 +582,21 @@ async def keycloak_callback(else:redirect_url = f'{redirect_url}?invitation_error=true'+ # Accept pending invitations addressed to the user's email. Runs before+ # the default-org bootstrap so an invitation's role (e.g. admin) wins+ # over the bootstrap's auto-add member role for the same org.+ try:+ accepted_invitations = (+ await OrgInvitationService.accept_pending_invitations_for_user(user)+ )+ if accepted_invitations:+ user = await UserStore.get_user_by_id(user_id) or user+ except Exception as e:+ logger.exception(+ 'Unexpected error accepting pending invitations at login',+ extra={'user_id': user_id, 'error': str(e)},+ )+try:user = await DefaultOrgBootstrapService.apply_for_user(user,diff --git a/enterprise/server/services/org_invitation_service.py b/enterprise/server/services/org_invitation_service.pyindex eb6e264d49..a46efa5733 100644--- a/enterprise/server/services/org_invitation_service.py+++ b/enterprise/server/services/org_invitation_service.py@@ -19,6 +19,7 @@ from storage.org_member_store import OrgMemberStorefrom storage.org_service import OrgServicefrom storage.org_store import OrgStorefrom storage.role_store import RoleStore+from storage.user import Userfrom storage.user_store import UserStorefrom openhands.app_server.utils.logger import openhands_logger as logger@@ -254,6 +255,103 @@ class OrgInvitationService:return successful, failed+ @staticmethod+ async def accept_pending_invitations_for_user(user: User) -> list[OrgInvitation]:+ """Accept pending invitations matching the user's email at sign-in.++ SSO-native acceptance: the IdP verified the address an invitation was+ sent to, which is the same assurance as clicking the emailed token+ link β so the token never needs delivering. Also marks invitations+ accepted when the user is already a member (e.g. default-org auto-add+ joined them first), so they stop showing as pending.++ Returns:+ The invitations this call newly accepted with a membership.+ """+ user_email = (user.email or '').strip().lower()+ if not user_email:+ return []++ invitations = await OrgInvitationStore.get_pending_invitations_for_email(+ user_email+ )+ accepted: list[OrgInvitation] = []+ for invitation in invitations:+ if OrgInvitationStore.is_token_expired(invitation):+ await OrgInvitationStore.update_invitation_status(+ invitation.id, OrgInvitation.STATUS_EXPIRED+ )+ continue++ existing_member = await OrgMemberStore.get_org_member(+ invitation.org_id, user.id+ )+ if existing_member:+ await OrgInvitationStore.update_invitation_status(+ invitation.id,+ OrgInvitation.STATUS_ACCEPTED,+ accepted_by_user_id=user.id,+ )+ continue++ org = await OrgStore.get_org_by_id(invitation.org_id)+ if not org:+ continue++ try:+ settings = await OrgService.create_litellm_integration(+ invitation.org_id, str(user.id)+ )+ except Exception:+ logger.exception(+ 'Failed to create LiteLLM integration for login-time '+ 'invitation acceptance',+ extra={+ 'invitation_id': invitation.id,+ 'user_id': str(user.id),+ 'org_id': str(invitation.org_id),+ },+ )+ continue++ llm_api_key_secret = settings.agent_settings.llm.api_key+ llm_api_key = (+ llm_api_key_secret.get_secret_value() if llm_api_key_secret else '' # type: ignore[union-attr]+ )+ # Status flips LAST: any failure leaves the invitation pending so+ # the next sign-in retries it (the already-member branch above+ # reconciles a member whose status update was lost).+ await OrgMemberStore.add_user_to_org(+ org_id=invitation.org_id,+ user_id=user.id,+ role_id=invitation.role_id,+ llm_api_key=llm_api_key,+ status='active',+ agent_settings_diff={},+ conversation_settings_diff={},+ )+ await OrgInvitationStore.update_invitation_status(+ invitation.id,+ OrgInvitation.STATUS_ACCEPTED,+ accepted_by_user_id=user.id,+ )+ accepted.append(invitation)+ logger.info(+ 'Organization invitation accepted via email match at login',+ extra={+ 'invitation_id': invitation.id,+ 'user_id': str(user.id),+ 'org_id': str(invitation.org_id),+ },+ )++ # Land the user in the first newly joined org when they're parked on+ # their personal workspace; a deliberately chosen team org is kept.+ if accepted and user.current_org_id == user.id:+ await UserStore.update_current_org(str(user.id), accepted[0].org_id)++ return accepted+@staticmethodasync def accept_invitation(token: str, user_id: UUID) -> OrgInvitation:"""Accept an organization invitation.diff --git a/enterprise/storage/org_invitation_store.py b/enterprise/storage/org_invitation_store.pyindex ed21143b2c..cc629c6dff 100644--- a/enterprise/storage/org_invitation_store.py+++ b/enterprise/storage/org_invitation_store.py@@ -117,6 +117,29 @@ class OrgInvitationStore:)return result.scalars().first()+ @staticmethod+ async def get_pending_invitations_for_email(email: str) -> list[OrgInvitation]:+ """Get all pending invitations addressed to an email, oldest first.++ Args:+ email: Invitee email address (matched case-insensitively)++ Returns:+ List of pending OrgInvitation rows across all orgs+ """+ async with a_session_maker() as session:+ result = await session.execute(+ select(OrgInvitation)+ .filter(+ and_(+ OrgInvitation.email == email.lower().strip(),+ OrgInvitation.status == OrgInvitation.STATUS_PENDING,+ )+ )+ .order_by(OrgInvitation.created_at.asc())+ )+ return list(result.scalars().all())+@staticmethodasync def get_pending_invitations_for_org(org_id: UUID) -> list[OrgInvitation]:"""Get all pending invitations for an organization, newest first.diff --git a/enterprise/tests/unit/test_org_invitation_service.py b/enterprise/tests/unit/test_org_invitation_service.pyindex b4005743c8..fd9f25a3f3 100644--- a/enterprise/tests/unit/test_org_invitation_service.py+++ b/enterprise/tests/unit/test_org_invitation_service.py@@ -820,3 +820,267 @@ class TestRevokeInvitation:await OrgInvitationService.revoke_invitation(invitation.org_id, invitation.id)+++class TestAcceptPendingInvitationsForUser:+ """Login-time acceptance of invitations by verified-email match."""++ @staticmethod+ def _user(email='[email protected]'):+ import uuid as uuid_mod++ user = MagicMock()+ user.id = uuid_mod.uuid4()+ user.email = email+ user.current_org_id = user.id # parked on personal workspace+ return user++ @staticmethod+ def _invitation(invitation_id=1):+ import uuid as uuid_mod++ invitation = MagicMock()+ invitation.id = invitation_id+ invitation.org_id = uuid_mod.uuid4()+ invitation.role_id = 3+ invitation.status = OrgInvitation.STATUS_PENDING+ return invitation++ @staticmethod+ def _settings():+ settings = MagicMock()+ settings.agent_settings.llm.api_key = SecretStr('llm-key')+ return settings++ @pytest.mark.asyncio+ async def test_accepts_matching_invitation_and_moves_off_personal(self):+ user = self._user()+ invitation = self._invitation()++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore'+ ) as mock_store,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore'+ ) as mock_member_store,+ patch('server.services.org_invitation_service.OrgStore') as mock_org_store,+ patch(+ 'server.services.org_invitation_service.OrgService'+ ) as mock_org_service,+ patch(+ 'server.services.org_invitation_service.UserStore'+ ) as mock_user_store,+ ):+ mock_store.get_pending_invitations_for_email = AsyncMock(+ return_value=[invitation]+ )+ mock_store.is_token_expired = MagicMock(return_value=False)+ mock_store.update_invitation_status = AsyncMock()+ mock_member_store.get_org_member = AsyncMock(return_value=None)+ mock_member_store.add_user_to_org = AsyncMock()+ mock_org_store.get_org_by_id = AsyncMock(return_value=MagicMock())+ mock_org_service.create_litellm_integration = AsyncMock(+ return_value=self._settings()+ )+ mock_user_store.update_current_org = AsyncMock()++ accepted = await OrgInvitationService.accept_pending_invitations_for_user(+ user+ )++ assert accepted == [invitation]+ mock_member_store.add_user_to_org.assert_awaited_once()+ add_kwargs = mock_member_store.add_user_to_org.await_args.kwargs+ assert add_kwargs['org_id'] == invitation.org_id+ assert add_kwargs['role_id'] == invitation.role_id+ mock_store.update_invitation_status.assert_awaited_once_with(+ invitation.id,+ OrgInvitation.STATUS_ACCEPTED,+ accepted_by_user_id=user.id,+ )+ # Parked on personal workspace: land them in the newly joined org.+ mock_user_store.update_current_org.assert_awaited_once_with(+ str(user.id), invitation.org_id+ )++ @pytest.mark.asyncio+ async def test_already_member_marks_invitation_accepted_without_adding(self):+ """Auto-add can beat an invitation; the ghost pending row is cleared."""+ user = self._user()+ invitation = self._invitation()++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore'+ ) as mock_store,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore'+ ) as mock_member_store,+ patch(+ 'server.services.org_invitation_service.UserStore'+ ) as mock_user_store,+ ):+ mock_store.get_pending_invitations_for_email = AsyncMock(+ return_value=[invitation]+ )+ mock_store.is_token_expired = MagicMock(return_value=False)+ mock_store.update_invitation_status = AsyncMock()+ mock_member_store.get_org_member = AsyncMock(return_value=MagicMock())+ mock_member_store.add_user_to_org = AsyncMock()+ mock_user_store.update_current_org = AsyncMock()++ accepted = await OrgInvitationService.accept_pending_invitations_for_user(+ user+ )++ assert accepted == []+ mock_member_store.add_user_to_org.assert_not_called()+ mock_store.update_invitation_status.assert_awaited_once_with(+ invitation.id,+ OrgInvitation.STATUS_ACCEPTED,+ accepted_by_user_id=user.id,+ )+ mock_user_store.update_current_org.assert_not_called()++ @pytest.mark.asyncio+ async def test_expired_invitation_marked_expired_and_skipped(self):+ user = self._user()+ invitation = self._invitation()++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore'+ ) as mock_store,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore'+ ) as mock_member_store,+ ):+ mock_store.get_pending_invitations_for_email = AsyncMock(+ return_value=[invitation]+ )+ mock_store.is_token_expired = MagicMock(return_value=True)+ mock_store.update_invitation_status = AsyncMock()+ mock_member_store.add_user_to_org = AsyncMock()++ accepted = await OrgInvitationService.accept_pending_invitations_for_user(+ user+ )++ assert accepted == []+ mock_store.update_invitation_status.assert_awaited_once_with(+ invitation.id, OrgInvitation.STATUS_EXPIRED+ )+ mock_member_store.add_user_to_org.assert_not_called()++ @pytest.mark.asyncio+ async def test_user_in_team_org_is_not_moved(self):+ import uuid as uuid_mod++ user = self._user()+ user.current_org_id = uuid_mod.uuid4() # deliberately in another team org+ invitation = self._invitation()++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore'+ ) as mock_store,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore'+ ) as mock_member_store,+ patch('server.services.org_invitation_service.OrgStore') as mock_org_store,+ patch(+ 'server.services.org_invitation_service.OrgService'+ ) as mock_org_service,+ patch(+ 'server.services.org_invitation_service.UserStore'+ ) as mock_user_store,+ ):+ mock_store.get_pending_invitations_for_email = AsyncMock(+ return_value=[invitation]+ )+ mock_store.is_token_expired = MagicMock(return_value=False)+ mock_store.update_invitation_status = AsyncMock()+ mock_member_store.get_org_member = AsyncMock(return_value=None)+ mock_member_store.add_user_to_org = AsyncMock()+ mock_org_store.get_org_by_id = AsyncMock(return_value=MagicMock())+ mock_org_service.create_litellm_integration = AsyncMock(+ return_value=self._settings()+ )+ mock_user_store.update_current_org = AsyncMock()++ accepted = await OrgInvitationService.accept_pending_invitations_for_user(+ user+ )++ assert len(accepted) == 1+ mock_user_store.update_current_org.assert_not_called()++ @pytest.mark.asyncio+ async def test_user_without_email_is_a_noop(self):+ user = self._user(email=None)++ with patch(+ 'server.services.org_invitation_service.OrgInvitationStore'+ ) as mock_store:+ mock_store.get_pending_invitations_for_email = AsyncMock()++ accepted = await OrgInvitationService.accept_pending_invitations_for_user(+ user+ )++ assert accepted == []+ mock_store.get_pending_invitations_for_email.assert_not_called()++ @pytest.mark.asyncio+ async def test_litellm_failure_skips_invitation_and_continues(self):+ """A LiteLLM outage must not break login or consume the invitation."""+ user = self._user()+ failing = self._invitation(invitation_id=1)+ succeeding = self._invitation(invitation_id=2)++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore'+ ) as mock_store,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore'+ ) as mock_member_store,+ patch('server.services.org_invitation_service.OrgStore') as mock_org_store,+ patch(+ 'server.services.org_invitation_service.OrgService'+ ) as mock_org_service,+ patch(+ 'server.services.org_invitation_service.UserStore'+ ) as mock_user_store,+ ):+ mock_store.get_pending_invitations_for_email = AsyncMock(+ return_value=[failing, succeeding]+ )+ mock_store.is_token_expired = MagicMock(return_value=False)+ mock_store.update_invitation_status = AsyncMock()+ mock_member_store.get_org_member = AsyncMock(return_value=None)+ mock_member_store.add_user_to_org = AsyncMock()+ mock_org_store.get_org_by_id = AsyncMock(return_value=MagicMock())+ mock_org_service.create_litellm_integration = AsyncMock(+ side_effect=[Exception('LiteLLM unavailable'), self._settings()]+ )+ mock_user_store.update_current_org = AsyncMock()++ accepted = await OrgInvitationService.accept_pending_invitations_for_user(+ user+ )++ # The failing invitation is skipped (stays pending, retried at next+ # sign-in); the rest of the batch still processes.+ assert accepted == [succeeding]+ mock_member_store.add_user_to_org.assert_awaited_once()+ assert (+ mock_member_store.add_user_to_org.await_args.kwargs['org_id']+ == succeeding.org_id+ )+ mock_store.update_invitation_status.assert_awaited_once_with(+ succeeding.id,+ OrgInvitation.STATUS_ACCEPTED,+ accepted_by_user_id=user.id,+ )