π OpenHands: AI-Driven Development
feat(jira-dc): email-mode auto-link, targeted repo lookup, and picker mentions (#15001)
Alonae2a05a9d41b4
diff --git a/enterprise/integrations/jira_dc/jira_dc_manager.py b/enterprise/integrations/jira_dc/jira_dc_manager.pyindex fe8649b327..e734e2e905 100644--- a/enterprise/integrations/jira_dc/jira_dc_manager.py+++ b/enterprise/integrations/jira_dc/jira_dc_manager.py@@ -21,11 +21,11 @@ from integrations.models import JobContext, Messagefrom integrations.utils import (HOST_URL,OPENHANDS_RESOLVER_TEMPLATES_DIR,- filter_potential_repos_by_user_msg,get_account_not_linked_message,get_jira_dc_relink_message,get_session_expired_message,get_user_not_found_message,+ has_exact_mention,infer_repo_from_message,markdown_to_jira_markup,)@@ -39,7 +39,6 @@ from storage.jira_dc_workspace import JiraDcWorkspacefrom openhands.app_server.integrations.provider import ProviderHandlerfrom openhands.app_server.integrations.service_types import Comment, Repository-from openhands.app_server.shared import server_configfrom openhands.app_server.types import (LLMAuthenticationError,MissingSettingsError,@@ -107,6 +106,22 @@ def _extract_workspace_hosts(payload: Dict) -> set[str]:}+def _comment_addresses_openhands(comment: str, bot_mentions: set[str] | None) -> bool:+ # Literal @openhands always triggers (works even when the bot username can't+ # be resolved). Jira's mention picker serializes a real mention as wiki+ # markup [~name]/[~key], so match those too once resolved.+ if not comment:+ return False+ # Boundary-aware + case-insensitive: matches @OpenHands but not an email like+ # [email protected] (incl. the service account's own address).+ if has_exact_mention(comment, '@openhands'):+ return True+ if bot_mentions:+ lowered = comment.lower()+ return any(token in lowered for token in bot_mentions)+ return False++class JiraDcManager(Manager[JiraDcViewInterface]):def __init__(self, token_manager: TokenManager):self.token_manager = token_manager@@ -114,6 +129,9 @@ class JiraDcManager(Manager[JiraDcViewInterface]):self.jinja_env = Environment(loader=FileSystemLoader(OPENHANDS_RESOLVER_TEMPLATES_DIR + 'jira_dc'))+ # Bot mention tokens ([~name]/[~key]/...) per workspace.id, resolved+ # lazily from /myself for matching picker mentions.+ self._svc_mentions_cache: dict[int, set[str]] = {}async def authenticate_user(self, user_email: str, jira_dc_user_id: str, workspace_id: int@@ -140,6 +158,15 @@ class JiraDcManager(Manager[JiraDcViewInterface]):jira_dc_user = await self.integration_store.get_active_user_by_keycloak_id_and_workspace(keycloak_user_id, workspace_id)+ # Email mode is itself the admin's opt-in: a user whose Jira email+ # matches an OpenHands account is auto-enrolled, no manual link step.+ # Never in OAuth mode, which requires a verified per-user token.+ if not jira_dc_user and not JIRA_DC_ENABLE_OAUTH:+ jira_dc_user = (+ await self.integration_store.get_or_create_active_email_link(+ keycloak_user_id, workspace_id+ )+ )else:jira_dc_user = await self.integration_store.get_active_user(jira_dc_user_id, workspace_id@@ -156,22 +183,43 @@ class JiraDcManager(Manager[JiraDcViewInterface]):)return jira_dc_user, saas_user_auth- async def _get_repositories(self, user_auth: UserAuth) -> list[Repository]:- """Get repositories that the user has access to."""+ async def _create_provider_handler(+ self, user_auth: UserAuth+ ) -> ProviderHandler | None:+ """Build a ProviderHandler for the user, or None if no provider is linked."""provider_tokens = await user_auth.get_provider_tokens()if provider_tokens is None:- return []+ return Noneaccess_token = await user_auth.get_access_token()user_id = await user_auth.get_user_id()- client = ProviderHandler(+ return ProviderHandler(provider_tokens=provider_tokens,external_auth_token=access_token,external_auth_id=user_id,)- repos: list[Repository] = await client.get_repositories(- 'pushed', server_config.app_mode, None, None, None, None- )- return repos++ async def _verify_mentioned_repos(+ self, provider_handler: ProviderHandler, mentioned_repos: list[str]+ ) -> list[Repository]:+ """Resolve each mentioned repo with a targeted lookup.++ Avoids enumerating the user's full repo list, which is capped and misses+ repos on large Bitbucket DC instances (40k+ repos).+ """+ # Dedupe by canonical full_name: two forms of one repo (case/URL variants,+ # a rename) resolve to the same repo and must count once -- otherwise+ # is_job_requested sees >1 and asks the user to disambiguate a single repo.+ verified: dict[str, Repository] = {}+ for repo_name in mentioned_repos:+ try:+ repo = await provider_handler.verify_repo_provider(+ repo_name, is_optional=True+ )+ except Exception as e:+ logger.debug(f'[Jira DC] Repo verification failed for {repo_name}: {e}')+ continue+ verified.setdefault(repo.full_name.lower(), repo)+ return list(verified.values())async def validate_request(self, request: Request@@ -244,7 +292,9 @@ class JiraDcManager(Manager[JiraDcViewInterface]):return False, None, None, None- def parse_webhook(self, payload: Dict) -> JobContext | None:+ def parse_webhook(+ self, payload: Dict, bot_mentions: set[str] | None = None+ ) -> JobContext | None:event_type = payload.get('webhookEvent')if event_type == 'comment_created':@@ -252,7 +302,7 @@ class JiraDcManager(Manager[JiraDcViewInterface]):comment = comment_data.get('body', '')comment_id = comment_data.get('id')- if '@openhands' not in comment:+ if not _comment_addresses_openhands(comment, bot_mentions):return Noneissue_data = payload.get('issue', {})@@ -324,7 +374,8 @@ class JiraDcManager(Manager[JiraDcViewInterface]):async def receive_message(self, message: Message):"""Process incoming Jira DC webhook message."""payload = message.message.get('payload', {})- job_context = self.parse_webhook(payload)+ bot_mentions = await self._resolve_service_account_mentions(payload)+ job_context = self.parse_webhook(payload, bot_mentions)if not job_context:logger.info('[Jira DC] Webhook does not match trigger conditions')@@ -441,36 +492,33 @@ class JiraDcManager(Manager[JiraDcViewInterface]):return Truetry:- # Get user repositories- user_repos: list[Repository] = await self._get_repositories(- jira_dc_view.saas_user_auth- )-target_str = f'{jira_dc_view.job_context.issue_description}\n{jira_dc_view.job_context.user_msg}'mentioned_repos = infer_repo_from_message(target_str)- # Try to infer repository from issue description- match, repos = filter_potential_repos_by_user_msg(target_str, user_repos)+ # Verify each mentioned repo directly rather than enumerating the+ # user's full repo list (which is capped and misses repos on large+ # Bitbucket DC instances).+ provider_handler = await self._create_provider_handler(+ jira_dc_view.saas_user_auth+ )+ verified_repos = (+ await self._verify_mentioned_repos(provider_handler, mentioned_repos)+ if provider_handler+ else []+ )- if match:- # Found exact repository match- jira_dc_view.selected_repo = repos[0].full_name- logger.info(f'[Jira DC] Inferred repository: {repos[0].full_name}')- return True- else:- # No clear match - send repository selection comment- matched_repos = [- repo- for repo in user_repos- if any(- mentioned_repo.lower() in repo.full_name.lower()- for mentioned_repo in mentioned_repos- )- ]- await self._send_repo_selection_comment(- jira_dc_view, mentioned_repos, matched_repos+ if len(verified_repos) == 1:+ jira_dc_view.selected_repo = verified_repos[0].full_name+ logger.info(+ f'[Jira DC] Inferred repository: {verified_repos[0].full_name}')- return False+ return True++ # Zero or multiple matches -- ask the user to disambiguate.+ await self._send_repo_selection_comment(+ jira_dc_view, mentioned_repos, verified_repos+ )+ return Falseexcept Exception as e:logger.error(f'[Jira DC] Error in is_job_requested: {str(e)}')@@ -534,6 +582,65 @@ class JiraDcManager(Manager[JiraDcViewInterface]):except Exception as e:logger.error(f'[Jira] Failed to send response message: {str(e)}')+ async def _resolve_service_account_mentions(self, payload: Dict) -> set[str] | None:+ """Best-effort bot mention tokens ([~name]/[~key]) for a picker mention.++ Gated so only wiki-markup mentions pay a lookup; literal @openhands and+ non-comment payloads short-circuit. Cached per workspace; failures are not+ cached, so a later comment re-attempts resolution (this event is dropped,+ not retried).+ """+ comment = (payload.get('comment') or {}).get('body', '') or ''+ if has_exact_mention(comment, '@openhands') or '[~' not in comment:+ return None+ try:+ base_api_url = (+ (payload.get('issue') or {}).get('self', '').split('/rest/')[0]+ )+ workspace_name = urlparse(base_api_url).hostname+ if not workspace_name:+ return None+ workspace = await self.integration_store.get_workspace_by_name(+ workspace_name+ )+ if not workspace:+ return None+ if workspace.id in self._svc_mentions_cache:+ return self._svc_mentions_cache[workspace.id]+ service_account = resolve_jira_dc_service_account(+ workspace, self.token_manager+ )+ name, key = await self._fetch_service_account_identity(+ base_api_url, service_account.api_key+ )+ mentions = {+ token.lower()+ for token in (+ f'[~{name}]' if name else None,+ f'[~{key}]' if key else None,+ f'[~accountid:{key}]' if key else None,+ )+ if token+ }+ if mentions:+ self._svc_mentions_cache[workspace.id] = mentions+ return mentions or None+ except Exception as e:+ logger.warning(f'[Jira DC] Could not resolve bot mentions: {str(e)}')+ return None++ async def _fetch_service_account_identity(+ self, base_api_url: str, svc_acc_api_key: str+ ) -> tuple[str | None, str | None]:+ """Return the service account's Jira (name, key) from /myself."""+ url = f'{base_api_url}/rest/api/2/myself'+ headers = {'Authorization': f'Bearer {svc_acc_api_key}'}+ async with httpx.AsyncClient(verify=httpx_verify_option()) as client:+ response = await client.get(url, headers=headers)+ response.raise_for_status()+ data = response.json()+ return data.get('name'), data.get('key')+async def get_issue_details(self, job_context: JobContext, svc_acc_api_key: str) -> Tuple[str, str]:diff --git a/enterprise/server/auth/token_manager.py b/enterprise/server/auth/token_manager.pyindex 51b636b301..b2e7340bc0 100644--- a/enterprise/server/auth/token_manager.py+++ b/enterprise/server/auth/token_manager.py@@ -624,10 +624,19 @@ class TokenManager:async def get_user_id_from_user_email(self, email: str) -> str | None:keycloak_admin = get_keycloak_admin(self.external)users = await keycloak_admin.a_get_users({'q': f'email:{email}'})- if not users:+ # Keycloak's email query is a substring match, so narrow to an exact,+ # unique match -- otherwise users[0] could be a different user whose email+ # merely contains this one (e.g. [email protected] vs [email protected]).+ exact = [u for u in users if (u.get('email') or '').lower() == email.lower()]+ if not exact:logger.error(f'User with email {email} not found.')return None- keycloak_user_id = users[0]['id']+ if len(exact) > 1:+ logger.error(+ f'Multiple users with email {email}; refusing ambiguous match.'+ )+ return None+ keycloak_user_id = exact[0]['id']logger.info(f'Got user ID {keycloak_user_id} from email: {email}')return keycloak_user_iddiff --git a/enterprise/storage/jira_dc_integration_store.py b/enterprise/storage/jira_dc_integration_store.pyindex 9e5ef1495d..0c072d8c2e 100644--- a/enterprise/storage/jira_dc_integration_store.py+++ b/enterprise/storage/jira_dc_integration_store.py@@ -5,6 +5,7 @@ from typing import Optionalfrom uuid import UUIDfrom sqlalchemy import select, update+from sqlalchemy.exc import IntegrityErrorfrom storage.database import a_session_makerfrom storage.jira_dc_conversation import JiraDcConversationfrom storage.jira_dc_user import JiraDcUser@@ -182,6 +183,70 @@ class JiraDcIntegrationStore:)return result.scalar_one_or_none()+ async def get_or_create_active_email_link(+ self, keycloak_user_id: str, jira_dc_workspace_id: int+ ) -> Optional[JiraDcUser]:+ """Return the user's active link for this workspace, reactivating a prior+ inactive link or creating one if none exists.++ Used by email-match mode to auto-enroll a matched user; a new row mirrors a+ manually-linked email row ('unavailable' Jira id, no OAuth tokens). Reuses+ the existing (user, workspace) row so callers that treat the pair as unique+ (status-agnostic scalar_one_or_none) stay valid. Safe under concurrent first+ webhooks: a losing write trips the partial unique index and we re-read the+ winner.+ """+ async with a_session_maker() as session:+ # Match ANY status so a prior inactive link is reactivated in place,+ # not duplicated.+ result = await session.execute(+ select(JiraDcUser).where(+ JiraDcUser.keycloak_user_id == keycloak_user_id,+ JiraDcUser.jira_dc_workspace_id == jira_dc_workspace_id,+ )+ )+ user = result.scalar_one_or_none()+ if user is not None and user.status == 'active':+ return user++ if user is None:+ user = JiraDcUser(+ keycloak_user_id=keycloak_user_id,+ jira_dc_user_id='unavailable',+ jira_dc_workspace_id=jira_dc_workspace_id,+ status='active',+ )+ session.add(user)+ else:+ user.status = 'active'++ try:+ await session.commit()+ await session.refresh(user)+ logger.info(+ f'[Jira DC] Auto-enrolled email-match user for workspace '+ f'{jira_dc_workspace_id}'+ )+ return user+ except IntegrityError:+ await session.rollback()++ # A concurrent insert, or an active link in another workspace (the+ # one-active-link index), won; return whatever active row now exists.+ active = await self.get_active_user_by_keycloak_id_and_workspace(+ keycloak_user_id, jira_dc_workspace_id+ )+ if active is None:+ # Most likely cause for an empty re-read: the user already holds an+ # active link in a different workspace (one-active-link constraint), so+ # auto-enroll here is rejected and they'll see "account not linked".+ logger.warning(+ f'[Jira DC] Could not auto-enroll {keycloak_user_id} in workspace '+ f'{jira_dc_workspace_id}; they likely have an active link in another '+ f'workspace (one-active-link constraint)'+ )+ return active+async def update_user_integration_status(self, keycloak_user_id: str, jira_dc_workspace_id: int, status: str) -> JiraDcUser:diff --git a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.pyindex e522aba6af..15eafdebe6 100644--- a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py+++ b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py@@ -136,41 +136,119 @@ class TestAuthenticateUser:)jira_dc_manager.integration_store.get_active_user.assert_not_called()+ @pytest.mark.asyncio+ async def test_authenticate_user_email_mode_auto_enrolls(+ self,+ jira_dc_manager,+ mock_token_manager,+ sample_jira_dc_user,+ sample_user_auth,+ ):+ """Email mode auto-enrolls a matched user who has no link row yet."""+ mock_token_manager.get_user_id_from_user_email.return_value = 'kc-id'+ jira_dc_manager.integration_store.get_active_user_by_keycloak_id_and_workspace = AsyncMock(+ return_value=None+ )+ jira_dc_manager.integration_store.get_or_create_active_email_link = AsyncMock(+ return_value=sample_jira_dc_user+ )++ with (+ patch('integrations.jira_dc.jira_dc_manager.JIRA_DC_ENABLE_OAUTH', False),+ patch(+ 'integrations.jira_dc.jira_dc_manager.get_user_auth_from_keycloak_id',+ return_value=sample_user_auth,+ ),+ ):+ jira_dc_user, user_auth = await jira_dc_manager.authenticate_user(+ '[email protected]', 'none', 1+ )++ assert jira_dc_user == sample_jira_dc_user+ assert user_auth == sample_user_auth+ jira_dc_manager.integration_store.get_or_create_active_email_link.assert_called_once_with(+ 'kc-id', 1+ )++ @pytest.mark.asyncio+ async def test_authenticate_user_oauth_mode_does_not_auto_enroll(+ self, jira_dc_manager, mock_token_manager+ ):+ """OAuth mode never auto-enrolls, even when the email branch is reached via+ a missing/sentinel Jira id."""+ mock_token_manager.get_user_id_from_user_email.return_value = 'kc-id'+ jira_dc_manager.integration_store.get_active_user_by_keycloak_id_and_workspace = AsyncMock(+ return_value=None+ )+ jira_dc_manager.integration_store.get_or_create_active_email_link = AsyncMock()++ with patch('integrations.jira_dc.jira_dc_manager.JIRA_DC_ENABLE_OAUTH', True):+ jira_dc_user, user_auth = await jira_dc_manager.authenticate_user(+ '[email protected]', 'none', 1+ )++ assert jira_dc_user is None+ assert user_auth is None+ jira_dc_manager.integration_store.get_or_create_active_email_link.assert_not_called()+class TestGetRepositories:"""Test repository retrieval functionality."""@pytest.mark.asyncio- async def test_get_repositories_success(self, jira_dc_manager, sample_user_auth):- """Test successful repository retrieval."""- mock_repos = [- Repository(- id='1',- full_name='company/repo1',- stargazers_count=10,- git_provider=ProviderType.GITHUB,- is_public=True,- ),- Repository(- id='2',- full_name='company/repo2',- stargazers_count=5,- git_provider=ProviderType.GITHUB,- is_public=False,- ),- ]+ async def test_verify_mentioned_repos_targeted_lookup(self, jira_dc_manager):+ """Each mentioned repo is resolved via a targeted verify_repo_provider+ call -- not by enumerating the user's full (capped) repo list."""+ repo = Repository(+ id='1',+ full_name='company/repo',+ stargazers_count=0,+ git_provider=ProviderType.GITHUB,+ is_public=True,+ )+ handler = MagicMock()+ handler.verify_repo_provider = AsyncMock(return_value=repo)- with patch(- 'integrations.jira_dc.jira_dc_manager.ProviderHandler'- ) as mock_provider:- mock_client = MagicMock()- mock_client.get_repositories = AsyncMock(return_value=mock_repos)- mock_provider.return_value = mock_client+ verified = await jira_dc_manager._verify_mentioned_repos(+ handler, ['company/repo']+ )- repos = await jira_dc_manager._get_repositories(sample_user_auth)+ assert verified == [repo]+ handler.verify_repo_provider.assert_awaited_once_with(+ 'company/repo', is_optional=True+ )++ @pytest.mark.asyncio+ async def test_verify_mentioned_repos_skips_inaccessible(self, jira_dc_manager):+ """A repo that fails verification is dropped, not raised."""+ handler = MagicMock()+ handler.verify_repo_provider = AsyncMock(side_effect=Exception('no access'))- assert repos == mock_repos- mock_client.get_repositories.assert_called_once()+ verified = await jira_dc_manager._verify_mentioned_repos(handler, ['x/y'])++ assert verified == []++ @pytest.mark.asyncio+ async def test_verify_mentioned_repos_dedupes_same_repo(self, jira_dc_manager):+ """Two forms of one repo (case/URL variants, a rename) resolve to the same+ canonical full_name and must collapse to a single entry -- otherwise the+ len()==1 auto-select in is_job_requested fails and asks the user to pick+ between a repo and itself."""+ canonical = Repository(+ id='1',+ full_name='PF/WebApp',+ stargazers_count=0,+ git_provider=ProviderType.GITHUB,+ is_public=True,+ )+ handler = MagicMock()+ handler.verify_repo_provider = AsyncMock(return_value=canonical)++ verified = await jira_dc_manager._verify_mentioned_repos(+ handler, ['PF/WebApp', 'pf/webapp']+ )++ assert verified == [canonical] # one unique repo, not twoclass TestValidateRequest:@@ -442,6 +520,114 @@ class TestValidateRequest:assert payload is None+def _jdc_comment_payload(body: str) -> dict:+ return {+ 'webhookEvent': 'comment_created',+ 'comment': {+ 'id': '999',+ 'body': body,+ 'author': {+ 'emailAddress': '[email protected]',+ 'displayName': 'Test User',+ 'key': 'JIRAUSER10000',+ },+ },+ 'issue': {+ 'id': '12345',+ 'key': 'PROJ-123',+ 'self': 'https://jira.company.com/rest/api/2/issue/12345',+ },+ }+++class TestResolveServiceAccountMentions:+ """Lazy, cached bot-username resolution for picker mentions (FDE-84)."""++ @pytest.mark.asyncio+ async def test_skips_ordinary_comment(self, jira_dc_manager):+ jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock()+ result = await jira_dc_manager._resolve_service_account_mentions(+ _jdc_comment_payload('just a regular comment')+ )+ assert result is None+ jira_dc_manager.integration_store.get_workspace_by_name.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_skips_literal_mention(self, jira_dc_manager):+ """Literal @openhands never pays a /myself lookup."""+ jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock()+ result = await jira_dc_manager._resolve_service_account_mentions(+ _jdc_comment_payload('hey @openhands and [~openhands]')+ )+ assert result is None+ jira_dc_manager.integration_store.get_workspace_by_name.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_resolves_name_and_key_then_caches(self, jira_dc_manager):+ workspace = MagicMock()+ workspace.id = 1+ jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(+ return_value=workspace+ )++ mock_response = MagicMock()+ mock_response.raise_for_status = MagicMock()+ mock_response.json.return_value = {'name': 'openhands', 'key': 'JIRAUSER1'}+ mock_client = AsyncMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=False)+ mock_client.get = AsyncMock(return_value=mock_response)++ payload = _jdc_comment_payload('cc [~openhands]')+ with (+ patch(+ 'integrations.jira_dc.jira_dc_manager.resolve_jira_dc_service_account',+ return_value=MagicMock(api_key='pat'),+ ),+ patch('httpx.AsyncClient', return_value=mock_client),+ ):+ first = await jira_dc_manager._resolve_service_account_mentions(payload)+ second = await jira_dc_manager._resolve_service_account_mentions(payload)++ assert '[~openhands]' in first+ assert '[~jirauser1]' in first+ assert '[~accountid:jirauser1]' in first+ assert jira_dc_manager._svc_mentions_cache[1] == first+ # Second call served from cache -> only one /myself fetch.+ mock_client.get.assert_awaited_once()+ assert second == first++ @pytest.mark.asyncio+ async def test_myself_failure_not_cached(self, jira_dc_manager):+ workspace = MagicMock()+ workspace.id = 1+ jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(+ return_value=workspace+ )+ with (+ patch(+ 'integrations.jira_dc.jira_dc_manager.resolve_jira_dc_service_account',+ return_value=MagicMock(api_key='pat'),+ ),+ patch('httpx.AsyncClient', side_effect=Exception('myself down')),+ ):+ result = await jira_dc_manager._resolve_service_account_mentions(+ _jdc_comment_payload('cc [~openhands]')+ )+ assert result is None+ assert 1 not in jira_dc_manager._svc_mentions_cache++ @pytest.mark.asyncio+ async def test_missing_workspace(self, jira_dc_manager):+ jira_dc_manager.integration_store.get_workspace_by_name = AsyncMock(+ return_value=None+ )+ result = await jira_dc_manager._resolve_service_account_mentions(+ _jdc_comment_payload('cc [~openhands]')+ )+ assert result is None++class TestParseWebhook:"""Test webhook parsing functionality."""@@ -482,6 +668,53 @@ class TestParseWebhook:job_context = jira_dc_manager.parse_webhook(payload)assert job_context is None+ def test_parse_webhook_literal_mention_without_username(self, jira_dc_manager):+ """Literal @openhands triggers even when the bot username is unresolved."""+ payload = _jdc_comment_payload('Please fix this @openhands')+ assert jira_dc_manager.parse_webhook(payload, bot_mentions=None) is not None++ def test_parse_webhook_wiki_mention_triggers(self, jira_dc_manager):+ """A picker mention [~name] triggers once the bot mentions are known."""+ payload = _jdc_comment_payload('cc [~openhands] please review')+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'[~openhands]'})+ assert result is not None++ def test_parse_webhook_wiki_mention_case_insensitive(self, jira_dc_manager):+ payload = _jdc_comment_payload('cc [~OpenHands]')+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'[~openhands]'})+ assert result is not None++ def test_parse_webhook_wiki_mention_by_key(self, jira_dc_manager):+ """The bot's Jira key form ([~JIRAUSER...]) also triggers."""+ payload = _jdc_comment_payload('cc [~jirauser173929] please')+ result = jira_dc_manager.parse_webhook(+ payload, bot_mentions={'[~jirauser173929]'}+ )+ assert result is not None++ def test_parse_webhook_wiki_mention_other_user_no_trigger(self, jira_dc_manager):+ payload = _jdc_comment_payload('cc [~someoneelse] review')+ result = jira_dc_manager.parse_webhook(payload, bot_mentions={'[~openhands]'})+ assert result is None++ def test_parse_webhook_wiki_mention_dropped_when_unresolved(self, jira_dc_manager):+ """Picker mention with no resolved username falls back to literal-only."""+ payload = _jdc_comment_payload('cc [~openhands] please')+ assert jira_dc_manager.parse_webhook(payload, bot_mentions=None) is None++ def test_parse_webhook_literal_mention_case_insensitive(self, jira_dc_manager):+ """@OpenHands (any case) triggers like @openhands."""+ payload = _jdc_comment_payload('Hey @OpenHands take a look')+ assert jira_dc_manager.parse_webhook(payload, bot_mentions=None) is not None++ def test_parse_webhook_email_substring_does_not_trigger(self, jira_dc_manager):+ """An email merely containing '@openhands' (e.g. the service account's own+ address) must NOT be treated as a mention."""+ payload = _jdc_comment_payload(+ 'Reassigned from [email protected] for review'+ )+ assert jira_dc_manager.parse_webhook(payload, bot_mentions=None) is None+def test_parse_webhook_issue_update_with_openhands_label(self, jira_dc_manager, sample_issue_update_webhook_payload):@@ -851,69 +1084,91 @@ class TestIsJobRequested:mock_view.saas_user_auth = sample_user_authmock_view.job_context = sample_job_context- mock_repos = [- Repository(- id='1',- full_name='company/repo',- stargazers_count=10,- git_provider=ProviderType.GITHUB,- is_public=True,- )- ]- jira_dc_manager._get_repositories = AsyncMock(return_value=mock_repos)-- with patch(- 'integrations.jira_dc.jira_dc_manager.filter_potential_repos_by_user_msg'- ) as mock_filter:- mock_filter.return_value = (True, mock_repos)+ repo = Repository(+ id='1',+ full_name='company/repo',+ stargazers_count=10,+ git_provider=ProviderType.GITHUB,+ is_public=True,+ )+ jira_dc_manager._create_provider_handler = AsyncMock(return_value=MagicMock())+ jira_dc_manager._verify_mentioned_repos = AsyncMock(return_value=[repo])- message = Message(source=SourceType.JIRA_DC, message={})- result = await jira_dc_manager.is_job_requested(message, mock_view)+ message = Message(source=SourceType.JIRA_DC, message={})+ result = await jira_dc_manager.is_job_requested(message, mock_view)- assert result is True- assert mock_view.selected_repo == 'company/repo'+ assert result is True+ assert mock_view.selected_repo == 'company/repo'@pytest.mark.asyncioasync def test_is_job_requested_new_conversation_no_repo_match(self, jira_dc_manager, sample_job_context, sample_user_auth):- """Test job request validation for new conversation without repository match."""+ """Zero verified repos -> repository-selection comment, job blocked."""mock_view = MagicMock(spec=JiraDcNewConversationView)mock_view.saas_user_auth = sample_user_authmock_view.job_context = sample_job_context- mock_repos = [- Repository(- id='1',- full_name='company/repo',- stargazers_count=10,- git_provider=ProviderType.GITHUB,- is_public=True,- )- ]- jira_dc_manager._get_repositories = AsyncMock(return_value=mock_repos)+ jira_dc_manager._create_provider_handler = AsyncMock(return_value=MagicMock())+ jira_dc_manager._verify_mentioned_repos = AsyncMock(return_value=[])jira_dc_manager._send_repo_selection_comment = AsyncMock()with patch(- 'integrations.jira_dc.jira_dc_manager.filter_potential_repos_by_user_msg'- ) as mock_filter:- mock_filter.return_value = (False, [])+ 'integrations.jira_dc.jira_dc_manager.infer_repo_from_message',+ return_value=[],+ ):+ message = Message(source=SourceType.JIRA_DC, message={})+ result = await jira_dc_manager.is_job_requested(message, mock_view)++ assert result is False+ jira_dc_manager._send_repo_selection_comment.assert_called_once_with(+ mock_view, [], []+ )+ @pytest.mark.asyncio+ async def test_is_job_requested_resolves_repo_beyond_enumeration_cap(+ self, jira_dc_manager, sample_job_context, sample_user_auth+ ):+ """FDE-86: a repo a capped full-list enumeration would miss still resolves,+ because verification is a targeted per-repo lookup."""+ mock_view = MagicMock(spec=JiraDcNewConversationView)+ mock_view.saas_user_auth = sample_user_auth+ mock_view.job_context = sample_job_context++ deep = Repository(+ id='99',+ full_name='pf/deep-repo',+ stargazers_count=0,+ git_provider=ProviderType.GITHUB,+ is_public=False,+ )+ handler = MagicMock()+ handler.verify_repo_provider = AsyncMock(return_value=deep)+ jira_dc_manager._create_provider_handler = AsyncMock(return_value=handler)++ with patch(+ 'integrations.jira_dc.jira_dc_manager.infer_repo_from_message',+ return_value=['pf/deep-repo'],+ ):message = Message(source=SourceType.JIRA_DC, message={})result = await jira_dc_manager.is_job_requested(message, mock_view)- assert result is False- jira_dc_manager._send_repo_selection_comment.assert_called_once_with(- mock_view, [], []- )+ assert result is True+ assert mock_view.selected_repo == 'pf/deep-repo'+ handler.verify_repo_provider.assert_awaited_once_with(+ 'pf/deep-repo', is_optional=True+ )@pytest.mark.asyncioasync def test_is_job_requested_exception(self, jira_dc_manager, sample_user_auth):- """Test job request validation when an exception occurs."""+ """An unexpected error blocks the job (returns False)."""mock_view = MagicMock(spec=JiraDcNewConversationView)mock_view.saas_user_auth = sample_user_auth- jira_dc_manager._get_repositories = AsyncMock(- side_effect=Exception('Repository error')+ mock_view.job_context = MagicMock()+ mock_view.job_context.issue_description = ''+ mock_view.job_context.user_msg = ''+ jira_dc_manager._create_provider_handler = AsyncMock(+ side_effect=Exception('boom'))message = Message(source=SourceType.JIRA_DC, message={})diff --git a/enterprise/tests/unit/storage/test_jira_dc_active_link_constraint.py b/enterprise/tests/unit/storage/test_jira_dc_active_link_constraint.pyindex baf370f172..4d2a49597d 100644--- a/enterprise/tests/unit/storage/test_jira_dc_active_link_constraint.py+++ b/enterprise/tests/unit/storage/test_jira_dc_active_link_constraint.py@@ -176,3 +176,109 @@ async def test_deactivate_user_links_except_workspace_targets_stale_active_linksassert 'jira_dc_users.jira_dc_workspace_id !=' in statement_textassert 'jira_dc_users.status' in statement_textsession.commit.assert_awaited_once()+++def _session_with_existing(existing):+ """Mock session whose initial (user, workspace) SELECT yields `existing`."""+ result = Mock()+ result.scalar_one_or_none.return_value = existing+ session = Mock()+ session.execute = AsyncMock(return_value=result)+ session.add = Mock()+ session.commit = AsyncMock()+ session.refresh = AsyncMock()+ session.rollback = AsyncMock()+ return session+++async def test_get_or_create_active_email_link_returns_existing_active():+ store = JiraDcIntegrationStore()+ active = Mock(spec=JiraDcUser)+ active.status = 'active'+ session = _session_with_existing(active)++ @asynccontextmanager+ async def mock_session_maker():+ yield session++ with patch('storage.jira_dc_integration_store.a_session_maker', mock_session_maker):+ result = await store.get_or_create_active_email_link('kc-1', 1)++ assert result is active+ session.add.assert_not_called()+ session.commit.assert_not_awaited() # already active, nothing written+++async def test_get_or_create_active_email_link_inserts_when_absent():+ store = JiraDcIntegrationStore()+ session = _session_with_existing(None)++ @asynccontextmanager+ async def mock_session_maker():+ yield session++ with patch('storage.jira_dc_integration_store.a_session_maker', mock_session_maker):+ result = await store.get_or_create_active_email_link('kc-1', 7)++ session.add.assert_called_once()+ added = session.add.call_args.args[0]+ assert isinstance(added, JiraDcUser)+ assert added.keycloak_user_id == 'kc-1'+ assert added.jira_dc_workspace_id == 7+ assert added.jira_dc_user_id == 'unavailable' # email-mode sentinel+ assert added.status == 'active'+ session.commit.assert_awaited_once()+ session.refresh.assert_awaited_once_with(added)+ assert result is added+++async def test_get_or_create_active_email_link_reactivates_inactive_link():+ """A prior inactive link for the same workspace is reactivated in place, not+ duplicated -- otherwise status-agnostic scalar_one_or_none callers (unlink,+ relink) hit MultipleResultsFound."""+ store = JiraDcIntegrationStore()+ inactive = Mock(spec=JiraDcUser)+ inactive.status = 'inactive'+ session = _session_with_existing(inactive)++ @asynccontextmanager+ async def mock_session_maker():+ yield session++ with patch('storage.jira_dc_integration_store.a_session_maker', mock_session_maker):+ result = await store.get_or_create_active_email_link('kc-1', 1)++ assert inactive.status == 'active' # reactivated in place+ session.add.assert_not_called() # no duplicate row+ session.commit.assert_awaited_once()+ session.refresh.assert_awaited_once_with(inactive)+ assert result is inactive+++async def test_get_or_create_active_email_link_handles_concurrent_insert_race():+ """A concurrent first webhook wins the insert; ours trips the unique index ->+ IntegrityError -> rollback -> re-read returns the winning row."""+ store = JiraDcIntegrationStore()+ winner = Mock(spec=JiraDcUser)+ store.get_active_user_by_keycloak_id_and_workspace = AsyncMock(return_value=winner)++ session = _session_with_existing(None)+ session.commit = AsyncMock(+ side_effect=IntegrityError('insert', {}, Exception('unique violation'))+ )++ @asynccontextmanager+ async def mock_session_maker():+ yield session++ with patch('storage.jira_dc_integration_store.a_session_maker', mock_session_maker):+ result = await store.get_or_create_active_email_link('kc-1', 1)++ session.commit.assert_awaited_once()+ session.rollback.assert_awaited_once() # failed write rolled back, not cached+ assert result is winner+ store.get_active_user_by_keycloak_id_and_workspace.assert_awaited_once()diff --git a/enterprise/tests/unit/test_token_manager.py b/enterprise/tests/unit/test_token_manager.pyindex d225639e39..47978088de 100644--- a/enterprise/tests/unit/test_token_manager.py+++ b/enterprise/tests/unit/test_token_manager.py@@ -518,3 +518,57 @@ class TestCreateKeycloakUser:# the atomic create failed, so nothing was persisted.mock_admin.a_set_user_password.assert_not_called()mock_admin.delete_user.assert_not_called()+++class TestGetUserIdFromUserEmail:+ """Keycloak's email query is a substring match, so the result must be+ narrowed to an exact, unique email match."""++ @pytest.mark.asyncio+ async def test_picks_exact_match_not_substring_collision(self, token_manager):+ """A substring-colliding email ([email protected] vs [email protected]) must not+ be returned in place of the exact user, regardless of result order."""+ with patch('server.auth.token_manager.get_keycloak_admin') as mock_get_admin:+ mock_admin = MagicMock()+ mock_admin.a_get_users = AsyncMock(+ return_value=[+ {'id': 'wrong', 'email': '[email protected]'},+ {'id': 'right', 'email': '[email protected]'},+ ]+ )+ mock_get_admin.return_value = mock_admin++ result = await token_manager.get_user_id_from_user_email('[email protected]')++ assert result == 'right'++ @pytest.mark.asyncio+ async def test_returns_none_when_only_substring_matches(self, token_manager):+ """If the query returns only non-exact matches, refuse (no wrong user)."""+ with patch('server.auth.token_manager.get_keycloak_admin') as mock_get_admin:+ mock_admin = MagicMock()+ mock_admin.a_get_users = AsyncMock(+ return_value=[{'id': 'wrong', 'email': '[email protected]'}]+ )+ mock_get_admin.return_value = mock_admin++ result = await token_manager.get_user_id_from_user_email('[email protected]')++ assert result is None++ @pytest.mark.asyncio+ async def test_returns_none_on_ambiguous_duplicate_email(self, token_manager):+ """Two users with the same exact email is ambiguous -> refuse."""+ with patch('server.auth.token_manager.get_keycloak_admin') as mock_get_admin:+ mock_admin = MagicMock()+ mock_admin.a_get_users = AsyncMock(+ return_value=[+ {'id': 'a', 'email': '[email protected]'},+ {'id': 'b', 'email': '[email protected]'},+ ]+ )+ mock_get_admin.return_value = mock_admin++ result = await token_manager.get_user_id_from_user_email('[email protected]')++ assert result is None