Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: use API key's org_id when creating conversations via API key auth (#13568)

Hiep Le889754abfd21
diff --git a/enterprise/server/utils/saas_app_conversation_info_injector.py b/enterprise/server/utils/saas_app_conversation_info_injector.py
index 987f42ca10..a9432c76b3 100644
--- a/enterprise/server/utils/saas_app_conversation_info_injector.py
+++ b/enterprise/server/utils/saas_app_conversation_info_injector.py
@@ -354,6 +354,15 @@ class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
user = result.scalar_one_or_none()
assert user
+ # Determine org_id: prefer API key's org_id if authenticated via API key
+ org_id = user.current_org_id # Default fallback
+ if hasattr(self.user_context, 'user_auth'):
+ user_auth = self.user_context.user_auth
+ if hasattr(user_auth, 'get_api_key_org_id'):
+ api_key_org_id = user_auth.get_api_key_org_id()
+ if api_key_org_id is not None:
+ org_id = api_key_org_id
+
# Check if SAAS metadata already exists
saas_query = select(StoredConversationMetadataSaas).where(
StoredConversationMetadataSaas.conversation_id == str(info.id)
@@ -362,16 +371,15 @@ class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
existing_saas_metadata = result.scalar_one_or_none()
assert existing_saas_metadata is None or (
existing_saas_metadata.user_id == user_id_uuid
- and existing_saas_metadata.org_id == user.current_org_id
+ and existing_saas_metadata.org_id == org_id
)
if not existing_saas_metadata:
- # Create new SAAS metadata
- # Set org_id to user_id as specified in requirements
+ # Create new SAAS metadata with the determined org_id
saas_metadata = StoredConversationMetadataSaas(
conversation_id=str(info.id),
user_id=user_id_uuid,
- org_id=user.current_org_id,
+ org_id=org_id,
)
self.db_session.add(saas_metadata)
diff --git a/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py b/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py
index 0e0d1e9d35..144e4150fa 100644
--- a/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py
+++ b/enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py
@@ -990,3 +990,317 @@ class TestSandboxIdFilterSaas:
sandbox_id__eq=shared_sandbox_id
)
assert count == 1
+
+
+class TestApiKeyOrgIdHandling:
+ """Test suite for API key organization ID handling in save_app_conversation_info.
+
+ These tests verify that when a conversation is created using API key authentication,
+ the conversation is associated with the API key's bound organization, not the user's
+ currently selected organization.
+ """
+
+ @pytest.mark.asyncio
+ async def test_api_key_org_id_used_when_available(
+ self,
+ async_session_with_users: AsyncSession,
+ ):
+ """Test that API key's org_id is used when saving conversation via API key auth.
+
+ This tests the main bug fix: when a user creates an API key in Personal Workspace,
+ then switches to OpenHands org in browser, and uses the API key to create a
+ conversation, the conversation should be saved in Personal Workspace (API key's org),
+ not OpenHands (user's current org).
+ """
+ from dataclasses import dataclass
+
+ from storage.stored_conversation_metadata_saas import (
+ StoredConversationMetadataSaas,
+ )
+
+ # Create a mock UserAuth with API key org_id
+ @dataclass
+ class MockUserAuth:
+ user_id: str
+ api_key_org_id: UUID | None = None
+
+ async def get_user_id(self) -> str:
+ return self.user_id
+
+ def get_api_key_org_id(self) -> UUID | None:
+ return self.api_key_org_id
+
+ # Create a mock UserContext that wraps the MockUserAuth
+ @dataclass
+ class MockAuthUserContext:
+ user_auth: MockUserAuth
+
+ async def get_user_id(self) -> str | None:
+ return await self.user_auth.get_user_id()
+
+ # Simulate: User1's current org is ORG2, but API key is bound to ORG1
+ # First, update user1's current_org_id to ORG2
+ result = await async_session_with_users.execute(
+ select(User).where(User.id == USER1_ID)
+ )
+ user_to_update = result.scalars().first()
+ user_to_update.current_org_id = ORG2_ID # User is viewing ORG2
+ await async_session_with_users.commit()
+ async_session_with_users.expire_all()
+
+ # Create service with mock auth context where API key is bound to ORG1
+ mock_user_auth = MockUserAuth(
+ user_id=str(USER1_ID),
+ api_key_org_id=ORG1_ID, # API key created in ORG1
+ )
+ mock_context = MockAuthUserContext(user_auth=mock_user_auth)
+
+ service = SaasSQLAppConversationInfoService(
+ db_session=async_session_with_users,
+ user_context=mock_context,
+ )
+
+ # Create and save a conversation
+ conv_id = uuid4()
+ conv_info = AppConversationInfo(
+ id=conv_id,
+ created_by_user_id=str(USER1_ID),
+ sandbox_id='sandbox_api_key_test',
+ title='API Key Created Conversation',
+ )
+ await service.save_app_conversation_info(conv_info)
+
+ # Verify: SAAS metadata should have ORG1 (API key's org), not ORG2 (user's current org)
+ saas_query = select(StoredConversationMetadataSaas).where(
+ StoredConversationMetadataSaas.conversation_id == str(conv_id)
+ )
+ result = await async_session_with_users.execute(saas_query)
+ saas_metadata = result.scalar_one_or_none()
+
+ assert saas_metadata is not None, 'SAAS metadata should be created'
+ assert saas_metadata.user_id == USER1_ID
+ assert (
+ saas_metadata.org_id == ORG1_ID
+ ), 'Conversation should be in API key org (ORG1), not user current org (ORG2)'
+
+ @pytest.mark.asyncio
+ async def test_legacy_api_key_without_org_uses_user_current_org(
+ self,
+ async_session_with_users: AsyncSession,
+ ):
+ """Test that legacy API keys (without org_id) fall back to user's current org.
+
+ Legacy API keys created before the org_id feature was added will have
+ api_key_org_id = None. In this case, we should fall back to the user's
+ current_org_id.
+ """
+ from dataclasses import dataclass
+
+ from storage.stored_conversation_metadata_saas import (
+ StoredConversationMetadataSaas,
+ )
+
+ # Create a mock UserAuth with API key but NO org_id (legacy key)
+ @dataclass
+ class MockUserAuth:
+ user_id: str
+ api_key_org_id: UUID | None = None
+
+ async def get_user_id(self) -> str:
+ return self.user_id
+
+ def get_api_key_org_id(self) -> UUID | None:
+ return self.api_key_org_id
+
+ @dataclass
+ class MockAuthUserContext:
+ user_auth: MockUserAuth
+
+ async def get_user_id(self) -> str | None:
+ return await self.user_auth.get_user_id()
+
+ # Create service with mock auth context where API key has NO org_id
+ mock_user_auth = MockUserAuth(
+ user_id=str(USER1_ID),
+ api_key_org_id=None, # Legacy key without org binding
+ )
+ mock_context = MockAuthUserContext(user_auth=mock_user_auth)
+
+ service = SaasSQLAppConversationInfoService(
+ db_session=async_session_with_users,
+ user_context=mock_context,
+ )
+
+ # Create and save a conversation
+ conv_id = uuid4()
+ conv_info = AppConversationInfo(
+ id=conv_id,
+ created_by_user_id=str(USER1_ID),
+ sandbox_id='sandbox_legacy_key_test',
+ title='Legacy API Key Conversation',
+ )
+ await service.save_app_conversation_info(conv_info)
+
+ # Verify: SAAS metadata should use user's current org (ORG1) as fallback
+ saas_query = select(StoredConversationMetadataSaas).where(
+ StoredConversationMetadataSaas.conversation_id == str(conv_id)
+ )
+ result = await async_session_with_users.execute(saas_query)
+ saas_metadata = result.scalar_one_or_none()
+
+ assert saas_metadata is not None, 'SAAS metadata should be created'
+ assert saas_metadata.user_id == USER1_ID
+ assert (
+ saas_metadata.org_id == ORG1_ID
+ ), 'Legacy key should fall back to user current org (ORG1)'
+
+ @pytest.mark.asyncio
+ async def test_cookie_auth_without_api_key_uses_user_current_org(
+ self,
+ async_session_with_users: AsyncSession,
+ ):
+ """Test that cookie auth (no API key) uses user's current org.
+
+ When authenticated via browser cookie (no API key), there's no
+ get_api_key_org_id method, so we use user's current_org_id.
+ This is already tested by other tests using SpecifyUserContext,
+ but we explicitly test the case where user_context doesn't have user_auth.
+ """
+ from storage.stored_conversation_metadata_saas import (
+ StoredConversationMetadataSaas,
+ )
+
+ # Use SpecifyUserContext which doesn't have user_auth attribute
+ service = SaasSQLAppConversationInfoService(
+ db_session=async_session_with_users,
+ user_context=SpecifyUserContext(user_id=str(USER1_ID)),
+ )
+
+ # Create and save a conversation
+ conv_id = uuid4()
+ conv_info = AppConversationInfo(
+ id=conv_id,
+ created_by_user_id=str(USER1_ID),
+ sandbox_id='sandbox_cookie_auth_test',
+ title='Cookie Auth Conversation',
+ )
+ await service.save_app_conversation_info(conv_info)
+
+ # Verify: SAAS metadata should use user's current org (ORG1)
+ saas_query = select(StoredConversationMetadataSaas).where(
+ StoredConversationMetadataSaas.conversation_id == str(conv_id)
+ )
+ result = await async_session_with_users.execute(saas_query)
+ saas_metadata = result.scalar_one_or_none()
+
+ assert saas_metadata is not None, 'SAAS metadata should be created'
+ assert saas_metadata.user_id == USER1_ID
+ assert (
+ saas_metadata.org_id == ORG1_ID
+ ), 'Cookie auth should use user current org (ORG1)'
+
+ @pytest.mark.asyncio
+ async def test_api_key_org_isolation_cross_org_visibility(
+ self,
+ async_session_with_users: AsyncSession,
+ ):
+ """Test end-to-end: conversation created via API key is visible in correct org.
+
+ Simulates the full bug scenario:
+ 1. Create conversation via API key (bound to ORG1)
+ 2. User switches to ORG2
+ 3. User should NOT see the conversation in ORG2
+ 4. User switches back to ORG1
+ 5. User should see the conversation in ORG1
+ """
+ from dataclasses import dataclass
+
+ @dataclass
+ class MockUserAuth:
+ user_id: str
+ api_key_org_id: UUID | None = None
+
+ async def get_user_id(self) -> str:
+ return self.user_id
+
+ def get_api_key_org_id(self) -> UUID | None:
+ return self.api_key_org_id
+
+ @dataclass
+ class MockAuthUserContext:
+ user_auth: MockUserAuth
+
+ async def get_user_id(self) -> str | None:
+ return await self.user_auth.get_user_id()
+
+ # Step 1: Create conversation via API key bound to ORG1
+ mock_user_auth = MockUserAuth(
+ user_id=str(USER1_ID),
+ api_key_org_id=ORG1_ID,
+ )
+ mock_context = MockAuthUserContext(user_auth=mock_user_auth)
+
+ api_key_service = SaasSQLAppConversationInfoService(
+ db_session=async_session_with_users,
+ user_context=mock_context,
+ )
+
+ conv_id = uuid4()
+ conv_info = AppConversationInfo(
+ id=conv_id,
+ created_by_user_id=str(USER1_ID),
+ sandbox_id='sandbox_e2e_api_key',
+ title='E2E API Key Conversation',
+ )
+ await api_key_service.save_app_conversation_info(conv_info)
+
+ # Step 2: Switch user to ORG2 in browser session
+ result = await async_session_with_users.execute(
+ select(User).where(User.id == USER1_ID)
+ )
+ user_to_update = result.scalars().first()
+ user_to_update.current_org_id = ORG2_ID
+ await async_session_with_users.commit()
+ async_session_with_users.expire_all()
+
+ # Step 3: User in ORG2 should NOT see the conversation
+ user_service_org2 = SaasSQLAppConversationInfoService(
+ db_session=async_session_with_users,
+ user_context=SpecifyUserContext(user_id=str(USER1_ID)),
+ )
+ page_org2 = await user_service_org2.search_app_conversation_info()
+ assert (
+ len(page_org2.items) == 0
+ ), 'User in ORG2 should not see conversation created via API key in ORG1'
+
+ # Also verify get_app_conversation_info returns None
+ conv_from_org2 = await user_service_org2.get_app_conversation_info(conv_id)
+ assert (
+ conv_from_org2 is None
+ ), 'User in ORG2 should not access conversation from ORG1'
+
+ # Step 4: Switch user back to ORG1
+ result = await async_session_with_users.execute(
+ select(User).where(User.id == USER1_ID)
+ )
+ user_to_update = result.scalars().first()
+ user_to_update.current_org_id = ORG1_ID
+ await async_session_with_users.commit()
+ async_session_with_users.expire_all()
+
+ # Step 5: User in ORG1 should see the conversation
+ user_service_org1 = SaasSQLAppConversationInfoService(
+ db_session=async_session_with_users,
+ user_context=SpecifyUserContext(user_id=str(USER1_ID)),
+ )
+ page_org1 = await user_service_org1.search_app_conversation_info()
+ assert (
+ len(page_org1.items) == 1
+ ), 'User in ORG1 should see conversation created via API key in ORG1'
+ assert page_org1.items[0].id == conv_id
+ assert page_org1.items[0].title == 'E2E API Key Conversation'
+
+ # Also verify get_app_conversation_info works
+ conv_from_org1 = await user_service_org1.get_app_conversation_info(conv_id)
+ assert conv_from_org1 is not None
+ assert conv_from_org1.id == conv_id