π OpenHands: AI-Driven Development
Add connection-scoped Bitbucket DC webhooks
Alona4335396c6be0
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.pyindex c23c91a8a4..48cbdbe01a 100644--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py@@ -68,9 +68,11 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):async def _commenter_has_write_access(self, message: Message, installer_user_id: str) -> bool:- """Use the installer's Bitbucket DC token to check whether the- commenter has ``REPO_WRITE``/``REPO_ADMIN`` permission on the PR's- repository β mirrors the Cloud manager's installer-scoped check.+ """Check commenter permissions using the installer's Bitbucket DC token.++ The check confirms whether the commenter has ``REPO_WRITE`` or+ ``REPO_ADMIN`` permission on the PR's repository, mirroring the Cloud+ manager's installer-scoped check."""from integrations.bitbucket_data_center.bitbucket_dc_service import (SaaSBitbucketDCService,@@ -172,8 +174,7 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):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``.+ """Ask an unenrolled mentioner to sign up in a PR reply.The mentioner has no OHE account, so there is no token to post asthem; the reply goes out under the installer's BBDC token (the@@ -200,9 +201,11 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):returnproject_key, repo_slug = self._extract_repo_identity(message)- installer_user_id = await self.webhook_store.get_webhook_user_id(- project_key=project_key, repo_slug=repo_slug- )+ installer_user_id = message.message.get('installer_user_id')+ if not installer_user_id:+ installer_user_id = await self.webhook_store.get_webhook_user_id(+ project_key=project_key, repo_slug=repo_slug+ )if not installer_user_id:logger.warning(f'[Bitbucket DC] No installer recorded for 'diff --git a/enterprise/server/routes/integration/bitbucket_dc.py b/enterprise/server/routes/integration/bitbucket_dc.pyindex d143d41b8c..6ae7442c24 100644--- a/enterprise/server/routes/integration/bitbucket_dc.py+++ b/enterprise/server/routes/integration/bitbucket_dc.py@@ -59,7 +59,10 @@ BITBUCKET_DC_WEBHOOK_EVENTS = ['pr:comment:edited','pr:comment:deleted',]-BITBUCKET_DC_WEBHOOK_URL = f'{HOST_URL}/integration/bitbucket-dc/events'+++def bitbucket_dc_webhook_url(connection_id: int) -> str:+ return f'{HOST_URL}/integration/bitbucket-dc/connections/{connection_id}/events'class BitbucketDCResourceIdentifier(BaseModel):@@ -73,8 +76,10 @@ class BitbucketDCResourceWithWebhookStatus(BaseModel):name: strfull_name: strtype: str = 'repository'+ connection_id: int | Nonewebhook_enrolled: boolwebhook_id: str | None+ webhook_url: str | Nonewebhook_secret_set: boolinstalled_by_user_id: str | Nonelast_synced: str | None@@ -93,6 +98,7 @@ class BitbucketDCWebhookEnrollmentResult(BaseModel):repo_slug: strsuccess: boolerror: str | None+ connection_id: int | Nonewebhook_url: str | Nonewebhook_secret: str | Nonewebhook_name: str@@ -121,6 +127,8 @@ class BitbucketDCWebhookInstallationResult(BaseModel):success: boolerror: str | Nonewebhook_id: str | None+ connection_id: int | None = None+ webhook_url: str | None = Nonedef _normalize_dc_resource(@@ -161,6 +169,7 @@ async def _get_or_create_dc_webhook(project_key: str,repo_slug: str,webhook_secret: str,+ webhook_url: str,) -> str | None:"""Idempotent webhook (re)installation against BBDC.@@ -173,7 +182,7 @@ async def _get_or_create_dc_webhook(webhook_exists,webhook_id,) = await bitbucket_dc_service.check_webhook_exists_on_repository(- project_key, repo_slug, BITBUCKET_DC_WEBHOOK_URL+ project_key, repo_slug, webhook_url)if webhook_exists and webhook_id:return await bitbucket_dc_service.update_repository_webhook(@@ -181,7 +190,7 @@ async def _get_or_create_dc_webhook(repo_slug=repo_slug,webhook_id=webhook_id,name=BITBUCKET_DC_WEBHOOK_NAME,- webhook_url=BITBUCKET_DC_WEBHOOK_URL,+ webhook_url=webhook_url,webhook_secret=webhook_secret,events=BITBUCKET_DC_WEBHOOK_EVENTS,)@@ -190,12 +199,31 @@ async def _get_or_create_dc_webhook(owner=project_key,repo_slug=repo_slug,name=BITBUCKET_DC_WEBHOOK_NAME,- webhook_url=BITBUCKET_DC_WEBHOOK_URL,+ webhook_url=webhook_url,webhook_secret=webhook_secret,events=BITBUCKET_DC_WEBHOOK_EVENTS,)+async def _find_existing_dc_webhook_id(+ bitbucket_dc_service: SaaSBitbucketDCService,+ project_key: str,+ repo_slug: str,+ webhook_url: str,+) -> str | None:+ if not webhook_url:+ return None+ (+ webhook_exists,+ webhook_id,+ ) = await bitbucket_dc_service.check_webhook_exists_on_repository(+ project_key, repo_slug, webhook_url+ )+ if webhook_exists and webhook_id:+ return webhook_id+ return None++def _extract_repo_identity(payload_data: dict) -> tuple[str, str]:"""Pull ``(project_key, repo_slug)`` out of a DC webhook payload.@@ -233,34 +261,21 @@ async def verify_bitbucket_dc_signature(*,signature_header: str | None,body: bytes,- project_key: str,- repo_slug: str,+ webhook_secret: str | None = None,) -> None:- """Verify ``X-Hub-Signature`` against the per-repository secret.+ """Verify ``X-Hub-Signature`` against the connection-scoped secret.Bitbucket Data Center signs each webhook delivery with HMAC-SHA256 ofthe request body using the secret configured on the repository's- webhook. The header has the form ``sha256=<hex>``. There is no- per-installation UUID header on DC, so we look up the secret by the- ``(project_key, repo_slug)`` carried in the payload.+ webhook. The header has the form ``sha256=<hex>``."""- if not project_key or not repo_slug:- raise HTTPException(- status_code=403,- detail='Missing repository identity in payload',- )-if IS_LOCAL_DEPLOYMENT:- webhook_secret: str | None = 'localdeploymentwebhooktesttoken'- else:- webhook_secret = await webhook_store.get_webhook_secret(- project_key=project_key, repo_slug=repo_slug- )+ webhook_secret = webhook_secret or 'localdeploymentwebhooktesttoken'if not webhook_secret:raise HTTPException(status_code=403,- detail='No webhook secret found for repository',+ detail='No webhook secret found for connection',)if IS_LOCAL_DEPLOYMENT and signature_header in (@@ -311,8 +326,12 @@ async def get_bitbucket_dc_resources(repo_slug=repo_slug,name=repo_slug,full_name=f'{project_key}/{repo_slug}',+ connection_id=webhook.id if webhook else None,webhook_enrolled=bool(webhook and webhook.webhook_secret),webhook_id=webhook.webhook_id if webhook else None,+ webhook_url=(+ bitbucket_dc_webhook_url(webhook.id) if webhook else None+ ),webhook_secret_set=bool(webhook and webhook.webhook_secret),installed_by_user_id=webhook.user_id if webhook else None,last_synced=(@@ -352,19 +371,21 @@ async def enroll_bitbucket_dc_webhook(webhook_secret = secrets.token_urlsafe(32)try:- await webhook_store.upsert_webhook_enrollment(+ webhook = await webhook_store.upsert_webhook_enrollment(project_key=project_key,repo_slug=repo_slug,user_id=user_id,webhook_secret=webhook_secret,)+ webhook_url = bitbucket_dc_webhook_url(webhook.id)return BitbucketDCWebhookEnrollmentResult(project_key=project_key,repo_slug=repo_slug,success=True,error=None,- webhook_url=BITBUCKET_DC_WEBHOOK_URL,+ connection_id=webhook.id,+ webhook_url=webhook_url,webhook_secret=webhook_secret,webhook_name=BITBUCKET_DC_WEBHOOK_NAME,events=BITBUCKET_DC_WEBHOOK_EVENTS,@@ -449,9 +470,19 @@ async def reinstall_bitbucket_dc_webhook(try:await _ensure_dc_admin_access(bitbucket_dc_service, project_key, repo_slug)+ webhook = await webhook_store.ensure_webhook_enrollment(+ project_key=project_key,+ repo_slug=repo_slug,+ user_id=user_id,+ )webhook_secret = secrets.token_urlsafe(32)+ webhook_url = bitbucket_dc_webhook_url(webhook.id)webhook_id = await _get_or_create_dc_webhook(- bitbucket_dc_service, project_key, repo_slug, webhook_secret+ bitbucket_dc_service,+ project_key,+ repo_slug,+ webhook_secret,+ webhook_url,)if not webhook_id:raise HTTPException(@@ -488,6 +519,8 @@ async def reinstall_bitbucket_dc_webhook(success=True,error=None,webhook_id=webhook_id,+ connection_id=webhook.id,+ webhook_url=webhook_url,)except HTTPException:@@ -519,11 +552,11 @@ async def uninstall_bitbucket_dc_webhook(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+ provider_id = await _find_existing_dc_webhook_id(+ bitbucket_dc_service,+ project_key,+ repo_slug,+ bitbucket_dc_webhook_url(webhook.id) if webhook else '',)db_id = webhook.webhook_id if webhook else Nonewebhook_id = provider_id or db_id@@ -531,11 +564,16 @@ async def uninstall_bitbucket_dc_webhook(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',- )+ elif db_id:+ try:+ await bitbucket_dc_service.delete_repository_webhook(+ project_key, repo_slug, db_id+ )+ except Exception as e:+ logger.warning(+ f'[Bitbucket DC] Stored webhook id {db_id} for '+ f'{project_key}/{repo_slug} could not be deleted: {e}'+ )await webhook_store.delete_webhook_by_repo(project_key=project_key,@@ -558,6 +596,8 @@ async def uninstall_bitbucket_dc_webhook(success=True,error=None,webhook_id=webhook_id,+ connection_id=webhook.id if webhook else None,+ webhook_url=bitbucket_dc_webhook_url(webhook.id) if webhook else None,)except HTTPException:@@ -570,13 +610,13 @@ async def uninstall_bitbucket_dc_webhook()-@bitbucket_dc_integration_router.post('/bitbucket-dc/events')-async def bitbucket_dc_events(+async def _handle_bitbucket_dc_event(request: Request,background_tasks: BackgroundTasks,- x_hub_signature: str | None = Header(None),- x_event_key: str | None = Header(None),- x_request_id: str | None = Header(None),+ x_hub_signature: str | None,+ x_event_key: str | None,+ x_request_id: str | None,+ connection_id: int,):try:body = await request.body()@@ -594,11 +634,28 @@ async def bitbucket_dc_events(payload_data = _normalize_bitbucket_dc_event_payload(payload_data, x_event_key)project_key, repo_slug = _extract_repo_identity(payload_data)+ webhook = await webhook_store.get_webhook_by_id(connection_id)+ if not webhook:+ raise HTTPException(+ status_code=403,+ detail='No webhook found for connection',+ )+ if (+ project_key+ and repo_slug+ and (webhook.project_key != project_key or webhook.repo_slug != repo_slug)+ ):+ raise HTTPException(+ status_code=403,+ detail='Webhook connection does not match payload repository',+ )+ project_key = project_key or webhook.project_key+ repo_slug = repo_slug or webhook.repo_slug+ installer_user_id: str | None = webhook.user_idawait verify_bitbucket_dc_signature(signature_header=x_hub_signature,body=body,- project_key=project_key,- repo_slug=repo_slug,+ webhook_secret=webhook.webhook_secret,)pr_id = (payload_data.get('pullRequest') or {}).get('id')@@ -634,6 +691,8 @@ async def bitbucket_dc_events('payload': payload_data,'event_key': x_event_key,'installation_id': installation_id,+ 'connection_id': connection_id,+ 'installer_user_id': installer_user_id,},)await bitbucket_dc_manager.receive_message(message)@@ -656,3 +715,24 @@ async def bitbucket_dc_events(status_code=400,content={'error': 'Invalid payload.', 'error_type': type(e).__name__},)+++@bitbucket_dc_integration_router.post(+ '/bitbucket-dc/connections/{connection_id}/events'+)+async def bitbucket_dc_connection_events(+ connection_id: int,+ request: Request,+ background_tasks: BackgroundTasks,+ x_hub_signature: str | None = Header(None),+ x_event_key: str | None = Header(None),+ x_request_id: str | None = Header(None),+):+ return await _handle_bitbucket_dc_event(+ request=request,+ background_tasks=background_tasks,+ x_hub_signature=x_hub_signature,+ x_event_key=x_event_key,+ x_request_id=x_request_id,+ connection_id=connection_id,+ )diff --git a/enterprise/storage/bitbucket_dc_webhook_store.py b/enterprise/storage/bitbucket_dc_webhook_store.pyindex 1123fa7405..c242302073 100644--- a/enterprise/storage/bitbucket_dc_webhook_store.py+++ b/enterprise/storage/bitbucket_dc_webhook_store.py@@ -32,6 +32,16 @@ class BitbucketDCWebhookStore:webhook = result.scalars().first()return webhook.webhook_secret if webhook else None+ async def get_webhook_by_id(self, webhook_id: int) -> BitbucketDCWebhook | None:+ async with a_session_maker() as session:+ query = (+ select(BitbucketDCWebhook)+ .where(BitbucketDCWebhook.id == webhook_id)+ .limit(1)+ )+ result = await session.execute(query)+ return result.scalars().first()+async def get_webhook_user_id(self, project_key: str, repo_slug: str) -> str | None:async with a_session_maker() as session:query = (@@ -45,6 +55,45 @@ class BitbucketDCWebhookStore:result = await session.execute(query)return result.scalar_one_or_none()+ async def ensure_webhook_enrollment(+ self,+ *,+ project_key: str,+ repo_slug: str,+ user_id: str,+ ) -> BitbucketDCWebhook:+ """Ensure a local row exists so its id can be used in webhook URLs.++ This intentionally does not rotate an existing secret. Automatic+ reinstall first needs a stable row id to build the provider webhook URL;+ the active secret is updated only after the Bitbucket-side write+ succeeds.+ """+ async with a_session_maker() as session:+ async with session.begin():+ query = (+ select(BitbucketDCWebhook)+ .where(+ BitbucketDCWebhook.project_key == project_key,+ BitbucketDCWebhook.repo_slug == repo_slug,+ )+ .limit(1)+ )+ result = await session.execute(query)+ webhook = result.scalars().first()++ if not webhook:+ webhook = BitbucketDCWebhook(+ project_key=project_key,+ repo_slug=repo_slug,+ user_id=user_id,+ webhook_secret=None,+ )+ session.add(webhook)++ await session.refresh(webhook)+ return webhook+async def get_webhook_by_repo(self, project_key: str, repo_slug: str) -> BitbucketDCWebhook | None:diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhook.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhook.pyindex 52c9ff0541..da09a6ceba 100644--- a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhook.py+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_webhook.py@@ -9,9 +9,10 @@ import pytestfrom fastapi import HTTPExceptionfrom server.routes.integration.bitbucket_dc import (BITBUCKET_DC_WEBHOOK_EVENTS,- bitbucket_dc_events,+ bitbucket_dc_connection_events,enroll_bitbucket_dc_webhook,get_bitbucket_dc_resources,+ reinstall_bitbucket_dc_webhook,update_bitbucket_dc_webhook_id,)@@ -45,6 +46,23 @@ def _pr_comment_body() -> bytes:).encode()+def _webhook(+ *,+ webhook_id: int = 123,+ project_key: str = 'PROJ',+ repo_slug: str = 'myrepo',+ webhook_secret: str = 'shared-secret',+ user_id: str = 'kc-installer',+) -> MagicMock:+ webhook = MagicMock()+ webhook.id = webhook_id+ webhook.project_key = project_key+ webhook.repo_slug = repo_slug+ webhook.webhook_secret = webhook_secret+ webhook.user_id = user_id+ return webhook++def test_bitbucket_dc_webhook_events_cover_automation_sources():assert {'repo:refs_changed',@@ -74,14 +92,15 @@ def test_bitbucket_dc_webhook_events_cover_automation_sources():async def test_signature_verification_rejects_bad_signature_with_403(mock_get_redis_client_async, mock_manager, mock_store):- mock_store.get_webhook_secret = AsyncMock(return_value='shared-secret')+ mock_store.get_webhook_by_id = AsyncMock(return_value=_webhook())mock_manager.receive_message = AsyncMock()mock_get_redis_client_async.return_value = AsyncMock()body = _pr_comment_body()with pytest.raises(HTTPException) as exc:- await bitbucket_dc_events(+ await bitbucket_dc_connection_events(+ connection_id=123,request=_request_with_body(body),background_tasks=MagicMock(),x_hub_signature='sha256=deadbeef',@@ -98,26 +117,35 @@ async def test_signature_verification_rejects_bad_signature_with_403(@patch('server.routes.integration.bitbucket_dc.webhook_store')@patch('server.routes.integration.bitbucket_dc.bitbucket_dc_manager')@patch('server.routes.integration.bitbucket_dc.get_redis_client_async')-async def test_missing_repo_identity_rejected_with_403(+async def test_connection_event_uses_connection_repository_when_payload_identity_missing(mock_get_redis_client_async, mock_manager, mock_store):- mock_store.get_webhook_secret = AsyncMock(return_value='shared-secret')+ mock_store.get_webhook_by_id = AsyncMock(return_value=_webhook())mock_manager.receive_message = AsyncMock()- mock_get_redis_client_async.return_value = AsyncMock()+ redis = AsyncMock()+ redis.set = AsyncMock(return_value=True)+ mock_get_redis_client_async.return_value = redis- body = json.dumps({'pullRequest': {'id': 1}}).encode()+ body = json.dumps(+ {+ 'pullRequest': {'id': 1},+ 'comment': {'id': 99, 'text': 'Hey @openhands'},+ }+ ).encode()- with pytest.raises(HTTPException) as exc:- await bitbucket_dc_events(- request=_request_with_body(body),- background_tasks=MagicMock(),- x_hub_signature=_signed(body),- x_event_key='pr:comment:added',- x_request_id='req-1',- )+ response = await bitbucket_dc_connection_events(+ connection_id=123,+ request=_request_with_body(body),+ background_tasks=MagicMock(),+ x_hub_signature=_signed(body),+ x_event_key='pr:comment:added',+ x_request_id='req-1',+ )- assert exc.value.status_code == 403- mock_manager.receive_message.assert_not_called()+ mock_manager.receive_message.assert_awaited_once()+ dispatched = mock_manager.receive_message.call_args.args[0]+ assert dispatched.message['installation_id'] == 'PROJ/myrepo'+ assert response.status_code == 200@pytest.mark.asyncio@@ -128,7 +156,7 @@ async def test_missing_repo_identity_rejected_with_403(async def test_duplicate_event_returns_200_and_skips_dispatch(mock_get_redis_client_async, mock_manager, mock_store):- mock_store.get_webhook_secret = AsyncMock(return_value='shared-secret')+ mock_store.get_webhook_by_id = AsyncMock(return_value=_webhook())mock_manager.receive_message = AsyncMock()redis = AsyncMock()redis.set = AsyncMock(return_value=False) # duplicate@@ -136,7 +164,8 @@ async def test_duplicate_event_returns_200_and_skips_dispatch(body = _pr_comment_body()- response = await bitbucket_dc_events(+ response = await bitbucket_dc_connection_events(+ connection_id=123,request=_request_with_body(body),background_tasks=MagicMock(),x_hub_signature=_signed(body),@@ -157,7 +186,7 @@ async def test_duplicate_event_returns_200_and_skips_dispatch(async def test_valid_pr_comment_event_dispatches_to_manager_and_returns_200(mock_get_redis_client_async, mock_manager, mock_store):- mock_store.get_webhook_secret = AsyncMock(return_value='shared-secret')+ mock_store.get_webhook_by_id = AsyncMock(return_value=_webhook())mock_manager.receive_message = AsyncMock()redis = AsyncMock()redis.set = AsyncMock(return_value=True)@@ -165,7 +194,8 @@ async def test_valid_pr_comment_event_dispatches_to_manager_and_returns_200(body = _pr_comment_body()- response = await bitbucket_dc_events(+ response = await bitbucket_dc_connection_events(+ connection_id=123,request=_request_with_body(body),background_tasks=MagicMock(),x_hub_signature=_signed(body),@@ -193,7 +223,7 @@ async def test_valid_event_forwards_to_automations_when_enabled(mock_store,mock_automation_service,):- mock_store.get_webhook_secret = AsyncMock(return_value='shared-secret')+ mock_store.get_webhook_by_id = AsyncMock(return_value=_webhook())mock_manager.receive_message = AsyncMock()redis = AsyncMock()redis.set = AsyncMock(return_value=True)@@ -206,7 +236,8 @@ async def test_valid_event_forwards_to_automations_when_enabled('server.routes.integration.bitbucket_dc.AUTOMATION_EVENT_FORWARDING_ENABLED',True,):- response = await bitbucket_dc_events(+ response = await bitbucket_dc_connection_events(+ connection_id=123,request=_request_with_body(body),background_tasks=background_tasks,x_hub_signature=_signed(body),@@ -232,7 +263,8 @@ async def test_valid_event_forwards_to_automations_when_enabled(async def test_diagnostics_ping_returns_200_without_dispatch(mock_manager):mock_manager.receive_message = AsyncMock()- response = await bitbucket_dc_events(+ response = await bitbucket_dc_connection_events(+ connection_id=123,request=_request_with_body(b'{}'),background_tasks=MagicMock(),x_hub_signature=None,@@ -268,6 +300,7 @@ async def test_get_bitbucket_dc_resources_returns_repo_enrollment_status(webhook.repo_slug = 'myrepo'webhook.webhook_secret = 'shared-secret'webhook.webhook_id = '42'+ webhook.id = 7webhook.user_id = 'kc-installer'webhook.last_synced = Nonemock_store.get_webhooks_by_repos = AsyncMock(@@ -282,8 +315,12 @@ async def test_get_bitbucket_dc_resources_returns_repo_enrollment_status(resource = response.resources[0]assert resource.project_key == 'PROJ'assert resource.repo_slug == 'myrepo'+ assert resource.connection_id == 7assert resource.webhook_enrolled is Trueassert resource.webhook_id == '42'+ assert resource.webhook_url.endswith(+ '/integration/bitbucket-dc/connections/7/events'+ )assert resource.installed_by_user_id == 'kc-installer'@@ -299,7 +336,9 @@ async def test_enroll_bitbucket_dc_webhook_generates_secret_and_stores_row()mock_token_urlsafe.return_value = 'generated-secret'- mock_store.upsert_webhook_enrollment = AsyncMock()+ webhook = MagicMock()+ webhook.id = 123+ mock_store.upsert_webhook_enrollment = AsyncMock(return_value=webhook)response = await enroll_bitbucket_dc_webhook(body=EnrollBitbucketDCWebhookRequest(@@ -318,11 +357,152 @@ async def test_enroll_bitbucket_dc_webhook_generates_secret_and_stores_row(webhook_secret='generated-secret',)assert response.success is True+ assert response.connection_id == 123assert response.webhook_secret == 'generated-secret'- assert response.webhook_url.endswith('/integration/bitbucket-dc/events')+ assert response.webhook_url.endswith(+ '/integration/bitbucket-dc/connections/123/events'+ )assert response.events == BITBUCKET_DC_WEBHOOK_EVENTS+@patch('server.routes.integration.bitbucket_dc.secrets.token_urlsafe')+@patch('server.routes.integration.bitbucket_dc.webhook_store')+@patch('server.routes.integration.bitbucket_dc.SaaSBitbucketDCService')+async def test_reinstall_bitbucket_dc_webhook_installs_connection_scoped_url(+ mock_service_cls, mock_store, mock_token_urlsafe+):+ from server.routes.integration.bitbucket_dc import (+ BitbucketDCResourceIdentifier,+ BitbucketDCWebhookRequest,+ )++ mock_token_urlsafe.return_value = 'generated-secret'+ webhook = MagicMock()+ webhook.id = 123+ mock_store.ensure_webhook_enrollment = AsyncMock(return_value=webhook)+ mock_store.upsert_webhook_enrollment = AsyncMock()++ service = MagicMock()+ service.user_has_admin_access = AsyncMock(return_value=True)+ service.check_webhook_exists_on_repository = AsyncMock(return_value=(False, None))+ service.create_repository_webhook = AsyncMock(return_value='101')+ mock_service_cls.return_value = service++ response = await reinstall_bitbucket_dc_webhook(+ body=BitbucketDCWebhookRequest(+ resource=BitbucketDCResourceIdentifier(+ project_key='PROJ',+ repo_slug='myrepo',+ )+ ),+ user_id='kc-installer',+ )++ mock_store.ensure_webhook_enrollment.assert_awaited_once_with(+ project_key='PROJ',+ repo_slug='myrepo',+ user_id='kc-installer',+ )+ service.create_repository_webhook.assert_awaited_once()+ service.check_webhook_exists_on_repository.assert_awaited_once_with(+ 'PROJ',+ 'myrepo',+ 'https://app.all-hands.dev/integration/bitbucket-dc/connections/123/events',+ )+ create_kwargs = service.create_repository_webhook.await_args.kwargs+ assert create_kwargs['webhook_url'].endswith(+ '/integration/bitbucket-dc/connections/123/events'+ )+ mock_store.upsert_webhook_enrollment.assert_awaited_once_with(+ project_key='PROJ',+ repo_slug='myrepo',+ user_id='kc-installer',+ webhook_id='101',+ webhook_secret='generated-secret',+ )+ assert response.success is True+ assert response.webhook_id == '101'+ assert response.connection_id == 123+ assert response.webhook_url.endswith(+ '/integration/bitbucket-dc/connections/123/events'+ )+++@patch('server.routes.integration.bitbucket_dc.IS_LOCAL_DEPLOYMENT', False)+@patch('server.routes.integration.bitbucket_dc.webhook_store')+@patch('server.routes.integration.bitbucket_dc.bitbucket_dc_manager')+@patch('server.routes.integration.bitbucket_dc.get_redis_client_async')+async def test_connection_event_verifies_with_connection_secret_and_dispatches_installer(+ mock_get_redis_client_async, mock_manager, mock_store+):+ webhook = MagicMock()+ webhook.id = 123+ webhook.project_key = 'PROJ'+ webhook.repo_slug = 'myrepo'+ webhook.webhook_secret = 'shared-secret'+ webhook.user_id = 'kc-installer'+ mock_store.get_webhook_by_id = AsyncMock(return_value=webhook)+ mock_manager.receive_message = AsyncMock()+ redis = AsyncMock()+ redis.set = AsyncMock(return_value=True)+ mock_get_redis_client_async.return_value = redis++ body = _pr_comment_body()++ response = await bitbucket_dc_connection_events(+ connection_id=123,+ request=_request_with_body(body),+ background_tasks=MagicMock(),+ x_hub_signature=_signed(body),+ x_event_key='pr:comment:added',+ x_request_id='req-1',+ )++ mock_store.get_webhook_by_id.assert_awaited_once_with(123)+ mock_manager.receive_message.assert_awaited_once()+ dispatched = mock_manager.receive_message.call_args.args[0]+ assert dispatched.message['connection_id'] == 123+ assert dispatched.message['installer_user_id'] == 'kc-installer'+ assert dispatched.message['installation_id'] == 'PROJ/myrepo'+ assert response.status_code == 200+++@patch('server.routes.integration.bitbucket_dc.IS_LOCAL_DEPLOYMENT', False)+@patch('server.routes.integration.bitbucket_dc.webhook_store')+@patch('server.routes.integration.bitbucket_dc.bitbucket_dc_manager')+@patch('server.routes.integration.bitbucket_dc.get_redis_client_async')+async def test_connection_event_rejects_payload_for_different_repository(+ mock_get_redis_client_async, mock_manager, mock_store+):+ webhook = MagicMock()+ webhook.id = 123+ webhook.project_key = 'OTHER'+ webhook.repo_slug = 'repo'+ webhook.webhook_secret = 'shared-secret'+ webhook.user_id = 'kc-installer'+ mock_store.get_webhook_by_id = AsyncMock(return_value=webhook)+ mock_manager.receive_message = AsyncMock()+ mock_get_redis_client_async.return_value = AsyncMock()++ body = _pr_comment_body()++ with pytest.raises(HTTPException) as exc:+ await bitbucket_dc_connection_events(+ connection_id=123,+ request=_request_with_body(body),+ background_tasks=MagicMock(),+ x_hub_signature=_signed(body),+ x_event_key='pr:comment:added',+ x_request_id='req-1',+ )++ assert exc.value.status_code == 403+ mock_manager.receive_message.assert_not_called()++@pytest.mark.asyncio@patch('server.routes.integration.bitbucket_dc.webhook_store')async def test_update_bitbucket_dc_webhook_id_records_webhook_id(mock_store):diff --git a/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.py b/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.pyindex 03cb1ac582..5c5f7bbc3c 100644--- a/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.py+++ b/enterprise/tests/unit/storage/test_bitbucket_dc_webhook_store.py@@ -78,6 +78,22 @@ async def test_get_webhook_secret_returns_none_when_repo_not_registered(webhook_assert secret is None+async def test_get_webhook_by_id_returns_matching_row(webhook_store, sample_webhook):+ webhook = await webhook_store.get_webhook_by_id(sample_webhook.id)++ assert webhook is not None+ assert webhook.project_key == 'PROJ'+ assert webhook.repo_slug == 'myrepo'+++async def test_get_webhook_by_id_returns_none_when_absent(webhook_store):+ webhook = await webhook_store.get_webhook_by_id(999)++ assert webhook is None++@pytest.mark.asyncioasync def test_get_webhook_user_id_returns_installer_keycloak_id(webhook_store, sample_webhook@@ -100,6 +116,36 @@ async def test_get_webhooks_by_repos_returns_matching_webhooks(assert webhook_map[('PROJ', 'myrepo')].webhook_secret == 'shared-secret'+async def test_ensure_webhook_enrollment_creates_placeholder_row(webhook_store):+ webhook = await webhook_store.ensure_webhook_enrollment(+ project_key='PROJ',+ repo_slug='newrepo',+ user_id='kc-user',+ )++ assert webhook.id is not None+ assert webhook.project_key == 'PROJ'+ assert webhook.repo_slug == 'newrepo'+ assert webhook.user_id == 'kc-user'+ assert webhook.webhook_secret is None+++async def test_ensure_webhook_enrollment_preserves_existing_secret(+ webhook_store, sample_webhook+):+ webhook = await webhook_store.ensure_webhook_enrollment(+ project_key='PROJ',+ repo_slug='myrepo',+ user_id='kc-new-user',+ )++ assert webhook.id == sample_webhook.id+ assert webhook.user_id == 'kc-installer'+ assert webhook.webhook_secret == 'shared-secret'++@pytest.mark.asyncioasync def test_upsert_webhook_enrollment_creates_row(webhook_store):webhook = await webhook_store.upsert_webhook_enrollment(diff --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 39b4b287d4..49d2a5720e 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@@ -19,8 +19,10 @@ const mockResources: BitbucketDCResource[] = [name: "myrepo",full_name: "PROJ/myrepo",type: "repository",+ connection_id: null,webhook_enrolled: false,webhook_id: null,+ webhook_url: null,webhook_secret_set: false,installed_by_user_id: null,last_synced: null,@@ -31,8 +33,11 @@ const mockResources: BitbucketDCResource[] = [name: "platform",full_name: "OPS/platform",type: "repository",+ connection_id: 7,webhook_enrolled: true,webhook_id: "42",+ webhook_url:+ "https://example.com/integration/bitbucket-dc/connections/7/events",webhook_secret_set: true,installed_by_user_id: "kc-bot",last_synced: "2026-01-01T00:00:00",@@ -99,6 +104,9 @@ describe("BitbucketDCWebhookManager", () => {success: true,error: null,webhook_id: "101",+ connection_id: 8,+ webhook_url:+ "https://example.com/integration/bitbucket-dc/connections/8/events",});renderComponent();@@ -127,6 +135,9 @@ describe("BitbucketDCWebhookManager", () => {success: true,error: null,webhook_id: "42",+ connection_id: 7,+ webhook_url:+ "https://example.com/integration/bitbucket-dc/connections/7/events",});renderComponent();diff --git a/frontend/src/api/integration-service/integration-service.types.ts b/frontend/src/api/integration-service/integration-service.types.tsindex ed5e9eff5f..31df81c943 100644--- a/frontend/src/api/integration-service/integration-service.types.ts+++ b/frontend/src/api/integration-service/integration-service.types.ts@@ -34,8 +34,10 @@ export interface BitbucketDCResource {name: string;full_name: string;type: "repository";+ connection_id: number | null;webhook_enrolled: boolean;webhook_id: string | null;+ webhook_url: string | null;webhook_secret_set: boolean;installed_by_user_id: string | null;last_synced: string | null;@@ -59,6 +61,7 @@ export interface BitbucketDCWebhookEnrollmentResult {repo_slug: string;success: boolean;error: string | null;+ connection_id: number | null;webhook_url: string | null;webhook_secret: string | null;webhook_name: string;@@ -87,4 +90,6 @@ export interface BitbucketDCWebhookInstallationResult {success: boolean;error: string | null;webhook_id: string | null;+ connection_id: number | null;+ webhook_url: string | null;}