Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(enterprise/auth): super-admin management endpoint (grant/revoke/list) (#15006)

John-Mason P. Shackelford0107d955a5e8
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index 999cbdb94c..4a61b3bbbf 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -54,6 +54,7 @@ from server.routes.org_profiles import router as org_profiles_router # noqa: E4
from server.routes.orgs import org_router # noqa: E402
from server.routes.readiness import readiness_router # noqa: E402
from server.routes.service import service_router # noqa: E402
+from server.routes.super_admins import super_admin_router # noqa: E402
from server.routes.user_app_settings import user_app_settings_router # noqa: E402
from server.routes.user_provisioning import ( # noqa: E402
user_provisioning_router,
@@ -153,6 +154,9 @@ if AZURE_DEVOPS_CLIENT_ID:
base_app.include_router(api_keys_router) # Add routes for API key management
base_app.include_router(service_router) # Add routes for internal service API
base_app.include_router(org_router) # Add routes for organization management
+base_app.include_router(
+ super_admin_router
+) # Add routes for instance-level super-admin management
if USER_PROVISIONING_ENABLED:
# Privileged admin route β€” registered only when the
# USER_PROVISIONING_ENABLED env var (driven by Helm value
diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.py
index 6ee92a00ba..f859ca504c 100644
--- a/enterprise/server/auth/authorization.py
+++ b/enterprise/server/auth/authorization.py
@@ -101,6 +101,12 @@ class Permission(str, Enum):
# Organization Conversations (Admin/Owner only)
VIEW_ORG_CONVERSATIONS = 'view_org_conversations'
+ # Instance-level super-role administration: grant/revoke the super-admin
+ # role (``user.role_id``) on other users. This is deliberately a distinct,
+ # explicit permission -- it is NOT implied by any org-scoped role and is
+ # granted only to the ``superadmin`` super role.
+ MANAGE_SUPER_ADMINS = 'manage_super_admins'
+
class RoleName(str, Enum):
"""Role names used in the system.
@@ -225,14 +231,18 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
# This keeps instance administration separate from organization-scoped
# product/configuration administration.
SUPER_ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
- # Only superadmin is functional for now. It can create organizations
- # and provision users into a selected organization without becoming
- # an org member itself. Additional instance-admin capabilities should
- # be added here explicitly as the corresponding routes are wired to
- # permission checks.
+ # Only superadmin is functional for now. It can create organizations,
+ # provision users into a selected organization without becoming an org
+ # member itself, and grant/revoke the super-admin role on other users.
+ # Additional instance-admin capabilities should be added here explicitly
+ # as the corresponding routes are wired to permission checks.
RoleName.OWNER: frozenset(),
RoleName.ADMIN: frozenset(
- [Permission.CREATE_ORGANIZATION, Permission.PROVISION_USER]
+ [
+ Permission.CREATE_ORGANIZATION,
+ Permission.PROVISION_USER,
+ Permission.MANAGE_SUPER_ADMINS,
+ ]
),
RoleName.MEMBER: frozenset(),
}
diff --git a/enterprise/server/routes/super_admins.py b/enterprise/server/routes/super_admins.py
new file mode 100644
index 0000000000..d542c9a42d
--- /dev/null
+++ b/enterprise/server/routes/super_admins.py
@@ -0,0 +1,167 @@
+"""Instance-level super-admin management.
+
+Exposes a small, explicit API for managing *super admins* β€” users whose
+``user.role_id`` references the ``admin`` role row and therefore hold the
+instance-level ``superadmin`` super role (see ``server.auth.authorization``
+for the super-role model).
+
+Every endpoint here is gated by the dedicated
+``Permission.MANAGE_SUPER_ADMINS`` permission, which is granted **only** to
+the ``superadmin`` super role β€” no org-scoped role can reach these routes.
+In other words: only a super admin can create or remove other super admins.
+
+Safety invariant: the API refuses to remove the **last** remaining super
+admin (enforced atomically in ``UserStore.revoke_super_admin``), so an
+installation can never be locked out of instance administration. A super
+admin may demote themselves as long as another super admin still exists.
+"""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException, status
+from pydantic import BaseModel, Field, model_validator
+from server.auth.authorization import Permission, require_permission
+from storage.user_store import SuperAdminRevokeResult, UserStore
+
+from openhands.app_server.utils.logger import openhands_logger as logger
+
+super_admin_router = APIRouter(prefix='/api/admin/super-admins', tags=['Admin'])
+
+
+class GrantSuperAdminRequest(BaseModel):
+ """Identify the user to promote to super admin.
+
+ Provide exactly one of ``user_id`` or ``email``. ``email`` is a
+ convenience for installers/operators who key on email rather than the
+ Keycloak ``sub``; it is resolved to a user id before the grant.
+ """
+
+ user_id: str | None = Field(
+ default=None,
+ description='Target user id (Keycloak sub / UUID string).',
+ )
+ email: str | None = Field(
+ default=None,
+ description='Target user email. Resolved to a user id before granting.',
+ )
+
+ @model_validator(mode='after')
+ def _exactly_one_identifier(self) -> 'GrantSuperAdminRequest':
+ if bool(self.user_id) == bool(self.email):
+ raise ValueError('Provide exactly one of "user_id" or "email".')
+ return self
+
+
+class SuperAdminResponse(BaseModel):
+ """A single super admin."""
+
+ user_id: str
+ email: str | None = None
+
+
+class SuperAdminListResponse(BaseModel):
+ """The full set of current super admins."""
+
+ super_admins: list[SuperAdminResponse]
+
+
+def _to_response(user) -> SuperAdminResponse:
+ return SuperAdminResponse(user_id=str(user.id), email=user.email)
+
+
+@super_admin_router.get('', response_model=SuperAdminListResponse)
+async def list_super_admins(
+ _: str = Depends(require_permission(Permission.MANAGE_SUPER_ADMINS)),
+) -> SuperAdminListResponse:
+ """List all current super admins. Requires ``MANAGE_SUPER_ADMINS``."""
+ users = await UserStore.list_super_admins()
+ return SuperAdminListResponse(super_admins=[_to_response(u) for u in users])
+
+
+@super_admin_router.post(
+ '',
+ response_model=SuperAdminResponse,
+ status_code=status.HTTP_201_CREATED,
+)
+async def grant_super_admin(
+ body: GrantSuperAdminRequest,
+ caller_user_id: str = Depends(require_permission(Permission.MANAGE_SUPER_ADMINS)),
+) -> SuperAdminResponse:
+ """Grant the super-admin role to an existing user.
+
+ Idempotent: granting to a user who is already a super admin succeeds and
+ returns their record. Requires ``MANAGE_SUPER_ADMINS``.
+ """
+ if body.email:
+ target = await UserStore.get_user_by_email(body.email)
+ if target is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='No user found with that email',
+ )
+ target_user_id = str(target.id)
+ else:
+ # Validator guarantees exactly one of user_id/email is truthy, so
+ # (email falsy) implies user_id is a non-empty string here. Branch on
+ # truthiness -- not ``is not None`` -- to stay consistent with the
+ # validator, otherwise an empty-string ``email`` would wrongly take
+ # the email branch and 404.
+ target_user_id = body.user_id # type: ignore[assignment]
+
+ try:
+ user = await UserStore.grant_super_admin(target_user_id)
+ except ValueError as exc:
+ # Malformed user_id (not a UUID) or missing seeded admin role.
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
+ ) from exc
+
+ if user is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail='User not found'
+ )
+
+ logger.info(
+ 'super_admins:grant',
+ extra={'caller_user_id': caller_user_id, 'target_user_id': target_user_id},
+ )
+ return _to_response(user)
+
+
+@super_admin_router.delete('/{user_id}', response_model=SuperAdminResponse)
+async def revoke_super_admin(
+ user_id: str,
+ caller_user_id: str = Depends(require_permission(Permission.MANAGE_SUPER_ADMINS)),
+) -> SuperAdminResponse:
+ """Revoke the super-admin role from a user (including oneself).
+
+ Refuses with ``409 Conflict`` if the target is the only remaining super
+ admin. Requires ``MANAGE_SUPER_ADMINS``.
+ """
+ try:
+ result = await UserStore.revoke_super_admin(user_id)
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
+ ) from exc
+
+ if result is SuperAdminRevokeResult.NOT_FOUND:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail='User not found'
+ )
+ if result is SuperAdminRevokeResult.NOT_SUPER_ADMIN:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail='User is not a super admin',
+ )
+ if result is SuperAdminRevokeResult.LAST_SUPER_ADMIN:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail='Cannot remove the last remaining super admin',
+ )
+
+ logger.info(
+ 'super_admins:revoke',
+ extra={'caller_user_id': caller_user_id, 'target_user_id': user_id},
+ )
+ return SuperAdminResponse(user_id=user_id)
diff --git a/enterprise/storage/user_store.py b/enterprise/storage/user_store.py
index 227e6c22ba..a2197ac97b 100644
--- a/enterprise/storage/user_store.py
+++ b/enterprise/storage/user_store.py
@@ -2,6 +2,7 @@
import asyncio
import uuid
+from enum import Enum
from typing import Optional
from uuid import UUID
@@ -41,6 +42,23 @@ _RETRY_LOAD_DELAY_SECONDS = 2
# Redis key prefix for user creation locks
_REDIS_USER_CREATION_KEY_PREFIX = 'create_user:'
+# Role name whose row, when referenced by ``user.role_id``, makes a user a
+# ``superadmin`` (see ``server.auth.authorization`` for the super-role model).
+_SUPER_ADMIN_ROLE_NAME = 'admin'
+
+
+class SuperAdminRevokeResult(str, Enum):
+ """Outcome of an attempt to revoke a user's super-admin role.
+
+ Returned (rather than raising) so the calling route can map each case
+ to an appropriate HTTP status without sniffing exception types.
+ """
+
+ REVOKED = 'revoked'
+ NOT_FOUND = 'not_found'
+ NOT_SUPER_ADMIN = 'not_super_admin'
+ LAST_SUPER_ADMIN = 'last_super_admin'
+
class UserStore:
"""Store for managing users."""
@@ -854,6 +872,126 @@ class UserStore:
)
return user
+ @staticmethod
+ async def _get_super_admin_role_id(session) -> int:
+ """Resolve the role id that designates a super admin.
+
+ Fails fast if the ``admin`` role row is missing -- it is seeded by
+ migration, so its absence is a deployment error, not a runtime
+ condition to be tolerated (mirrors the ``owner`` lookup in
+ ``create_user``).
+ """
+ role = await RoleStore.get_role_by_name(_SUPER_ADMIN_ROLE_NAME, session)
+ if role is None:
+ raise ValueError(
+ f'Super-admin role {_SUPER_ADMIN_ROLE_NAME!r} not found in database'
+ )
+ return role.id
+
+ @staticmethod
+ async def list_super_admins() -> list[User]:
+ """List all users that currently hold the instance-level super-admin role.
+
+ A super admin is a user whose ``user.role_id`` references the
+ ``admin`` role row (distinct from any org-scoped ``org_member.role_id``).
+ """
+ async with a_session_maker() as session:
+ admin_role_id = await UserStore._get_super_admin_role_id(session)
+ result = await session.execute(
+ select(User).filter(User.role_id == admin_role_id)
+ )
+ return list(result.scalars().all())
+
+ @staticmethod
+ async def grant_super_admin(user_id: str) -> Optional[User]:
+ """Grant the instance-level super-admin role to an existing user.
+
+ Sets ``user.role_id`` to the ``admin`` role row. Idempotent: if the
+ user already holds the super-admin role the row is returned unchanged.
+
+ Args:
+ user_id: The target user's ID.
+
+ Returns:
+ The updated (or already-super-admin) user, or ``None`` if no user
+ exists with the given id.
+ """
+ async with a_session_maker() as session:
+ admin_role_id = await UserStore._get_super_admin_role_id(session)
+ result = await session.execute(
+ select(User).filter(User.id == uuid.UUID(user_id)).with_for_update()
+ )
+ user = result.scalars().first()
+ if not user:
+ return None
+
+ if user.role_id != admin_role_id:
+ user.role_id = admin_role_id
+ await session.commit()
+ await session.refresh(user)
+ logger.info(
+ 'user_store:grant_super_admin:granted',
+ extra={'user_id': user_id},
+ )
+ return user
+
+ @staticmethod
+ async def revoke_super_admin(user_id: str) -> SuperAdminRevokeResult:
+ """Revoke the instance-level super-admin role from a user.
+
+ Clears ``user.role_id``. Refuses to remove the **last** remaining
+ super admin so an installation can never be left with no instance
+ administrator (this also covers self-removal: a super admin may
+ demote themselves as long as another super admin still exists).
+
+ Concurrency: the whole set of current super admins is selected
+ ``FOR UPDATE`` before the count/clear, so simultaneous revokes
+ serialize. A transaction that waited re-evaluates the predicate
+ after acquiring the lock, so it sees an up-to-date set and cannot
+ race two "second-to-last" revocations down to zero. (On SQLite,
+ used in tests, ``FOR UPDATE`` is a no-op but the surrounding
+ transaction still serializes writes.)
+
+ Args:
+ user_id: The target user's ID.
+
+ Returns:
+ A :class:`SuperAdminRevokeResult` describing the outcome.
+ """
+ target_uuid = uuid.UUID(user_id)
+ async with a_session_maker() as session:
+ admin_role_id = await UserStore._get_super_admin_role_id(session)
+ result = await session.execute(
+ select(User).filter(User.role_id == admin_role_id).with_for_update()
+ )
+ super_admins = list(result.scalars().all())
+
+ target = next((u for u in super_admins if u.id == target_uuid), None)
+ if target is None:
+ exists = await session.scalar(
+ select(User.id).filter(User.id == target_uuid)
+ )
+ return (
+ SuperAdminRevokeResult.NOT_FOUND
+ if exists is None
+ else SuperAdminRevokeResult.NOT_SUPER_ADMIN
+ )
+
+ if len(super_admins) <= 1:
+ logger.warning(
+ 'user_store:revoke_super_admin:refused_last_super_admin',
+ extra={'user_id': user_id},
+ )
+ return SuperAdminRevokeResult.LAST_SUPER_ADMIN
+
+ target.role_id = None
+ await session.commit()
+ logger.info(
+ 'user_store:revoke_super_admin:revoked',
+ extra={'user_id': user_id},
+ )
+ return SuperAdminRevokeResult.REVOKED
+
@staticmethod
async def get_first_owner_in_org(org_id: UUID) -> Optional[User]:
"""Get the first owner in an organization who accepted the Terms of Service.
diff --git a/enterprise/tests/unit/server/routes/test_super_admins.py b/enterprise/tests/unit/server/routes/test_super_admins.py
new file mode 100644
index 0000000000..739a93e2a9
--- /dev/null
+++ b/enterprise/tests/unit/server/routes/test_super_admins.py
@@ -0,0 +1,235 @@
+"""Route-level tests for the super-admin management API.
+
+These exercise the FastAPI routes through ``require_permission`` and stub
+``UserStore`` at the route module boundary. Authorization itself is faked the
+same way ``test_orgs.py`` fakes ``CREATE_ORGANIZATION``: short-circuit the
+org-role lookup to ``None`` and stack a ``superadmin`` super role on top of the
+conftest-level ``get_user_super_role -> None`` default.
+"""
+
+import uuid
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from fastapi import FastAPI
+from httpx import ASGITransport, AsyncClient
+from server.routes.super_admins import super_admin_router
+from storage.user_store import SuperAdminRevokeResult
+
+from openhands.app_server.user_auth import get_user_id
+
+CALLER_USER_ID = str(uuid.uuid4())
+
+
+def mock_app():
+ app = FastAPI()
+ app.include_router(super_admin_router)
+ app.dependency_overrides[get_user_id] = lambda: CALLER_USER_ID
+ return app
+
+
+def grant_manage_super_admins():
+ """Make ``MANAGE_SUPER_ADMINS`` succeed by faking a ``superadmin`` role."""
+ superadmin = MagicMock()
+ superadmin.name = 'admin'
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=superadmin),
+ ),
+ ):
+ yield
+
+
+def _client(app):
+ return AsyncClient(transport=ASGITransport(app=app), base_url='http://test')
+
+
+def _fake_user(user_id: str, email: str | None = None):
+ user = MagicMock()
+ user.id = uuid.UUID(user_id)
+ user.email = email
+ return user
+
+
+async def test_grant_by_user_id_success(mock_app, grant_manage_super_admins):
+ target = str(uuid.uuid4())
+ with patch(
+ 'server.routes.super_admins.UserStore.grant_super_admin',
+ AsyncMock(return_value=_fake_user(target, '[email protected]')),
+ ) as grant_mock:
+ async with _client(mock_app) as client:
+ resp = await client.post(
+ '/api/admin/super-admins', json={'user_id': target}
+ )
+
+ assert resp.status_code == 201
+ assert resp.json()['user_id'] == target
+ grant_mock.assert_awaited_once_with(target)
+
+
+async def test_grant_by_email_resolves_user(mock_app, grant_manage_super_admins):
+ target = str(uuid.uuid4())
+ with (
+ patch(
+ 'server.routes.super_admins.UserStore.get_user_by_email',
+ AsyncMock(return_value=_fake_user(target, '[email protected]')),
+ ),
+ patch(
+ 'server.routes.super_admins.UserStore.grant_super_admin',
+ AsyncMock(return_value=_fake_user(target, '[email protected]')),
+ ) as grant_mock,
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.post(
+ '/api/admin/super-admins', json={'email': '[email protected]'}
+ )
+
+ assert resp.status_code == 201
+ grant_mock.assert_awaited_once_with(target)
+
+
+async def test_grant_requires_exactly_one_identifier(
+ mock_app, grant_manage_super_admins
+):
+ async with _client(mock_app) as client:
+ both = await client.post(
+ '/api/admin/super-admins',
+ json={'user_id': str(uuid.uuid4()), 'email': '[email protected]'},
+ )
+ neither = await client.post('/api/admin/super-admins', json={})
+
+ assert both.status_code == 422
+ assert neither.status_code == 422
+
+
+async def test_grant_user_not_found(mock_app, grant_manage_super_admins):
+ with patch(
+ 'server.routes.super_admins.UserStore.grant_super_admin',
+ AsyncMock(return_value=None),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.post(
+ '/api/admin/super-admins', json={'user_id': str(uuid.uuid4())}
+ )
+
+ assert resp.status_code == 404
+
+
+async def test_grant_by_email_unknown(mock_app, grant_manage_super_admins):
+ with patch(
+ 'server.routes.super_admins.UserStore.get_user_by_email',
+ AsyncMock(return_value=None),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.post(
+ '/api/admin/super-admins', json={'email': '[email protected]'}
+ )
+
+ assert resp.status_code == 404
+
+
+async def test_revoke_success(mock_app, grant_manage_super_admins):
+ target = str(uuid.uuid4())
+ with patch(
+ 'server.routes.super_admins.UserStore.revoke_super_admin',
+ AsyncMock(return_value=SuperAdminRevokeResult.REVOKED),
+ ) as revoke_mock:
+ async with _client(mock_app) as client:
+ resp = await client.delete(f'/api/admin/super-admins/{target}')
+
+ assert resp.status_code == 200
+ assert resp.json()['user_id'] == target
+ revoke_mock.assert_awaited_once_with(target)
+
+
+async def test_revoke_self_success(mock_app, grant_manage_super_admins):
+ """Caller revoking their own id succeeds when another super admin exists."""
+ with patch(
+ 'server.routes.super_admins.UserStore.revoke_super_admin',
+ AsyncMock(return_value=SuperAdminRevokeResult.REVOKED),
+ ) as revoke_mock:
+ async with _client(mock_app) as client:
+ resp = await client.delete(f'/api/admin/super-admins/{CALLER_USER_ID}')
+
+ assert resp.status_code == 200
+ revoke_mock.assert_awaited_once_with(CALLER_USER_ID)
+
+
+async def test_revoke_last_super_admin_conflict(mock_app, grant_manage_super_admins):
+ with patch(
+ 'server.routes.super_admins.UserStore.revoke_super_admin',
+ AsyncMock(return_value=SuperAdminRevokeResult.LAST_SUPER_ADMIN),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.delete(f'/api/admin/super-admins/{uuid.uuid4()}')
+
+ assert resp.status_code == 409
+
+
+async def test_revoke_not_super_admin_404(mock_app, grant_manage_super_admins):
+ with patch(
+ 'server.routes.super_admins.UserStore.revoke_super_admin',
+ AsyncMock(return_value=SuperAdminRevokeResult.NOT_SUPER_ADMIN),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.delete(f'/api/admin/super-admins/{uuid.uuid4()}')
+
+ assert resp.status_code == 404
+
+
+async def test_revoke_unknown_user_404(mock_app, grant_manage_super_admins):
+ with patch(
+ 'server.routes.super_admins.UserStore.revoke_super_admin',
+ AsyncMock(return_value=SuperAdminRevokeResult.NOT_FOUND),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.delete(f'/api/admin/super-admins/{uuid.uuid4()}')
+
+ assert resp.status_code == 404
+
+
+async def test_list_super_admins(mock_app, grant_manage_super_admins):
+ a, b = str(uuid.uuid4()), str(uuid.uuid4())
+ with patch(
+ 'server.routes.super_admins.UserStore.list_super_admins',
+ AsyncMock(return_value=[_fake_user(a, '[email protected]'), _fake_user(b, '[email protected]')]),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.get('/api/admin/super-admins')
+
+ assert resp.status_code == 200
+ ids = [s['user_id'] for s in resp.json()['super_admins']]
+ assert ids == [a, b]
+
+
+async def test_manage_super_admins_forbidden_without_permission(mock_app):
+ """Without a super role, the conftest default denies access (403)."""
+ # No ``grant_manage_super_admins`` fixture here: org-role lookup must also
+ # resolve to None so the permission check falls through to a denial.
+ with patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ):
+ async with _client(mock_app) as client:
+ resp = await client.get('/api/admin/super-admins')
+
+ assert resp.status_code == 403
diff --git a/enterprise/tests/unit/test_authorization.py b/enterprise/tests/unit/test_authorization.py
index 8ff5075fdb..d93a7ab71b 100644
--- a/enterprise/tests/unit/test_authorization.py
+++ b/enterprise/tests/unit/test_authorization.py
@@ -1327,7 +1327,11 @@ class TestSuperRolePermissions:
"""
assert SUPER_ROLE_PERMISSIONS[RoleName.OWNER] == frozenset()
assert SUPER_ROLE_PERMISSIONS[RoleName.ADMIN] == frozenset(
- [Permission.CREATE_ORGANIZATION, Permission.PROVISION_USER]
+ [
+ Permission.CREATE_ORGANIZATION,
+ Permission.PROVISION_USER,
+ Permission.MANAGE_SUPER_ADMINS,
+ ]
)
assert SUPER_ROLE_PERMISSIONS[RoleName.MEMBER] == frozenset()
diff --git a/enterprise/tests/unit/test_user_store.py b/enterprise/tests/unit/test_user_store.py
index 5ffb040f20..48b7e874c2 100644
--- a/enterprise/tests/unit/test_user_store.py
+++ b/enterprise/tests/unit/test_user_store.py
@@ -13,7 +13,7 @@ from storage.org import Org
from storage.org_member import OrgMember
from storage.role import Role
from storage.user import User
-from storage.user_store import UserStore
+from storage.user_store import SuperAdminRevokeResult, UserStore
from openhands.app_server.settings.settings_models import Settings
@@ -2073,3 +2073,184 @@ async def test_get_first_owner_in_org_returns_none_for_empty_org(async_session_m
result = await UserStore.get_first_owner_in_org(org_id)
assert result is None
+
+
+# --- Tests for super-admin grant / revoke / list ---
+
+
+async def _seed_org(async_session_maker) -> uuid.UUID:
+ """Create a shared org so seeded users satisfy the non-null FK."""
+ org_id = uuid.uuid4()
+ async with async_session_maker() as session:
+ session.add(Org(id=org_id, name=f'org_{org_id}'))
+ await session.commit()
+ return org_id
+
+
+async def _seed_user(
+ async_session_maker, org_id: uuid.UUID, role_id: int | None, email: str
+) -> str:
+ """Insert a User row with the given super ``role_id`` and return its id."""
+ user_id = uuid.uuid4()
+ async with async_session_maker() as session:
+ session.add(
+ User(
+ id=user_id,
+ current_org_id=org_id,
+ role_id=role_id,
+ email=email,
+ )
+ )
+ await session.commit()
+ return str(user_id)
+
+
+def _patch_stores(async_session_maker):
+ return (
+ patch('storage.user_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ )
+
+
+async def test_grant_super_admin_promotes_user(async_session_maker):
+ """Granting sets ``user.role_id`` to the admin role row."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ user_id = await _seed_user(async_session_maker, org_id, None, '[email protected]')
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ user = await UserStore.grant_super_admin(user_id)
+
+ assert user is not None
+ assert user.role_id == admin_role_id
+
+
+async def test_grant_super_admin_is_idempotent(async_session_maker):
+ """Granting to an existing super admin is a no-op success."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ user_id = await _seed_user(
+ async_session_maker, org_id, admin_role_id, '[email protected]'
+ )
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ user = await UserStore.grant_super_admin(user_id)
+ admins = await UserStore.list_super_admins()
+
+ assert user is not None
+ assert user.role_id == admin_role_id
+ assert len(admins) == 1
+
+
+async def test_grant_super_admin_user_not_found(async_session_maker):
+ """Granting to a non-existent user returns ``None``."""
+ await _seed_admin_role(async_session_maker)
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ user = await UserStore.grant_super_admin(str(uuid.uuid4()))
+
+ assert user is None
+
+
+async def test_list_super_admins_only_returns_super_admins(async_session_maker):
+ """Only users whose ``role_id`` is the admin role are returned."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ a = await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+ await _seed_user(async_session_maker, org_id, None, '[email protected]')
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ admins = await UserStore.list_super_admins()
+
+ assert [str(u.id) for u in admins] == [a]
+
+
+async def test_revoke_super_admin_success_when_another_exists(async_session_maker):
+ """Revoking one of several super admins clears their role."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ a = await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+ await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ result = await UserStore.revoke_super_admin(a)
+ admins = await UserStore.list_super_admins()
+
+ assert result is SuperAdminRevokeResult.REVOKED
+ assert a not in [str(u.id) for u in admins]
+ assert len(admins) == 1
+
+
+async def test_revoke_self_allowed_when_another_super_admin_exists(
+ async_session_maker,
+):
+ """A super admin may demote themselves while another still exists."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ me = await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+ await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ # ``me`` removing ``me`` is just a revoke of the caller's own id.
+ result = await UserStore.revoke_super_admin(me)
+
+ assert result is SuperAdminRevokeResult.REVOKED
+
+
+async def test_revoke_last_super_admin_is_refused(async_session_maker):
+ """The only remaining super admin cannot be removed."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ only = await _seed_user(
+ async_session_maker, org_id, admin_role_id, '[email protected]'
+ )
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ result = await UserStore.revoke_super_admin(only)
+ admins = await UserStore.list_super_admins()
+
+ assert result is SuperAdminRevokeResult.LAST_SUPER_ADMIN
+ assert [str(u.id) for u in admins] == [only]
+
+
+async def test_revoke_non_super_admin_reports_not_super_admin(async_session_maker):
+ """Revoking a user who isn't a super admin is reported distinctly."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+ plain = await _seed_user(async_session_maker, org_id, None, '[email protected]')
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ result = await UserStore.revoke_super_admin(plain)
+
+ assert result is SuperAdminRevokeResult.NOT_SUPER_ADMIN
+
+
+async def test_revoke_unknown_user_reports_not_found(async_session_maker):
+ """Revoking a non-existent user is reported as not found."""
+ admin_role_id = await _seed_admin_role(async_session_maker)
+ org_id = await _seed_org(async_session_maker)
+ await _seed_user(async_session_maker, org_id, admin_role_id, '[email protected]')
+
+ p1, p2 = _patch_stores(async_session_maker)
+ with p1, p2:
+ result = await UserStore.revoke_super_admin(str(uuid.uuid4()))
+
+ assert result is SuperAdminRevokeResult.NOT_FOUND