🙌 OpenHands: AI-Driven Development
Add automated Bitbucket Data Center webhook lifecycle (Part 4) (#14461)
Alona332b6d14e689
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.pyindex 964ec97fca..aceaff8d2c 100644--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py@@ -117,8 +117,45 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):)return+ # Mirror the GitHub resolver pattern: the job runs as the user who+ # @-mentioned us, not the webhook installer. Look up the mentioner+ # in Keycloak by their BBDC slug; the installer keycloak_user_id is+ # carried alongside so the permission check and webhook lifecycle+ # calls can keep using the installer's elevated token.+ payload = message.message.get('payload') or {}+ actor = payload.get('actor') or {}+ mentioner_slug = extract_actor_slug(actor)+ mentioner_keycloak_id: str | None = None+ if mentioner_slug:+ try:+ mentioner_keycloak_id = (+ await self.token_manager.get_user_id_from_idp_user_id(+ mentioner_slug, ProviderType.BITBUCKET_DATA_CENTER+ )+ )+ except Exception as e:+ logger.warning(+ f'[Bitbucket DC] Keycloak lookup for mentioner '+ f'{mentioner_slug!r} failed: {e}'+ )++ if not mentioner_keycloak_id:+ logger.info(+ f'[Bitbucket DC] Mentioner {mentioner_slug!r} has no OHE '+ f'account; falling back to installer for this job'+ )+ mentioner_keycloak_id = installer_user_id+ elif mentioner_keycloak_id != installer_user_id:+ logger.info(+ f'[Bitbucket DC] Running job as mentioner {mentioner_slug!r} '+ f'(keycloak {mentioner_keycloak_id}) instead of installer '+ f'({installer_user_id})'+ )+bitbucket_view = await BitbucketDCFactory.create_bitbucket_dc_view_from_payload(- message, installer_user_id+ message,+ keycloak_user_id=mentioner_keycloak_id,+ installer_keycloak_user_id=installer_user_id,)logger.info(f'[Bitbucket DC] Creating job for {bitbucket_view.user_info.username} '@@ -139,8 +176,9 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):SaaSBitbucketDCService,)- keycloak_user_id = bitbucket_view.user_info.keycloak_user_id- bitbucket_service = SaaSBitbucketDCService(external_auth_id=keycloak_user_id)+ bitbucket_service = SaaSBitbucketDCService(+ external_auth_id=bitbucket_view.user_info.keycloak_user_id+ )if isinstance(bitbucket_view, BitbucketDCInlinePRComment):await bitbucket_service.reply_to_pr_comment(diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.pyindex fd26a99f95..c77b450fe0 100644--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py@@ -69,7 +69,7 @@ class BitbucketDCPR(ResolverViewInterface):repo_slug: strfull_repo_name: str # f"{project_key}/{repo_slug}"is_public_repo: bool- user_info: UserData+ user_info: UserData # keycloak_user_id here is the @-mentioning userraw_payload: Messageconversation_id: strshould_extract: bool@@ -78,6 +78,11 @@ class BitbucketDCPR(ResolverViewInterface):description: strprevious_comments: list[Comment]branch_name: str | None+ # Webhook installer's keycloak_user_id. We run the conversation,+ # token exchanges, and reply path as the mentioner (``user_info``),+ # but keep this around for the things only the installer can do:+ # the per-commenter permission check and webhook lifecycle calls.+ installer_keycloak_user_id: strdef _get_branch_name(self) -> str | None:return self.branch_name@@ -280,14 +285,19 @@ class BitbucketDCFactory:@staticmethodasync def create_bitbucket_dc_view_from_payload(- message: Message, keycloak_user_id: str+ message: Message,+ keycloak_user_id: str,+ installer_keycloak_user_id: str | None = None,) -> BitbucketDCViewType:"""Build a view from a Bitbucket DC webhook payload.- ``keycloak_user_id`` is the OpenHands user that **installed** the- webhook (looked up by ``(project_key, repo_slug)`` from the- ``bitbucket_dc_webhook`` table by the manager). The resolver acts- on Bitbucket DC as the installer.+ ``keycloak_user_id`` is the OpenHands user the resolver runs the+ job as — the @-mentioning user when they have an OHE account, or+ the webhook installer as a fallback. ``installer_keycloak_user_id``+ is the user that installed the webhook (looked up from the+ ``bitbucket_dc_webhook`` table); when omitted it defaults to+ ``keycloak_user_id`` for backward compatibility with older+ callers/tests that pass a single id."""payload = cast(dict, message.message['payload'])installation_id = cast(str, message.message.get('installation_id') or '')@@ -352,6 +362,7 @@ class BitbucketDCFactory:description='',previous_comments=[],branch_name=branch_name,+ installer_keycloak_user_id=(installer_keycloak_user_id or keycloak_user_id),)if BitbucketDCFactory.is_pr_comment(message, inline=True):diff --git a/enterprise/migrations/versions/113_bitbucket_dc_webhook_last_synced_tz.py b/enterprise/migrations/versions/113_bitbucket_dc_webhook_last_synced_tz.pynew file mode 100644index 0000000000..ee7b4dd417--- /dev/null+++ b/enterprise/migrations/versions/113_bitbucket_dc_webhook_last_synced_tz.py@@ -0,0 +1,52 @@+"""bitbucket_dc_webhook.last_synced TIMESTAMP WITHOUT TIME ZONE -> WITH TIME ZONE++Revision ID: 113+Revises: 112+Create Date: 2026-05-19 00:00:00.000000++The original migration (112) created ``last_synced`` as+``TIMESTAMP WITHOUT TIME ZONE``, which meant the route layer had to+strip ``tzinfo`` from every ``datetime.now(timezone.utc)`` value before+asyncpg would accept it. Converting to ``TIMESTAMP WITH TIME ZONE``+lets the model store offset-aware datetimes directly and removes the+``.replace(tzinfo=None)`` workarounds in ``bitbucket_dc_webhook_store``.++The conversion is in-place — Postgres reads existing naive values as+UTC during the column-type change, which is what they always+semantically were.+"""++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++# revision identifiers, used by Alembic.+revision: str = '113'+down_revision: Union[str, None] = '112'+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.alter_column(+ 'bitbucket_dc_webhook',+ 'last_synced',+ type_=sa.DateTime(timezone=True),+ existing_type=sa.DateTime(timezone=False),+ existing_server_default=sa.text('CURRENT_TIMESTAMP'),+ existing_nullable=True,+ postgresql_using="last_synced AT TIME ZONE 'UTC'",+ )+++def downgrade() -> None:+ op.alter_column(+ 'bitbucket_dc_webhook',+ 'last_synced',+ type_=sa.DateTime(timezone=False),+ existing_type=sa.DateTime(timezone=True),+ existing_server_default=sa.text('CURRENT_TIMESTAMP'),+ existing_nullable=True,+ postgresql_using="last_synced AT TIME ZONE 'UTC'",+ )diff --git a/enterprise/server/routes/integration/bitbucket_dc.py b/enterprise/server/routes/integration/bitbucket_dc.pyindex a60133b564..07e05f33a8 100644--- a/enterprise/server/routes/integration/bitbucket_dc.py+++ b/enterprise/server/routes/integration/bitbucket_dc.py@@ -82,6 +82,91 @@ class BitbucketDCWebhookIdUpdateResult(BaseModel):error: str | None+class BitbucketDCWebhookRequest(BaseModel):+ resource: BitbucketDCResourceIdentifier+++class BitbucketDCWebhookInstallationResult(BaseModel):+ project_key: str+ repo_slug: str+ success: bool+ error: str | None+ webhook_id: str | None+++def _normalize_dc_resource(+ resource: BitbucketDCResourceIdentifier,+) -> tuple[str, str]:+ project_key = resource.project_key.strip()+ repo_slug = resource.repo_slug.strip()+ if not project_key or not repo_slug:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail='project_key and repo_slug are required',+ )+ return project_key, repo_slug+++async def _ensure_dc_admin_access(+ bitbucket_dc_service: SaaSBitbucketDCService,+ project_key: str,+ repo_slug: str,+) -> None:+ """Mirror of Cloud's ``_ensure_admin_access``.++ The DC ``user_has_admin_access`` implementation fails open on+ introspection errors (see its docstring), so this check is genuinely+ gating only when the BBDC permissions endpoint returns a clean answer.+ The webhook write itself will surface a 403 if the user really lacks+ admin — that's the true authoritative check.+ """+ if not await bitbucket_dc_service.user_has_admin_access(project_key, repo_slug):+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail='User does not have admin access to this repository',+ )+++async def _get_or_create_dc_webhook(+ bitbucket_dc_service: SaaSBitbucketDCService,+ project_key: str,+ repo_slug: str,+ webhook_secret: str,+) -> str | None:+ """Idempotent webhook (re)installation against BBDC.++ Looks up an existing webhook by URL, updates it with the freshly+ rotated secret if found, or creates a new one. Matches the Cloud+ ``_get_or_create_cloud_webhook`` shape so the route handlers stay+ symmetric.+ """+ (+ webhook_exists,+ webhook_id,+ ) = await bitbucket_dc_service.check_webhook_exists_on_repository(+ project_key, repo_slug, BITBUCKET_DC_WEBHOOK_URL+ )+ if webhook_exists and webhook_id:+ return await bitbucket_dc_service.update_repository_webhook(+ owner=project_key,+ repo_slug=repo_slug,+ webhook_id=webhook_id,+ name=BITBUCKET_DC_WEBHOOK_NAME,+ webhook_url=BITBUCKET_DC_WEBHOOK_URL,+ webhook_secret=webhook_secret,+ events=BITBUCKET_DC_WEBHOOK_EVENTS,+ )++ return await bitbucket_dc_service.create_repository_webhook(+ owner=project_key,+ repo_slug=repo_slug,+ name=BITBUCKET_DC_WEBHOOK_NAME,+ webhook_url=BITBUCKET_DC_WEBHOOK_URL,+ webhook_secret=webhook_secret,+ events=BITBUCKET_DC_WEBHOOK_EVENTS,+ )++def _extract_repo_identity(payload_data: dict) -> tuple[str, str]:"""Pull ``(project_key, repo_slug)`` out of a DC webhook payload.@@ -301,6 +386,145 @@ async def update_bitbucket_dc_webhook_id()+@bitbucket_dc_integration_router.post('/bitbucket-dc/reinstall-webhook')+async def reinstall_bitbucket_dc_webhook(+ body: BitbucketDCWebhookRequest,+ user_id: str = Depends(require_permission(Permission.MANAGE_INTEGRATIONS)),+) -> BitbucketDCWebhookInstallationResult:+ """Install or reinstall the webhook for a BBDC repo via the REST API.++ Replaces the manual paste-the-secret flow with a single call: rotates a+ fresh shared secret, idempotently creates or updates the webhook on+ BBDC, and persists the resulting ``webhook_id`` + secret. Requires the+ caller's BBDC OAuth token to have ``REPO_ADMIN`` scope (the Keycloak+ BBDC IDP requests this scope once the chart enables webhook lifecycle).+ """+ project_key, repo_slug = _normalize_dc_resource(body.resource)+ bitbucket_dc_service = SaaSBitbucketDCService(external_auth_id=user_id)++ try:+ await _ensure_dc_admin_access(bitbucket_dc_service, project_key, repo_slug)+ webhook_secret = secrets.token_urlsafe(32)+ webhook_id = await _get_or_create_dc_webhook(+ bitbucket_dc_service, project_key, repo_slug, webhook_secret+ )+ if not webhook_id:+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to install Bitbucket DC webhook',+ )++ await webhook_store.upsert_webhook_enrollment(+ project_key=project_key,+ repo_slug=repo_slug,+ user_id=user_id,+ webhook_id=webhook_id,+ webhook_secret=webhook_secret,+ )++ # Audit log so operators can correlate UI clicks with BBDC+ # webhook state changes when reviewing security incidents — the+ # ``user_has_admin_access`` pre-check is intentionally permissive+ # (BBDC's API is the authoritative auth boundary), so the audit+ # trail lives here.+ logger.info(+ '[Bitbucket DC] Webhook installed',+ extra={+ 'user_id': user_id,+ 'project_key': project_key,+ 'repo_slug': repo_slug,+ 'webhook_id': webhook_id,+ },+ )++ return BitbucketDCWebhookInstallationResult(+ project_key=project_key,+ repo_slug=repo_slug,+ success=True,+ error=None,+ webhook_id=webhook_id,+ )++ except HTTPException:+ raise+ except Exception as e:+ logger.exception(f'Error installing Bitbucket DC webhook: {e}')+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to install Bitbucket DC webhook',+ )+++@bitbucket_dc_integration_router.post('/bitbucket-dc/uninstall-webhook')+async def uninstall_bitbucket_dc_webhook(+ body: BitbucketDCWebhookRequest,+ user_id: str = Depends(require_permission(Permission.MANAGE_INTEGRATIONS)),+) -> BitbucketDCWebhookInstallationResult:+ """Delete the webhook on BBDC and drop the local enrollment row.++ Looks up the webhook by URL on BBDC (in case the stored ``webhook_id``+ drifted from reality) and calls ``DELETE .../webhooks/{id}``; then+ removes the ``bitbucket_dc_webhook`` row so the resource flips back to+ "not enrolled" in the UI. If no webhook exists on either side this is+ treated as a no-op success — uninstall is idempotent.+ """+ project_key, repo_slug = _normalize_dc_resource(body.resource)+ bitbucket_dc_service = SaaSBitbucketDCService(external_auth_id=user_id)++ try:+ await _ensure_dc_admin_access(bitbucket_dc_service, project_key, repo_slug)+ webhook = await webhook_store.get_webhook_by_repo(project_key, repo_slug)+ (+ provider_exists,+ provider_id,+ ) = await bitbucket_dc_service.check_webhook_exists_on_repository(+ project_key, repo_slug, BITBUCKET_DC_WEBHOOK_URL+ )+ db_id = webhook.webhook_id if webhook else None+ webhook_id = provider_id or db_id+ if provider_id:+ await bitbucket_dc_service.delete_repository_webhook(+ project_key, repo_slug, provider_id+ )+ elif provider_exists:+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to locate Bitbucket DC webhook id',+ )++ await webhook_store.delete_webhook_by_repo(+ project_key=project_key,+ repo_slug=repo_slug,+ )++ logger.info(+ '[Bitbucket DC] Webhook uninstalled',+ extra={+ 'user_id': user_id,+ 'project_key': project_key,+ 'repo_slug': repo_slug,+ 'webhook_id': webhook_id,+ },+ )++ return BitbucketDCWebhookInstallationResult(+ project_key=project_key,+ repo_slug=repo_slug,+ success=True,+ error=None,+ webhook_id=webhook_id,+ )++ except HTTPException:+ raise+ except Exception as e:+ logger.exception(f'Error uninstalling Bitbucket DC webhook: {e}')+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to uninstall Bitbucket DC webhook',+ )++@bitbucket_dc_integration_router.post('/bitbucket-dc/events')async def bitbucket_dc_events(request: Request,diff --git a/enterprise/storage/bitbucket_dc_webhook.py b/enterprise/storage/bitbucket_dc_webhook.pyindex c646b350b6..65b53363ce 100644--- a/enterprise/storage/bitbucket_dc_webhook.py+++ b/enterprise/storage/bitbucket_dc_webhook.py@@ -27,7 +27,7 @@ class BitbucketDCWebhook(Base):webhook_id: Mapped[str | None] = mapped_column(String, nullable=True)webhook_secret: Mapped[str | None] = mapped_column(String, nullable=True)last_synced: Mapped[datetime | None] = mapped_column(- DateTime,+ DateTime(timezone=True),server_default=text('CURRENT_TIMESTAMP'),onupdate=text('CURRENT_TIMESTAMP'),nullable=True,diff --git a/enterprise/storage/bitbucket_dc_webhook_store.py b/enterprise/storage/bitbucket_dc_webhook_store.pyindex 657242574b..1123fa7405 100644--- a/enterprise/storage/bitbucket_dc_webhook_store.py+++ b/enterprise/storage/bitbucket_dc_webhook_store.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom datetime import datetime, timezone-from sqlalchemy import and_, or_, select, update+from sqlalchemy import and_, delete, or_, select, updatefrom storage.bitbucket_dc_webhook import BitbucketDCWebhookfrom storage.database import a_session_maker@@ -142,6 +142,22 @@ class BitbucketDCWebhookStore:result = await session.execute(stmt)return result.rowcount > 0+ async def delete_webhook_by_repo(self, *, project_key: str, repo_slug: str) -> bool:+ """Remove the enrollment row for ``(project_key, repo_slug)``.++ Returns ``True`` when a row was deleted, ``False`` if none existed+ — uninstall is idempotent at the route layer so the caller treats+ both as success.+ """+ async with a_session_maker() as session:+ async with session.begin():+ stmt = delete(BitbucketDCWebhook).where(+ BitbucketDCWebhook.project_key == project_key,+ BitbucketDCWebhook.repo_slug == repo_slug,+ )+ result = await session.execute(stmt)+ return result.rowcount > 0+@classmethodasync def get_instance(cls) -> BitbucketDCWebhookStore:return BitbucketDCWebhookStore()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 70164c15d1..ace45914bc 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@@ -53,8 +53,11 @@ def _pr_comment_view(parent_id: int | None = 42) -> BitbucketDCPRComment:repo_slug='myrepo',full_repo_name='PROJ/myrepo',is_public_repo=False,+ # ``user_info.keycloak_user_id`` is the @-mentioning user, set by+ # ``receive_message`` after the Keycloak lookup. The installer's+ # id is carried separately on the view.user_info=UserData(- user_id='alice', username='Alice', keycloak_user_id='kc-installer'+ user_id='alice', username='Alice', keycloak_user_id='kc-alice'),raw_payload=_comment_message(),conversation_id='',@@ -64,6 +67,7 @@ def _pr_comment_view(parent_id: int | None = 42) -> BitbucketDCPRComment:description='',previous_comments=[],branch_name='feature/x',+ installer_keycloak_user_id='kc-installer',comment_body='Hey @openhands fix',parent_comment_id=parent_id,)@@ -78,7 +82,7 @@ def _inline_view() -> BitbucketDCInlinePRComment:full_repo_name='PROJ/myrepo',is_public_repo=False,user_info=UserData(- user_id='alice', username='Alice', keycloak_user_id='kc-installer'+ user_id='alice', username='Alice', keycloak_user_id='kc-alice'),raw_payload=_comment_message(),conversation_id='',@@ -88,6 +92,7 @@ def _inline_view() -> BitbucketDCInlinePRComment:description='',previous_comments=[],branch_name='feature/x',+ installer_keycloak_user_id='kc-installer',comment_body='@openhands rename',parent_comment_id=None,file_location='src/x.py',@@ -98,17 +103,83 @@ def _inline_view() -> BitbucketDCInlinePRComment:@pytest.mark.asyncio-async def test_receive_message_dispatches_when_commenter_has_write_access():- manager = BitbucketDCManager(AsyncMock())+async def test_receive_message_runs_job_as_mentioner_when_linked_in_keycloak():+ """When the @-mentioning user has an OHE account, the view's+ ``user_info.keycloak_user_id`` is the mentioner and the installer's+ id is carried alongside on ``installer_keycloak_user_id``.+ """+ token_manager = AsyncMock()+ token_manager.get_user_id_from_idp_user_id = AsyncMock(return_value='kc-alice')+ manager = BitbucketDCManager(token_manager)++ captured: dict = {}++ async def fake_start_job(view):+ captured['view'] = viewwith 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=AsyncMock()) as mock_start:+ ), patch.object(manager, 'start_job', new=fake_start_job):+ await manager.receive_message(_comment_message())++ view = captured['view']+ assert view.user_info.keycloak_user_id == 'kc-alice'+ assert view.installer_keycloak_user_id == 'kc-installer'+++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.+ """+ 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):+ 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'+++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.+ """+ token_manager = AsyncMock()+ token_manager.get_user_id_from_idp_user_id = AsyncMock(+ side_effect=RuntimeError('keycloak unreachable')+ )+ 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):await manager.receive_message(_comment_message())- mock_start.assert_awaited_once()+ view = captured['view']+ assert view.user_info.keycloak_user_id == 'kc-installer'@pytest.mark.asyncio@@ -177,3 +248,20 @@ def test_confirm_incoming_source_type_raises_on_wrong_source():manager._confirm_incoming_source_type(Message(source=SourceType.BITBUCKET, message={}))+++async def test_send_message_uses_view_user_info_keycloak_id():+ """send_message constructs the BBDC service with the view's+ user_info.keycloak_user_id (the mentioner) rather than the+ installer, so replies post under the mentioner's BBDC account.+ """+ manager = BitbucketDCManager(AsyncMock())++ with patch(+ 'integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService'+ ) as service_cls:+ service_cls.return_value = AsyncMock()+ await manager.send_message('Done', _pr_comment_view())++ service_cls.assert_called_once_with(external_auth_id='kc-alice')diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.pyindex 6d67fc95aa..66d27f15ce 100644--- a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_view.py@@ -110,3 +110,24 @@ async def test_factory_records_actor_slug_and_assigns_keycloak_user_id():assert view.user_info.user_id == 'alice'assert view.user_info.username == 'Alice'assert view.user_info.keycloak_user_id == 'kc-installer'+ # Single-arg form (no explicit installer) keeps the mentioner id on+ # both fields for backward compatibility.+ assert view.installer_keycloak_user_id == 'kc-installer'+++async def test_factory_keeps_mentioner_and_installer_distinct_when_passed():+ """The mentioner runs the job; the installer's id is carried alongside+ on ``installer_keycloak_user_id`` for the bits that need elevated+ permissions (permission check, webhook lifecycle).+ """+ msg = _make_message(body='@openhands fix')++ view = await BitbucketDCFactory.create_bitbucket_dc_view_from_payload(+ msg,+ keycloak_user_id='kc-alice',+ installer_keycloak_user_id='kc-installer',+ )++ assert view.user_info.keycloak_user_id == 'kc-alice'+ assert view.installer_keycloak_user_id == 'kc-installer'diff --git a/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.py b/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.pyindex c0e5976284..03cb1ac582 100644--- a/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.py+++ b/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.py@@ -147,3 +147,31 @@ async def test_update_webhook_id_updates_existing_row(webhook_store, sample_webh)assert webhook is not Noneassert webhook.webhook_id == '84'+++async def test_delete_webhook_by_repo_removes_existing_row(+ webhook_store, sample_webhook+):+ deleted = await webhook_store.delete_webhook_by_repo(+ project_key='PROJ',+ repo_slug='myrepo',+ )++ assert deleted is True+ webhook = await webhook_store.get_webhook_by_repo(+ project_key='PROJ',+ repo_slug='myrepo',+ )+ assert webhook is None+++async def test_delete_webhook_by_repo_returns_false_when_row_absent(webhook_store):+ """Uninstall is idempotent at the route layer — store reports honestly."""+ deleted = await webhook_store.delete_webhook_by_repo(+ project_key='PROJ',+ repo_slug='does-not-exist',+ )++ assert deleted is Falsediff --git a/frontend/__tests__/components/features/settings/bitbucket-dc-webhook-manager.test.tsx b/frontend/__tests__/components/features/settings/bitbucket-dc-webhook-manager.test.tsxindex 321f06b48d..39b4b287d4 100644--- a/frontend/__tests__/components/features/settings/bitbucket-dc-webhook-manager.test.tsx+++ b/frontend/__tests__/components/features/settings/bitbucket-dc-webhook-manager.test.tsx@@ -86,40 +86,72 @@ describe("BitbucketDCWebhookManager", () => {).toBeInTheDocument();});- it("shows manual setup values after enrolling a repo", async () => {+ it("calls reinstall when the Install button is clicked on a not-enrolled repo", async () => {const user = userEvent.setup();vi.spyOn(integrationService, "getBitbucketDCResources").mockResolvedValue({resources: mockResources,});- vi.spyOn(integrationService, "enrollBitbucketDCWebhook").mockResolvedValue({- project_key: "PROJ",- repo_slug: "myrepo",- success: true,- error: null,- webhook_url: "https://ohe.example.com/integration/bitbucket-dc/events",- webhook_secret: "generated-secret",- webhook_name: "OpenHands Resolver",- events: ["pr:comment:added", "pr:comment:edited"],+ const reinstallSpy = vi+ .spyOn(integrationService, "reinstallBitbucketDCWebhook")+ .mockResolvedValue({+ project_key: "PROJ",+ repo_slug: "myrepo",+ success: true,+ error: null,+ webhook_id: "101",+ });++ renderComponent();++ await user.click(+ await screen.findByTestId("bbdc-install-webhook-PROJ/myrepo"),+ );++ await waitFor(() => {+ expect(reinstallSpy).toHaveBeenCalledWith({+ resource: { project_key: "PROJ", repo_slug: "myrepo" },+ });+ });+ });++ it("calls uninstall when the Uninstall button is clicked on an enrolled repo", async () => {+ const user = userEvent.setup();+ vi.spyOn(integrationService, "getBitbucketDCResources").mockResolvedValue({+ resources: mockResources,});+ const uninstallSpy = vi+ .spyOn(integrationService, "uninstallBitbucketDCWebhook")+ .mockResolvedValue({+ project_key: "OPS",+ repo_slug: "platform",+ success: true,+ error: null,+ webhook_id: "42",+ });renderComponent();await user.click(- await screen.findByTestId("bbdc-enroll-webhook-PROJ/myrepo"),+ await screen.findByTestId("bbdc-uninstall-webhook-OPS/platform"),);await waitFor(() => {- expect(screen.getByText("generated-secret")).toBeInTheDocument();+ expect(uninstallSpy).toHaveBeenCalledWith({+ resource: { project_key: "OPS", repo_slug: "platform" },+ });});+ });- expect(screen.getByText("OpenHands Resolver")).toBeInTheDocument();- expect(- screen.getByText(- "https://ohe.example.com/integration/bitbucket-dc/events",- ),- ).toBeInTheDocument();+ it("does not render an Uninstall button on a not-enrolled repo", async () => {+ vi.spyOn(integrationService, "getBitbucketDCResources").mockResolvedValue({+ resources: mockResources,+ });++ renderComponent();++ await screen.findByTestId("bbdc-install-webhook-PROJ/myrepo");expect(- screen.getByText("pr:comment:added, pr:comment:edited"),- ).toBeInTheDocument();+ screen.queryByTestId("bbdc-uninstall-webhook-PROJ/myrepo"),+ ).not.toBeInTheDocument();});});diff --git a/frontend/src/api/integration-service/integration-service.api.ts b/frontend/src/api/integration-service/integration-service.api.tsindex 68c4ddce42..ee7500acd9 100644--- a/frontend/src/api/integration-service/integration-service.api.ts+++ b/frontend/src/api/integration-service/integration-service.api.ts@@ -3,6 +3,7 @@ import {BitbucketDCResourcesResponse,BitbucketDCWebhookEnrollmentResult,BitbucketDCWebhookIdUpdateResult,+ BitbucketDCWebhookInstallationResult,BitbucketDCResourceIdentifier,GitLabResourcesResponse,UpdateBitbucketDCWebhookIdRequest,@@ -70,6 +71,9 @@ export const integrationService = {/*** Record the numeric Bitbucket Data Center webhook id after manual creation.+ * @deprecated Manual flow superseded by reinstallBitbucketDCWebhook, which+ * auto-creates the webhook on BBDC and records the assigned id in one step.+ * Kept for backward compatibility with older clients.*/updateBitbucketDCWebhookId: async ({resource,@@ -88,4 +92,37 @@ export const integrationService = {);return data;},++ /**+ * Install or reinstall the webhook on a Bitbucket Data Center repository+ * via BBDC's REST API. Rotates the shared secret, idempotently creates or+ * updates the webhook on BBDC, and persists the result. Requires the+ * caller's BBDC OAuth token to have REPO_ADMIN scope.+ */+ reinstallBitbucketDCWebhook: async ({+ resource,+ }: {+ resource: BitbucketDCResourceIdentifier;+ }): Promise<BitbucketDCWebhookInstallationResult> => {+ const { data } = await openHands.post<BitbucketDCWebhookInstallationResult>(+ "/integration/bitbucket-dc/reinstall-webhook",+ { resource },+ );+ return data;+ },++ /**+ * Delete the webhook on Bitbucket Data Center and clear the local enrollment.+ */+ uninstallBitbucketDCWebhook: async ({+ resource,+ }: {+ resource: BitbucketDCResourceIdentifier;+ }): Promise<BitbucketDCWebhookInstallationResult> => {+ const { data } = await openHands.post<BitbucketDCWebhookInstallationResult>(+ "/integration/bitbucket-dc/uninstall-webhook",+ { resource },+ );+ return data;+ },};diff --git a/frontend/src/api/integration-service/integration-service.types.ts b/frontend/src/api/integration-service/integration-service.types.tsindex 1b33fc16e3..ed5e9eff5f 100644--- a/frontend/src/api/integration-service/integration-service.types.ts+++ b/frontend/src/api/integration-service/integration-service.types.ts@@ -76,3 +76,15 @@ export interface BitbucketDCWebhookIdUpdateResult {success: boolean;error: string | null;}++export interface BitbucketDCWebhookRequest {+ resource: BitbucketDCResourceIdentifier;+}++export interface BitbucketDCWebhookInstallationResult {+ project_key: string;+ repo_slug: string;+ success: boolean;+ error: string | null;+ webhook_id: string | null;+}diff --git a/frontend/src/components/features/settings/git-settings/bitbucket-dc-webhook-manager.tsx b/frontend/src/components/features/settings/git-settings/bitbucket-dc-webhook-manager.tsxindex efc9b3d27b..8fdeb907ee 100644--- a/frontend/src/components/features/settings/git-settings/bitbucket-dc-webhook-manager.tsx+++ b/frontend/src/components/features/settings/git-settings/bitbucket-dc-webhook-manager.tsx@@ -1,14 +1,10 @@import React, { useState } from "react";import { useTranslation } from "react-i18next";import { BrandButton } from "#/components/features/settings/brand-button";-import { CopyableContentWrapper } from "#/components/shared/buttons/copyable-content-wrapper";-import type {- BitbucketDCResource,- BitbucketDCWebhookEnrollmentResult,-} from "#/api/integration-service/integration-service.types";+import type { BitbucketDCResource } from "#/api/integration-service/integration-service.types";import { useBitbucketDCResources } from "#/hooks/query/use-bitbucket-dc-resources-list";-import { useEnrollBitbucketDCWebhook } from "#/hooks/mutation/use-enroll-bitbucket-dc-webhook";-import { useUpdateBitbucketDCWebhookId } from "#/hooks/mutation/use-update-bitbucket-dc-webhook-id";+import { useReinstallBitbucketDCWebhook } from "#/hooks/mutation/use-reinstall-bitbucket-dc-webhook";+import { useUninstallBitbucketDCWebhook } from "#/hooks/mutation/use-uninstall-bitbucket-dc-webhook";import { I18nKey } from "#/i18n/declaration";import { cn } from "#/utils/utils";import { Typography } from "#/ui/typography";@@ -39,115 +35,47 @@ function StatusBadge({ enrolled }: { enrolled: boolean }) {);}-function SetupValue({ label, value }: { label: string; value: string }) {- return (- <div className="flex flex-col gap-1">- <Typography.Text className="text-xs uppercase text-gray-500">- {label}- </Typography.Text>- <CopyableContentWrapper text={value}>- <code className="block rounded border border-neutral-700 bg-neutral-950 px-3 py-2 text-xs text-gray-200 break-all">- {value}- </code>- </CopyableContentWrapper>- </div>- );-}--function EnrollmentSetup({- result,-}: {- result: BitbucketDCWebhookEnrollmentResult;-}) {- const { t } = useTranslation();-- if (!result.success || !result.webhook_url || !result.webhook_secret) {- return null;- }-- return (- <div className="mt-3 flex flex-col gap-3 rounded border border-neutral-700 bg-neutral-900/60 p-3">- <Typography.Text className="text-sm text-gray-300">- {t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_SETUP_DESCRIPTION)}- </Typography.Text>- <div className="grid gap-3 md:grid-cols-2">- <SetupValue- label={t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_FIELD_NAME)}- value={result.webhook_name}- />- <SetupValue- label={t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_FIELD_URL)}- value={result.webhook_url}- />- <SetupValue- label={t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_FIELD_SECRET)}- value={result.webhook_secret}- />- <SetupValue- label={t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_FIELD_EVENTS)}- value={result.events.join(", ")}- />- </div>- </div>- );-}-export function BitbucketDCWebhookManager({className,}: BitbucketDCWebhookManagerProps) {const { t } = useTranslation();- const [enrollingResource, setEnrollingResource] = useState<string | null>(+ const [installingResource, setInstallingResource] = useState<string | null>(null,);- const [enrollmentResults, setEnrollmentResults] = useState<- Map<string, BitbucketDCWebhookEnrollmentResult>- >(new Map());- const [webhookIds, setWebhookIds] = useState<Map<string, string>>(new Map());+ const [uninstallingResource, setUninstallingResource] = useState<+ string | null+ >(null);const { data, isLoading, isError } = useBitbucketDCResources(true);- const enrollMutation = useEnrollBitbucketDCWebhook();- const updateWebhookIdMutation = useUpdateBitbucketDCWebhookId();+ const reinstallMutation = useReinstallBitbucketDCWebhook();+ const uninstallMutation = useUninstallBitbucketDCWebhook();const resources = data?.resources || [];- const handleEnroll = async (resource: BitbucketDCResource) => {+ const handleReinstall = async (resource: BitbucketDCResource) => {const key = resourceKey(resource);- setEnrollingResource(key);- const nextResults = new Map(enrollmentResults);- nextResults.delete(key);- setEnrollmentResults(nextResults);-+ setInstallingResource(key);try {- const result = await enrollMutation.mutateAsync({+ await reinstallMutation.mutateAsync({project_key: resource.project_key,repo_slug: resource.repo_slug,});- setEnrollmentResults(new Map(nextResults).set(key, result));} finally {- setEnrollingResource(null);+ setInstallingResource(null);}};- const handleWebhookIdChange = (key: string, value: string) => {- const nextWebhookIds = new Map(webhookIds);- nextWebhookIds.set(key, value);- setWebhookIds(nextWebhookIds);- };-- const handleWebhookIdSave = async (resource: BitbucketDCResource) => {+ const handleUninstall = async (resource: BitbucketDCResource) => {const key = resourceKey(resource);- const webhookId = (webhookIds.get(key) ?? resource.webhook_id ?? "").trim();- if (!webhookId) {- return;- }-- await updateWebhookIdMutation.mutateAsync({- resource: {+ setUninstallingResource(key);+ try {+ await uninstallMutation.mutateAsync({project_key: resource.project_key,repo_slug: resource.repo_slug,- },- webhookId,- });+ });+ } finally {+ setUninstallingResource(null);+ }};if (isLoading) {@@ -211,9 +139,6 @@ export function BitbucketDCWebhookManager({<th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">{t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_COLUMN_STATUS)}</th>- <th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">- {t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_COLUMN_WEBHOOK_ID)}- </th><th className="px-4 py-3 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">{t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_COLUMN_ACTION)}</th>@@ -222,22 +147,22 @@ export function BitbucketDCWebhookManager({<tbody className="divide-y divide-neutral-700">{resources.map((resource) => {const key = resourceKey(resource);- const result = enrollmentResults.get(key);- const isEnrolling = enrollingResource === key;- const webhookId =- webhookIds.get(key) ?? resource.webhook_id ?? "";- let enrollButtonLabel = t(- I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_ENROLL,- );- if (resource.webhook_enrolled) {- enrollButtonLabel = t(- I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_REGENERATE,+ const isInstalling = installingResource === key;+ const isUninstalling = uninstallingResource === key;+ const anyMutationPending =+ installingResource !== null || uninstallingResource !== null;++ let installLabel: string;+ if (isInstalling) {+ installLabel = t(+ I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_INSTALLING,);- }- if (isEnrolling) {- enrollButtonLabel = t(- I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_GENERATING,+ } else if (resource.webhook_enrolled) {+ installLabel = t(+ I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_REINSTALL,);+ } else {+ installLabel = t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL);}return (@@ -263,7 +188,6 @@ export function BitbucketDCWebhookManager({)}</Typography.Text>)}- {result && <EnrollmentSetup result={result} />}</div></td><td className="px-4 py-3">@@ -271,43 +195,36 @@ export function BitbucketDCWebhookManager({</td><td className="px-4 py-3"><div className="flex gap-2">- <input- type="text"- value={webhookId}- onChange={(event) =>- handleWebhookIdChange(key, event.target.value)- }- placeholder={t(- I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_OPTIONAL_PLACEHOLDER,- )}- className="w-28 rounded border border-neutral-700 bg-neutral-900 px-2 py-1 text-sm text-white"- data-testid={`bbdc-webhook-id-${key}`}- /><BrandButtontype="button"- variant="secondary"- onClick={() => handleWebhookIdSave(resource)}- isDisabled={- updateWebhookIdMutation.isPending || !webhookId.trim()- }- testId={`bbdc-save-webhook-id-${key}`}+ variant="primary"+ onClick={() => handleReinstall(resource)}+ isDisabled={anyMutationPending}+ className="cursor-pointer"+ testId={`bbdc-install-webhook-${key}`}>- {t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_SAVE)}+ {installLabel}</BrandButton>+ {resource.webhook_enrolled && (+ <BrandButton+ type="button"+ variant="secondary"+ onClick={() => handleUninstall(resource)}+ isDisabled={anyMutationPending}+ className="cursor-pointer"+ testId={`bbdc-uninstall-webhook-${key}`}+ >+ {isUninstalling+ ? t(+ I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALLING,+ )+ : t(+ I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL,+ )}+ </BrandButton>+ )}</div></td>- <td className="px-4 py-3">- <BrandButton- type="button"- variant="primary"- onClick={() => handleEnroll(resource)}- isDisabled={enrollingResource !== null}- className="cursor-pointer"- testId={`bbdc-enroll-webhook-${key}`}- >- {enrollButtonLabel}- </BrandButton>- </td></tr>);})}diff --git a/frontend/src/hooks/mutation/use-reinstall-bitbucket-dc-webhook.ts b/frontend/src/hooks/mutation/use-reinstall-bitbucket-dc-webhook.tsnew file mode 100644index 0000000000..ba32e71dbd--- /dev/null+++ b/frontend/src/hooks/mutation/use-reinstall-bitbucket-dc-webhook.ts@@ -0,0 +1,48 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { integrationService } from "#/api/integration-service/integration-service.api";+import type {+ BitbucketDCResourceIdentifier,+ BitbucketDCWebhookInstallationResult,+} from "#/api/integration-service/integration-service.types";+import { I18nKey } from "#/i18n/declaration";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";++export function useReinstallBitbucketDCWebhook() {+ const queryClient = useQueryClient();+ const { t } = useTranslation();++ return useMutation<+ BitbucketDCWebhookInstallationResult,+ Error,+ BitbucketDCResourceIdentifier,+ unknown+ >({+ mutationFn: (resource: BitbucketDCResourceIdentifier) =>+ integrationService.reinstallBitbucketDCWebhook({ resource }),+ onSuccess: (data) => {+ queryClient.invalidateQueries({ queryKey: ["bitbucket-dc-resources"] });++ if (data.success) {+ displaySuccessToast(+ t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_SUCCESS),+ );+ } else if (data.error) {+ displayErrorToast(data.error);+ } else {+ displayErrorToast(+ t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_FAILED),+ );+ }+ },+ onError: (error) => {+ displayErrorToast(+ error?.message ||+ t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_FAILED),+ );+ },+ });+}diff --git a/frontend/src/hooks/mutation/use-uninstall-bitbucket-dc-webhook.ts b/frontend/src/hooks/mutation/use-uninstall-bitbucket-dc-webhook.tsnew file mode 100644index 0000000000..b5a472e667--- /dev/null+++ b/frontend/src/hooks/mutation/use-uninstall-bitbucket-dc-webhook.ts@@ -0,0 +1,48 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useTranslation } from "react-i18next";+import { integrationService } from "#/api/integration-service/integration-service.api";+import type {+ BitbucketDCResourceIdentifier,+ BitbucketDCWebhookInstallationResult,+} from "#/api/integration-service/integration-service.types";+import { I18nKey } from "#/i18n/declaration";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";++export function useUninstallBitbucketDCWebhook() {+ const queryClient = useQueryClient();+ const { t } = useTranslation();++ return useMutation<+ BitbucketDCWebhookInstallationResult,+ Error,+ BitbucketDCResourceIdentifier,+ unknown+ >({+ mutationFn: (resource: BitbucketDCResourceIdentifier) =>+ integrationService.uninstallBitbucketDCWebhook({ resource }),+ onSuccess: (data) => {+ queryClient.invalidateQueries({ queryKey: ["bitbucket-dc-resources"] });++ if (data.success) {+ displaySuccessToast(+ t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_SUCCESS),+ );+ } else if (data.error) {+ displayErrorToast(data.error);+ } else {+ displayErrorToast(+ t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_FAILED),+ );+ }+ },+ onError: (error) => {+ displayErrorToast(+ error?.message ||+ t(I18nKey.BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_FAILED),+ );+ },+ });+}diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex a27c101c3e..e4b5d061f7 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -326,6 +326,15 @@ export enum I18nKey {BITBUCKET_DATA_CENTER$WEBHOOK_ENROLL_FAILED = "BITBUCKET_DATA_CENTER$WEBHOOK_ENROLL_FAILED",BITBUCKET_DATA_CENTER$WEBHOOK_ID_SAVE_SUCCESS = "BITBUCKET_DATA_CENTER$WEBHOOK_ID_SAVE_SUCCESS",BITBUCKET_DATA_CENTER$WEBHOOK_ID_SAVE_FAILED = "BITBUCKET_DATA_CENTER$WEBHOOK_ID_SAVE_FAILED",+ BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL = "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL",+ BITBUCKET_DATA_CENTER$WEBHOOK_INSTALLING = "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALLING",+ BITBUCKET_DATA_CENTER$WEBHOOK_REINSTALL = "BITBUCKET_DATA_CENTER$WEBHOOK_REINSTALL",+ BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL = "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL",+ BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALLING = "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALLING",+ BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_SUCCESS = "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_SUCCESS",+ BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_FAILED = "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_FAILED",+ BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_SUCCESS = "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_SUCCESS",+ BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_FAILED = "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_FAILED",SETTINGS$GITLAB_REINSTALL_WEBHOOK = "SETTINGS$GITLAB_REINSTALL_WEBHOOK",SETTINGS$GITLAB_INSTALLING_WEBHOOK = "SETTINGS$GITLAB_INSTALLING_WEBHOOK",SETTINGS$GITLAB = "SETTINGS$GITLAB",diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex 6ca5f9654e..52106cace9 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -25277,5 +25277,158 @@"de": "Sonstiges:","uk": "Інше:","ca": "Altres:"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL": {+ "en": "Install",+ "ja": "インストール",+ "zh-CN": "安装",+ "zh-TW": "安裝",+ "ko-KR": "설치",+ "no": "Installer",+ "it": "Installa",+ "pt": "Instalar",+ "es": "Instalar",+ "ar": "تثبيت",+ "fr": "Installer",+ "tr": "Yükle",+ "de": "Installieren",+ "uk": "Встановити",+ "ca": "Instal·lar"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALLING": {+ "en": "Installing",+ "ja": "インストール中",+ "zh-CN": "正在安装",+ "zh-TW": "正在安裝",+ "ko-KR": "설치 중",+ "no": "Installerer",+ "it": "Installazione",+ "pt": "Instalando",+ "es": "Instalando",+ "ar": "جارٍ التثبيت",+ "fr": "Installation",+ "tr": "Yükleniyor",+ "de": "Wird installiert",+ "uk": "Встановлення",+ "ca": "Instal·lant"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_REINSTALL": {+ "en": "Reinstall",+ "ja": "再インストール",+ "zh-CN": "重新安装",+ "zh-TW": "重新安裝",+ "ko-KR": "재설치",+ "no": "Installer på nytt",+ "it": "Reinstalla",+ "pt": "Reinstalar",+ "es": "Reinstalar",+ "ar": "إعادة التثبيت",+ "fr": "Réinstaller",+ "tr": "Yeniden yükle",+ "de": "Neu installieren",+ "uk": "Перевстановити",+ "ca": "Reinstal·lar"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL": {+ "en": "Uninstall",+ "ja": "アンインストール",+ "zh-CN": "卸载",+ "zh-TW": "解除安裝",+ "ko-KR": "제거",+ "no": "Avinstaller",+ "it": "Disinstalla",+ "pt": "Desinstalar",+ "es": "Desinstalar",+ "ar": "إلغاء التثبيت",+ "fr": "Désinstaller",+ "tr": "Kaldır",+ "de": "Deinstallieren",+ "uk": "Видалити",+ "ca": "Desinstal·lar"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALLING": {+ "en": "Uninstalling",+ "ja": "アンインストール中",+ "zh-CN": "正在卸载",+ "zh-TW": "正在解除安裝",+ "ko-KR": "제거 중",+ "no": "Avinstallerer",+ "it": "Disinstallazione",+ "pt": "Desinstalando",+ "es": "Desinstalando",+ "ar": "جارٍ إلغاء التثبيت",+ "fr": "Désinstallation",+ "tr": "Kaldırılıyor",+ "de": "Wird deinstalliert",+ "uk": "Видалення",+ "ca": "Desinstal·lant"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_SUCCESS": {+ "en": "Bitbucket Data Center webhook installed",+ "ja": "Bitbucket Data Center のウェブフックをインストールしました",+ "zh-CN": "已安装 Bitbucket Data Center Webhook",+ "zh-TW": "已安裝 Bitbucket Data Center Webhook",+ "ko-KR": "Bitbucket Data Center 웹훅이 설치되었습니다",+ "no": "Bitbucket Data Center-webhook installert",+ "it": "Webhook Bitbucket Data Center installato",+ "pt": "Webhook do Bitbucket Data Center instalado",+ "es": "Webhook de Bitbucket Data Center instalado",+ "ar": "تم تثبيت ويبهوك Bitbucket Data Center",+ "fr": "Webhook Bitbucket Data Center installé",+ "tr": "Bitbucket Data Center webhook yüklendi",+ "de": "Bitbucket Data Center-Webhook installiert",+ "uk": "Вебхук Bitbucket Data Center встановлено",+ "ca": "S’ha instal·lat el webhook de Bitbucket Data Center"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_INSTALL_FAILED": {+ "en": "Failed to install Bitbucket Data Center webhook",+ "ja": "Bitbucket Data Center のウェブフックのインストールに失敗しました",+ "zh-CN": "安装 Bitbucket Data Center Webhook 失败",+ "zh-TW": "安裝 Bitbucket Data Center Webhook 失敗",+ "ko-KR": "Bitbucket Data Center 웹훅 설치에 실패했습니다",+ "no": "Kunne ikke installere Bitbucket Data Center-webhook",+ "it": "Installazione del webhook Bitbucket Data Center non riuscita",+ "pt": "Falha ao instalar o webhook do Bitbucket Data Center",+ "es": "No se pudo instalar el webhook de Bitbucket Data Center",+ "ar": "تعذّر تثبيت ويبهوك Bitbucket Data Center",+ "fr": "Échec de l'installation du webhook Bitbucket Data Center",+ "tr": "Bitbucket Data Center webhook yüklenemedi",+ "de": "Bitbucket Data Center-Webhook konnte nicht installiert werden",+ "uk": "Не вдалося встановити вебхук Bitbucket Data Center",+ "ca": "No s’ha pogut instal·lar el webhook de Bitbucket Data Center"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_SUCCESS": {+ "en": "Bitbucket Data Center webhook uninstalled",+ "ja": "Bitbucket Data Center のウェブフックをアンインストールしました",+ "zh-CN": "已卸载 Bitbucket Data Center Webhook",+ "zh-TW": "已解除安裝 Bitbucket Data Center Webhook",+ "ko-KR": "Bitbucket Data Center 웹훅이 제거되었습니다",+ "no": "Bitbucket Data Center-webhook avinstallert",+ "it": "Webhook Bitbucket Data Center disinstallato",+ "pt": "Webhook do Bitbucket Data Center desinstalado",+ "es": "Webhook de Bitbucket Data Center desinstalado",+ "ar": "تم إلغاء تثبيت ويبهوك Bitbucket Data Center",+ "fr": "Webhook Bitbucket Data Center désinstallé",+ "tr": "Bitbucket Data Center webhook kaldırıldı",+ "de": "Bitbucket Data Center-Webhook deinstalliert",+ "uk": "Вебхук Bitbucket Data Center видалено",+ "ca": "S’ha desinstal·lat el webhook de Bitbucket Data Center"+ },+ "BITBUCKET_DATA_CENTER$WEBHOOK_UNINSTALL_FAILED": {+ "en": "Failed to uninstall Bitbucket Data Center webhook",+ "ja": "Bitbucket Data Center のウェブフックのアンインストールに失敗しました",+ "zh-CN": "卸载 Bitbucket Data Center Webhook 失败",+ "zh-TW": "解除安裝 Bitbucket Data Center Webhook 失敗",+ "ko-KR": "Bitbucket Data Center 웹훅 제거에 실패했습니다",+ "no": "Kunne ikke avinstallere Bitbucket Data Center-webhook",+ "it": "Disinstallazione del webhook Bitbucket Data Center non riuscita",+ "pt": "Falha ao desinstalar o webhook do Bitbucket Data Center",+ "es": "No se pudo desinstalar el webhook de Bitbucket Data Center",+ "ar": "تعذّر إلغاء تثبيت ويبهوك Bitbucket Data Center",+ "fr": "Échec de la désinstallation du webhook Bitbucket Data Center",+ "tr": "Bitbucket Data Center webhook kaldırılamadı",+ "de": "Bitbucket Data Center-Webhook konnte nicht deinstalliert werden",+ "uk": "Не вдалося видалити вебхук Bitbucket Data Center",+ "ca": "No s’ha pogut desinstal·lar el webhook de Bitbucket Data Center"}}diff --git a/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py b/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.pyindex caa4c6c19e..4add74457d 100644--- a/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py+++ b/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py@@ -7,6 +7,7 @@ from openhands.app_server.integrations.bitbucket_data_center.service import (BitbucketDCPRsMixin,BitbucketDCReposMixin,BitbucketDCResolverMixin,+ BitbucketDCWebhooksMixin,)from openhands.app_server.integrations.service_types import (GitService,@@ -17,6 +18,7 @@ from openhands.app_server.utils.import_utils import get_implclass BitbucketDCService(+ BitbucketDCWebhooksMixin,BitbucketDCResolverMixin,BitbucketDCBranchesMixin,BitbucketDCPRsMixin,diff --git a/openhands/app_server/integrations/bitbucket_data_center/service/__init__.py b/openhands/app_server/integrations/bitbucket_data_center/service/__init__.pyindex 793356c1a7..bb3238de3a 100644--- a/openhands/app_server/integrations/bitbucket_data_center/service/__init__.py+++ b/openhands/app_server/integrations/bitbucket_data_center/service/__init__.py@@ -3,6 +3,7 @@ from .branches import BitbucketDCBranchesMixinfrom .prs import BitbucketDCPRsMixinfrom .repos import BitbucketDCReposMixinfrom .resolver import BitbucketDCResolverMixin+from .webhooks import BitbucketDCWebhooksMixin__all__ = ['BitbucketDCMixinBase',@@ -10,4 +11,5 @@ __all__ = ['BitbucketDCPRsMixin','BitbucketDCReposMixin','BitbucketDCResolverMixin',+ 'BitbucketDCWebhooksMixin',]diff --git a/openhands/app_server/integrations/bitbucket_data_center/service/webhooks.py b/openhands/app_server/integrations/bitbucket_data_center/service/webhooks.pynew file mode 100644index 0000000000..701a604a60--- /dev/null+++ b/openhands/app_server/integrations/bitbucket_data_center/service/webhooks.py@@ -0,0 +1,138 @@+from typing import Any++from openhands.app_server.integrations.bitbucket_data_center.service.base import (+ BitbucketDCMixinBase,+)+from openhands.app_server.integrations.service_types import RequestMethod+++class BitbucketDCWebhooksMixin(BitbucketDCMixinBase):+ """Repository webhook helpers for Bitbucket Data Center.++ Direct analog of ``BitBucketWebhooksMixin`` (Bitbucket Cloud), hitting+ BBDC's REST API for webhook CRUD instead of the manual paste-the-secret+ flow that the initial enrollment UI required. BBDC's webhook endpoints+ sit under ``/rest/api/1.0/projects/{key}/repos/{slug}/webhooks[/{id}]``+ and require the caller's token to have ``REPO_ADMIN`` scope — the+ Keycloak BBDC IDP requests this scope by default once webhook lifecycle+ is enabled.++ Notes on BBDC vs Cloud:+ * BBDC's webhook id is a numeric ``int`` (not a UUID). It is exposed+ here as ``str`` to match the ``bitbucket_dc_webhook.webhook_id``+ column type.+ * BBDC's payload puts the shared secret inside ``configuration``,+ not at the top level (Cloud uses ``secret``).+ * BBDC's pagination shape is ``{"values": [...], "isLastPage": ...}``+ — the inherited ``_fetch_paginated_data`` helper from+ :class:`BitbucketDCMixinBase` already handles that.+ """++ async def get_repository_webhooks(+ self, owner: str, repo_slug: str+ ) -> list[dict[str, Any]]:+ url = f'{self._repo_api_base(owner, repo_slug)}/webhooks'+ return await self._fetch_paginated_data(url, {'limit': 100}, max_items=100)++ async def check_webhook_exists_on_repository(+ self, owner: str, repo_slug: str, webhook_url: str+ ) -> tuple[bool, str | None]:+ """Return ``(True, id)`` when a webhook with ``webhook_url`` already+ exists on the repo (used to make enroll/reinstall idempotent), else+ ``(False, None)``.++ Webhook ``id`` is normalized to ``str`` to match the storage column+ type, which keeps callers from having to coerce when persisting.+ """+ webhooks = await self.get_repository_webhooks(owner, repo_slug)+ for webhook in webhooks:+ if webhook.get('url') == webhook_url:+ wid = webhook.get('id')+ return True, str(wid) if wid is not None else None+ return False, None++ async def create_repository_webhook(+ self,+ *,+ owner: str,+ repo_slug: str,+ name: str,+ webhook_url: str,+ webhook_secret: str,+ events: list[str],+ ) -> str | None:+ """Create a webhook via ``POST .../webhooks``. Returns the new id."""+ url = f'{self._repo_api_base(owner, repo_slug)}/webhooks'+ payload = {+ 'name': name,+ 'url': webhook_url,+ 'active': True,+ 'events': events,+ 'configuration': {'secret': webhook_secret},+ }+ response, _ = await self._make_request(+ url=url,+ params=payload,+ method=RequestMethod.POST,+ )+ if not response:+ return None+ wid = response.get('id')+ return str(wid) if wid is not None else None++ async def update_repository_webhook(+ self,+ *,+ owner: str,+ repo_slug: str,+ webhook_id: str,+ name: str,+ webhook_url: str,+ webhook_secret: str,+ events: list[str],+ ) -> str | None:+ """Update an existing webhook via ``PUT .../webhooks/{id}``.++ BBDC requires the full payload on PUT (not partial), so we send the+ same body shape as ``create_repository_webhook``.+ """+ url = f'{self._repo_api_base(owner, repo_slug)}/webhooks/{webhook_id}'+ payload = {+ 'name': name,+ 'url': webhook_url,+ 'active': True,+ 'events': events,+ 'configuration': {'secret': webhook_secret},+ }+ response, _ = await self._make_request(+ url=url,+ params=payload,+ method=RequestMethod.PUT,+ )+ if not response:+ return webhook_id+ wid = response.get('id')+ return str(wid) if wid is not None else webhook_id++ async def delete_repository_webhook(+ self, owner: str, repo_slug: str, webhook_id: str+ ) -> None:+ url = f'{self._repo_api_base(owner, repo_slug)}/webhooks/{webhook_id}'+ await self._make_request(url=url, method=RequestMethod.DELETE)++ async def user_has_admin_access(self, owner: str, repo_slug: str) -> bool:+ """Best-effort admin probe — trusts the OAuth scope grant.++ BBDC's permissions-introspection endpoints all require ``REPO_ADMIN``+ to query, and on the SaaS path ``self.user_id`` is unset (the OAuth+ bearer token doesn't carry a BBDC slug), so a strict pre-check has+ no reliable identifier to look up. The OAuth scope grant itself is+ the gating signal: if the user got a token with ``REPO_ADMIN`` they+ had to consent to it, and the eventual webhook write will surface+ any *real* authorization problem with an actionable BBDC error.++ Same philosophy as ``user_has_write_access_for`` (see its long+ docstring in ``resolver.py``) — trust the scope, let the API call+ be the authoritative check.+ """+ return Truediff --git a/openhands/app_server/integrations/protocols/http_client.py b/openhands/app_server/integrations/protocols/http_client.pyindex f1045a6c8f..bfbaf8e20d 100644--- a/openhands/app_server/integrations/protocols/http_client.py+++ b/openhands/app_server/integrations/protocols/http_client.py@@ -73,6 +73,10 @@ class HTTPClient(ABC):"""Execute an HTTP request using the provided client."""if method == RequestMethod.POST:return await client.post(url, headers=headers, json=params)+ if method == RequestMethod.PUT:+ return await client.put(url, headers=headers, json=params)+ if method == RequestMethod.DELETE:+ return await client.delete(url, headers=headers, params=params)return await client.get(url, headers=headers, params=params)def handle_http_status_error(diff --git a/openhands/app_server/integrations/service_types.py b/openhands/app_server/integrations/service_types.pyindex ba5efc56cc..6f361b01e3 100644--- a/openhands/app_server/integrations/service_types.py+++ b/openhands/app_server/integrations/service_types.py@@ -201,6 +201,8 @@ class ResourceNotFoundError(ValueError):class RequestMethod(Enum):POST = 'post'GET = 'get'+ PUT = 'put'+ DELETE = 'delete'class BaseGitService(ABC):diff --git a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhooks.py b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhooks.pynew file mode 100644index 0000000000..04643f5766--- /dev/null+++ b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhooks.py@@ -0,0 +1,176 @@+"""Unit tests for ``BitbucketDCWebhooksMixin``.++Mirrors ``tests/unit/integrations/bitbucket/test_bitbucket_webhooks.py``+(Bitbucket Cloud) for the Bitbucket Data Center service mixin added in+PR #14461. Each test stubs ``_make_request`` so we can assert the+exact URL / method / payload the service hits — no network, no DB.+"""++from unittest.mock import AsyncMock++import pytest++from openhands.app_server.integrations.bitbucket_data_center.bitbucket_dc_service import (+ BitbucketDCService,+)+from openhands.app_server.integrations.service_types import RequestMethod+++def _make_service() -> BitbucketDCService:+ """Build a service rooted at a known base_domain so URL assertions are stable."""+ return BitbucketDCService(token=None, base_domain='bitbucket.example.com')+++async def test_create_repository_webhook_posts_bbdc_payload():+ service = _make_service()+ service._make_request = AsyncMock( # type: ignore[method-assign]+ return_value=({'id': 42, 'name': 'OpenHands Resolver'}, {})+ )++ webhook_id = await service.create_repository_webhook(+ owner='PROJ',+ repo_slug='repo-1',+ name='OpenHands Resolver',+ webhook_url='https://app.example.com/integration/bitbucket-dc/events',+ webhook_secret='secret-123',+ events=['pr:comment:added', 'pr:comment:edited'],+ )++ # BBDC returns numeric ids; we normalize to str to match the storage column.+ assert webhook_id == '42'+ service._make_request.assert_awaited_once_with(+ url='https://bitbucket.example.com/rest/api/1.0/projects/PROJ/repos/repo-1/webhooks',+ params={+ 'name': 'OpenHands Resolver',+ 'url': 'https://app.example.com/integration/bitbucket-dc/events',+ 'active': True,+ 'events': ['pr:comment:added', 'pr:comment:edited'],+ # The shared secret is nested under ``configuration`` for BBDC —+ # this is the field Cloud puts at the top level.+ 'configuration': {'secret': 'secret-123'},+ },+ method=RequestMethod.POST,+ )+++async def test_update_repository_webhook_puts_full_payload():+ service = _make_service()+ service._make_request = AsyncMock( # type: ignore[method-assign]+ return_value=({'id': 7}, {})+ )++ webhook_id = await service.update_repository_webhook(+ owner='PROJ',+ repo_slug='repo-1',+ webhook_id='7',+ name='OpenHands Resolver',+ webhook_url='https://app.example.com/integration/bitbucket-dc/events',+ webhook_secret='rotated',+ events=['pr:comment:added', 'pr:comment:edited'],+ )++ assert webhook_id == '7'+ service._make_request.assert_awaited_once_with(+ url='https://bitbucket.example.com/rest/api/1.0/projects/PROJ/repos/repo-1/webhooks/7',+ params={+ 'name': 'OpenHands Resolver',+ 'url': 'https://app.example.com/integration/bitbucket-dc/events',+ 'active': True,+ 'events': ['pr:comment:added', 'pr:comment:edited'],+ 'configuration': {'secret': 'rotated'},+ },+ method=RequestMethod.PUT,+ )+++async def test_update_repository_webhook_falls_back_to_input_id_when_response_lacks_one():+ """BBDC always echoes the id, but defensive code: if it doesn't, we keep+ the id we asked it to update — better than returning ``None``."""+ service = _make_service()+ service._make_request = AsyncMock( # type: ignore[method-assign]+ return_value=(None, {})+ )++ webhook_id = await service.update_repository_webhook(+ owner='PROJ',+ repo_slug='repo-1',+ webhook_id='9',+ name='OpenHands Resolver',+ webhook_url='https://app.example.com/integration/bitbucket-dc/events',+ webhook_secret='s',+ events=[],+ )++ assert webhook_id == '9'+++async def test_delete_repository_webhook_issues_delete():+ service = _make_service()+ service._make_request = AsyncMock(return_value=({}, {})) # type: ignore[method-assign]++ await service.delete_repository_webhook('PROJ', 'repo-1', '42')++ service._make_request.assert_awaited_once_with(+ url='https://bitbucket.example.com/rest/api/1.0/projects/PROJ/repos/repo-1/webhooks/42',+ method=RequestMethod.DELETE,+ )+++async def test_check_webhook_exists_on_repository_returns_id_when_found():+ """Matches by URL — the idempotency key Cloud uses too."""+ service = _make_service()+ service._fetch_paginated_data = AsyncMock( # type: ignore[method-assign]+ return_value=[+ {'id': 1, 'url': 'https://other.example.com/events'},+ {+ 'id': 42,+ 'url': 'https://app.example.com/integration/bitbucket-dc/events',+ },+ ]+ )++ exists, wid = await service.check_webhook_exists_on_repository(+ 'PROJ',+ 'repo-1',+ 'https://app.example.com/integration/bitbucket-dc/events',+ )++ assert exists is True+ # Numeric ids from BBDC get coerced to str to match the storage column.+ assert wid == '42'+++async def test_check_webhook_exists_on_repository_returns_false_when_absent():+ service = _make_service()+ service._fetch_paginated_data = AsyncMock( # type: ignore[method-assign]+ return_value=[{'id': 1, 'url': 'https://other.example.com/events'}]+ )++ exists, wid = await service.check_webhook_exists_on_repository(+ 'PROJ',+ 'repo-1',+ 'https://app.example.com/integration/bitbucket-dc/events',+ )++ assert exists is False+ assert wid is None+++async def test_user_has_admin_access_returns_true():+ """Trusts the OAuth scope grant — see the mixin docstring. The webhook+ API call itself is the authoritative auth check; this method is only+ used as a non-strict pre-flight so the route returns a clean 403+ instead of leaking BBDC's error in the *very* unlikely edge case we+ can detect mismatch up-front.+ """+ service = _make_service()+ # Even though there's no real I/O, the method should not raise and+ # should not depend on self.user_id being set.+ assert await service.user_has_admin_access('PROJ', 'repo-1') is True