π OpenHands: AI-Driven Development
BBDC: prompt unenrolled @-mentioners to sign up instead of falling back to the installer (#14509)
Alonaf4c76596fc2c
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.pyindex fc0905c7a4..cbd7ed87b6 100644--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py@@ -17,6 +17,7 @@ from integrations.utils import (HOST_URL,OPENHANDS_RESOLVER_TEMPLATES_DIR,get_session_expired_message,+ get_user_not_found_message,)from integrations.v1_utils import get_saas_user_authfrom jinja2 import Environment, FileSystemLoader@@ -139,6 +140,34 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):f'{project_key}/{repo_slug} PR#{pr_id} comment#{comment_id}: {e}')+ async def _send_user_not_found_message(+ self,+ message: Message,+ installer_user_id: str,+ mentioner_slug: str | None,+ ) -> None:+ """Reply to the triggering comment asking an unenrolled mentioner to+ sign up, mirroring ``GithubManager._send_user_not_found_message``.++ The mentioner has no OHE account, so there is no token to post as+ them; the reply goes out under the installer's BBDC token (the+ installer has write access -- the closest analog to GitHub's+ installation token). Best-effort: a failure here must not raise out+ of ``receive_message``.+ """+ try:+ view = await BitbucketDCFactory.create_bitbucket_dc_view_from_payload(+ message,+ keycloak_user_id=installer_user_id,+ installer_keycloak_user_id=installer_user_id,+ )+ await self.send_message(get_user_not_found_message(mentioner_slug), view)+ except Exception as e:+ logger.warning(+ f'[Bitbucket DC] Failed to send user-not-found message to '+ f'{mentioner_slug!r}: {e}'+ )+async def receive_message(self, message: Message) -> None:self._confirm_incoming_source_type(message)if not self.is_job_requested(message):@@ -182,6 +211,7 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):mentioner_slug = extract_actor_slug(actor)mentioner_idp_id = str(actor.get('id') or '')mentioner_keycloak_id: str | None = None+ lookup_failed = Falseif mentioner_idp_id:try:mentioner_keycloak_id = (@@ -190,19 +220,39 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):))except Exception as e:+ lookup_failed = Truelogger.warning(f'[Bitbucket DC] Keycloak lookup for mentioner 'f'{mentioner_slug!r} (id {mentioner_idp_id}) failed: {e}')+ # A transient Keycloak error leaves us unsure whether the mentioner is+ # enrolled. Drop the event rather than guess -- we must neither+ # silently run as the installer nor wrongly tell an enrolled user to+ # sign up.+ if lookup_failed:+ logger.info(+ f'[Bitbucket DC] Dropping event for {mentioner_slug!r}: Keycloak '+ f'lookup failed, enrollment status unknown'+ )+ return++ # Mirror the GitHub manager: a mentioner with no OHE account is NOT run+ # as the installer. Refuse the job and reply asking them to sign up, so+ # every job runs as -- and is billed to -- the actual requester, with+ # correct git attribution.if not mentioner_keycloak_id:logger.info(f'[Bitbucket DC] Mentioner {mentioner_slug!r} (id '- f'{mentioner_idp_id}) has no OHE account; falling back to '- f'installer for this job'+ f'{mentioner_idp_id}) has no OHE account; asking them to sign '+ f'up instead of starting a job'+ )+ await self._send_user_not_found_message(+ message, installer_user_id, mentioner_slug)- mentioner_keycloak_id = installer_user_id- elif mentioner_keycloak_id != installer_user_id:+ return++ if mentioner_keycloak_id != installer_user_id:logger.info(f'[Bitbucket DC] Running job as mentioner {mentioner_slug!r} 'f'(id {mentioner_idp_id}, keycloak {mentioner_keycloak_id}) 'diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.pyindex fa9fe207ae..eedfcd325c 100644--- a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_manager.py@@ -137,35 +137,36 @@ async def test_receive_message_runs_job_as_mentioner_when_linked_in_keycloak():@pytest.mark.asyncio-async def test_receive_message_falls_back_to_installer_when_mentioner_has_no_account():- """A mentioner with no OHE account leaves the view running as the- installer, so the resolver still works for unenrolled BBDC users.+async def test_receive_message_asks_unenrolled_mentioner_to_sign_up():+ """A mentioner with no OHE account is NOT run as the installer. We mirror+ the GitHub manager: refuse the job and reply asking them to sign up, so+ every job runs as (and is billed to) the actual requester."""token_manager = AsyncMock()token_manager.get_user_id_from_idp_user_id = AsyncMock(return_value=None)manager = BitbucketDCManager(token_manager)- captured: dict = {}-- async def fake_start_job(view):- captured['view'] = view-with patch.object(manager.webhook_store, 'get_webhook_user_id', return_value='kc-installer'), patch.object(manager, '_commenter_has_write_access', return_value=True- ), patch.object(manager, 'start_job', new=fake_start_job):+ ), patch.object(manager, 'start_job', new=AsyncMock()) as mock_start, patch.object(+ manager, '_send_user_not_found_message', new=AsyncMock()+ ) as mock_not_found:await manager.receive_message(_comment_message())- view = captured['view']- assert view.user_info.keycloak_user_id == 'kc-installer'- assert view.installer_keycloak_user_id == 'kc-installer'+ mock_start.assert_not_called()+ mock_not_found.assert_awaited_once()+ # Posted under the installer's token, mentioning the actual commenter slug.+ assert mock_not_found.await_args.args[1] == 'kc-installer'+ assert mock_not_found.await_args.args[2] == 'alice'@pytest.mark.asyncio-async def test_receive_message_falls_back_to_installer_when_keycloak_lookup_raises():- """Transient Keycloak errors must not block the resolver β fall- back to the installer rather than dropping the event.+async def test_receive_message_drops_event_when_keycloak_lookup_raises():+ """A transient Keycloak error leaves enrollment status unknown. We drop+ the event rather than guess β neither silently running as the installer+ nor wrongly telling a (possibly enrolled) user to sign up."""token_manager = AsyncMock()token_manager.get_user_id_from_idp_user_id = AsyncMock(@@ -173,20 +174,47 @@ async def test_receive_message_falls_back_to_installer_when_keycloak_lookup_rais)manager = BitbucketDCManager(token_manager)- captured: dict = {}-- async def fake_start_job(view):- captured['view'] = view-with patch.object(manager.webhook_store, 'get_webhook_user_id', return_value='kc-installer'), patch.object(manager, '_commenter_has_write_access', return_value=True- ), patch.object(manager, 'start_job', new=fake_start_job):+ ), patch.object(manager, 'start_job', new=AsyncMock()) as mock_start, patch.object(+ manager, '_send_user_not_found_message', new=AsyncMock()+ ) as mock_not_found:await manager.receive_message(_comment_message())- view = captured['view']- assert view.user_info.keycloak_user_id == 'kc-installer'+ mock_start.assert_not_called()+ mock_not_found.assert_not_called()+++async def test_send_user_not_found_message_replies_as_installer():+ """The sign-up reply is built from the payload with the installer as the+ posting identity and carries the user-not-found copy.+ """+ manager = BitbucketDCManager(AsyncMock())+ sentinel_view = object()++ with patch(+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BitbucketDCFactory.create_bitbucket_dc_view_from_payload',+ new=AsyncMock(return_value=sentinel_view),+ ) as mock_factory, patch.object(+ manager, 'send_message', new=AsyncMock()+ ) as mock_send:+ await manager._send_user_not_found_message(+ _comment_message(), 'kc-installer', 'alice'+ )++ mock_factory.assert_awaited_once()+ assert mock_factory.await_args.kwargs['keycloak_user_id'] == 'kc-installer'+ assert (+ mock_factory.await_args.kwargs['installer_keycloak_user_id'] == 'kc-installer'+ )+ mock_send.assert_awaited_once()+ body, view = mock_send.await_args.args+ assert view is sentinel_view+ assert 'sign up' in body.lower()+ assert '@alice' in body@pytest.mark.asyncio