Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Cascade-delete sole-org requester on DELETE /api/organizations (#14617)

John-Mason P. Shackelford82744a0bc3e5
diff --git a/enterprise/server/routes/org_models.py b/enterprise/server/routes/org_models.py
index 5a427e1316..4d264579ec 100644
--- a/enterprise/server/routes/org_models.py
+++ b/enterprise/server/routes/org_models.py
@@ -81,12 +81,22 @@ class OrgAuthorizationError(OrgDeletionError):
class OrphanedUserError(OrgDeletionError):
- """Raised when deleting an org would leave users without any organization."""
+ """Raised when deleting an org would leave OTHER users (not the requester)
+ without any organization.
+
+ A user is "orphaned" when their only ``org_member`` row is for the org being
+ deleted. The deletion path tolerates *the requester themselves* being orphaned
+ (the personal-org self-service case β€” the requester is consenting to their
+ own deletion by calling ``DELETE``), but refuses to silently destroy the
+ accounts of other members. In that case it raises this error so the org
+ owner can transfer or remove those members first.
+ """
def __init__(self, user_ids: list[str]):
self.user_ids = user_ids
super().__init__(
- f'Cannot delete organization: {len(user_ids)} user(s) would have no remaining organization'
+ f'Cannot delete organization: {len(user_ids)} other user(s) '
+ 'would have no remaining organization'
)
diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.py
index 2e2e614559..a83abb4601 100644
--- a/enterprise/server/routes/orgs.py
+++ b/enterprise/server/routes/orgs.py
@@ -664,7 +664,7 @@ async def delete_org(
)
except OrphanedUserError as e:
logger.warning(
- 'Cannot delete organization: users would be orphaned',
+ 'Cannot delete organization: other members would be orphaned',
extra={
'user_id': user_id,
'org_id': str(org_id),
diff --git a/enterprise/storage/org_service.py b/enterprise/storage/org_service.py
index 720b6276b8..d47e91902d 100644
--- a/enterprise/storage/org_service.py
+++ b/enterprise/storage/org_service.py
@@ -19,6 +19,7 @@ from server.routes.org_models import (
OrgNameExistsError,
OrgNotFoundError,
OrgUpdate,
+ OrphanedUserError,
)
from storage.lite_llm_manager import LiteLlmManager
from storage.org import Org
@@ -799,7 +800,9 @@ class OrgService:
# Step 2: Perform database cascade deletion with LiteLLM cleanup in transaction
try:
- deleted_org = await OrgStore.delete_org_cascade(org_id)
+ deleted_org = await OrgStore.delete_org_cascade(
+ org_id, requester_user_id=user_id
+ )
if not deleted_org:
# This shouldn't happen since we verified existence above
raise OrgDatabaseError('Organization not found during deletion')
@@ -815,6 +818,11 @@ class OrgService:
return deleted_org
+ except OrphanedUserError:
+ # Propagate as-is so the route can return a 400 with the affected
+ # user list. Wrapping into OrgDatabaseError below would mask the
+ # specific failure mode and force a 500.
+ raise
except Exception as e:
logger.error(
'Organization deletion failed',
diff --git a/enterprise/storage/org_store.py b/enterprise/storage/org_store.py
index 56a6b6797c..6adc7819aa 100644
--- a/enterprise/storage/org_store.py
+++ b/enterprise/storage/org_store.py
@@ -16,11 +16,13 @@ from server.routes.org_models import (
OrgUpdate,
OrphanedUserError,
)
-from sqlalchemy import select, text
+from sqlalchemy import delete, select, text
from sqlalchemy.orm import joinedload
from storage.database import a_session_maker
from storage.lite_llm_manager import LiteLlmManager, get_openhands_cloud_key_alias
from storage.org import Org
+from storage.org_git_claim import OrgGitClaim
+from storage.org_invitation import OrgInvitation
from storage.org_member import OrgMember
from storage.user import User
from storage.user_settings import UserSettings
@@ -422,16 +424,44 @@ class OrgStore:
return org
@staticmethod
- async def delete_org_cascade(org_id: UUID) -> Org | None:
+ async def delete_org_cascade(
+ org_id: UUID, requester_user_id: str | None = None
+ ) -> Org | None:
"""Delete organization and all associated data in cascade, including external LiteLLM cleanup.
+ Users that belong to the org being deleted are handled in three ways:
+
+ * Users with a membership in at least one other org have their
+ ``current_org_id`` reassigned to one of those alternative orgs.
+ * If the *requester themselves* is the only orphaned user (sole member
+ of the org being deleted β€” the personal-org self-service case), the
+ requester's user row is cascade-deleted in the same transaction. The
+ Keycloak account is left untouched, so on the user's next login
+ ``UserStore.create_user`` re-onboards them as a brand-new user. The
+ new ``User.id`` and ``Org.id`` are derived from the Keycloak ``sub``
+ claim, which is stable across logins, so the re-created personal-org
+ identity matches the deleted one (``User.id == Org.id ==
+ UUID(keycloak.sub)``) and downstream automations that key on
+ ``keycloak_user_id`` continue to resolve correctly.
+ * If any orphan is **not** the requester (i.e., a multi-user org where
+ another member has no other org), ``OrphanedUserError`` is raised
+ and the whole transaction is rolled back. The org owner must
+ transfer or remove those members before deletion can proceed β€”
+ we refuse to silently destroy accounts that did not consent.
+
Args:
org_id: UUID of the organization to delete
+ requester_user_id: Keycloak ``sub`` of the user initiating the
+ deletion. Required for the sole-orphan personal-org case;
+ when ``None`` (e.g., internal callers), any orphan triggers
+ ``OrphanedUserError``.
Returns:
Org: The deleted organization object, or None if not found
Raises:
+ OrphanedUserError: If any non-requester member of the org would be
+ left without any organization by the deletion.
Exception: If database operations or LiteLLM cleanup fail
"""
async with a_session_maker() as session:
@@ -442,6 +472,60 @@ class OrgStore:
return None
try:
+ # Preflight orphan check β€” fail fast before any writes.
+ #
+ # The orphan SELECT only reads ``user`` and ``org_member``,
+ # neither of which is modified by the org-data cleanup
+ # below, so we hoist it to the top of the transaction. If
+ # the check fails we raise immediately and the rollback
+ # has essentially no write work to undo.
+ #
+ # Running it inside the transaction (rather than as a
+ # separate pre-flight call before opening the session) is
+ # deliberate: it ensures the orphan computation shares the
+ # same snapshot/locks as the destructive writes below, so
+ # another session cannot create a new orphan between
+ # check-and-act.
+ #
+ # No row-level lock (``FOR UPDATE``) is acquired here. A
+ # concurrent session could in principle insert or remove
+ # an ``org_member`` row for the requester between this
+ # read and the ``DELETE User`` write below; we accept
+ # that as an unlikely edge case for the personal-org
+ # self-service path, where the requester is the only
+ # actor with permission to mutate their own memberships.
+ # Promote to ``FOR UPDATE`` if this code starts running
+ # on behalf of multi-actor flows.
+ orphaned_result = await session.execute(
+ text("""
+ SELECT u.id
+ FROM "user" u
+ WHERE u.current_org_id = :org_id
+ AND NOT EXISTS (
+ SELECT 1 FROM org_member om
+ WHERE om.user_id = u.id AND om.org_id != :org_id
+ )
+ """),
+ {'org_id': str(org_id)},
+ )
+ orphaned_user_ids = [str(row[0]) for row in orphaned_result.fetchall()]
+
+ # Split the orphaned users into the requester and everyone
+ # else. Only the requester is cascade-deleted: by calling
+ # DELETE on their own org they've consented to losing their
+ # account. Other members have not consented, so if any
+ # non-requester would be orphaned we raise OrphanedUserError
+ # and let the transaction roll back.
+ other_orphans = [
+ uid for uid in orphaned_user_ids if uid != requester_user_id
+ ]
+ if other_orphans:
+ raise OrphanedUserError(other_orphans)
+
+ requester_orphan_ids = [
+ uid for uid in orphaned_user_ids if uid == requester_user_id
+ ]
+
# 1. Delete conversation data for organization conversations
await session.execute(
text("""
@@ -495,26 +579,69 @@ class OrgStore:
{'org_id': str(org_id)},
)
- # 3. Handle users with this as current_org_id BEFORE deleting memberships
- # Single query to find orphaned users (those with no alternative org)
- orphaned_result = await session.execute(
- text("""
- SELECT u.id
- FROM "user" u
- WHERE u.current_org_id = :org_id
- AND NOT EXISTS (
- SELECT 1 FROM org_member om
- WHERE om.user_id = u.id AND om.org_id != :org_id
+ # 3. Handle users with this as current_org_id BEFORE deleting
+ # memberships. The orphan partition was computed in the
+ # preflight check at the top of this try block;
+ # ``requester_orphan_ids`` is set iff the requester is a
+ # sole-org member of this org.
+
+ # 3a. Cascade-delete the requester if they are a sole-org user
+ # (personal-org self-service path). Their personal-org identity
+ # is preserved on re-login because UserStore.create_user derives
+ # both User.id and Org.id from the Keycloak ``sub`` claim (which
+ # is stable across logins), so a re-onboarded user receives the
+ # same UUIDs they had before. Downstream systems keyed on
+ # ``keycloak_user_id``/``org_id`` continue to resolve correctly.
+ #
+ # We must remove the user row BEFORE deleting the org row,
+ # because ``user.current_org_id`` is a NOT NULL FK to
+ # ``org.id``. That in turn requires releasing other inbound
+ # FKs to ``user.id`` first: ``org_invitation`` and
+ # ``org_git_claim`` cascade on ``org.id`` in the DB schema,
+ # but the org row still exists at this point, so we clean
+ # those references explicitly here.
+ #
+ # FK edges on ``user.id`` cleared before ``DELETE User``:
+ # * ``org_invitation.inviter_id``
+ # * ``org_invitation.accepted_by_user_id``
+ # * ``org_git_claim.claimed_by``
+ # * ``org_member.user_id``
+ # *** If a future migration adds another table with a
+ # FK to ``user.id`` (e.g. ``user_api_key``, ``audit_log``)
+ # this block MUST be updated to release it, or the
+ # ``DELETE User`` below will raise a runtime FK violation
+ # with no obvious pointer back to this site. ***
+ if requester_orphan_ids:
+ await session.execute(
+ delete(OrgInvitation).where(
+ OrgInvitation.inviter_id.in_(requester_orphan_ids)
+ | OrgInvitation.accepted_by_user_id.in_(
+ requester_orphan_ids
+ )
)
- """),
- {'org_id': str(org_id)},
- )
- orphaned_users = orphaned_result.fetchall()
-
- if orphaned_users:
- raise OrphanedUserError([str(row[0]) for row in orphaned_users])
+ )
+ await session.execute(
+ delete(OrgGitClaim).where(
+ OrgGitClaim.claimed_by.in_(requester_orphan_ids)
+ )
+ )
+ # All of the orphan's memberships are for the org being
+ # deleted (definition of "orphan") and so would be removed
+ # by step 4 anyway, but we have to release them now to drop
+ # the user_id FK before the user row goes away.
+ await session.execute(
+ delete(OrgMember).where(
+ OrgMember.user_id.in_(requester_orphan_ids)
+ )
+ )
+ await session.execute(
+ delete(User).where(User.id.in_(requester_orphan_ids))
+ )
- # Batch update: reassign current_org_id to an alternative org for all affected users
+ # 3b. Batch update: reassign current_org_id to an alternative org
+ # for any remaining users. Orphan rows are gone at this point, so
+ # the subquery is guaranteed to return a non-null org for every
+ # row touched by the UPDATE.
await session.execute(
text("""
UPDATE "user"
@@ -534,8 +661,17 @@ class OrgStore:
{'org_id': str(org_id)},
)
- # 5. Finally delete the organization
- session.delete(org)
+ # 5. Finally delete the organization.
+ # ``AsyncSession.delete`` is a coroutine; without ``await``
+ # it is a silent no-op β€” the ORM never flushes the DELETE
+ # and the ``org`` row survives the transaction even though
+ # every preceding step committed. Forgetting the ``await``
+ # here would leave the next sign-in colliding on
+ # ``org_pkey`` in ``UserStore.create_user``, because both
+ # the surviving row and the new row are keyed on the same
+ # stable Keycloak ``sub``. Awaited explicitly to make that
+ # invariant load-bearing rather than incidental.
+ await session.delete(org)
# 6. Clean up LiteLLM team before committing transaction
logger.info(
diff --git a/enterprise/storage/user_store.py b/enterprise/storage/user_store.py
index 857abecb7b..e1ee4e0725 100644
--- a/enterprise/storage/user_store.py
+++ b/enterprise/storage/user_store.py
@@ -50,7 +50,25 @@ class UserStore:
user_info: dict,
role_id: Optional[int] = None,
) -> User | None:
- """Create a new user."""
+ """Create a new user.
+
+ Identity-preservation contract (load-bearing for
+ ``OrgStore.delete_org_cascade``): both ``Org.id`` and ``User.id``
+ are derived from the caller-provided ``user_id`` (the Keycloak
+ ``sub`` claim, stable across logins). This means a user whose
+ personal org was previously cascade-deleted will be re-onboarded
+ here with the **same** ``User.id`` / ``Org.id`` as before,
+ restoring the ``User.id == Org.id == UUID(keycloak.sub)``
+ invariant that downstream lookups keyed on ``keycloak_user_id``
+ depend on.
+
+ If this derivation ever changes (for example, switching to a
+ server-generated UUID), the personal-org self-service recovery
+ path in ``delete_org_cascade`` step 3a will silently break:
+ re-login will succeed but the new IDs will not match the
+ deleted-tenant IDs, breaking any external reference that pinned
+ on the old values.
+ """
async with a_session_maker() as session:
# create personal org
org = Org(
diff --git a/enterprise/tests/unit/server/routes/test_orgs.py b/enterprise/tests/unit/server/routes/test_orgs.py
index fb6caed331..a356a8afe7 100644
--- a/enterprise/tests/unit/server/routes/test_orgs.py
+++ b/enterprise/tests/unit/server/routes/test_orgs.py
@@ -1487,11 +1487,17 @@ async def test_delete_org_unauthorized(mock_app, mock_owner_role):
@pytest.mark.asyncio
-async def test_delete_org_orphaned_users(mock_app, mock_owner_role):
+async def test_delete_org_other_members_would_be_orphaned(mock_app, mock_owner_role):
"""
- GIVEN: Deleting org would leave users without any organization
- WHEN: DELETE /api/organizations/{org_id} is called
- THEN: 400 Bad Request error is returned with user count in message
+ GIVEN: A multi-user org where some members other than the requester would
+ be left without any organization
+ WHEN: DELETE /api/organizations/{org_id} is called
+ THEN: 400 Bad Request is returned listing the affected member count, and
+ the requester's account is NOT silently destroyed.
+
+ This is the multi-user safeguard: an org owner cannot delete an org if
+ doing so would orphan another member's account. Only the requester
+ themselves may be cascade-deleted as a sole-org user.
"""
# Arrange
org_id = uuid.uuid4()
@@ -1514,7 +1520,7 @@ async def test_delete_org_orphaned_users(mock_app, mock_owner_role):
# Assert
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert '2 user(s)' in response.json()['detail']
+ assert '2 other user(s)' in response.json()['detail']
assert 'no remaining organization' in response.json()['detail']
diff --git a/enterprise/tests/unit/test_org_store.py b/enterprise/tests/unit/test_org_store.py
index 7ddbccaef4..f7be58c4d9 100644
--- a/enterprise/tests/unit/test_org_store.py
+++ b/enterprise/tests/unit/test_org_store.py
@@ -963,23 +963,236 @@ async def test_get_user_orgs_paginated_ordering(async_session_maker, mock_litell
def test_orphaned_user_error_contains_user_ids():
"""
GIVEN: OrphanedUserError is created with a list of user IDs
- WHEN: The error message is accessed
- THEN: Message includes the count and stores user IDs
+ WHEN: The error message is accessed
+ THEN: Message includes the count and stores user IDs.
+
+ The error is raised only for orphans OTHER than the requester (so the
+ count refers to "other users"), preserving the safeguard that a
+ multi-user org owner cannot silently destroy other members' accounts.
"""
- # Arrange
from server.routes.org_models import OrphanedUserError
user_ids = [str(uuid.uuid4()), str(uuid.uuid4())]
-
- # Act
error = OrphanedUserError(user_ids)
- # Assert
assert error.user_ids == user_ids
- assert '2 user(s)' in str(error)
+ assert '2 other user(s)' in str(error)
assert 'no remaining organization' in str(error)
+ reason='Uses PostgreSQL-specific ::uuid cast syntax not supported by SQLite'
+)
+async def test_delete_org_cascade_sole_org_requester_is_deleted(
+ async_session_maker, mock_litellm_api
+):
+ """
+ GIVEN: A sole-org user (orphan) whose only membership is in the org being
+ deleted, AND that user is the requester of the deletion
+ WHEN: delete_org_cascade is called with requester_user_id=the user's id
+ THEN: The user, org, and org_member rows are all removed in the same
+ transaction. No OrphanedUserError is raised.
+
+ Re-onboarding contract: because UserStore.create_user derives both User.id
+ and Org.id from the Keycloak ``sub`` claim (which is stable across logins),
+ a re-login after this cascade reproduces the same UUIDs the user had
+ before, preserving personal-org identity for downstream lookups keyed on
+ ``keycloak_user_id``. See ``enterprise/storage/user_store.py:create_user``.
+ """
+ # Arrange β€” personal-org invariant: User.id == Org.id == UUID(keycloak.sub)
+ user_id = uuid.uuid4()
+ org_id = user_id
+ role_id = 1
+
+ async with async_session_maker() as session:
+ session.add_all(
+ [
+ Role(id=role_id, name='owner', rank=1),
+ Org(
+ id=org_id,
+ name='Personal Org',
+ contact_name='Sole Owner',
+ contact_email='[email protected]',
+ ),
+ User(id=user_id, current_org_id=org_id),
+ OrgMember(
+ org_id=org_id,
+ user_id=user_id,
+ role_id=role_id,
+ status='active',
+ llm_api_key='test-key',
+ ),
+ ]
+ )
+ await session.commit()
+
+ # Act
+ with patch('storage.org_store.a_session_maker', async_session_maker):
+ result = await OrgStore.delete_org_cascade(
+ org_id, requester_user_id=str(user_id)
+ )
+
+ # Assert: the deleted org is returned, and the user/org/member rows are gone.
+ assert result is not None
+ assert result.id == org_id
+
+ async with async_session_maker() as session:
+ assert await session.get(Org, org_id) is None
+ assert await session.get(User, user_id) is None
+ remaining_members = (
+ (await session.execute(select(OrgMember).filter_by(org_id=org_id)))
+ .scalars()
+ .all()
+ )
+ assert remaining_members == []
+
+
+ reason='Uses PostgreSQL-specific ::uuid cast syntax not supported by SQLite'
+)
+async def test_delete_org_cascade_keeps_user_with_alternative_org(
+ async_session_maker, mock_litellm_api
+):
+ """
+ GIVEN: A user belonging to two orgs whose current_org_id points at the org
+ being deleted
+ WHEN: delete_org_cascade is called on that org
+ THEN: The user row survives with current_org_id reassigned to the
+ remaining org. No orphan handling is triggered.
+ """
+ deleted_org_id = uuid.uuid4()
+ other_org_id = uuid.uuid4()
+ user_id = uuid.uuid4()
+ role_id = 1
+
+ async with async_session_maker() as session:
+ session.add_all(
+ [
+ Role(id=role_id, name='owner', rank=1),
+ Org(
+ id=deleted_org_id,
+ name='Org to delete',
+ contact_email='[email protected]',
+ ),
+ Org(
+ id=other_org_id,
+ name='Other Org',
+ contact_email='[email protected]',
+ ),
+ User(id=user_id, current_org_id=deleted_org_id),
+ OrgMember(
+ org_id=deleted_org_id,
+ user_id=user_id,
+ role_id=role_id,
+ status='active',
+ llm_api_key='k1',
+ ),
+ OrgMember(
+ org_id=other_org_id,
+ user_id=user_id,
+ role_id=role_id,
+ status='active',
+ llm_api_key='k2',
+ ),
+ ]
+ )
+ await session.commit()
+
+ with patch('storage.org_store.a_session_maker', async_session_maker):
+ result = await OrgStore.delete_org_cascade(
+ deleted_org_id, requester_user_id=str(user_id)
+ )
+
+ assert result is not None
+ async with async_session_maker() as session:
+ assert await session.get(Org, deleted_org_id) is None
+ surviving_user = await session.get(User, user_id)
+ assert surviving_user is not None
+ assert surviving_user.current_org_id == other_org_id
+
+
+ reason='Uses PostgreSQL-specific ::uuid cast syntax not supported by SQLite'
+)
+async def test_delete_org_cascade_raises_for_non_requester_orphans(
+ async_session_maker, mock_litellm_api
+):
+ """
+ GIVEN: A multi-user org where the requester has another org to fall back
+ on, but a second member's only membership is in this org
+ WHEN: delete_org_cascade is called with requester_user_id=the requester
+ THEN: OrphanedUserError is raised listing the OTHER member's id; the
+ whole transaction is rolled back, so org/user/member rows survive.
+
+ This is the multi-user safeguard: an org owner cannot delete an org if
+ doing so would silently destroy another member's account. The owner must
+ first transfer or remove those members.
+ """
+ org_id = uuid.uuid4()
+ other_org_id = uuid.uuid4()
+ requester_id = uuid.uuid4()
+ other_user_id = uuid.uuid4()
+ role_id = 1
+
+ async with async_session_maker() as session:
+ session.add_all(
+ [
+ Role(id=role_id, name='owner', rank=1),
+ Org(id=org_id, name='Shared Org', contact_email='[email protected]'),
+ Org(
+ id=other_org_id,
+ name='Requester Alt Org',
+ contact_email='[email protected]',
+ ),
+ # Requester: member of both orgs (NOT orphaned by deleting `org_id`)
+ User(id=requester_id, current_org_id=org_id),
+ OrgMember(
+ org_id=org_id,
+ user_id=requester_id,
+ role_id=role_id,
+ status='active',
+ llm_api_key='k1',
+ ),
+ OrgMember(
+ org_id=other_org_id,
+ user_id=requester_id,
+ role_id=role_id,
+ status='active',
+ llm_api_key='k2',
+ ),
+ # Other member: sole-org in `org_id` β†’ would be orphaned
+ User(id=other_user_id, current_org_id=org_id),
+ OrgMember(
+ org_id=org_id,
+ user_id=other_user_id,
+ role_id=role_id,
+ status='active',
+ llm_api_key='k3',
+ ),
+ ]
+ )
+ await session.commit()
+
+ from server.routes.org_models import OrphanedUserError
+
+ with patch('storage.org_store.a_session_maker', async_session_maker):
+ with pytest.raises(OrphanedUserError) as exc_info:
+ await OrgStore.delete_org_cascade(
+ org_id, requester_user_id=str(requester_id)
+ )
+
+ assert exc_info.value.user_ids == [str(other_user_id)]
+
+ # Transaction rolled back β€” nothing should have been deleted.
+ async with async_session_maker() as session:
+ assert await session.get(Org, org_id) is not None
+ assert await session.get(User, requester_id) is not None
+ assert await session.get(User, other_user_id) is not None
+
+
def test_org_deletion_with_invitations_uses_passive_deletes(
session_maker, mock_litellm_api
):