π OpenHands: AI-Driven Development
Make load_org_token and store_org_token async in TokenManager (#13147)
Tim O'Farrell17347a95f8dd
diff --git a/enterprise/integrations/github/github_manager.py b/enterprise/integrations/github/github_manager.pyindex d7989d25ca..de4f45d755 100644--- a/enterprise/integrations/github/github_manager.py+++ b/enterprise/integrations/github/github_manager.py@@ -193,7 +193,7 @@ class GithubManager(Manager):github_view.installation_id)# Store the installation token- self.token_manager.store_org_token(+ await self.token_manager.store_org_token(github_view.installation_id, installation_token)# Add eyes reaction to acknowledge we've read the request@@ -201,7 +201,7 @@ class GithubManager(Manager):await self.start_job(github_view)async def send_message(self, message: Message, github_view: ResolverViewInterface):- installation_token = self.token_manager.load_org_token(+ installation_token = await self.token_manager.load_org_token(github_view.installation_id)if not installation_token:diff --git a/enterprise/server/auth/token_manager.py b/enterprise/server/auth/token_manager.pyindex 6cd4c5276a..80ed958412 100644--- a/enterprise/server/auth/token_manager.py+++ b/enterprise/server/auth/token_manager.py@@ -38,9 +38,9 @@ from server.auth.keycloak_manager import get_keycloak_admin, get_keycloak_openidfrom server.config import get_configfrom server.logger import loggerfrom sqlalchemy import String as SQLString-from sqlalchemy import type_coerce+from sqlalchemy import select, type_coercefrom storage.auth_token_store import AuthTokenStore-from storage.database import session_maker+from storage.database import a_session_makerfrom storage.github_app_installation import GithubAppInstallationfrom storage.offline_token_store import OfflineTokenStorefrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt@@ -783,25 +783,24 @@ class TokenManager:exc_info=True,)- def store_org_token(self, installation_id: int, installation_token: str):+ async def store_org_token(self, installation_id: int, installation_token: str):"""Store a GitHub App installation token.Args:installation_id: GitHub installation ID (integer or string)installation_token: The token to store"""- with session_maker() as session:+ async with a_session_maker() as session:# Ensure installation_id is a stringstr_installation_id = str(installation_id)# Use type_coerce to ensure SQLAlchemy treats the parameter as a string- installation = (- session.query(GithubAppInstallation)- .filter(+ result = await session.execute(+ select(GithubAppInstallation).filter(GithubAppInstallation.installation_id== type_coerce(str_installation_id, SQLString))- .first())+ installation = result.scalars().first()if installation:installation.encrypted_token = self.encrypt_text(installation_token)else:@@ -811,9 +810,9 @@ class TokenManager:encrypted_token=self.encrypt_text(installation_token),))- session.commit()+ await session.commit()- def load_org_token(self, installation_id: int) -> str | None:+ async def load_org_token(self, installation_id: int) -> str | None:"""Load a GitHub App installation token.Args:@@ -822,17 +821,16 @@ class TokenManager:Returns:The decrypted token if found, None otherwise"""- with session_maker() as session:+ async with a_session_maker() as session:# Ensure installation_id is a string and use type_coercestr_installation_id = str(installation_id)- installation = (- session.query(GithubAppInstallation)- .filter(+ result = await session.execute(+ select(GithubAppInstallation).filter(GithubAppInstallation.installation_id== type_coerce(str_installation_id, SQLString))- .first())+ installation = result.scalars().first()if not installation:return Nonetoken = self.decrypt_text(installation.encrypted_token)diff --git a/enterprise/tests/unit/test_token_manager_extended.py b/enterprise/tests/unit/test_token_manager_extended.pyindex c3b09434a3..edaf1a2ff9 100644--- a/enterprise/tests/unit/test_token_manager_extended.py+++ b/enterprise/tests/unit/test_token_manager_extended.py@@ -346,3 +346,169 @@ async def test_disable_keycloak_user_exception_handling(token_manager):# Verify the method was calledmock_admin.a_get_user.assert_called_once_with(user_id)+++class TestOrgTokenMethods:+ """Test cases for store_org_token and load_org_token methods."""++ @pytest.mark.asyncio+ async def test_store_org_token_new_installation(self, token_manager):+ """Test storing a token for a new installation."""+ installation_id = 12345+ installation_token = 'ghs_test_token_abc123'++ mock_session = AsyncMock()+ mock_result = MagicMock()+ mock_result.scalars.return_value.first.return_value = None+ mock_session.execute = AsyncMock(return_value=mock_result)+ mock_session.add = MagicMock()+ mock_session.commit = AsyncMock()++ mock_context_manager = AsyncMock()+ mock_context_manager.__aenter__ = AsyncMock(return_value=mock_session)+ mock_context_manager.__aexit__ = AsyncMock(return_value=None)++ with patch(+ 'server.auth.token_manager.a_session_maker',+ return_value=mock_context_manager,+ ):+ await token_manager.store_org_token(installation_id, installation_token)++ mock_session.add.assert_called_once()+ mock_session.commit.assert_called_once()++ @pytest.mark.asyncio+ async def test_store_org_token_update_existing_installation(self, token_manager):+ """Test updating a token for an existing installation."""+ installation_id = 12345+ installation_token = 'ghs_test_token_abc123'++ mock_installation = MagicMock()+ mock_installation.encrypted_token = 'old_encrypted_token'++ mock_session = AsyncMock()+ mock_result = MagicMock()+ mock_result.scalars.return_value.first.return_value = mock_installation+ mock_session.execute = AsyncMock(return_value=mock_result)+ mock_session.commit = AsyncMock()++ mock_context_manager = AsyncMock()+ mock_context_manager.__aenter__ = AsyncMock(return_value=mock_session)+ mock_context_manager.__aexit__ = AsyncMock(return_value=None)++ with patch(+ 'server.auth.token_manager.a_session_maker',+ return_value=mock_context_manager,+ ):+ await token_manager.store_org_token(installation_id, installation_token)++ # Verify token was updated (encrypted)+ assert mock_installation.encrypted_token != 'old_encrypted_token'+ mock_session.commit.assert_called_once()++ @pytest.mark.asyncio+ async def test_load_org_token_found(self, token_manager):+ """Test loading a token that exists."""+ installation_id = 12345+ original_token = 'ghs_test_token_abc123'+ encrypted_token = token_manager.encrypt_text(original_token)++ mock_installation = MagicMock()+ mock_installation.encrypted_token = encrypted_token++ mock_session = AsyncMock()+ mock_result = MagicMock()+ mock_result.scalars.return_value.first.return_value = mock_installation+ mock_session.execute = AsyncMock(return_value=mock_result)++ mock_context_manager = AsyncMock()+ mock_context_manager.__aenter__ = AsyncMock(return_value=mock_session)+ mock_context_manager.__aexit__ = AsyncMock(return_value=None)++ with patch(+ 'server.auth.token_manager.a_session_maker',+ return_value=mock_context_manager,+ ):+ result = await token_manager.load_org_token(installation_id)++ assert result == original_token++ @pytest.mark.asyncio+ async def test_load_org_token_not_found(self, token_manager):+ """Test loading a token that doesn't exist."""+ installation_id = 99999++ mock_session = AsyncMock()+ mock_result = MagicMock()+ mock_result.scalars.return_value.first.return_value = None+ mock_session.execute = AsyncMock(return_value=mock_result)++ mock_context_manager = AsyncMock()+ mock_context_manager.__aenter__ = AsyncMock(return_value=mock_session)+ mock_context_manager.__aexit__ = AsyncMock(return_value=None)++ with patch(+ 'server.auth.token_manager.a_session_maker',+ return_value=mock_context_manager,+ ):+ result = await token_manager.load_org_token(installation_id)++ assert result is None++ @pytest.mark.asyncio+ async def test_store_and_load_org_token_integration(self, token_manager):+ """Test that store and load work together using the same encryption."""+ installation_id = 12345+ original_token = 'ghs_test_token_abc123'++ # Store+ stored_encrypted_token = None++ def capture_add(obj):+ nonlocal stored_encrypted_token+ stored_encrypted_token = obj.encrypted_token++ mock_session_store = AsyncMock()+ mock_result_store = MagicMock()+ mock_result_store.scalars.return_value.first.return_value = None+ mock_session_store.execute = AsyncMock(return_value=mock_result_store)+ mock_session_store.add = capture_add+ mock_session_store.commit = AsyncMock()++ mock_context_manager_store = AsyncMock()+ mock_context_manager_store.__aenter__ = AsyncMock(+ return_value=mock_session_store+ )+ mock_context_manager_store.__aexit__ = AsyncMock(return_value=None)++ with patch(+ 'server.auth.token_manager.a_session_maker',+ return_value=mock_context_manager_store,+ ):+ await token_manager.store_org_token(installation_id, original_token)++ # Verify we captured the encrypted token+ assert stored_encrypted_token is not None++ # Load - using the captured encrypted token+ mock_installation_load = MagicMock()+ mock_installation_load.encrypted_token = stored_encrypted_token++ mock_session_load = AsyncMock()+ mock_result_load = MagicMock()+ mock_result_load.scalars.return_value.first.return_value = (+ mock_installation_load+ )+ mock_session_load.execute = AsyncMock(return_value=mock_result_load)++ mock_context_manager_load = AsyncMock()+ mock_context_manager_load.__aenter__ = AsyncMock(return_value=mock_session_load)+ mock_context_manager_load.__aexit__ = AsyncMock(return_value=None)++ with patch(+ 'server.auth.token_manager.a_session_maker',+ return_value=mock_context_manager_load,+ ):+ loaded_token = await token_manager.load_org_token(installation_id)++ assert loaded_token == original_token