π OpenHands: AI-Driven Development
fix: return actionable error when Jira DC token endpoint is unreachable (#14990)
Alona2b904742a5b6
diff --git a/enterprise/integrations/jira_dc/jira_dc_user_token.py b/enterprise/integrations/jira_dc/jira_dc_user_token.pyindex 50079e56e7..c0759efe35 100644--- a/enterprise/integrations/jira_dc/jira_dc_user_token.py+++ b/enterprise/integrations/jira_dc/jira_dc_user_token.py@@ -79,27 +79,44 @@ async def get_user_jira_dc_token()refresh_token = token_manager.decrypt_text(enc_refresh)- async with httpx.AsyncClient(verify=httpx_verify_option(), timeout=30.0) as client:- response = await client.post(+ try:+ async with httpx.AsyncClient(+ verify=httpx_verify_option(), timeout=30.0+ ) as client:+ response = await client.post(+ JIRA_DC_TOKEN_URL,+ data={+ 'grant_type': 'refresh_token',+ 'client_id': JIRA_DC_CLIENT_ID,+ 'client_secret': JIRA_DC_CLIENT_SECRET,+ 'refresh_token': refresh_token,+ },+ )+ except httpx.RequestError as e:+ # Unreachable token endpoint -- usually wrong scheme (http vs https) or+ # blocked egress; surface that instead of a bare connection error.+ logger.warning(+ '[Jira DC] Token refresh could not reach %s: %s',JIRA_DC_TOKEN_URL,- data={- 'grant_type': 'refresh_token',- 'client_id': JIRA_DC_CLIENT_ID,- 'client_secret': JIRA_DC_CLIENT_SECRET,- 'refresh_token': refresh_token,- },+ type(e).__name__,)- if response.status_code != 200:- logger.warning(- '[Jira DC] Token refresh failed: %s %s',- response.status_code,- response.text[:200],- )- raise JiraDcUserTokenError(- 'Jira DC token refresh failed. '- 'Please re-link via OpenHands Settings β Integrations.'- )- data = response.json()+ raise JiraDcUserTokenError(+ f'Could not reach the Jira Data Center token endpoint '+ f'({JIRA_DC_TOKEN_URL}): {type(e).__name__}. Check that the Jira Base '+ f'URL uses https and that OpenHands can reach the Jira server.'+ ) from e++ if response.status_code != 200:+ logger.warning(+ '[Jira DC] Token refresh failed: %s %s',+ response.status_code,+ response.text[:200],+ )+ raise JiraDcUserTokenError(+ 'Jira DC token refresh failed. '+ 'Please re-link via OpenHands Settings β Integrations.'+ )+ data = response.json()new_access = data.get('access_token')if not new_access:diff --git a/enterprise/server/routes/integration/jira_dc.py b/enterprise/server/routes/integration/jira_dc.pyindex 4659dfcc0a..b5215d0e04 100644--- a/enterprise/server/routes/integration/jira_dc.py+++ b/enterprise/server/routes/integration/jira_dc.py@@ -912,8 +912,21 @@ async def jira_dc_callback(request: Request, code: str, state: str):'code': code,'redirect_uri': JIRA_DC_REDIRECT_URI,}- async with httpx.AsyncClient() as client:- response = await client.post(JIRA_DC_TOKEN_URL, data=token_payload)+ try:+ async with httpx.AsyncClient() as client:+ response = await client.post(JIRA_DC_TOKEN_URL, data=token_payload)+ except httpx.RequestError as e:+ # Token endpoint unreachable -- almost always JIRA_DC_BASE_URL using the+ # wrong scheme (http vs https) or blocked egress to the Jira server.+ raise HTTPException(+ status_code=502,+ detail=(+ f'Could not reach the Jira Data Center token endpoint '+ f'({JIRA_DC_TOKEN_URL}): {type(e).__name__}. Check that the Jira '+ f'Base URL uses the correct https scheme and that OpenHands can '+ f'reach the Jira server.'+ ),+ ) from eif response.status_code != 200:raise HTTPException(status_code=400, detail=f'Error fetching token: {response.text}'@@ -938,8 +951,20 @@ async def jira_dc_callback(request: Request, code: str, state: str):if target_workspace != urlparse(JIRA_DC_BASE_URL).hostname:raise HTTPException(status_code=400, detail='Target workspace mismatch.')- async with httpx.AsyncClient() as client:- jira_dc_user_response = await client.get(JIRA_DC_USER_INFO_URL, headers=headers)+ try:+ async with httpx.AsyncClient() as client:+ jira_dc_user_response = await client.get(+ JIRA_DC_USER_INFO_URL, headers=headers+ )+ except httpx.RequestError as e:+ raise HTTPException(+ status_code=502,+ detail=(+ f'Could not reach the Jira Data Center server '+ f'({JIRA_DC_USER_INFO_URL}): {type(e).__name__}. Check that the '+ f'Jira Base URL and network egress are correct.'+ ),+ ) from eif jira_dc_user_response.status_code != 200:raise HTTPException(status_code=400,diff --git a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_user_token.py b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_user_token.pyindex ec9ead589a..f5f8a2644a 100644--- a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_user_token.py+++ b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_user_token.py@@ -3,6 +3,7 @@import timefrom unittest.mock import AsyncMock, MagicMock, patch+import httpximport pytestfrom integrations.jira_dc.jira_dc_user_token import (JiraDcUserToken,@@ -253,6 +254,35 @@ async def test_raises_when_refresh_request_fails():)+async def test_raises_actionable_error_when_token_endpoint_unreachable():+ """A connection error (wrong scheme / blocked egress) surfaces an actionable+ JiraDcUserTokenError, not a bare httpx exception."""+ expired = int(time.time()) - 100+ future_refresh = int(time.time()) + 86400+ store = _make_store(('enc_access', 'enc_refresh', expired, future_refresh))+ tm = _make_token_manager(decrypt_return='tok')++ mock_client = AsyncMock()+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=False)+ mock_client.post = AsyncMock(side_effect=httpx.ConnectTimeout('timed out'))++ with patch(+ 'integrations.jira_dc.jira_dc_user_token.httpx.AsyncClient',+ return_value=mock_client,+ ):+ with pytest.raises(JiraDcUserTokenError, match='Could not reach'):+ await get_user_jira_dc_token(+ keycloak_user_id='kc1',+ workspace_id=1,+ token_manager=tm,+ store=store,+ )++ store.update_user_oauth_tokens.assert_not_called()++@pytest.mark.asyncioasync def test_raises_when_refresh_response_has_no_access_token():expired = int(time.time()) - 100diff --git a/enterprise/tests/unit/server/routes/test_jira_dc_integration_routes.py b/enterprise/tests/unit/server/routes/test_jira_dc_integration_routes.pyindex 94c4e80771..66aa2eb326 100644--- a/enterprise/tests/unit/server/routes/test_jira_dc_integration_routes.py+++ b/enterprise/tests/unit/server/routes/test_jira_dc_integration_routes.py@@ -6,6 +6,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchfrom urllib.parse import parse_qs, urlparse+import httpximport pytestfrom fastapi import HTTPException, Request, statusfrom fastapi.responses import RedirectResponse@@ -500,6 +501,37 @@ async def test_jira_dc_callback_token_exchange_uses_form_encoding(assert 'json' not in kwargs+@patch('server.routes.integration.jira_dc.redis_client')+@patch('server.routes.integration.jira_dc.jira_dc_manager', new_callable=AsyncMock)+async def test_jira_dc_callback_token_endpoint_unreachable_returns_502(+ mock_manager, mock_redis, mock_request+):+ """An unreachable token endpoint (wrong scheme / blocked egress) returns an+ actionable 502, not a bare 500."""+ state = 'test_state'+ session_data = {+ 'operation_type': 'workspace_integration',+ 'keycloak_user_id': 'user1',+ 'target_workspace': 'test.atlassian.net',+ 'state': state,+ }+ mock_redis.get.return_value = json.dumps(session_data)++ mock_client = AsyncMock()+ mock_client.post = AsyncMock(side_effect=httpx.ConnectTimeout('timed out'))+ mock_httpx = AsyncMock()+ mock_httpx.__aenter__ = AsyncMock(return_value=mock_client)+ mock_httpx.__aexit__ = AsyncMock(return_value=None)++ with patch('httpx.AsyncClient', return_value=mock_httpx):+ with pytest.raises(HTTPException) as exc_info:+ await jira_dc_callback(mock_request, 'code', state)++ assert exc_info.value.status_code == 502+ assert 'Could not reach' in exc_info.value.detail++@pytest.mark.asyncio@patch('server.routes.integration.jira_dc.get_user_auth')@patch('server.routes.integration.jira_dc.jira_dc_manager', new_callable=AsyncMock)