Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: post Bitbucket DC comments as the bot account and background webhook handling (#14881)

Alona947d112f84d9
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py
index 584772d542..b904cb8fde 100644
--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py
+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py
@@ -2,6 +2,9 @@ from __future__ import annotations
from types import MappingProxyType
+from integrations.bitbucket_data_center.bitbucket_dc_service_account import (
+ bitbucket_dc_posting_service,
+)
from integrations.bitbucket_data_center.bitbucket_dc_view import (
BitbucketDCFactory,
BitbucketDCInlinePRComment,
@@ -22,7 +25,10 @@ from integrations.utils import (
from integrations.v1_utils import get_saas_user_auth
from jinja2 import Environment, FileSystemLoader
from pydantic import SecretStr
-from server.auth.constants import BITBUCKET_DATA_CENTER_BOT_TOKEN
+from server.auth.constants import (
+ BITBUCKET_DATA_CENTER_BOT_TOKEN,
+ BITBUCKET_DATA_CENTER_BOT_USERNAME,
+)
from server.auth.token_manager import TokenManager
from storage.bitbucket_dc_webhook_store import BitbucketDCWebhookStore
@@ -96,39 +102,22 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
)
return False
- def _posting_service(self, fallback_external_auth_id: str):
+ def _posting_service(self):
"""Build the Bitbucket DC service used to POST comments/reactions.
- When a bot service-account token is configured
- (``BITBUCKET_DATA_CENTER_BOT_TOKEN``), every outbound comment and
- reaction is posted as that bot -- mirroring the GitHub App's
- ``openhands[bot]`` identity -- instead of as the @-mentioning user or
- the webhook installer. Otherwise we fall back to the per-user/installer
- OAuth token (``fallback_external_auth_id``).
+ Always posts as the configured bot account -- mirroring the GitHub
+ App's ``openhands[bot]`` identity. ``receive_message`` gates on the bot
+ token, so this never falls back to a user token.
This affects only who *posts*. The resolver job itself always runs with
the invoking user's own token (see ``start_job``); the bot token is
never used to create conversations or touch the repo.
"""
- from integrations.bitbucket_data_center.bitbucket_dc_service import (
- SaaSBitbucketDCService,
- )
-
- if BITBUCKET_DATA_CENTER_BOT_TOKEN:
- # BBDC HTTP access tokens authenticate via Bearer. The service's
- # ``token=`` constructor arg rewrites a colon-less token to
- # ``x-token-auth:<token>`` (a Bitbucket *Cloud* convention) and
- # sends it as HTTP Basic, which Data Center rejects with 401. Set
- # the raw token directly so ``_get_headers`` uses Bearer.
- service = SaaSBitbucketDCService()
- service.token = SecretStr(BITBUCKET_DATA_CENTER_BOT_TOKEN)
- return service
- return SaaSBitbucketDCService(external_auth_id=fallback_external_auth_id)
+ return bitbucket_dc_posting_service()
async def _add_eyes_reaction(
self,
message: Message,
- reacting_user_id: str,
project_key: str,
repo_slug: str,
) -> None:
@@ -137,9 +126,7 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
Mirrors ``GithubManager._add_reaction``: posted once we've decided
the request will be acted on (permission check passed, mentioner
resolved), before view construction or conversation creation. Posted
- as the resolved invoking user (``reacting_user_id`` -- the mentioner's
- keycloak id, or the installer when the mentioner has no OHE account)
- so the reaction is attributed to whoever triggered the job.
+ as the bot account, like every other Bitbucket DC comment/reaction.
Any failure here is logged at INFO and swallowed -- older BBDC
installs return 404/400 on the reactions endpoint, and a missing
@@ -154,7 +141,7 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
return
try:
- service = self._posting_service(reacting_user_id)
+ service = self._posting_service()
await service.add_comment_reaction(
owner=project_key,
repo_slug=repo_slug,
@@ -176,10 +163,9 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
) -> None:
"""Ask an unenrolled mentioner to sign up in a PR reply.
- The mentioner has no OHE account, so there is no token to post as
- them; the reply goes out under the installer's BBDC token (the
- installer has write access -- the closest analog to GitHub's
- installation token). Best-effort: a failure here must not raise out
+ The mentioner has no OHE account. The reply is posted as the bot
+ account (via ``send_message β†’ _posting_service()``), like every other
+ Bitbucket DC comment. Best-effort: a failure here must not raise out
of ``receive_message``.
"""
try:
@@ -200,6 +186,32 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
if not self.is_job_requested(message):
return
+ # The bot account is required as one unit: the token to post results, and
+ # the username to skip the bot's own replies (below). With either missing
+ # we'd risk re-firing the webhook on our own "@openhands" comment, so skip
+ # the event -- like the Jira DC service-account gate.
+ if not (BITBUCKET_DATA_CENTER_BOT_TOKEN and BITBUCKET_DATA_CENTER_BOT_USERNAME):
+ logger.error(
+ '[Bitbucket DC] BITBUCKET_DATA_CENTER_BOT_TOKEN and '
+ 'BITBUCKET_DATA_CENTER_BOT_USERNAME are both required; skipping event'
+ )
+ return
+
+ # Skip events the bot account authored. The agent's reply is posted via
+ # the bot PAT and can contain "@openhands"; without this guard it would
+ # re-trigger a second job. Mirrors the Jira DC service-account guard;
+ # BBDC's stable author id is the (lowercased) slug.
+ actor = (message.message.get('payload') or {}).get('actor') or {}
+ if (
+ extract_actor_slug(actor).lower()
+ == BITBUCKET_DATA_CENTER_BOT_USERNAME.lower()
+ ):
+ logger.info(
+ '[Bitbucket DC] Ignoring event authored by the bot account '
+ f'{BITBUCKET_DATA_CENTER_BOT_USERNAME!r}'
+ )
+ return
+
project_key, repo_slug = self._extract_repo_identity(message)
installer_user_id = message.message.get('installer_user_id')
if not installer_user_id:
@@ -291,9 +303,7 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
# mirroring the GitHub manager. Posted as the resolved invoking user.
# Best-effort: failures (e.g. legacy BBDC without the reactions
# endpoint) must not block conversation creation.
- await self._add_eyes_reaction(
- message, mentioner_keycloak_id, project_key, repo_slug
- )
+ await self._add_eyes_reaction(message, project_key, repo_slug)
bitbucket_view = await BitbucketDCFactory.create_bitbucket_dc_view_from_payload(
message,
@@ -315,9 +325,7 @@ class BitbucketDCManager(Manager[BitbucketDCViewType]):
async def send_message(
self, message: str, bitbucket_view: ResolverViewInterface
) -> None:
- bitbucket_service = self._posting_service(
- bitbucket_view.user_info.keycloak_user_id
- )
+ bitbucket_service = self._posting_service()
if isinstance(bitbucket_view, BitbucketDCInlinePRComment):
await bitbucket_service.reply_to_pr_comment(
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_service_account.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_service_account.py
new file mode 100644
index 0000000000..0f0e0bea12
--- /dev/null
+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_service_account.py
@@ -0,0 +1,34 @@
+"""Posting-identity resolution for Bitbucket Data Center integrations.
+
+Single source of truth for the credential that posts comments/reactions back to
+Bitbucket DC: always the configured bot account, never the invoking user. A
+user-authored reply containing "@openhands" would re-fire the webhook, so we
+post only as the bot (mirroring the Jira DC service-account pattern). Callers
+gate the event on ``BITBUCKET_DATA_CENTER_BOT_TOKEN`` before posting.
+"""
+
+from integrations.bitbucket_data_center.bitbucket_dc_service import (
+ SaaSBitbucketDCService,
+)
+from pydantic import SecretStr
+from server.auth.constants import BITBUCKET_DATA_CENTER_BOT_TOKEN
+
+
+def bitbucket_dc_posting_service() -> SaaSBitbucketDCService:
+ """Bitbucket DC service that posts as the configured bot account.
+
+ Raises if the bot token is unset -- callers gate on it first, so this is a
+ defensive check (we never fall back to the user's token).
+ """
+ if not BITBUCKET_DATA_CENTER_BOT_TOKEN:
+ raise RuntimeError(
+ 'BITBUCKET_DATA_CENTER_BOT_TOKEN is not configured (required to '
+ 'post as the Bitbucket DC bot)'
+ )
+ # BBDC HTTP access tokens authenticate via Bearer. Set the raw token
+ # directly so _get_headers uses Bearer -- the ``token=`` constructor arg
+ # rewrites a colon-less token to ``x-token-auth:<token>`` (a Bitbucket
+ # *Cloud* convention) sent as HTTP Basic, which Data Center 401s.
+ service = SaaSBitbucketDCService()
+ service.token = SecretStr(BITBUCKET_DATA_CENTER_BOT_TOKEN)
+ return service
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_v1_callback_processor.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_v1_callback_processor.py
index 96e94b46ea..0750a127e3 100644
--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_v1_callback_processor.py
+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_v1_callback_processor.py
@@ -88,15 +88,13 @@ class BitbucketDCV1CallbackProcessor(EventCallbackProcessor):
)
async def _post_summary_to_bitbucket_dc(self, summary: str) -> None:
- from integrations.bitbucket_data_center.bitbucket_dc_service import (
- SaaSBitbucketDCService,
+ from integrations.bitbucket_data_center.bitbucket_dc_service_account import (
+ bitbucket_dc_posting_service,
)
- keycloak_user_id = self.bitbucket_dc_view_data.get('keycloak_user_id')
- if not keycloak_user_id:
- raise RuntimeError('Missing keycloak user ID for Bitbucket DC')
-
- bitbucket_service = SaaSBitbucketDCService(external_auth_id=keycloak_user_id)
+ # Always post as the bot account -- a user-authored reply containing
+ # "@openhands" would re-fire the webhook (duplicate run).
+ bitbucket_service = bitbucket_dc_posting_service()
await bitbucket_service.reply_to_pr_comment(
owner=self.bitbucket_dc_view_data['project_key'],
repo_slug=self.bitbucket_dc_view_data['repo_slug'],
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py
index 9d87efa13c..d806e9e6fd 100644
--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py
+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_view.py
@@ -51,7 +51,9 @@ def extract_actor_slug(actor: dict) -> str:
return actor.get('slug') or actor.get('name') or str(actor.get('id') or '') or ''
-PR_COMMENT_EVENTS = ('pr:comment:added', 'pr:comment:edited')
+# Created-only, like GitHub (action == 'created') and Jira DC (comment_created):
+# editing an existing @openhands comment must not start a second job.
+PR_COMMENT_EVENTS = ('pr:comment:added',)
# =============================================================================
@@ -256,11 +258,12 @@ BitbucketDCViewType = BitbucketDCInlinePRComment | BitbucketDCPRComment | Bitbuc
class BitbucketDCFactory:
"""Inspect a Bitbucket Data Center webhook payload and decide which view to build.
- Bitbucket DC fires ``pr:comment:added`` (and ``pr:comment:edited``)
- when a PR receives a comment. The resolver activates when the comment
- body contains a case-insensitive mention of the configured
- ``@openhands`` handle. Inline comments include an ``anchor`` block
- with the file path and line number.
+ Bitbucket DC fires ``pr:comment:added`` when a PR receives a comment;
+ we act only on that (not ``pr:comment:edited``, so editing a comment
+ can't re-trigger). The resolver activates when the comment body
+ contains a case-insensitive mention of the configured ``@openhands``
+ handle. Inline comments include an ``anchor`` block with the file path
+ and line number.
"""
@staticmethod
diff --git a/enterprise/server/auth/constants.py b/enterprise/server/auth/constants.py
index f0c63adbdc..e0ed643ccd 100644
--- a/enterprise/server/auth/constants.py
+++ b/enterprise/server/auth/constants.py
@@ -73,6 +73,12 @@ BITBUCKET_DATA_CENTER_HOST = os.getenv('BITBUCKET_DATA_CENTER_HOST', '').strip()
BITBUCKET_DATA_CENTER_BOT_TOKEN = os.getenv(
'BITBUCKET_DATA_CENTER_BOT_TOKEN', ''
).strip()
+# Username (slug) of the bot account whose PAT is set above. Lets us skip
+# webhook events the bot itself authored, so the agent's reply (posted via the
+# bot PAT) can't re-trigger a job. BBDC's stable author id is the slug, not email.
+BITBUCKET_DATA_CENTER_BOT_USERNAME = os.getenv(
+ 'BITBUCKET_DATA_CENTER_BOT_USERNAME', ''
+).strip()
BITBUCKET_DATA_CENTER_TOKEN_URL = (
f'https://{BITBUCKET_DATA_CENTER_HOST}/rest/oauth2/latest/token'
)
diff --git a/enterprise/server/routes/integration/bitbucket_dc.py b/enterprise/server/routes/integration/bitbucket_dc.py
index 6ae7442c24..b6de9c68a1 100644
--- a/enterprise/server/routes/integration/bitbucket_dc.py
+++ b/enterprise/server/routes/integration/bitbucket_dc.py
@@ -695,7 +695,11 @@ async def _handle_bitbucket_dc_event(
'installer_user_id': installer_user_id,
},
)
- await bitbucket_dc_manager.receive_message(message)
+ # Process in the background so we return 200 fast. Creating the
+ # conversation + sandbox synchronously can take ~tens of seconds, which
+ # blows Bitbucket DC's webhook timeout -> it marks the delivery failed
+ # and retries (a duplicate-trigger risk). Mirrors the Jira DC route.
+ background_tasks.add_task(bitbucket_dc_manager.receive_message, message)
return JSONResponse(
status_code=200,
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.py
index 2480504d64..45ee9a0d9e 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
@@ -122,10 +122,19 @@ async def test_receive_message_runs_job_as_mentioner_when_linked_in_keycloak():
captured['view'] = view
with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ 'openhands-bot',
+ ),
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, '_add_eyes_reaction', new=AsyncMock()),
patch.object(manager, 'start_job', new=fake_start_job),
):
await manager.receive_message(_comment_message())
@@ -155,6 +164,14 @@ async def test_receive_message_asks_unenrolled_mentioner_to_sign_up():
manager = BitbucketDCManager(token_manager)
with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ 'openhands-bot',
+ ),
patch.object(
manager.webhook_store, 'get_webhook_user_id', return_value='kc-installer'
),
@@ -188,6 +205,14 @@ async def test_receive_message_drops_event_when_keycloak_lookup_raises():
manager = BitbucketDCManager(token_manager)
with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ 'openhands-bot',
+ ),
patch.object(
manager.webhook_store, 'get_webhook_user_id', return_value='kc-installer'
),
@@ -203,6 +228,106 @@ async def test_receive_message_drops_event_when_keycloak_lookup_raises():
mock_not_found.assert_not_called()
+async def test_receive_message_skips_when_bot_token_unset():
+ """Drop the event when no bot token is configured.
+
+ Without the bot PAT there is no safe identity to post results, so the gate
+ drops the event before any installer/permission/lookup work.
+ """
+ token_manager = AsyncMock()
+ manager = BitbucketDCManager(token_manager)
+
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ '',
+ ),
+ 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, '_send_user_not_found_message', new=AsyncMock()
+ ) as mock_not_found,
+ ):
+ await manager.receive_message(_comment_message())
+
+ mock_start.assert_not_called()
+ mock_not_found.assert_not_called()
+ token_manager.get_user_id_from_idp_user_id.assert_not_awaited()
+
+
+async def test_receive_message_skips_when_bot_username_unset():
+ """Drop the event when the bot username is missing even if the token is set.
+
+ Token + username are one required unit: without the username the self-author
+ guard can't run, so a bot reply could re-trigger a job -- so gate on both.
+ """
+ token_manager = AsyncMock()
+ manager = BitbucketDCManager(token_manager)
+
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ '',
+ ),
+ 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, '_send_user_not_found_message', new=AsyncMock()
+ ) as mock_not_found,
+ ):
+ await manager.receive_message(_comment_message())
+
+ mock_start.assert_not_called()
+ mock_not_found.assert_not_called()
+ token_manager.get_user_id_from_idp_user_id.assert_not_awaited()
+
+
[email protected]('actor_slug', ['openhands', 'OpenHands'])
+async def test_receive_message_skips_event_authored_by_bot(actor_slug):
+ """Skip events the bot account authored (case-insensitive).
+
+ The agent's reply is posted via the bot PAT and can contain "@openhands";
+ the self-author guard stops it from re-triggering a job.
+ """
+ token_manager = AsyncMock()
+ manager = BitbucketDCManager(token_manager)
+ message = _comment_message()
+ message.message['payload']['actor']['slug'] = actor_slug
+
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ 'openhands',
+ ),
+ 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,
+ ):
+ await manager.receive_message(message)
+
+ mock_start.assert_not_called()
+ token_manager.get_user_id_from_idp_user_id.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_send_user_not_found_message_replies_as_installer():
"""Post the sign-up reply as the installer.
@@ -241,6 +366,14 @@ async def test_receive_message_skips_when_commenter_lacks_write_access():
manager = BitbucketDCManager(AsyncMock())
with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ 'openhands-bot',
+ ),
patch.object(
manager.webhook_store, 'get_webhook_user_id', return_value='kc-installer'
),
@@ -257,6 +390,14 @@ async def test_receive_message_skips_when_no_installer_recorded_for_repo():
manager = BitbucketDCManager(AsyncMock())
with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_USERNAME',
+ 'openhands-bot',
+ ),
patch.object(manager.webhook_store, 'get_webhook_user_id', return_value=None),
patch.object(manager, 'start_job', new=AsyncMock()) as mock_start,
):
@@ -269,9 +410,15 @@ async def test_receive_message_skips_when_no_installer_recorded_for_repo():
async def test_send_message_replies_inline_with_anchor_for_inline_view():
manager = BitbucketDCManager(AsyncMock())
fake_service = AsyncMock()
- with patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService',
- return_value=fake_service,
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.SaaSBitbucketDCService',
+ return_value=fake_service,
+ ),
):
await manager.send_message('Done', _inline_view())
@@ -288,9 +435,15 @@ async def test_send_message_replies_inline_with_anchor_for_inline_view():
async def test_send_message_replies_via_parent_id_for_pr_comment_view():
manager = BitbucketDCManager(AsyncMock())
fake_service = AsyncMock()
- with patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService',
- return_value=fake_service,
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.SaaSBitbucketDCService',
+ return_value=fake_service,
+ ),
):
await manager.send_message('I am on it!', _pr_comment_view(parent_id=42))
@@ -308,68 +461,73 @@ def test_confirm_incoming_source_type_raises_on_wrong_source():
@pytest.mark.asyncio
-async def test_send_message_uses_view_user_info_keycloak_id():
- """Post replies with the view user auth id.
+async def test_send_message_posts_as_bot_not_mentioner():
+ """Post replies as the bot, never the mentioner.
- 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.
+ send_message builds the posting service via ``bitbucket_dc_posting_service``,
+ which auths as the bot account. The service is constructed with no per-user
+ ``external_auth_id`` and the raw bot token is set directly.
"""
manager = BitbucketDCManager(AsyncMock())
+ fake_service = AsyncMock()
- with patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService'
- ) as service_cls:
- service_cls.return_value = AsyncMock()
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat-123',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.SaaSBitbucketDCService',
+ return_value=fake_service,
+ ) as service_cls,
+ ):
await manager.send_message('Done', _pr_comment_view())
- service_cls.assert_called_once_with(external_auth_id='kc-alice')
+ service_cls.assert_called_once_with()
+ assert 'external_auth_id' not in service_cls.call_args.kwargs
+ assert fake_service.token.get_secret_value() == 'bot-pat-123'
def test_posting_service_uses_bot_token_when_set():
"""Use the bot token when it is configured.
- With ``BITBUCKET_DATA_CENTER_BOT_TOKEN`` set, the posting service auths as
- the bot and does not fall back to the per-user token.
+ ``_posting_service`` takes no args and always auths as the bot, never the
+ per-user token.
"""
manager = BitbucketDCManager(AsyncMock())
with (
patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
'bot-pat-123',
),
patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService'
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.SaaSBitbucketDCService'
) as service_cls,
):
- svc = manager._posting_service('kc-alice')
+ svc = manager._posting_service()
# Built with no per-user auth; the raw bot token is set directly so the
# service sends Bearer. NOT via external_auth_id, and NOT via the token=
# constructor arg (which would downgrade it to x-token-auth HTTP Basic,
# rejected by Bitbucket Data Center).
+ service_cls.assert_called_once_with()
assert 'external_auth_id' not in service_cls.call_args.kwargs
assert svc.token.get_secret_value() == 'bot-pat-123'
-def test_posting_service_falls_back_to_user_token_when_bot_unset():
- """Use the per-user token when no bot token is configured.
+def test_posting_service_raises_when_bot_token_unset():
+ """Raise instead of falling back to a user token.
- Without a bot token, the posting service uses the per-user/installer OAuth
- token.
+ Without a bot token there is no safe posting identity (a user-authored
+ reply with "@openhands" would re-fire the webhook), so building the posting
+ service must raise rather than fall back.
"""
manager = BitbucketDCManager(AsyncMock())
- with (
- patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_manager.BITBUCKET_DATA_CENTER_BOT_TOKEN',
- '',
- ),
- patch(
- 'integrations.bitbucket_data_center.bitbucket_dc_service.SaaSBitbucketDCService'
- ) as service_cls,
+ with patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ '',
):
- manager._posting_service('kc-alice')
-
- service_cls.assert_called_once_with(external_auth_id='kc-alice')
+ with pytest.raises(RuntimeError):
+ manager._posting_service()
diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_service_account.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_service_account.py
new file mode 100644
index 0000000000..f21a100ed0
--- /dev/null
+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_service_account.py
@@ -0,0 +1,38 @@
+"""Tests for the Bitbucket DC posting-identity service account."""
+
+from unittest.mock import patch
+
+import pytest
+from integrations.bitbucket_data_center.bitbucket_dc_service_account import (
+ bitbucket_dc_posting_service,
+)
+
+
+def test_posting_service_uses_bot_token_when_set():
+ """Return a service authed as the bot when the token is configured."""
+ with (
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ 'bot-pat-123',
+ ),
+ patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.SaaSBitbucketDCService'
+ ) as service_cls,
+ ):
+ svc = bitbucket_dc_posting_service()
+
+ # No per-user auth; the raw bot token is set directly so the service sends
+ # Bearer (the token= ctor arg would downgrade to HTTP Basic, which DC 401s).
+ service_cls.assert_called_once_with()
+ assert 'external_auth_id' not in service_cls.call_args.kwargs
+ assert svc.token.get_secret_value() == 'bot-pat-123'
+
+
+def test_posting_service_raises_when_bot_token_unset():
+ """Raise rather than fall back to a user token when no bot token is set."""
+ with patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.BITBUCKET_DATA_CENTER_BOT_TOKEN',
+ '',
+ ):
+ with pytest.raises(RuntimeError):
+ bitbucket_dc_posting_service()
diff --git a/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_v1_callback_processor.py b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_v1_callback_processor.py
new file mode 100644
index 0000000000..7f24acd85f
--- /dev/null
+++ b/enterprise/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_v1_callback_processor.py
@@ -0,0 +1,37 @@
+"""Tests for the Bitbucket DC v1 callback processor summary posting."""
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from integrations.bitbucket_data_center.bitbucket_dc_v1_callback_processor import (
+ BitbucketDCV1CallbackProcessor,
+)
+
+
+async def test_post_summary_uses_bot_posting_service():
+ """Summary comments post via the bot posting service, not a user token."""
+ processor = BitbucketDCV1CallbackProcessor(
+ bitbucket_dc_view_data={
+ 'project_key': 'PROJ',
+ 'repo_slug': 'myrepo',
+ 'pr_id': 7,
+ 'parent_comment_id': 42,
+ }
+ )
+ fake_service = AsyncMock()
+
+ with patch(
+ 'integrations.bitbucket_data_center.bitbucket_dc_service_account.bitbucket_dc_posting_service',
+ return_value=fake_service,
+ ) as mock_posting:
+ await processor._post_summary_to_bitbucket_dc('All done!')
+
+ mock_posting.assert_called_once_with()
+ fake_service.reply_to_pr_comment.assert_awaited_once_with(
+ owner='PROJ',
+ repo_slug='myrepo',
+ pr_id=7,
+ body='All done!',
+ parent_comment_id=42,
+ )
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.py
index 18531138c5..a7e6f68afb 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
@@ -118,6 +118,17 @@ def test_is_pr_comment_returns_false_for_unknown_event_key():
assert BitbucketDCFactory.is_pr_comment(msg) is False
+def test_is_pr_comment_returns_false_for_edited_event():
+ # Created-only: editing an @openhands comment must not re-trigger a job.
+ msg = _make_message(body='@openhands fix', event_key='pr:comment:edited')
+ assert BitbucketDCFactory.is_pr_comment(msg) is False
+
+
+def test_is_pr_comment_returns_true_for_added_event_with_mention():
+ msg = _make_message(body='@openhands fix', event_key='pr:comment:added')
+ assert BitbucketDCFactory.is_pr_comment(msg) is True
+
+
@pytest.mark.asyncio
async def test_factory_records_actor_slug_and_assigns_keycloak_user_id():
msg = _make_message(body='@openhands fix')
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.py
index da09a6ceba..58992382fb 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
@@ -63,6 +63,18 @@ def _webhook(
return webhook
+def _scheduled_message(background_tasks, mock_manager):
+ """Return the Message the route scheduled for manager.receive_message.
+
+ The route returns 200 fast and backgrounds the manager, so the dispatch is
+ a scheduled task arg rather than an awaited call.
+ """
+ for call in background_tasks.add_task.call_args_list:
+ if call.args and call.args[0] is mock_manager.receive_message:
+ return call.args[1]
+ raise AssertionError('receive_message was not scheduled as a background task')
+
+
def test_bitbucket_dc_webhook_events_cover_automation_sources():
assert {
'repo:refs_changed',
@@ -133,17 +145,17 @@ async def test_connection_event_uses_connection_repository_when_payload_identity
}
).encode()
+ background_tasks = MagicMock()
response = await bitbucket_dc_connection_events(
connection_id=123,
request=_request_with_body(body),
- background_tasks=MagicMock(),
+ background_tasks=background_tasks,
x_hub_signature=_signed(body),
x_event_key='pr:comment:added',
x_request_id='req-1',
)
- mock_manager.receive_message.assert_awaited_once()
- dispatched = mock_manager.receive_message.call_args.args[0]
+ dispatched = _scheduled_message(background_tasks, mock_manager)
assert dispatched.message['installation_id'] == 'PROJ/myrepo'
assert response.status_code == 200
@@ -194,17 +206,17 @@ async def test_valid_pr_comment_event_dispatches_to_manager_and_returns_200(
body = _pr_comment_body()
+ background_tasks = MagicMock()
response = await bitbucket_dc_connection_events(
connection_id=123,
request=_request_with_body(body),
- background_tasks=MagicMock(),
+ background_tasks=background_tasks,
x_hub_signature=_signed(body),
x_event_key='pr:comment:added',
x_request_id='req-1',
)
- mock_manager.receive_message.assert_awaited_once()
- dispatched = mock_manager.receive_message.call_args.args[0]
+ dispatched = _scheduled_message(background_tasks, mock_manager)
assert dispatched.source.value == 'bitbucket_data_center'
assert dispatched.message['event_key'] == 'pr:comment:added'
assert dispatched.message['installation_id'] == 'PROJ/myrepo'
@@ -246,7 +258,8 @@ async def test_valid_event_forwards_to_automations_when_enabled(
)
assert response.status_code == 200
- background_tasks.add_task.assert_called_once_with(
+ # Both the automation forward and the manager dispatch are scheduled.
+ background_tasks.add_task.assert_any_call(
mock_automation_service.forward_event,
provider=ProviderType.BITBUCKET_DATA_CENTER,
payload={
@@ -255,7 +268,7 @@ async def test_valid_event_forwards_to_automations_when_enabled(
},
installation_id='PROJ/myrepo',
)
- mock_manager.receive_message.assert_awaited_once()
+ assert _scheduled_message(background_tasks, mock_manager) is not None
@pytest.mark.asyncio
@@ -451,18 +464,18 @@ async def test_connection_event_verifies_with_connection_secret_and_dispatches_i
body = _pr_comment_body()
+ background_tasks = MagicMock()
response = await bitbucket_dc_connection_events(
connection_id=123,
request=_request_with_body(body),
- background_tasks=MagicMock(),
+ background_tasks=background_tasks,
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]
+ dispatched = _scheduled_message(background_tasks, mock_manager)
assert dispatched.message['connection_id'] == 123
assert dispatched.message['installer_user_id'] == 'kc-installer'
assert dispatched.message['installation_id'] == 'PROJ/myrepo'