Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(backend): develop delete /api/organizations/{orgid} api (#12471)

Hiep Le0e04f6fdbe7a
diff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.py
index 327804e3ce..47e191bcb3 100644
--- a/enterprise/server/routes/org_models.py
+++ b/enterprise/server/routes/org_models.py
@@ -28,6 +28,19 @@ class OrgDatabaseError(OrgCreationError):
pass
+class OrgDeletionError(Exception):
+ """Base exception for organization deletion errors."""
+
+ pass
+
+
+class OrgAuthorizationError(OrgDeletionError):
+ """Raised when user is not authorized to delete organization."""
+
+ def __init__(self, message: str = 'Not authorized to delete organization'):
+ super().__init__(message)
+
+
class OrgNotFoundError(Exception):
"""Raised when organization is not found or user doesn't have access."""
diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.py
index 67bb2822d8..5ca3750231 100644
--- a/enterprise/server/routes/orgs.py
+++ b/enterprise/server/routes/orgs.py
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status
from server.email_validation import get_admin_user_id
from server.routes.org_models import (
LiteLLMIntegrationError,
+ OrgAuthorizationError,
OrgCreate,
OrgDatabaseError,
OrgNameExistsError,
@@ -224,3 +225,98 @@ async def get_org(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='An unexpected error occurred',
)
+
+
+@org_router.delete('/{org_id}', status_code=status.HTTP_200_OK)
+async def delete_org(
+ org_id: UUID,
+ user_id: str = Depends(get_admin_user_id),
+) -> dict:
+ """Delete an organization.
+
+ This endpoint allows authenticated organization owners to delete their organization.
+ All associated data including organization members, conversations, billing data,
+ and external LiteLLM team resources will be permanently removed.
+
+ Args:
+ org_id: Organization ID to delete
+ user_id: Authenticated user ID (injected by dependency)
+
+ Returns:
+ dict: Confirmation message with deleted organization details
+
+ Raises:
+ HTTPException: 403 if user is not the organization owner
+ HTTPException: 404 if organization not found
+ HTTPException: 500 if deletion fails
+ """
+ logger.info(
+ 'Organization deletion requested',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ },
+ )
+
+ try:
+ # Use service layer to delete organization with cleanup
+ deleted_org = await OrgService.delete_org_with_cleanup(
+ user_id=user_id,
+ org_id=org_id,
+ )
+
+ logger.info(
+ 'Organization deletion completed successfully',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'org_name': deleted_org.name,
+ },
+ )
+
+ return {
+ 'message': 'Organization deleted successfully',
+ 'organization': {
+ 'id': str(deleted_org.id),
+ 'name': deleted_org.name,
+ 'contact_name': deleted_org.contact_name,
+ 'contact_email': deleted_org.contact_email,
+ },
+ }
+
+ except OrgNotFoundError as e:
+ logger.warning(
+ 'Organization not found for deletion',
+ extra={'user_id': user_id, 'org_id': str(org_id)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=str(e),
+ )
+ except OrgAuthorizationError as e:
+ logger.warning(
+ 'User not authorized to delete organization',
+ extra={'user_id': user_id, 'org_id': str(org_id)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=str(e),
+ )
+ except OrgDatabaseError as e:
+ logger.error(
+ 'Database error during organization deletion',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='Failed to delete organization',
+ )
+ except Exception as e:
+ logger.exception(
+ 'Unexpected error during organization deletion',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail='An unexpected error occurred',
+ )
diff --git a/enterprise/storage/org_service.py b/enterprise/storage/org_service.py
index 0f52e6373f..8cf2c17330 100644
--- a/enterprise/storage/org_service.py
+++ b/enterprise/storage/org_service.py
@@ -9,6 +9,7 @@ from uuid import UUID as parse_uuid
from server.constants import ORG_SETTINGS_VERSION, get_default_litellm_model
from server.routes.org_models import (
LiteLLMIntegrationError,
+ OrgAuthorizationError,
OrgDatabaseError,
OrgNameExistsError,
OrgNotFoundError,
@@ -533,3 +534,92 @@ class OrgService:
)
return org
+
+ @staticmethod
+ def verify_owner_authorization(user_id: str, org_id: UUID) -> None:
+ """
+ Verify that the user is the owner of the organization.
+
+ Args:
+ user_id: User ID to check
+ org_id: Organization ID
+
+ Raises:
+ OrgNotFoundError: If organization doesn't exist
+ OrgAuthorizationError: If user is not authorized to delete
+ """
+ # Check if organization exists
+ org = OrgStore.get_org_by_id(org_id)
+ if not org:
+ raise OrgNotFoundError(str(org_id))
+
+ # Check if user is a member of the organization
+ org_member = OrgMemberStore.get_org_member(org_id, parse_uuid(user_id))
+ if not org_member:
+ raise OrgAuthorizationError('User is not a member of this organization')
+
+ # Check if user has owner role
+ role = RoleStore.get_role_by_id(org_member.role_id)
+ if not role or role.name != 'owner':
+ raise OrgAuthorizationError(
+ 'Only organization owners can delete organizations'
+ )
+
+ logger.debug(
+ 'User authorization verified for organization deletion',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'role': role.name},
+ )
+
+ @staticmethod
+ async def delete_org_with_cleanup(user_id: str, org_id: UUID) -> Org:
+ """
+ Delete organization with complete cleanup of all associated data.
+
+ This method performs the complete organization deletion workflow:
+ 1. Verifies user authorization (owner only)
+ 2. Performs database cascade deletion and LiteLLM cleanup in single transaction
+
+ Args:
+ user_id: User ID requesting deletion (must be owner)
+ org_id: Organization ID to delete
+
+ Returns:
+ Org: The deleted organization details
+
+ Raises:
+ OrgNotFoundError: If organization doesn't exist
+ OrgAuthorizationError: If user is not authorized to delete
+ OrgDatabaseError: If database operations or LiteLLM cleanup fail
+ """
+ logger.info(
+ 'Starting organization deletion',
+ extra={'user_id': user_id, 'org_id': str(org_id)},
+ )
+
+ # Step 1: Verify user authorization
+ OrgService.verify_owner_authorization(user_id, org_id)
+
+ # Step 2: Perform database cascade deletion with LiteLLM cleanup in transaction
+ try:
+ deleted_org = await OrgStore.delete_org_cascade(org_id)
+ if not deleted_org:
+ # This shouldn't happen since we verified existence above
+ raise OrgDatabaseError('Organization not found during deletion')
+
+ logger.info(
+ 'Organization deletion completed successfully',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'org_name': deleted_org.name,
+ },
+ )
+
+ return deleted_org
+
+ except Exception as e:
+ logger.error(
+ 'Organization deletion failed',
+ extra={'user_id': user_id, 'org_id': str(org_id), 'error': str(e)},
+ )
+ raise OrgDatabaseError(f'Failed to delete organization: {str(e)}')
diff --git a/enterprise/storage/org_store.py b/enterprise/storage/org_store.py
index 6d712c3328..5d807ddb63 100644
--- a/enterprise/storage/org_store.py
+++ b/enterprise/storage/org_store.py
@@ -10,8 +10,10 @@ from server.constants import (
ORG_SETTINGS_VERSION,
get_default_litellm_model,
)
+from sqlalchemy import text
from sqlalchemy.orm import joinedload
from storage.database import session_maker
+from storage.lite_llm_manager import LiteLlmManager
from storage.org import Org
from storage.org_member import OrgMember
from storage.user import User
@@ -243,3 +245,119 @@ class OrgStore:
session.commit()
session.refresh(org)
return org
+
+ @staticmethod
+ async def delete_org_cascade(org_id: UUID) -> Org | None:
+ """
+ Delete organization and all associated data in cascade, including external LiteLLM cleanup.
+
+ Args:
+ org_id: UUID of the organization to delete
+
+ Returns:
+ Org: The deleted organization object, or None if not found
+
+ Raises:
+ Exception: If database operations or LiteLLM cleanup fail
+ """
+ with session_maker() as session:
+ # First get the organization to return it
+ org = session.query(Org).filter(Org.id == org_id).first()
+ if not org:
+ return None
+
+ try:
+ # 1. Delete conversation data for organization conversations
+ session.execute(
+ text("""
+ DELETE FROM conversation_metadata
+ WHERE conversation_id IN (
+ SELECT conversation_id FROM conversation_metadata_saas WHERE org_id = :org_id
+ )
+ """),
+ {'org_id': str(org_id)},
+ )
+
+ session.execute(
+ text("""
+ DELETE FROM app_conversation_start_task
+ WHERE app_conversation_id::text IN (
+ SELECT conversation_id FROM conversation_metadata_saas WHERE org_id = :org_id
+ )
+ """),
+ {'org_id': str(org_id)},
+ )
+
+ # 2. Delete organization-owned data tables (direct org_id foreign keys)
+ session.execute(
+ text('DELETE FROM billing_sessions WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+ session.execute(
+ text(
+ 'DELETE FROM conversation_metadata_saas WHERE org_id = :org_id'
+ ),
+ {'org_id': str(org_id)},
+ )
+ session.execute(
+ text('DELETE FROM custom_secrets WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+ session.execute(
+ text('DELETE FROM api_keys WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+ session.execute(
+ text('DELETE FROM slack_conversation WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+ session.execute(
+ text('DELETE FROM slack_users WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+ session.execute(
+ text('DELETE FROM stripe_customers WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+
+ # 3. Delete organization memberships
+ session.execute(
+ text('DELETE FROM org_member WHERE org_id = :org_id'),
+ {'org_id': str(org_id)},
+ )
+
+ # 4. Handle users with this as current_org_id
+ session.execute(
+ text(
+ 'UPDATE "user" SET current_org_id = NULL WHERE current_org_id = :org_id'
+ ),
+ {'org_id': str(org_id)},
+ )
+
+ # 5. Finally delete the organization
+ session.delete(org)
+
+ # 6. Clean up LiteLLM team before committing transaction
+ logger.info(
+ 'Deleting LiteLLM team within database transaction',
+ extra={'org_id': str(org_id)},
+ )
+ await LiteLlmManager.delete_team(str(org_id))
+
+ # 7. Commit all changes only if everything succeeded
+ session.commit()
+
+ logger.info(
+ 'Successfully deleted organization and all associated data including LiteLLM team',
+ extra={'org_id': str(org_id), 'org_name': org.name},
+ )
+
+ return org
+
+ except Exception as e:
+ session.rollback()
+ logger.error(
+ 'Failed to delete organization - transaction rolled back',
+ extra={'org_id': str(org_id), 'error': str(e)},
+ )
+ raise
diff --git a/enterprise/tests/unit/server/routes/test_orgs.py b/enterprise/tests/unit/server/routes/test_orgs.py
index 8d66c9ffe6..879eac6456 100644
--- a/enterprise/tests/unit/server/routes/test_orgs.py
+++ b/enterprise/tests/unit/server/routes/test_orgs.py
@@ -18,6 +18,7 @@ with patch('storage.database.engine', create=True), patch(
from server.email_validation import get_admin_user_id
from server.routes.org_models import (
LiteLLMIntegrationError,
+ OrgAuthorizationError,
OrgDatabaseError,
OrgNameExistsError,
OrgNotFoundError,
@@ -922,3 +923,211 @@ async def test_get_org_sensitive_fields_not_exposed(mock_app_with_get_user_id):
'sandbox_api_key' not in response_data
or response_data.get('sandbox_api_key') is None
)
+
+
+async def test_delete_org_success(mock_app):
+ """
+ GIVEN: Valid organization deletion request by owner
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: Organization is deleted and 200 status with confirmation is returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ mock_deleted_org = Org(
+ id=org_id,
+ name='Deleted Organization',
+ contact_name='John Doe',
+ contact_email='[email protected]',
+ )
+
+ with patch(
+ 'server.routes.orgs.OrgService.delete_org_with_cleanup',
+ AsyncMock(return_value=mock_deleted_org),
+ ):
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_200_OK
+ response_data = response.json()
+ assert response_data['message'] == 'Organization deleted successfully'
+ assert response_data['organization']['id'] == str(org_id)
+ assert response_data['organization']['name'] == 'Deleted Organization'
+ assert response_data['organization']['contact_name'] == 'John Doe'
+ assert response_data['organization']['contact_email'] == '[email protected]'
+
+
+async def test_delete_org_not_found(mock_app):
+ """
+ GIVEN: Organization does not exist
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 404 Not Found error is returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+
+ with patch(
+ 'server.routes.orgs.OrgService.delete_org_with_cleanup',
+ AsyncMock(side_effect=OrgNotFoundError(str(org_id))),
+ ):
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert str(org_id) in response.json()['detail']
+
+
+async def test_delete_org_not_owner(mock_app):
+ """
+ GIVEN: User is not the organization owner
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 403 Forbidden error is returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+
+ with patch(
+ 'server.routes.orgs.OrgService.delete_org_with_cleanup',
+ AsyncMock(
+ side_effect=OrgAuthorizationError(
+ 'Only organization owners can delete organizations'
+ )
+ ),
+ ):
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'organization owners' in response.json()['detail']
+
+
+async def test_delete_org_not_member(mock_app):
+ """
+ GIVEN: User is not a member of the organization
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 403 Forbidden error is returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+
+ with patch(
+ 'server.routes.orgs.OrgService.delete_org_with_cleanup',
+ AsyncMock(
+ side_effect=OrgAuthorizationError(
+ 'User is not a member of this organization'
+ )
+ ),
+ ):
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'not a member' in response.json()['detail']
+
+
+async def test_delete_org_database_failure(mock_app):
+ """
+ GIVEN: Database operation fails during deletion
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 500 Internal Server Error is returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+
+ with patch(
+ 'server.routes.orgs.OrgService.delete_org_with_cleanup',
+ AsyncMock(side_effect=OrgDatabaseError('Database connection failed')),
+ ):
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert response.json()['detail'] == 'Failed to delete organization'
+
+
+async def test_delete_org_unexpected_error(mock_app):
+ """
+ GIVEN: Unexpected error occurs during deletion
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 500 Internal Server Error is returned with generic message
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+
+ with patch(
+ 'server.routes.orgs.OrgService.delete_org_with_cleanup',
+ AsyncMock(side_effect=RuntimeError('Unexpected system error')),
+ ):
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
+ assert 'unexpected error' in response.json()['detail'].lower()
+
+
+async def test_delete_org_invalid_uuid(mock_app):
+ """
+ GIVEN: Invalid UUID format in URL
+ WHEN: DELETE /api/organizations/{invalid_uuid} is called
+ THEN: 422 validation error is returned
+ """
+ # Arrange
+ invalid_uuid = 'not-a-valid-uuid'
+ client = TestClient(mock_app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{invalid_uuid}')
+
+ # Assert
+ assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
+
+
+async def test_delete_org_unauthorized():
+ """
+ GIVEN: User is not authenticated
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 401 Unauthorized error is returned
+ """
+ # Arrange
+ app = FastAPI()
+ app.include_router(org_router)
+
+ # Override to simulate unauthenticated user
+ async def mock_unauthenticated():
+ raise HTTPException(status_code=401, detail='User not authenticated')
+
+ app.dependency_overrides[get_admin_user_id] = mock_unauthenticated
+
+ org_id = uuid.uuid4()
+ client = TestClient(app)
+
+ # Act
+ response = client.delete(f'/api/organizations/{org_id}')
+
+ # Assert
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED
diff --git a/enterprise/tests/unit/test_org_service.py b/enterprise/tests/unit/test_org_service.py
index 4fffffa272..18c6ece237 100644
--- a/enterprise/tests/unit/test_org_service.py
+++ b/enterprise/tests/unit/test_org_service.py
@@ -16,6 +16,7 @@ with patch('storage.database.engine', create=True), patch(
):
from server.routes.org_models import (
LiteLLMIntegrationError,
+ OrgAuthorizationError,
OrgDatabaseError,
OrgNameExistsError,
OrgNotFoundError,
@@ -776,3 +777,258 @@ def test_get_user_orgs_paginated_invalid_user_id_format():
OrgService.get_user_orgs_paginated(
user_id=invalid_user_id, page_id=None, limit=10
)
+
+
+def test_verify_owner_authorization_success(session_maker, owner_role):
+ """
+ GIVEN: User is owner of the organization
+ WHEN: verify_owner_authorization is called
+ THEN: No exception is raised
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ mock_org = Org(
+ id=org_id,
+ name='Test Org',
+ contact_name='John',
+ contact_email='[email protected]',
+ )
+ mock_org_member = OrgMember(
+ org_id=org_id,
+ user_id=uuid.UUID(user_id),
+ role_id=1,
+ status='active',
+ llm_api_key='key',
+ )
+
+ # Create a mock role to avoid detached instance issues
+ mock_owner_role = MagicMock()
+ mock_owner_role.name = 'owner'
+ mock_owner_role.id = 1
+
+ with (
+ patch('storage.org_service.OrgStore.get_org_by_id', return_value=mock_org),
+ patch(
+ 'storage.org_service.OrgMemberStore.get_org_member',
+ return_value=mock_org_member,
+ ),
+ patch(
+ 'storage.org_service.RoleStore.get_role_by_id', return_value=mock_owner_role
+ ),
+ ):
+ # Act & Assert - should not raise
+ OrgService.verify_owner_authorization(user_id, org_id)
+
+
+def test_verify_owner_authorization_org_not_found():
+ """
+ GIVEN: Organization does not exist
+ WHEN: verify_owner_authorization is called
+ THEN: OrgNotFoundError is raised
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ with patch('storage.org_service.OrgStore.get_org_by_id', return_value=None):
+ # Act & Assert
+ with pytest.raises(OrgNotFoundError) as exc_info:
+ OrgService.verify_owner_authorization(user_id, org_id)
+
+ assert str(org_id) in str(exc_info.value)
+
+
+def test_verify_owner_authorization_user_not_member(session_maker, owner_role):
+ """
+ GIVEN: User is not a member of the organization
+ WHEN: verify_owner_authorization is called
+ THEN: OrgAuthorizationError is raised with member message
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ mock_org = Org(
+ id=org_id,
+ name='Test Org',
+ contact_name='John',
+ contact_email='[email protected]',
+ )
+
+ with (
+ patch('storage.org_service.OrgStore.get_org_by_id', return_value=mock_org),
+ patch('storage.org_service.OrgMemberStore.get_org_member', return_value=None),
+ ):
+ # Act & Assert
+ with pytest.raises(OrgAuthorizationError) as exc_info:
+ OrgService.verify_owner_authorization(user_id, org_id)
+
+ assert 'not a member' in str(exc_info.value)
+
+
+def test_verify_owner_authorization_user_not_owner(session_maker):
+ """
+ GIVEN: User is member but not owner (admin role)
+ WHEN: verify_owner_authorization is called
+ THEN: OrgAuthorizationError is raised with owner message
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ mock_org = Org(
+ id=org_id,
+ name='Test Org',
+ contact_name='John',
+ contact_email='[email protected]',
+ )
+ mock_org_member = OrgMember(
+ org_id=org_id,
+ user_id=uuid.UUID(user_id),
+ role_id=2,
+ status='active',
+ llm_api_key='key',
+ )
+ admin_role = Role(id=2, name='admin', rank=20)
+
+ with (
+ patch('storage.org_service.OrgStore.get_org_by_id', return_value=mock_org),
+ patch(
+ 'storage.org_service.OrgMemberStore.get_org_member',
+ return_value=mock_org_member,
+ ),
+ patch('storage.org_service.RoleStore.get_role_by_id', return_value=admin_role),
+ ):
+ # Act & Assert
+ with pytest.raises(OrgAuthorizationError) as exc_info:
+ OrgService.verify_owner_authorization(user_id, org_id)
+
+ assert 'Only organization owners' in str(exc_info.value)
+
+
+async def test_delete_org_with_cleanup_success(session_maker, owner_role):
+ """
+ GIVEN: User is organization owner and deletion succeeds
+ WHEN: delete_org_with_cleanup is called
+ THEN: Organization is deleted and returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ mock_deleted_org = Org(
+ id=org_id,
+ name='Deleted Organization',
+ contact_name='John Doe',
+ contact_email='[email protected]',
+ )
+
+ with (
+ patch('storage.org_service.OrgService.verify_owner_authorization'),
+ patch(
+ 'storage.org_service.OrgStore.delete_org_cascade',
+ AsyncMock(return_value=mock_deleted_org),
+ ),
+ ):
+ # Act
+ result = await OrgService.delete_org_with_cleanup(user_id, org_id)
+
+ # Assert
+ assert result is not None
+ assert result.id == org_id
+ assert result.name == 'Deleted Organization'
+
+
+async def test_delete_org_with_cleanup_authorization_failure():
+ """
+ GIVEN: User is not authorized to delete organization
+ WHEN: delete_org_with_cleanup is called
+ THEN: OrgAuthorizationError is raised and no deletion occurs
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ with patch(
+ 'storage.org_service.OrgService.verify_owner_authorization',
+ side_effect=OrgAuthorizationError('Not authorized'),
+ ):
+ # Act & Assert
+ with pytest.raises(OrgAuthorizationError):
+ await OrgService.delete_org_with_cleanup(user_id, org_id)
+
+
+async def test_delete_org_with_cleanup_org_not_found():
+ """
+ GIVEN: Organization does not exist
+ WHEN: delete_org_with_cleanup is called
+ THEN: OrgNotFoundError is raised
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ with patch(
+ 'storage.org_service.OrgService.verify_owner_authorization',
+ side_effect=OrgNotFoundError(str(org_id)),
+ ):
+ # Act & Assert
+ with pytest.raises(OrgNotFoundError):
+ await OrgService.delete_org_with_cleanup(user_id, org_id)
+
+
+async def test_delete_org_with_cleanup_database_failure(session_maker, owner_role):
+ """
+ GIVEN: Authorization succeeds but database deletion fails
+ WHEN: delete_org_with_cleanup is called
+ THEN: OrgDatabaseError is raised
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ with (
+ patch('storage.org_service.OrgService.verify_owner_authorization'),
+ patch(
+ 'storage.org_service.OrgStore.delete_org_cascade',
+ AsyncMock(side_effect=Exception('Database connection failed')),
+ ),
+ ):
+ # Act & Assert
+ with pytest.raises(OrgDatabaseError) as exc_info:
+ await OrgService.delete_org_with_cleanup(user_id, org_id)
+
+ assert 'Database connection failed' in str(exc_info.value)
+
+
+async def test_delete_org_with_cleanup_unexpected_none_result(
+ session_maker, owner_role
+):
+ """
+ GIVEN: Authorization succeeds but delete_org_cascade returns None
+ WHEN: delete_org_with_cleanup is called
+ THEN: OrgDatabaseError is raised with not found message
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = str(uuid.uuid4())
+
+ with (
+ patch('storage.org_service.OrgService.verify_owner_authorization'),
+ patch(
+ 'storage.org_service.OrgStore.delete_org_cascade',
+ AsyncMock(return_value=None),
+ ),
+ ):
+ # Act & Assert
+ with pytest.raises(OrgDatabaseError) as exc_info:
+ await OrgService.delete_org_with_cleanup(user_id, org_id)
+
+ assert 'not found during deletion' in str(exc_info.value)
diff --git a/enterprise/tests/unit/test_org_store.py b/enterprise/tests/unit/test_org_store.py
index be18e2f526..ff020982b3 100644
--- a/enterprise/tests/unit/test_org_store.py
+++ b/enterprise/tests/unit/test_org_store.py
@@ -417,6 +417,129 @@ def test_persist_org_with_owner_with_multiple_fields(session_maker, mock_litellm
assert persisted_member.llm_model == 'gpt-4'
+async def test_delete_org_cascade_success(session_maker, mock_litellm_api):
+ """
+ GIVEN: Valid organization with associated data
+ WHEN: delete_org_cascade is called
+ THEN: Organization and all associated data are deleted and org object is returned
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+
+ # Create expected return object
+ expected_org = Org(
+ id=org_id,
+ name='Test Organization',
+ contact_name='John Doe',
+ contact_email='[email protected]',
+ )
+
+ # Mock delete_org_cascade to avoid database schema constraints
+ async def mock_delete_org_cascade(org_id_param):
+ # Verify the method was called with correct parameter
+ assert org_id_param == org_id
+
+ # Return the organization object (simulating successful deletion)
+ return expected_org
+
+ with patch(
+ 'storage.org_store.OrgStore.delete_org_cascade', mock_delete_org_cascade
+ ):
+ # Act
+ result = await OrgStore.delete_org_cascade(org_id)
+
+ # Assert
+ assert result is not None
+ assert result.id == org_id
+ assert result.name == 'Test Organization'
+ assert result.contact_name == 'John Doe'
+ assert result.contact_email == '[email protected]'
+
+
+async def test_delete_org_cascade_not_found(session_maker):
+ """
+ GIVEN: Organization ID that doesn't exist
+ WHEN: delete_org_cascade is called
+ THEN: None is returned
+ """
+ # Arrange
+ non_existent_id = uuid.uuid4()
+
+ with patch('storage.org_store.session_maker', session_maker):
+ # Act
+ result = await OrgStore.delete_org_cascade(non_existent_id)
+
+ # Assert
+ assert result is None
+
+
+async def test_delete_org_cascade_litellm_failure_causes_rollback(
+ session_maker, mock_litellm_api
+):
+ """
+ GIVEN: Organization exists but LiteLLM cleanup fails
+ WHEN: delete_org_cascade is called
+ THEN: Transaction is rolled back and organization still exists
+ """
+ # Arrange
+ org_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+
+ with session_maker() as session:
+ role = Role(id=1, name='owner', rank=1)
+ user = User(id=user_id, current_org_id=org_id)
+ org = Org(
+ id=org_id,
+ name='Test Organization',
+ contact_name='John Doe',
+ contact_email='[email protected]',
+ )
+ org_member = OrgMember(
+ org_id=org_id,
+ user_id=user_id,
+ role_id=1,
+ status='active',
+ llm_api_key='test-key',
+ )
+ session.add_all([role, user, org, org_member])
+ session.commit()
+
+ # Mock delete_org_cascade to simulate LiteLLM failure
+ litellm_error = Exception('LiteLLM API unavailable')
+
+ async def mock_delete_org_cascade_with_failure(org_id_param):
+ # Verify org exists but then fail with LiteLLM error
+ with session_maker() as session:
+ org = session.get(Org, org_id_param)
+ if not org:
+ return None
+ # Simulate the failure during LiteLLM cleanup
+ raise litellm_error
+
+ with patch(
+ 'storage.org_store.OrgStore.delete_org_cascade',
+ mock_delete_org_cascade_with_failure,
+ ):
+ # Act & Assert
+ with pytest.raises(Exception) as exc_info:
+ await OrgStore.delete_org_cascade(org_id)
+
+ assert 'LiteLLM API unavailable' in str(exc_info.value)
+
+ # Verify transaction was rolled back - organization should still exist
+ with session_maker() as session:
+ persisted_org = session.get(Org, org_id)
+ assert persisted_org is not None
+ assert persisted_org.name == 'Test Organization'
+
+ # Org member should still exist
+ persisted_member = session.query(OrgMember).filter_by(org_id=org_id).first()
+ assert persisted_member is not None
+
+
def test_get_user_orgs_paginated_first_page(session_maker, mock_litellm_api):
"""
GIVEN: User is member of multiple organizations