Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: align OAuth 2.0 with Jira DC server requirements (#14250)

Hiep Led280ed8027c5
diff --git a/enterprise/integrations/jira_dc/jira_dc_manager.py b/enterprise/integrations/jira_dc/jira_dc_manager.py
index d341767faf..1b2e135ac3 100644
--- a/enterprise/integrations/jira_dc/jira_dc_manager.py
+++ b/enterprise/integrations/jira_dc/jira_dc_manager.py
@@ -422,6 +422,19 @@ class JiraDcManager(Manager[JiraDcViewInterface]):
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)
+ if response.status_code == 401:
+ logger.error(
+ '[Jira DC] 401 from %s. PAT length=%d prefix=%s '
+ 'WWW-Authenticate=%r X-Seraph-LoginReason=%r '
+ 'X-AUSERNAME=%r body=%s',
+ url,
+ len(svc_acc_api_key),
+ svc_acc_api_key[:6] if svc_acc_api_key else '',
+ response.headers.get('WWW-Authenticate'),
+ response.headers.get('X-Seraph-LoginReason'),
+ response.headers.get('X-AUSERNAME'),
+ response.text[:500],
+ )
response.raise_for_status()
issue_payload = response.json()
diff --git a/enterprise/server/routes/integration/jira_dc.py b/enterprise/server/routes/integration/jira_dc.py
index a12f67a2aa..29173ba107 100644
--- a/enterprise/server/routes/integration/jira_dc.py
+++ b/enterprise/server/routes/integration/jira_dc.py
@@ -37,7 +37,7 @@ JIRA_DC_WEBHOOKS_ENABLED = os.environ.get('JIRA_DC_WEBHOOKS_ENABLED', '0') in (
'true',
)
JIRA_DC_REDIRECT_URI = f'https://{WEB_HOST}/integration/jira-dc/callback'
-JIRA_DC_SCOPES = 'read:me read:jira-user read:jira-work'
+JIRA_DC_SCOPES = 'WRITE'
JIRA_DC_AUTH_URL = f'{JIRA_DC_BASE_URL}/rest/oauth2/latest/authorize'
JIRA_DC_TOKEN_URL = f'{JIRA_DC_BASE_URL}/rest/oauth2/latest/token'
JIRA_DC_USER_INFO_URL = f'{JIRA_DC_BASE_URL}/rest/api/2/myself'
@@ -504,7 +504,7 @@ async def jira_dc_callback(request: Request, code: str, state: str):
'code': code,
'redirect_uri': JIRA_DC_REDIRECT_URI,
}
- response = requests.post(JIRA_DC_TOKEN_URL, json=token_payload)
+ response = requests.post(JIRA_DC_TOKEN_URL, data=token_payload)
if response.status_code != 200:
raise HTTPException(
status_code=400, detail=f'Error fetching token: {response.text}'
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.py
index b34a24820d..a6fb1f71a5 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
@@ -7,6 +7,7 @@ import hmac
import json
from unittest.mock import AsyncMock, MagicMock, patch
+import httpx
import pytest
from fastapi import Request
from integrations.jira_dc.jira_dc_manager import JiraDcManager
@@ -915,6 +916,57 @@ class TestGetIssueDetails:
sample_job_context, 'bearer_token'
)
+ @pytest.mark.asyncio
+ async def test_get_issue_details_logs_diagnostic_on_401(
+ self, jira_dc_manager, sample_job_context
+ ):
+ """A 401 response must surface auth diagnostics before re-raising.
+
+ Without these fields (PAT length, WWW-Authenticate, X-Seraph-LoginReason,
+ X-AUSERNAME), a silently-rejected PAT is indistinguishable from a permission
+ error β€” operators cannot tell if the token was wrong, the user has no app
+ access, or the instance only accepts a different auth scheme.
+ """
+ # Arrange
+ pat = 'OdC2NTPATfullValueXyz123456789'
+ mock_response = MagicMock()
+ mock_response.status_code = 401
+ mock_response.headers = {
+ 'WWW-Authenticate': 'OAuth realm="https%3A%2F%2Fjira.example.com"',
+ 'X-Seraph-LoginReason': 'AUTHENTICATED_FAILED',
+ 'X-AUSERNAME': 'anonymous',
+ }
+ mock_response.text = '{"errorMessages":["Login Required"]}'
+ mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
+ "Client error '401 Unauthorized'",
+ request=MagicMock(),
+ response=mock_response,
+ )
+
+ with patch('httpx.AsyncClient') as mock_client, patch(
+ 'integrations.jira_dc.jira_dc_manager.logger'
+ ) as mock_logger:
+ mock_client.return_value.__aenter__.return_value.get = AsyncMock(
+ return_value=mock_response
+ )
+
+ # Act
+ with pytest.raises(httpx.HTTPStatusError):
+ await jira_dc_manager.get_issue_details(sample_job_context, pat)
+
+ # Assert: log fires once, and carries every field operators need.
+ mock_logger.error.assert_called_once()
+ format_string, *log_args = mock_logger.error.call_args.args
+ assert log_args == [
+ f'{sample_job_context.base_api_url}/rest/api/2/issue/{sample_job_context.issue_key}',
+ len(pat),
+ pat[:6],
+ 'OAuth realm="https%3A%2F%2Fjira.example.com"',
+ 'AUTHENTICATED_FAILED',
+ 'anonymous',
+ '{"errorMessages":["Login Required"]}',
+ ]
+
class TestSendMessage:
"""Test message sending functionality."""
diff --git a/enterprise/tests/unit/server/routes/test_jira_dc_integration_routes.py b/enterprise/tests/unit/server/routes/test_jira_dc_integration_routes.py
index ff5388a35c..40ab1e9a5a 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
@@ -1,6 +1,7 @@
import json
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
+from urllib.parse import parse_qs, urlparse
import pytest
from fastapi import HTTPException, Request, status
@@ -112,6 +113,39 @@ async def test_create_jira_dc_workspace_oauth_success(
mock_redis.setex.assert_called_once()
+@patch('server.routes.integration.jira_dc.get_user_auth')
+@patch('server.routes.integration.jira_dc.redis_client')
+@patch('server.routes.integration.jira_dc.JIRA_DC_ENABLE_OAUTH', True)
+async def test_create_jira_dc_workspace_oauth_url_uses_jira_dc_write_scope(
+ mock_redis, mock_get_auth, mock_request, mock_user_auth
+):
+ """OAuth authorization URL must request the Jira DC `WRITE` scope.
+
+ Jira DC OAuth 2.0 uses coarse scopes (READ/WRITE/ADMIN/SYSTEM_ADMIN). Sending
+ Atlassian Cloud-style scopes such as `read:me read:jira-user read:jira-work`
+ is rejected with `invalid_scope`, which breaks the consent flow.
+ """
+ # Arrange
+ mock_get_auth.return_value = mock_user_auth
+ mock_redis.setex.return_value = True
+ workspace_data = JiraDcWorkspaceCreate(
+ workspace_name='test-workspace',
+ webhook_secret='secret',
+ svc_acc_email='[email protected]',
+ svc_acc_api_key='key',
+ is_active=True,
+ )
+
+ # Act
+ response = await create_jira_dc_workspace(mock_request, workspace_data)
+ content = json.loads(response.body)
+
+ # Assert
+ query = parse_qs(urlparse(content['authorizationUrl']).query)
+ assert query['scope'] == ['WRITE']
+
+
@pytest.mark.asyncio
@patch('server.routes.integration.jira_dc.get_user_auth')
@patch('server.routes.integration.jira_dc.redis_client')
@@ -198,6 +232,63 @@ async def test_jira_dc_callback_workspace_integration_new_workspace(
)
+@patch('server.routes.integration.jira_dc.redis_client')
+@patch('requests.post')
+@patch('requests.get')
+@patch('server.routes.integration.jira_dc.jira_dc_manager', new_callable=AsyncMock)
+@patch(
+ 'server.routes.integration.jira_dc._handle_workspace_link_creation',
+ new_callable=AsyncMock,
+)
+async def test_jira_dc_callback_token_exchange_uses_form_encoding(
+ mock_handle_link, mock_manager, mock_get, mock_post, mock_redis, mock_request
+):
+ """Token exchange must POST `application/x-www-form-urlencoded`, not JSON.
+
+ Jira DC's `/rest/oauth2/latest/token` endpoint is JAX-RS with @FormParam, which
+ only populates parameters when the body is form-encoded. Sending JSON returns
+ a 500 ("@FormParam is utilized when the content type ... is not
+ application/x-www-form-urlencoded").
+ """
+ # Arrange
+ state = 'test_state'
+ code = 'test_code'
+ session_data = {
+ 'operation_type': 'workspace_integration',
+ 'keycloak_user_id': 'user1',
+ 'target_workspace': 'test.atlassian.net',
+ 'webhook_secret': 'secret',
+ 'svc_acc_email': '[email protected]',
+ 'svc_acc_api_key': 'apikey',
+ 'is_active': True,
+ 'state': state,
+ }
+ mock_redis.get.return_value = json.dumps(session_data)
+ mock_post.return_value = MagicMock(
+ status_code=200, json=lambda: {'access_token': 'token'}
+ )
+ mock_get.return_value = MagicMock(
+ status_code=200, json=lambda: {'key': 'jira_user_123'}, text=''
+ )
+ mock_manager.integration_store.get_workspace_by_name.return_value = None
+
+ with patch('server.routes.integration.jira_dc.token_manager') as mock_token_manager:
+ with patch(
+ 'server.routes.integration.jira_dc.JIRA_DC_BASE_URL',
+ 'https://test.atlassian.net',
+ ):
+ mock_token_manager.encrypt_text.side_effect = lambda x: f'enc_{x}'
+
+ # Act
+ await jira_dc_callback(mock_request, code, state)
+
+ # Assert: token POST is form-encoded (data=), not JSON (json=).
+ kwargs = mock_post.call_args.kwargs
+ assert kwargs.get('data', {}).get('grant_type') == 'authorization_code'
+ assert 'json' not in kwargs
+
+
@pytest.mark.asyncio
@patch('server.routes.integration.jira_dc.get_user_auth')
@patch('server.routes.integration.jira_dc.jira_dc_manager', new_callable=AsyncMock)
@@ -1250,8 +1341,6 @@ class TestJiraDcOAuthUrlEncoding:
auth_url = content['authorizationUrl']
# Verify no raw spaces in the URL (spaces should be encoded as + or %20)
assert ' ' not in auth_url
- # Verify scope parameter contains encoded scopes (+ is valid URL encoding for space)
- assert 'scope=read%3Ame+read%3Ajira-user+read%3Ajira-work' in auth_url
# Verify redirect_uri is properly encoded
assert 'redirect_uri=https%3A%2F%2F' in auth_url
@@ -1273,7 +1362,5 @@ class TestJiraDcOAuthUrlEncoding:
auth_url = content['authorizationUrl']
# Verify no raw spaces in the URL (spaces should be encoded as + or %20)
assert ' ' not in auth_url
- # Verify scope parameter contains encoded scopes (+ is valid URL encoding for space)
- assert 'scope=read%3Ame+read%3Ajira-user+read%3Ajira-work' in auth_url
# Verify redirect_uri is properly encoded
assert 'redirect_uri=https%3A%2F%2F' in auth_url