Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(enterprise/auth): add super roles via user.role_id with permission fallback (#14937)

chuckbutkus4a0de6575a9a
diff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.py
index 6a981aff30..1d8469e8c1 100644
--- a/enterprise/server/auth/authorization.py
+++ b/enterprise/server/auth/authorization.py
@@ -39,6 +39,7 @@ from fastapi import Depends, HTTPException, Request, status
from storage.org_member_store import OrgMemberStore
from storage.role import Role
from storage.role_store import RoleStore
+from storage.user_store import UserStore
from openhands.app_server.user_auth import get_user_auth, get_user_id
from openhands.app_server.utils.logger import openhands_logger as logger
@@ -80,6 +81,7 @@ class Permission(str, Enum):
VIEW_ORG_SETTINGS = 'view_org_settings'
CHANGE_ORGANIZATION_NAME = 'change_organization_name'
DELETE_ORGANIZATION = 'delete_organization'
+ CREATE_ORGANIZATION = 'create_organization'
# Temporary permissions until we finish the API updates.
EDIT_ORG_SETTINGS = 'edit_org_settings'
@@ -98,14 +100,38 @@ class Permission(str, Enum):
class RoleName(str, Enum):
- """Role names used in the system."""
+ """Role names used in the system.
+
+ The same role rows (``owner``, ``admin``, ``member``) can be
+ assigned in two distinct places:
+
+ * **Org-scoped role** -- stored on ``org_member.role_id``. Applies
+ only to the user's membership in that organization. Permissions
+ are looked up via :data:`ROLE_PERMISSIONS`.
+ * **Super role** -- stored on ``user.role_id``. Applies at the
+ instance level across organizations. The only functional super
+ role currently defined is ``superadmin`` (``role_id`` pointing to
+ the ``admin`` role row). Super permissions are defined explicitly
+ in :data:`SUPER_ROLE_PERMISSIONS`; they do not inherit
+ org-scoped role permissions.
+ """
OWNER = 'owner'
ADMIN = 'admin'
MEMBER = 'member'
-# Permission mappings for each role
+def super_role_name(role_name: str) -> str:
+ """Return the conceptual super-role label for a regular role name.
+
+ For example, ``super_role_name('admin') == 'superadmin'``. Used only
+ for logging / API responses -- super roles share the same database
+ rows as their parallel regular roles.
+ """
+ return f'super{role_name}'
+
+
+# Base permission mappings for the regular (org-scoped) roles.
ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
RoleName.OWNER: frozenset(
[
@@ -187,6 +213,24 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {
}
+# Instance-level permissions for super roles. These are intentionally
+# explicit and do not inherit the parallel org-scoped role permissions.
+# 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.
+ RoleName.OWNER: frozenset(),
+ RoleName.ADMIN: frozenset(
+ [Permission.CREATE_ORGANIZATION, Permission.PROVISION_USER]
+ ),
+ RoleName.MEMBER: frozenset(),
+}
+
+
async def get_user_org_role(user_id: str, org_id: UUID | None) -> Role | None:
"""
Get the user's role in an organization.
@@ -212,15 +256,37 @@ async def get_user_org_role(user_id: str, org_id: UUID | None) -> Role | None:
return await RoleStore.get_role_by_id(org_member.role_id)
+async def get_user_super_role(user_id: str) -> Role | None:
+ """
+ Get the user's cross-organization ("super") role.
+
+ Super roles live on the ``user`` table (``user.role_id``) and apply to
+ the user across **every** organization, in contrast to the
+ organization-scoped role stored on ``org_member.role_id``.
+
+ Args:
+ user_id: User ID (string that will be converted to UUID)
+
+ Returns:
+ The :class:`Role` referenced by ``user.role_id`` if one is set,
+ otherwise ``None``.
+ """
+ user = await UserStore.get_user_by_id(user_id)
+ if not user or user.role_id is None:
+ return None
+
+ return await RoleStore.get_role_by_id(user.role_id)
+
+
def get_role_permissions(role_name: str) -> frozenset[Permission]:
"""
- Get the permissions for a role.
+ Get the org-scoped permissions for a role.
Args:
role_name: Name of the role
Returns:
- Set of permissions for the role
+ Set of permissions for the org-scoped role
"""
try:
role_enum = RoleName(role_name)
@@ -229,19 +295,48 @@ def get_role_permissions(role_name: str) -> frozenset[Permission]:
return frozenset()
-def has_permission(user_role: Role, permission: Permission) -> bool:
+def get_super_role_permissions(role_name: str) -> frozenset[Permission]:
+ """
+ Get the permissions for a "super" role.
+
+ A super role is the same role row (``owner`` / ``admin`` / ``member``)
+ referenced via ``user.role_id`` rather than ``org_member.role_id``;
+ its effective permissions are defined explicitly and do not inherit
+ org-scoped permissions.
+
+ Args:
+ role_name: Name of the role (e.g. ``'admin'`` for ``superadmin``)
+
+ Returns:
+ Set of permissions for the super role
+ """
+ try:
+ role_enum = RoleName(role_name)
+ return SUPER_ROLE_PERMISSIONS.get(role_enum, frozenset())
+ except ValueError:
+ return frozenset()
+
+
+def has_permission(
+ user_role: Role, permission: Permission, *, is_super: bool = False
+) -> bool:
"""
Check if a role has a specific permission.
Args:
user_role: User's Role object
permission: Permission to check
+ is_super: If ``True`` the role was looked up from ``user.role_id``
+ and should be treated as a "super" role -- i.e. permissions
+ are read from the explicit :data:`SUPER_ROLE_PERMISSIONS` mapping
+ instead of :data:`ROLE_PERMISSIONS`.
Returns:
True if the role has the permission
"""
- permissions = get_role_permissions(user_role.name)
- return permission in permissions
+ if is_super:
+ return permission in get_super_role_permissions(user_role.name)
+ return permission in get_role_permissions(user_role.name)
async def get_api_key_org_id_from_request(request: Request) -> UUID | None:
@@ -312,45 +407,80 @@ def require_permission(permission: Permission):
)
# If the route does not carry an ``{org_id}`` path parameter,
- # resolve the effective org for the request β€” which honors any
- # ``X-Org-Id`` header override (and validates membership /
- # API-key binding in the process). This keeps endpoints that
- # implicitly operate on the "current org" consistent with the
- # rest of the codebase.
+ # resolve the target org for the request -- honoring any
+ # ``X-Org-Id`` header override and the API-key binding, but
+ # *without* requiring the user to already be a member of that
+ # org. Membership is checked below via ``get_user_org_role``;
+ # if the user is not a member but has a super role with the
+ # required permission, they are still granted access. Routes
+ # that *do* carry ``{org_id}`` use the path value directly and
+ # skip this resolver, so their semantics are unchanged.
if org_id is None:
# Local import to avoid circular import via saas_user_auth.
- from server.auth.org_context import maybe_resolve_effective_org_id
+ from server.auth.org_context import (
+ resolve_target_org_id_for_permission_check,
+ )
- org_id = await maybe_resolve_effective_org_id(request)
+ org_id = await resolve_target_org_id_for_permission_check(request)
user_role = await get_user_org_role(user_id, org_id)
- if not user_role:
- logger.warning(
- 'User not a member of organization',
- extra={'user_id': user_id, 'org_id': str(org_id)},
- )
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail='User is not a member of this organization',
+ # 1. Org-scoped role check (existing behavior).
+ if user_role and has_permission(user_role, permission):
+ return user_id
+
+ # 2. Fall back to the user's "super" role. The role row is the
+ # same as a regular role, but because it is attached via
+ # ``user.role_id`` it grants the super-role permission set
+ # (parallel role perms + super-only extras) across every
+ # organization the user touches.
+ super_role = await get_user_super_role(user_id)
+ if super_role and has_permission(super_role, permission, is_super=True):
+ logger.debug(
+ 'Permission granted via super role',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'super_role': super_role_name(super_role.name),
+ 'required_permission': permission.value,
+ },
)
+ return user_id
- if not has_permission(user_role, permission):
+ # 3. Neither path granted access -- deny.
+ if not user_role:
logger.warning(
- 'Insufficient permissions',
+ 'User not a member of organization and lacks super-role permission',
extra={
'user_id': user_id,
'org_id': str(org_id),
- 'user_role': user_role.name,
+ 'super_role': (
+ super_role_name(super_role.name) if super_role else None
+ ),
'required_permission': permission.value,
},
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
- detail=f'Requires {permission.value} permission',
+ detail='User is not a member of this organization',
)
- return user_id
+ logger.warning(
+ 'Insufficient permissions',
+ extra={
+ 'user_id': user_id,
+ 'org_id': str(org_id),
+ 'user_role': user_role.name,
+ 'super_role': (
+ super_role_name(super_role.name) if super_role else None
+ ),
+ 'required_permission': permission.value,
+ },
+ )
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail=f'Requires {permission.value} permission',
+ )
return permission_checker
diff --git a/enterprise/server/auth/org_context.py b/enterprise/server/auth/org_context.py
index c6b366551a..7fd497c385 100644
--- a/enterprise/server/auth/org_context.py
+++ b/enterprise/server/auth/org_context.py
@@ -9,7 +9,12 @@ Precedence (highest first):
2. ``X-Org-Id`` header β€” explicit, per-request override sent by the
client. Validated against the authenticated user's org memberships;
- rejected with 403 if the user is not a member of that org.
+ rejected with 403 if the user is not a member of that org **and**
+ has no "super" role assigned. Super-role users may target orgs they
+ have not joined so that this resolver stays consistent with
+ ``require_permission``'s super-role fallback; the route's
+ ``require_permission`` dependency remains the authoritative check
+ for the specific permission needed.
3. ``user.current_org_id`` β€” the user's currently selected org (as
mutated by ``POST /api/organizations/{org_id}/switch``). Default
@@ -39,9 +44,10 @@ async def resolve_effective_org_id(request: Request) -> UUID:
Raises:
HTTPException 400: ``X-Org-Id`` header is present but is not a UUID.
- HTTPException 403: User is not a member of the requested org, or
- the request authenticates with an org-bound API key whose
- org does not match the ``X-Org-Id`` header.
+ HTTPException 403: User is not a member of the requested org and
+ has no super role assigned, or the request authenticates
+ with an org-bound API key whose org does not match the
+ ``X-Org-Id`` header.
HTTPException 404: No effective org could be determined (e.g.
user has no current org and did not supply the header).
"""
@@ -66,16 +72,27 @@ async def resolve_effective_org_id(request: Request) -> UUID:
return effective_org_id
-async def maybe_resolve_effective_org_id(request: Request) -> UUID | None:
- """Variant of :func:`resolve_effective_org_id` that returns ``None``
- rather than 404 when no effective org can be determined.
-
- Still raises 400/403 for malformed or unauthorized ``X-Org-Id`` headers.
+async def resolve_target_org_id_for_permission_check(
+ request: Request,
+) -> UUID | None:
+ """Resolve the target org id for a permission check **without**
+ requiring the authenticated user to be a member of that org.
+
+ This is the entry point used by ``require_permission`` for routes
+ that do not carry an explicit ``{org_id}`` path parameter. It lets
+ "super" role users (whose role is assigned via ``user.role_id``)
+ act on organizations they have not joined, while still enforcing
+ the API-key/header conflict checks performed by
+ :meth:`SaasUserAuth.get_target_org_id_for_permission_check`.
+
+ The membership check is intentionally skipped here -- callers must
+ follow up with an org/super role lookup, which is exactly what
+ ``require_permission`` already does.
"""
user_auth = await get_user_auth(request)
if not isinstance(user_auth, SaasUserAuth):
return None
- return await user_auth.get_effective_org_id()
+ return await user_auth.get_target_org_id_for_permission_check()
async def reject_x_org_id_path_mismatch(
@@ -149,5 +166,4 @@ async def reject_x_org_id_path_mismatch(
# Module-level Depends shortcuts so call sites read tidily:
# effective_org_id: UUID = EFFECTIVE_ORG_ID,
EFFECTIVE_ORG_ID = Depends(resolve_effective_org_id)
-MAYBE_EFFECTIVE_ORG_ID = Depends(maybe_resolve_effective_org_id)
REJECT_X_ORG_ID_PATH_MISMATCH = Depends(reject_x_org_id_path_mismatch)
diff --git a/enterprise/server/auth/saas_user_auth.py b/enterprise/server/auth/saas_user_auth.py
index 1a9a346d5e..419beb040e 100644
--- a/enterprise/server/auth/saas_user_auth.py
+++ b/enterprise/server/auth/saas_user_auth.py
@@ -17,6 +17,7 @@ from server.auth.auth_error import (
from server.auth.authorization import (
get_role_permissions,
get_user_org_role,
+ get_user_super_role,
)
from server.auth.constants import AZURE_DEVOPS_ORGANIZATION, BITBUCKET_DATA_CENTER_HOST
from server.auth.cookie_chunking import read_chunked_cookie
@@ -168,38 +169,49 @@ class SaasUserAuth(UserAuth):
)
return override_org_id
- async def get_effective_org_id(self) -> UUID | None:
- """Resolve the effective organization ID for this request.
+ async def _resolve_org_id(self, *, verify_membership: bool) -> UUID | None:
+ """Shared resolver for :meth:`get_effective_org_id` and
+ :meth:`get_target_org_id_for_permission_check`.
Precedence (highest first):
- 1. ``effective_org_id_override`` β€” trusted server-side resolver context.
- 2. ``api_key_org_id`` β€” if the request is authenticated with an
- org-bound API key, that org wins. If the caller also sent an
- ``X-Org-Id`` header that disagrees, raise 403.
- 3. ``X-Org-Id`` header β€” explicit, per-request override. The
- authenticated user must be a member of that org or we raise
- 403. Malformed UUIDs raise 400.
- 4. ``user.current_org_id`` β€” server-side default.
-
- The resolved value is cached on the auth instance for the rest
- of the request, so callers can invoke this freely.
+ 1. ``effective_org_id_override`` (trusted server-side resolver
+ context; always membership-checked by
+ :meth:`_resolve_and_verify_override_org`). The membership
+ check is intentional defense-in-depth for resolver code that
+ sets the override; it is not relaxed for super-role users.
+ 2. ``api_key_org_id`` if the request authenticated with an
+ org-bound API key. An ``X-Org-Id`` header that disagrees with
+ the API key org raises 403.
+ 3. ``X-Org-Id`` header. Validated as a UUID; the API-key/header
+ conflict above takes precedence. When ``verify_membership``
+ is ``True`` the user must be a member of the requested org,
+ **or** have a "super" role assigned via ``user.role_id``
+ (403 otherwise). When ``False`` the org id is returned
+ verbatim -- the caller is responsible for the access check
+ (used by ``require_permission`` to allow "super" roles to
+ target non-member orgs).
+ 4. ``user.current_org_id`` as a default.
+
+ Note on the super-role bypass in case 3: routes that declare
+ both ``Depends(require_permission(...))`` and ``EFFECTIVE_ORG_ID``
+ would otherwise be inconsistent for non-member super users --
+ ``require_permission`` would grant access via the super-role
+ fallback but ``EFFECTIVE_ORG_ID`` would 403 the same request at
+ the membership check here. This resolver only relaxes the
+ coarse "must be a member" gate when a super role is present;
+ the route's ``require_permission`` dependency is still the
+ authoritative check for the specific permission needed.
Raises:
- HTTPException: 400 for a malformed header, 403 for
- membership / API-key conflicts.
+ HTTPException: 400 for a malformed ``X-Org-Id`` header,
+ 403 for API-key / membership conflicts.
"""
- if self._effective_org_id_resolved:
- return self._effective_org_id
-
from fastapi import status
- from storage.org_member_store import OrgMemberStore
override_org_id = await self._resolve_and_verify_override_org()
if override_org_id is not None:
- self._effective_org_id = override_org_id
- self._effective_org_id_resolved = True
- return self._effective_org_id
+ return override_org_id
header_value = self._x_org_id_header
requested: UUID | None = None
@@ -231,12 +243,17 @@ class SaasUserAuth(UserAuth):
status_code=status.HTTP_403_FORBIDDEN,
detail='API key is not authorized for this organization',
)
- self._effective_org_id = self.api_key_org_id
- self._effective_org_id_resolved = True
- return self._effective_org_id
+ return self.api_key_org_id
- # Case 2: X-Org-Id override; verify membership.
+ # Case 2: X-Org-Id override.
if requested is not None:
+ if not verify_membership:
+ # ``require_permission`` will run the org-role + super-role
+ # fallback against this org id and decide.
+ return requested
+
+ from storage.org_member_store import OrgMemberStore
+
try:
user_uuid = UUID(self.user_id)
except ValueError as exc:
@@ -251,6 +268,25 @@ class SaasUserAuth(UserAuth):
) from exc
member = await OrgMemberStore.get_org_member(requested, user_uuid)
if member is None:
+ # Super-role bypass: a user with a cross-org "super"
+ # role (``user.role_id``) is allowed to target an org
+ # they have not joined. The route's
+ # ``require_permission`` dependency still gates the
+ # specific permission against this org id, so this only
+ # relaxes the coarse membership gate -- it does not
+ # grant access by itself.
+ super_role = await get_user_super_role(self.user_id)
+ if super_role is not None:
+ logger.debug(
+ 'x_org_id_super_role_bypass',
+ extra={
+ 'user_id': self.user_id,
+ 'x_org_id': str(requested),
+ 'super_role': super_role.name,
+ },
+ )
+ return requested
+
logger.warning(
'x_org_id_not_a_member',
extra={
@@ -262,17 +298,49 @@ class SaasUserAuth(UserAuth):
status_code=status.HTTP_403_FORBIDDEN,
detail='User is not a member of the requested organization',
)
- self._effective_org_id = requested
- self._effective_org_id_resolved = True
- return self._effective_org_id
+ return requested
# Case 3: Fall back to the user's currently-selected org.
user = await UserStore.get_user_by_id(self.user_id)
- if user is not None:
- self._effective_org_id = user.current_org_id
+ if user is None:
+ return None
+ return user.current_org_id
+
+ async def get_effective_org_id(self) -> UUID | None:
+ """Resolve the effective organization ID for this request.
+
+ Delegates to :meth:`_resolve_org_id` with ``verify_membership=True``
+ and caches the result on the auth instance for the rest of the
+ request. See the helper for the full precedence rules.
+
+ Raises:
+ HTTPException: 400 for a malformed header, 403 for
+ membership / API-key conflicts.
+ """
+ if self._effective_org_id_resolved:
+ return self._effective_org_id
+
+ self._effective_org_id = await self._resolve_org_id(verify_membership=True)
self._effective_org_id_resolved = True
return self._effective_org_id
+ async def get_target_org_id_for_permission_check(self) -> UUID | None:
+ """Resolve the target organization for a permission check
+ **without** requiring the authenticated user to be a member.
+
+ Delegates to :meth:`_resolve_org_id` with ``verify_membership=False``.
+ Used by ``require_permission`` on routes that lack an explicit
+ ``{org_id}`` path parameter so that "super" role users (assigned
+ via ``user.role_id``) can target orgs they have not joined. The
+ result is **not** cached -- callers should treat it as
+ request-scoped and call only once per request.
+
+ Raises:
+ HTTPException: 400 for a malformed ``X-Org-Id`` header,
+ 403 for API-key / header conflicts.
+ """
+ return await self._resolve_org_id(verify_membership=False)
+
async def get_user_id(self) -> str | None:
return self.user_id
diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.py
index 5253a194b6..5b21664e72 100644
--- a/enterprise/server/routes/orgs.py
+++ b/enterprise/server/routes/orgs.py
@@ -12,7 +12,6 @@ from server.auth.authorization import (
require_permission,
)
from server.auth.org_context import EFFECTIVE_ORG_ID, REJECT_X_ORG_ID_PATH_MISMATCH
-from server.email_validation import get_org_creator_user_id
from server.routes.org_models import (
CannotModifySelfError,
GitOrgAlreadyClaimedError,
@@ -170,26 +169,27 @@ async def list_user_orgs(
@org_router.post('', response_model=OrgResponse, status_code=status.HTTP_201_CREATED)
async def create_org(
org_data: OrgCreate,
- user_id: str = Depends(get_org_creator_user_id),
+ user_id: str = Depends(require_permission(Permission.CREATE_ORGANIZATION)),
) -> OrgResponse:
"""Create a new organization.
- By default this endpoint is restricted to authenticated users with an
- ``@openhands.dev`` email. When the ``OPEN_ORG_CREATION_ENABLED`` feature
- switch is enabled, any authenticated user is allowed to create an
- organization. The user who creates the organization automatically becomes
- its owner.
+ This endpoint allows authenticated users that hold the
+ ``CREATE_ORGANIZATION`` permission to create a new organization. In
+ practice this permission is only granted via the ``superadmin``
+ role; no regular,
+ org-scoped role carries it. The creator is not automatically added
+ as a member; a superadmin can provision the initial org users separately.
Args:
org_data: Organization creation data
- user_id: Authenticated user ID (injected by dependency)
+ user_id: Authenticated user ID (injected by ``require_permission``)
Returns:
OrgResponse: The created organization details
Raises:
- HTTPException: 403 if user email domain is not @openhands.dev and the
- ``OPEN_ORG_CREATION_ENABLED`` feature switch is disabled
+ HTTPException: 401 if the user is not authenticated
+ HTTPException: 403 if the user lacks ``CREATE_ORGANIZATION``
HTTPException: 409 if organization name already exists
HTTPException: 500 if creation fails
"""
@@ -208,6 +208,7 @@ async def create_org(
contact_name=org_data.contact_name,
contact_email=org_data.contact_email,
user_id=user_id,
+ add_creator_as_owner=False,
)
# Retrieve credits from LiteLLM
diff --git a/enterprise/server/routes/user_provisioning.py b/enterprise/server/routes/user_provisioning.py
index 38b7f212ac..af0b44b244 100644
--- a/enterprise/server/routes/user_provisioning.py
+++ b/enterprise/server/routes/user_provisioning.py
@@ -4,8 +4,9 @@ Admin endpoint for provisioning new users directly into an organization.
This is a privileged operation: it bypasses the normal sign-up flow
(email verification, TOS acceptance, OAuth IDP round-trip) and creates a
ready-to-use account on behalf of an org admin. Access is gated by the
-``PROVISION_USER`` permission, which is granted only to ``owner`` and
-``admin`` roles (see ``server.auth.authorization``).
+``PROVISION_USER`` permission, which is granted to org-scoped ``owner``
+and ``admin`` roles and explicit instance-level super roles (see
+``server.auth.authorization``).
Flow (POST ``/api/organizations/provision-user``):
@@ -21,7 +22,7 @@ Flow (POST ``/api/organizations/provision-user``):
shape), but with ``email_verified=True``, ``accepted_tos=now()``, and
``user_consents_to_analytics=True`` β€” no UI round-trips required.
5. Set up a LiteLLM integration for the user in the target org and add
- them as a member (default role ``member``).
+ them with the requested role (``member`` by default, ``admin``, or ``owner``).
6. Mint an API key bound to the target org and return it to the caller.
The caller receives the email, password (generated if not supplied) and
@@ -74,6 +75,7 @@ from __future__ import annotations
import secrets
import string
from datetime import datetime, timezone
+from typing import Literal
from uuid import UUID
from uuid import UUID as parse_uuid
@@ -103,8 +105,10 @@ from openhands.app_server.utils.logger import openhands_logger as logger
# keeping the routers split makes the intent explicit).
user_provisioning_router = APIRouter(prefix='/api/organizations', tags=['Orgs'])
-# Default role assigned to newly provisioned users in the target org.
-DEFAULT_PROVISIONED_ROLE = 'member'
+# Roles that can be assigned directly during provisioning. Provisioning
+# supports creating regular members, org admins, and org owners.
+ProvisionedRoleName = Literal['member', 'admin', 'owner']
+DEFAULT_PROVISIONED_ROLE: ProvisionedRoleName = 'member'
# Length of generated passwords. 24 characters from a 70-symbol alphabet
# yields well over 128 bits of entropy, which exceeds typical Keycloak
@@ -183,6 +187,13 @@ class ProvisionUserRequest(BaseModel):
max_length=255,
description='Optional name for the generated API key.',
)
+ role: ProvisionedRoleName = Field(
+ default=DEFAULT_PROVISIONED_ROLE,
+ description=(
+ 'Role to assign in the target organization. Provisioning supports '
+ 'member, admin, and owner.'
+ ),
+ )
class ProvisionUserResponse(BaseModel):
@@ -209,6 +220,7 @@ class ProvisionUserResponse(BaseModel):
api_key: str
user_id: str
org_id: str
+ role: str
async def _set_user_provisioned_flags(user_id: str) -> None:
@@ -250,7 +262,9 @@ async def provision_user(
The target org is the API key org if an API key is used, otherwise it is
taken from the ``X-Org-Id`` header (resolved by ``EFFECTIVE_ORG_ID``).
- The caller must hold the ``PROVISION_USER`` permission in that org (owner or admin).
+ The caller must hold the ``PROVISION_USER`` permission for that org.
+ Org-scoped owners/admins have it, and super roles may grant it explicitly
+ without org membership.
Returns the email, password (generated if not supplied) and the
new user's API key bound to the target org.
@@ -258,6 +272,7 @@ async def provision_user(
email = body.email.lower().strip()
password = body.password or _generate_password()
api_key_name = body.api_key_name or 'Initial API Key'
+ provisioned_role = body.role
# Confirm the target org actually exists before we mutate Keycloak.
# ``require_permission`` has already validated that the caller is a
@@ -397,11 +412,9 @@ async def provision_user(
else:
llm_api_key = llm_api_key_secret
- role = await RoleStore.get_role_by_name(DEFAULT_PROVISIONED_ROLE)
+ role = await RoleStore.get_role_by_name(provisioned_role)
if role is None:
- raise RuntimeError(
- f'Role {DEFAULT_PROVISIONED_ROLE!r} not found in database'
- )
+ raise RuntimeError(f'Role {provisioned_role!r} not found in database')
await OrgMemberStore.add_user_to_org(
org_id=target_org_id,
@@ -470,6 +483,7 @@ async def provision_user(
'caller_user_id': caller_user_id,
'provisioned_user_id': kc_user_id,
'target_org_id': str(target_org_id),
+ 'provisioned_role': provisioned_role,
# Intentionally omit email/password from the log line; the
# full audit trail of who provisioned whom is captured by
# caller_user_id + provisioned_user_id.
@@ -482,6 +496,7 @@ async def provision_user(
api_key=api_key,
user_id=kc_user_id,
org_id=str(target_org_id),
+ role=provisioned_role,
)
diff --git a/enterprise/storage/lite_llm_manager.py b/enterprise/storage/lite_llm_manager.py
index dd2fb1e821..6fd10d64de 100644
--- a/enterprise/storage/lite_llm_manager.py
+++ b/enterprise/storage/lite_llm_manager.py
@@ -124,6 +124,7 @@ class LiteLlmManager:
keycloak_user_id: str,
oss_settings: Settings,
create_user: bool,
+ add_user_to_team: bool = True,
) -> Settings | None:
logger.info(
'SettingsStore:update_settings_with_litellm_default:start',
@@ -199,81 +200,88 @@ class LiteLlmManager:
client, team_alias, org_id, team_budget
)
- if create_user:
- # create_user is True only when no OpenHands User row exists,
- # so a pre-existing LiteLLM record under this id is a stale
- # orphan (e.g. from an account reset). Reset it so _create_user
- # rebuilds a clean record rather than re-attaching it. Best-
- # effort: a failed reset must not block onboarding β€” _create_user
- # below still tolerates a surviving record (409).
- if await LiteLlmManager._user_exists(client, keycloak_user_id):
- logger.info(
- 'LiteLlmManager:create_entries:reset_stale_litellm_user',
- extra={'org_id': org_id, 'user_id': keycloak_user_id},
+ if add_user_to_team:
+ if create_user:
+ # create_user is True only when no OpenHands User row exists,
+ # so a pre-existing LiteLLM record under this id is a stale
+ # orphan (e.g. from an account reset). Reset it so _create_user
+ # rebuilds a clean record rather than re-attaching it. Best-
+ # effort: a failed reset must not block onboarding β€” _create_user
+ # below still tolerates a surviving record (409).
+ if await LiteLlmManager._user_exists(client, keycloak_user_id):
+ logger.info(
+ 'LiteLlmManager:create_entries:reset_stale_litellm_user',
+ extra={'org_id': org_id, 'user_id': keycloak_user_id},
+ )
+ try:
+ await LiteLlmManager._delete_user(
+ client, keycloak_user_id
+ )
+ except Exception as exc:
+ logger.warning(
+ 'LiteLlmManager:create_entries:reset_stale_litellm_user_failed',
+ extra={
+ 'org_id': org_id,
+ 'user_id': keycloak_user_id,
+ 'error': str(exc),
+ },
+ )
+
+ user_created = await LiteLlmManager._create_user(
+ client, keycloak_user_info.get('email'), keycloak_user_id
)
- try:
- await LiteLlmManager._delete_user(client, keycloak_user_id)
- except Exception as exc:
- logger.warning(
- 'LiteLlmManager:create_entries:reset_stale_litellm_user_failed',
+ if not user_created:
+ logger.error(
+ 'create_entries_failed_user_creation',
extra={
'org_id': org_id,
'user_id': keycloak_user_id,
- 'error': str(exc),
},
)
+ return None
- user_created = await LiteLlmManager._create_user(
- client, keycloak_user_info.get('email'), keycloak_user_id
+ # Verify user exists before proceeding with key generation
+ user_exists = await LiteLlmManager._user_exists(
+ client, keycloak_user_id
)
- if not user_created:
+ if not user_exists:
logger.error(
- 'create_entries_failed_user_creation',
+ 'create_entries_user_not_found_before_key_generation',
extra={
'org_id': org_id,
'user_id': keycloak_user_id,
+ 'create_user_flag': create_user,
},
)
return None
- # Verify user exists before proceeding with key generation
- user_exists = await LiteLlmManager._user_exists(
- client, keycloak_user_id
- )
- if not user_exists:
- logger.error(
- 'create_entries_user_not_found_before_key_generation',
- extra={
- 'org_id': org_id,
- 'user_id': keycloak_user_id,
- 'create_user_flag': create_user,
- },
+ await LiteLlmManager._add_user_to_team(
+ client, keycloak_user_id, org_id, team_budget
)
- return None
-
- await LiteLlmManager._add_user_to_team(
- client, keycloak_user_id, org_id, team_budget
- )
- # We delete the key if it already exists. In environments where multiple
- # installations are using the same keycloak and litellm instance, this
- # will mean other installations will have their key invalidated.
- key_alias = get_openhands_cloud_key_alias(keycloak_user_id, org_id)
- try:
- await LiteLlmManager._delete_key_by_alias(client, key_alias)
- except httpx.HTTPStatusError as ex:
- if ex.response and ex.response.status_code == 404:
- logger.debug(f'Key "{key_alias}" did not exist - continuing')
- else:
- raise
-
- key = await LiteLlmManager._generate_key(
- client,
- keycloak_user_id,
- org_id,
- key_alias,
- None,
- )
+ # We delete the key if it already exists. In environments where multiple
+ # installations are using the same keycloak and litellm instance, this
+ # will mean other installations will have their key invalidated.
+ key_alias = get_openhands_cloud_key_alias(keycloak_user_id, org_id)
+ try:
+ await LiteLlmManager._delete_key_by_alias(client, key_alias)
+ except httpx.HTTPStatusError as ex:
+ if ex.response and ex.response.status_code == 404:
+ logger.debug(
+ f'Key "{key_alias}" did not exist - continuing'
+ )
+ else:
+ raise
+
+ key = await LiteLlmManager._generate_key(
+ client,
+ keycloak_user_id,
+ org_id,
+ key_alias,
+ None,
+ )
+ else:
+ key = ''
oss_settings.update(
{
diff --git a/enterprise/storage/org_service.py b/enterprise/storage/org_service.py
index bf6466fac9..b351fac25c 100644
--- a/enterprise/storage/org_service.py
+++ b/enterprise/storage/org_service.py
@@ -53,7 +53,9 @@ class OrgService:
raise OrgNameExistsError(name)
@staticmethod
- async def create_litellm_integration(org_id: UUID, user_id: str) -> Settings:
+ async def create_litellm_integration(
+ org_id: UUID, user_id: str, add_user_to_litellm_team: bool = True
+ ) -> Settings:
"""
Create LiteLLM team integration for the organization.
@@ -69,7 +71,10 @@ class OrgService:
"""
try:
settings = await UserStore.create_default_settings(
- org_id=str(org_id), user_id=user_id, create_user=False
+ org_id=str(org_id),
+ user_id=user_id,
+ create_user=False,
+ add_user_to_litellm_team=add_user_to_litellm_team,
)
if not settings:
@@ -190,9 +195,10 @@ class OrgService:
contact_name: str,
contact_email: str,
user_id: str,
+ add_creator_as_owner: bool = True,
) -> Org:
"""
- Create a new organization with the specified user as owner.
+ Create a new organization, optionally with the specified user as owner.
This method orchestrates the complete organization creation workflow:
1. Validates that the organization name doesn't already exist
@@ -200,7 +206,7 @@ class OrgService:
3. Creates LiteLLM team integration
4. Creates the organization entity
5. Applies LiteLLM settings
- 6. Creates owner membership
+ 6. Creates owner membership when requested
7. Persists everything in a transaction
If database persistence fails, LiteLLM resources are cleaned up (compensation).
@@ -209,7 +215,8 @@ class OrgService:
name: Organization name (must be unique)
contact_name: Contact person name
contact_email: Contact email address
- user_id: ID of the user who will be the owner
+ user_id: ID of the user initiating creation
+ add_creator_as_owner: Whether to add the creator as org owner
Returns:
Org: The created organization object
@@ -231,7 +238,9 @@ class OrgService:
org_id = uuid4()
# Step 3: Create LiteLLM integration (external state created)
- settings = await OrgService.create_litellm_integration(org_id, user_id)
+ settings = await OrgService.create_litellm_integration(
+ org_id, user_id, add_user_to_litellm_team=add_creator_as_owner
+ )
# Steps 4-7: Create entities and persist with compensation
# If any of these fail, we need to clean up LiteLLM resources
@@ -247,14 +256,16 @@ class OrgService:
# Step 5: Apply LiteLLM settings
OrgService.apply_litellm_settings_to_org(org, settings)
- # Step 6: Get owner role and create member entity
- owner_role = await OrgService.get_owner_role()
- org_member = OrgService.create_org_member_entity(
- org_id=org_id,
- user_id=user_id,
- role_id=owner_role.id,
- settings=settings,
- )
+ org_member = None
+ if add_creator_as_owner:
+ # Step 6: Get owner role and create member entity
+ owner_role = await OrgService.get_owner_role()
+ org_member = OrgService.create_org_member_entity(
+ org_id=org_id,
+ user_id=user_id,
+ role_id=owner_role.id,
+ settings=settings,
+ )
# Step 7: Persist in transaction (critical section)
persisted_org = await OrgService._persist_with_compensation(
@@ -267,7 +278,7 @@ class OrgService:
'org_id': str(persisted_org.id),
'org_name': persisted_org.name,
'user_id': user_id,
- 'role': 'owner',
+ 'role': 'owner' if add_creator_as_owner else None,
},
)
@@ -293,7 +304,7 @@ class OrgService:
@staticmethod
async def _persist_with_compensation(
org: Org,
- org_member: OrgMember,
+ org_member: OrgMember | None,
org_id: UUID,
user_id: str,
) -> Org:
@@ -304,7 +315,7 @@ class OrgService:
Args:
org: Organization entity to persist
- org_member: Organization member entity to persist
+ org_member: Optional organization member entity to persist
org_id: Organization ID (for cleanup)
user_id: User ID (for cleanup)
diff --git a/enterprise/storage/org_store.py b/enterprise/storage/org_store.py
index b93ad3ecb9..7d02e61910 100644
--- a/enterprise/storage/org_store.py
+++ b/enterprise/storage/org_store.py
@@ -495,13 +495,13 @@ class OrgStore:
@staticmethod
async def persist_org_with_owner(
org: Org,
- org_member: OrgMember,
+ org_member: OrgMember | None,
) -> Org:
- """Persist organization and owner membership in a single transaction.
+ """Persist organization and optional owner membership in a single transaction.
Args:
org: Organization entity to persist
- org_member: Organization member entity to persist
+ org_member: Optional organization member entity to persist
Returns:
Org: The persisted organization object
@@ -511,7 +511,8 @@ class OrgStore:
"""
async with a_session_maker() as session:
session.add(org)
- session.add(org_member)
+ if org_member is not None:
+ session.add(org_member)
await session.commit()
await session.refresh(org)
return org
diff --git a/enterprise/storage/user.py b/enterprise/storage/user.py
index ab047f8ea5..154412f3fa 100644
--- a/enterprise/storage/user.py
+++ b/enterprise/storage/user.py
@@ -29,6 +29,8 @@ class User(Base):
id: Mapped[UUID] = mapped_column(primary_key=True, default=uuid4)
current_org_id: Mapped[UUID] = mapped_column(ForeignKey('org.id'), nullable=False)
+ # Instance-level super role; org membership roles live on OrgMember.role_id.
+ # Effective permissions are defined by SUPER_ROLE_PERMISSIONS.
role_id: Mapped[int | None] = mapped_column(ForeignKey('role.id'), nullable=True)
accepted_tos: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
enable_sound_notifications: Mapped[bool | None] = mapped_column(nullable=True)
@@ -50,6 +52,7 @@ class User(Base):
)
# Relationships
+ # Instance-level super-role relationship, not an org-scoped membership role.
role: Mapped['Role | None'] = relationship('Role', back_populates='users')
org_members: Mapped[list['OrgMember']] = relationship(
'OrgMember', back_populates='user'
diff --git a/enterprise/storage/user_store.py b/enterprise/storage/user_store.py
index 18cdfb1a64..227e6c22ba 100644
--- a/enterprise/storage/user_store.py
+++ b/enterprise/storage/user_store.py
@@ -15,7 +15,7 @@ from server.constants import (
get_default_llm_model,
)
from server.logger import logger
-from sqlalchemy import select, text
+from sqlalchemy import func, select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import selectinload
from storage.database import a_session_maker
@@ -81,6 +81,25 @@ class UserStore:
if existing_user:
return existing_user
+ # First-user β†’ superadmin: if the caller did not specify a
+ # super ``role_id`` and there are no existing users in the
+ # database, designate this user as a ``superadmin`` (the
+ # ``admin`` role attached via ``user.role_id``). Super-role
+ # permissions are explicit in ``server.auth.authorization``
+ # and do not inherit org-scoped admin permissions.
+ if role_id is None:
+ existing_user_count = await session.scalar(
+ select(func.count()).select_from(User)
+ )
+ if existing_user_count == 0:
+ superadmin_role = await RoleStore.get_role_by_name('admin', session)
+ if superadmin_role is not None:
+ role_id = superadmin_role.id
+ logger.info(
+ 'user_store:create_user:first_user_designated_superadmin',
+ extra={'user_id': user_id},
+ )
+
org = await session.get(Org, user_uuid)
org_created = False
if not org:
@@ -996,7 +1015,10 @@ class UserStore:
@staticmethod
async def create_default_settings(
- org_id: str, user_id: str, create_user: bool = True
+ org_id: str,
+ user_id: str,
+ create_user: bool = True,
+ add_user_to_litellm_team: bool = True,
) -> Optional['Settings']:
logger.info(
'UserStore:create_default_settings:start',
@@ -1017,7 +1039,11 @@ class UserStore:
from storage.lite_llm_manager import LiteLlmManager
settings = await LiteLlmManager.create_entries(
- org_id, user_id, default_settings, create_user
+ org_id,
+ user_id,
+ default_settings,
+ create_user,
+ add_user_to_team=add_user_to_litellm_team,
)
if not settings:
logger.info(
diff --git a/enterprise/tests/unit/routes/test_user_provisioning.py b/enterprise/tests/unit/routes/test_user_provisioning.py
index 7cc0eff7f9..8a46ed3a9e 100644
--- a/enterprise/tests/unit/routes/test_user_provisioning.py
+++ b/enterprise/tests/unit/routes/test_user_provisioning.py
@@ -48,7 +48,7 @@ class TestGeneratePassword:
class TestProvisionUserPermissionWiring:
- """The new permission must be present and assigned only to OWNER/ADMIN."""
+ """The provision permission is available to org admins and super roles."""
def test_permission_enum_includes_provision_user(self):
assert Permission.PROVISION_USER.value == 'provision_user'
@@ -62,6 +62,21 @@ class TestProvisionUserPermissionWiring:
def test_member_does_not_have_permission(self):
assert Permission.PROVISION_USER not in ROLE_PERMISSIONS[RoleName.MEMBER]
+ def test_superadmin_has_permission(self):
+ from server.auth.authorization import SUPER_ROLE_PERMISSIONS
+
+ assert Permission.PROVISION_USER in SUPER_ROLE_PERMISSIONS[RoleName.ADMIN]
+
+ def test_superowner_does_not_have_permission_yet(self):
+ from server.auth.authorization import SUPER_ROLE_PERMISSIONS
+
+ assert Permission.PROVISION_USER not in SUPER_ROLE_PERMISSIONS[RoleName.OWNER]
+
+ def test_supermember_does_not_have_permission(self):
+ from server.auth.authorization import SUPER_ROLE_PERMISSIONS
+
+ assert Permission.PROVISION_USER not in SUPER_ROLE_PERMISSIONS[RoleName.MEMBER]
+
class TestProvisionUserRequestValidation:
def test_email_is_required(self):
@@ -76,6 +91,18 @@ class TestProvisionUserRequestValidation:
req = ProvisionUserRequest(email='[email protected]')
assert req.password is None
+ def test_default_role_is_member(self):
+ req = ProvisionUserRequest(email='[email protected]')
+ assert req.role == 'member'
+
+ def test_admin_role_is_allowed(self):
+ req = ProvisionUserRequest(email='[email protected]', role='admin')
+ assert req.role == 'admin'
+
+ def test_owner_role_is_allowed(self):
+ req = ProvisionUserRequest(email='[email protected]', role='owner')
+ assert req.role == 'owner'
+
class TestProvisionUserHandler:
"""End-to-end handler test with all external collaborators mocked."""
@@ -126,6 +153,7 @@ class TestProvisionUserHandler:
role_mock = MagicMock()
role_mock.id = 42
+ role_store_mock = AsyncMock(return_value=role_mock)
api_key_store_mock = MagicMock()
api_key_store_mock.create_api_key = AsyncMock(
@@ -168,8 +196,7 @@ class TestProvisionUserHandler:
),
patch(
'server.routes.user_provisioning.RoleStore.get_role_by_name',
- new_callable=AsyncMock,
- return_value=role_mock,
+ role_store_mock,
),
patch(
'server.routes.user_provisioning.OrgMemberStore.add_user_to_org',
@@ -199,6 +226,7 @@ class TestProvisionUserHandler:
'api_key_store': api_key_store_mock,
'set_flags': set_flags_mock,
'add_user_to_org': add_user_to_org_mock,
+ 'role_store': role_store_mock,
'remove_member': remove_member_mock,
'delete_org_cascade': delete_org_cascade_mock,
}
@@ -237,12 +265,18 @@ class TestProvisionUserHandler:
assert resp.api_key == 'sk-oh-generated-api-key'
assert resp.user_id == new_user_id
assert resp.org_id == str(target_org_id)
+ assert resp.role == 'member'
# Offline token must have been stored against the newly created
# Keycloak user id, not against the caller.
handles['token_manager'].store_offline_token.assert_awaited_once_with(
user_id=new_user_id, offline_token='offline-refresh-token'
)
+ handles['role_store'].assert_awaited_once_with('member')
+ handles['add_user_to_org'].assert_awaited_once()
+ add_kwargs = handles['add_user_to_org'].await_args.kwargs
+ assert add_kwargs['role_id'] == 42
+
# API key must be bound to the target org, not the personal one.
handles['api_key_store'].create_api_key.assert_awaited_once()
kwargs = handles['api_key_store'].create_api_key.await_args.kwargs
@@ -253,6 +287,50 @@ class TestProvisionUserHandler:
handles['remove_member'].assert_not_awaited()
handles['token_manager'].delete_keycloak_user.assert_not_awaited()
+ @pytest.mark.asyncio
+ async def test_can_provision_admin_role(
+ self, caller_user_id, target_org_id, new_user_id
+ ):
+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)
+ with self._enter_all(patches):
+ resp = await provision_user(
+ body=ProvisionUserRequest(
+ password='SuperSecret-1234',
+ role='admin',
+ ),
+ caller_user_id=caller_user_id,
+ target_org_id=target_org_id,
+ )
+
+ assert resp.role == 'admin'
+ handles['role_store'].assert_awaited_once_with('admin')
+ handles['add_user_to_org'].assert_awaited_once()
+ add_kwargs = handles['add_user_to_org'].await_args.kwargs
+ assert add_kwargs['role_id'] == 42
+
+ @pytest.mark.asyncio
+ async def test_can_provision_owner_role(
+ self, caller_user_id, target_org_id, new_user_id
+ ):
+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)
+ with self._enter_all(patches):
+ resp = await provision_user(
+ body=ProvisionUserRequest(
+ password='SuperSecret-1234',
+ role='owner',
+ ),
+ caller_user_id=caller_user_id,
+ target_org_id=target_org_id,
+ )
+
+ assert resp.role == 'owner'
+ handles['role_store'].assert_awaited_once_with('owner')
+ handles['add_user_to_org'].assert_awaited_once()
+ add_kwargs = handles['add_user_to_org'].await_args.kwargs
+ assert add_kwargs['role_id'] == 42
+
@pytest.mark.asyncio
async def test_generates_password_when_not_supplied(
self, caller_user_id, target_org_id, new_user_id
diff --git a/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py b/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
index d9b761baad..38835a0b3c 100644
--- a/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
+++ b/enterprise/tests/unit/server/auth/test_saas_user_auth_effective_org.py
@@ -62,13 +62,33 @@ def other_org_id():
return uuid.uuid4()
-async def _seed_minimal(session_maker, user_id_str, current_org_id, *extra_org_ids):
- """Create a role, org(s), user, and org_member rows in the in-memory DB."""
+async def _seed_minimal(
+ session_maker,
+ user_id_str,
+ current_org_id,
+ *extra_org_ids,
+ super_role_name: str | None = None,
+):
+ """Create a role, org(s), user, and org_member rows in the in-memory DB.
+
+ When ``super_role_name`` is provided, also seed a separate role row
+ with that name and assign it to the user via ``User.role_id``. This
+ is what ``get_user_super_role`` consults; any non-None value flips
+ the user into a "super" role for tests that exercise the super-role
+ bypass in :meth:`SaasUserAuth._resolve_org_id`.
+ """
async with session_maker() as session:
role = Role(name='member', rank=3)
session.add(role)
await session.flush()
+ super_role_id: int | None = None
+ if super_role_name is not None:
+ super_role = Role(name=super_role_name, rank=0)
+ session.add(super_role)
+ await session.flush()
+ super_role_id = super_role.id
+
all_org_ids = [current_org_id, *extra_org_ids]
for o in all_org_ids:
session.add(
@@ -86,6 +106,7 @@ async def _seed_minimal(session_maker, user_id_str, current_org_id, *extra_org_i
id=uuid.UUID(user_id_str),
current_org_id=current_org_id,
user_consents_to_analytics=True,
+ role_id=super_role_id,
)
)
await session.flush()
@@ -180,6 +201,34 @@ class TestGetEffectiveOrgId:
assert exc_info.value.status_code == 403
+ @pytest.mark.asyncio
+ async def test_server_side_override_non_member_403_even_for_super_user(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ """The override path is for trusted server-side resolver code.
+
+ Its membership check is defense-in-depth against buggy resolver
+ contexts setting a wrong override; the super-role bypass only
+ applies to the client-driven ``X-Org-Id`` header. This test
+ pins that design so the two paths can't drift.
+ """
+ await _seed_minimal(
+ async_session_maker,
+ user_id,
+ org_id,
+ super_role_name='owner',
+ )
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ effective_org_id_override=other_org_id,
+ )
+ with _stores_patched(async_session_maker)[2]:
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_effective_org_id()
+
+ assert exc_info.value.status_code == 403
+
@pytest.mark.asyncio
async def test_server_side_override_api_key_org_mismatch_raises_403(
self, user_id, org_id, other_org_id
@@ -263,6 +312,88 @@ class TestGetEffectiveOrgId:
assert exc_info.value.status_code == 403
+ @pytest.mark.asyncio
+ async def test_header_non_member_super_role_bypasses_membership_check(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ """Regression for the super-role / EFFECTIVE_ORG_ID inconsistency.
+
+ A user with a super role (``user.role_id`` set) that targets a
+ non-member org via ``X-Org-Id`` must get the org id back. The
+ route's ``require_permission`` dependency is the authoritative
+ check for the actual permission; this resolver should not 403
+ such requests at the coarse membership gate.
+ """
+ # Seed user as member of ``org_id`` and as a super-role holder.
+ await _seed_minimal(
+ async_session_maker,
+ user_id,
+ org_id,
+ super_role_name='owner',
+ )
+ # Add ``other_org_id`` as a real org the user is *not* a member of.
+ async with async_session_maker() as session:
+ session.add(
+ Org(
+ id=other_org_id,
+ name='Outside Org',
+ org_version=1,
+ enable_proactive_conversation_starters=True,
+ )
+ )
+ await session.commit()
+
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header=str(other_org_id),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ _stores_patched(async_session_maker)[3],
+ ):
+ effective = await user_auth.get_effective_org_id()
+
+ assert effective == other_org_id
+
+ @pytest.mark.asyncio
+ async def test_header_non_member_without_super_role_still_403(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ """Ensure the super-role bypass is opt-in: regular users still 403.
+
+ Mirrors :meth:`test_header_with_non_member_org_raises_403` but
+ is named to make the intent of the bypass explicit -- the gate
+ is only relaxed when ``user.role_id`` is set.
+ """
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ async with async_session_maker() as session:
+ session.add(
+ Org(
+ id=other_org_id,
+ name='Outside Org',
+ org_version=1,
+ enable_proactive_conversation_starters=True,
+ )
+ )
+ await session.commit()
+
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header=str(other_org_id),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ _stores_patched(async_session_maker)[3],
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_effective_org_id()
+
+ assert exc_info.value.status_code == 403
+
@pytest.mark.asyncio
async def test_malformed_header_raises_400(self, async_session_maker, user_id):
user_auth = SaasUserAuth(
@@ -338,3 +469,116 @@ class TestGetEffectiveOrgId:
second = await user_auth.get_effective_org_id()
assert first == second == other_org_id
assert user_auth._effective_org_id_resolved is True
+
+
+class TestGetTargetOrgIdForPermissionCheck:
+ """Tests for ``SaasUserAuth.get_target_org_id_for_permission_check``.
+
+ Resolution must mirror ``get_effective_org_id`` for API-key binding
+ and header parsing, but **must not** verify that the user is an
+ ``org_member`` of the resolved org -- super-role users need to be
+ able to target orgs they have not joined.
+ """
+
+ @pytest.mark.asyncio
+ async def test_header_targets_non_member_org_without_403(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ # Seed the user as a member of `org_id` only, not `other_org_id`.
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ async with async_session_maker() as session:
+ session.add(
+ Org(
+ id=other_org_id,
+ name='Outside Org',
+ org_version=1,
+ enable_proactive_conversation_starters=True,
+ )
+ )
+ await session.commit()
+
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header=str(other_org_id),
+ )
+ with (
+ _stores_patched(async_session_maker)[0],
+ _stores_patched(async_session_maker)[2],
+ ):
+ target = await user_auth.get_target_org_id_for_permission_check()
+
+ # Non-member header value must still be returned -- the caller
+ # (require_permission) decides via the org/super role fallback.
+ assert target == other_org_id
+
+ @pytest.mark.asyncio
+ async def test_no_header_falls_back_to_current_org(
+ self, async_session_maker, user_id, org_id
+ ):
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ )
+ with _stores_patched(async_session_maker)[0]:
+ target = await user_auth.get_target_org_id_for_permission_check()
+
+ assert target == org_id
+
+ @pytest.mark.asyncio
+ async def test_malformed_header_still_raises_400(self, user_id):
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ _x_org_id_header='not-a-uuid',
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_target_org_id_for_permission_check()
+ assert exc_info.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_api_key_header_mismatch_still_raises_403(
+ self, user_id, org_id, other_org_id
+ ):
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ api_key_org_id=org_id,
+ _x_org_id_header=str(other_org_id),
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_target_org_id_for_permission_check()
+ assert exc_info.value.status_code == 403
+
+ @pytest.mark.asyncio
+ async def test_api_key_pins_org_when_no_header(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ api_key_org_id=other_org_id,
+ )
+ target = await user_auth.get_target_org_id_for_permission_check()
+ assert target == other_org_id
+
+ @pytest.mark.asyncio
+ async def test_server_side_override_still_requires_membership(
+ self, async_session_maker, user_id, org_id, other_org_id
+ ):
+ # ``effective_org_id_override`` is a trusted server-side
+ # mechanism with its own membership check -- super-role bypass
+ # only applies to client-supplied X-Org-Id headers, not to
+ # the override path.
+ await _seed_minimal(async_session_maker, user_id, org_id)
+ user_auth = SaasUserAuth(
+ user_id=user_id,
+ refresh_token=SecretStr('mock'),
+ effective_org_id_override=other_org_id,
+ )
+ with _stores_patched(async_session_maker)[2]:
+ with pytest.raises(HTTPException) as exc_info:
+ await user_auth.get_target_org_id_for_permission_check()
+ assert exc_info.value.status_code == 403
diff --git a/enterprise/tests/unit/server/routes/conftest.py b/enterprise/tests/unit/server/routes/conftest.py
new file mode 100644
index 0000000000..00caf3b0c1
--- /dev/null
+++ b/enterprise/tests/unit/server/routes/conftest.py
@@ -0,0 +1,26 @@
+"""Shared fixtures for route-level integration tests.
+
+These tests exercise FastAPI routes that go through ``require_permission``.
+Most of them only stub ``get_user_org_role`` and predate the user-scoped
+"super" role lookup, so without help they hit an unpatched
+``UserStore.get_user_by_id`` against a bare in-memory DB and explode with
+``no such table: user``. The autouse fixture below defaults the super-role
+lookup to ``None`` for every test in this directory. Tests that want to
+exercise super-role behavior can stack their own ``patch`` over it.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+
[email protected](autouse=True)
+def _default_no_super_role():
+ """Default ``get_user_super_role`` to return ``None`` for all route tests."""
+ with patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=None),
+ ):
+ yield
diff --git a/enterprise/tests/unit/server/routes/test_orgs.py b/enterprise/tests/unit/server/routes/test_orgs.py
index 0bf8ed21a8..cddac28b68 100644
--- a/enterprise/tests/unit/server/routes/test_orgs.py
+++ b/enterprise/tests/unit/server/routes/test_orgs.py
@@ -11,7 +11,6 @@ import httpx
import pytest
from fastapi import FastAPI, HTTPException, Request, status
from fastapi.testclient import TestClient
-from server.email_validation import get_admin_user_id, get_org_creator_user_id
from server.routes.org_models import (
CannotModifySelfError,
InsufficientPermissionError,
@@ -53,27 +52,53 @@ TEST_USER_ID = str(uuid.uuid4())
@pytest.fixture
def mock_app():
- """Create a test FastAPI app with organization routes and mocked auth."""
+ """Create a test FastAPI app with organization routes and ``get_user_id`` mocked.
+
+ Routes that go through ``require_permission`` rely on the autouse
+ ``_default_no_super_role`` fixture in ``conftest.py`` to default the
+ super-role lookup to ``None``. Tests that need a specific super or
+ org role stack their own ``patch`` on top.
+ """
app = FastAPI()
app.include_router(org_router)
- # Override the auth dependency to return a test user
- def mock_get_admin_user_id():
- return TEST_USER_ID
-
def mock_get_user_id():
return TEST_USER_ID
- def mock_get_org_creator_user_id():
- return TEST_USER_ID
-
- app.dependency_overrides[get_admin_user_id] = mock_get_admin_user_id
app.dependency_overrides[get_user_id] = mock_get_user_id
- app.dependency_overrides[get_org_creator_user_id] = mock_get_org_creator_user_id
return app
+def grant_create_organization():
+ """Make ``CREATE_ORGANIZATION`` succeed by faking a ``superadmin`` role.
+
+ The create-org route is gated by
+ ``require_permission(Permission.CREATE_ORGANIZATION)``, which is only
+ granted via a super role. ``require_permission`` always looks up the
+ org-scoped role first via ``get_user_org_role`` -- without a patch
+ that call hits ``OrgMemberStore`` against a bare in-memory SQLite DB
+ that has no ``org_member`` table. This fixture short-circuits the
+ org-role lookup to ``None`` and stacks a ``superadmin`` patch over
+ the conftest-level ``get_user_super_role -> None`` default so the
+ success path of the create-org route works without per-test plumbing.
+ """
+ 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
+
+
@pytest.fixture
def mock_request():
"""Create a mock request object."""
@@ -100,7 +125,7 @@ def target_user_id():
@pytest.mark.asyncio
-async def test_create_org_success(mock_app):
+async def test_create_org_success(mock_app, grant_create_organization):
"""
GIVEN: Valid organization creation request
WHEN: POST /api/organizations is called
@@ -130,7 +155,7 @@ async def test_create_org_success(mock_app):
patch(
'server.routes.orgs.OrgService.create_org_with_owner',
AsyncMock(return_value=mock_org),
- ),
+ ) as create_org_mock,
patch(
'server.routes.orgs.OrgService.get_org_credits',
AsyncMock(return_value=100.0),
@@ -143,6 +168,13 @@ async def test_create_org_success(mock_app):
# Assert
assert response.status_code == status.HTTP_201_CREATED
+ create_org_mock.assert_awaited_once_with(
+ name='Test Organization',
+ contact_name='John Doe',
+ contact_email='[email protected]',
+ user_id=TEST_USER_ID,
+ add_creator_as_owner=False,
+ )
response_data = response.json()
assert response_data['name'] == 'Test Organization'
assert response_data['contact_name'] == 'John Doe'
@@ -156,7 +188,7 @@ async def test_create_org_success(mock_app):
@pytest.mark.asyncio
-async def test_create_org_invalid_email(mock_app):
+async def test_create_org_invalid_email(mock_app, grant_create_organization):
"""
GIVEN: Request with invalid email format
WHEN: POST /api/organizations is called
@@ -179,7 +211,7 @@ async def test_create_org_invalid_email(mock_app):
@pytest.mark.asyncio
-async def test_create_org_empty_name(mock_app):
+async def test_create_org_empty_name(mock_app, grant_create_organization):
"""
GIVEN: Request with empty organization name
WHEN: POST /api/organizations is called
@@ -202,7 +234,7 @@ async def test_create_org_empty_name(mock_app):
@pytest.mark.asyncio
-async def test_create_org_duplicate_name(mock_app):
+async def test_create_org_duplicate_name(mock_app, grant_create_organization):
"""
GIVEN: Organization name already exists
WHEN: POST /api/organizations is called
@@ -230,7 +262,7 @@ async def test_create_org_duplicate_name(mock_app):
@pytest.mark.asyncio
-async def test_create_org_litellm_failure(mock_app):
+async def test_create_org_litellm_failure(mock_app, grant_create_organization):
"""
GIVEN: LiteLLM integration fails
WHEN: POST /api/organizations is called
@@ -258,7 +290,7 @@ async def test_create_org_litellm_failure(mock_app):
@pytest.mark.asyncio
-async def test_create_org_database_failure(mock_app):
+async def test_create_org_database_failure(mock_app, grant_create_organization):
"""
GIVEN: Database operation fails
WHEN: POST /api/organizations is called
@@ -286,7 +318,7 @@ async def test_create_org_database_failure(mock_app):
@pytest.mark.asyncio
-async def test_create_org_unexpected_error(mock_app):
+async def test_create_org_unexpected_error(mock_app, grant_create_organization):
"""
GIVEN: Unexpected error occurs
WHEN: POST /api/organizations is called
@@ -318,17 +350,19 @@ async def test_create_org_unauthorized():
"""
GIVEN: User is not authenticated
WHEN: POST /api/organizations is called
- THEN: 401 Unauthorized error is returned
+ THEN: 401 Unauthorized error is returned by the
+ ``require_permission`` dependency
"""
# 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')
+ # ``require_permission`` reads ``get_user_id``; returning ``None``
+ # makes it raise 401 before any role lookup runs.
+ def mock_unauthenticated():
+ return None
- app.dependency_overrides[get_org_creator_user_id] = mock_unauthenticated
+ app.dependency_overrides[get_user_id] = mock_unauthenticated
request_data = {
'name': 'Test Organization',
@@ -346,23 +380,25 @@ async def test_create_org_unauthorized():
@pytest.mark.asyncio
-async def test_create_org_forbidden_non_openhands_email():
+async def test_create_org_forbidden_lacks_create_organization():
"""
- GIVEN: User email is not @openhands.dev
+ GIVEN: An authenticated user who holds neither an org-scoped role
+ with ``CREATE_ORGANIZATION`` (none do) nor a super role that
+ grants it (only explicit instance-level super roles do)
WHEN: POST /api/organizations is called
- THEN: 403 Forbidden error is returned
+ THEN: 403 Forbidden is returned. ``require_permission`` raises with
+ the "not a member of this organization" detail when the
+ authenticated user is not a member of the target org and has
+ no super role granting the permission.
"""
# Arrange
app = FastAPI()
app.include_router(org_router)
- # Override to simulate [email protected] user
- async def mock_forbidden():
- raise HTTPException(
- status_code=403, detail='Access restricted to @openhands.dev users'
- )
+ def mock_get_user_id():
+ return TEST_USER_ID
- app.dependency_overrides[get_org_creator_user_id] = mock_forbidden
+ app.dependency_overrides[get_user_id] = mock_get_user_id
request_data = {
'name': 'Test Organization',
@@ -370,18 +406,170 @@ async def test_create_org_forbidden_non_openhands_email():
'contact_email': '[email protected]',
}
- client = TestClient(app)
-
- # Act
- response = client.post('/api/organizations', json=request_data)
+ # No org role and no super role -> CREATE_ORGANIZATION cannot be granted.
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=None),
+ ),
+ ):
+ client = TestClient(app)
+ response = client.post('/api/organizations', json=request_data)
# Assert
assert response.status_code == status.HTTP_403_FORBIDDEN
- assert 'openhands.dev' in response.json()['detail'].lower()
+ assert 'not a member' in response.json()['detail'].lower()
@pytest.mark.asyncio
-async def test_create_org_is_not_personal(mock_app):
+async def test_create_org_forbidden_for_supermember():
+ """
+ GIVEN: An authenticated user whose super role is ``supermember``
+ (which does NOT grant ``CREATE_ORGANIZATION``)
+ WHEN: POST /api/organizations is called
+ THEN: 403 Forbidden is returned -- only explicit instance-level
+ super roles may create organizations.
+ ``require_permission`` raises with the "not a member of this
+ organization" detail because the user has no org membership
+ either.
+ """
+ app = FastAPI()
+ app.include_router(org_router)
+
+ def mock_get_user_id():
+ return TEST_USER_ID
+
+ app.dependency_overrides[get_user_id] = mock_get_user_id
+
+ supermember = MagicMock()
+ supermember.name = 'member'
+
+ request_data = {
+ 'name': 'Test Organization',
+ 'contact_name': 'John Doe',
+ 'contact_email': '[email protected]',
+ }
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=supermember),
+ ),
+ ):
+ client = TestClient(app)
+ response = client.post('/api/organizations', json=request_data)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert 'not a member' in response.json()['detail'].lower()
+
+
+async def test_create_org_allowed_for_superadmin():
+ """
+ GIVEN: An authenticated user whose super role is ``superadmin``
+ WHEN: POST /api/organizations is called
+ THEN: The request is authorized and 201 Created is returned.
+ """
+ app = FastAPI()
+ app.include_router(org_router)
+
+ def mock_get_user_id():
+ return TEST_USER_ID
+
+ app.dependency_overrides[get_user_id] = mock_get_user_id
+
+ super_role = MagicMock()
+ super_role.name = 'admin'
+
+ org_id = uuid.uuid4()
+ mock_org = Org(
+ id=org_id,
+ name='Test Organization',
+ contact_name='John Doe',
+ contact_email='[email protected]',
+ org_version=5,
+ )
+
+ request_data = {
+ 'name': 'Test Organization',
+ 'contact_name': 'John Doe',
+ 'contact_email': '[email protected]',
+ }
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=super_role),
+ ),
+ patch(
+ 'server.routes.orgs.OrgService.create_org_with_owner',
+ AsyncMock(return_value=mock_org),
+ ),
+ patch(
+ 'server.routes.orgs.OrgService.get_org_credits',
+ AsyncMock(return_value=0.0),
+ ),
+ ):
+ client = TestClient(app)
+ response = client.post('/api/organizations', json=request_data)
+
+ assert response.status_code == status.HTTP_201_CREATED
+
+
+async def test_create_org_forbidden_for_superowner():
+ """
+ GIVEN: An authenticated user whose user.role_id points to owner
+ WHEN: POST /api/organizations is called
+ THEN: The request is forbidden because superowner is not functional yet.
+ """
+ app = FastAPI()
+ app.include_router(org_router)
+
+ def mock_get_user_id():
+ return TEST_USER_ID
+
+ app.dependency_overrides[get_user_id] = mock_get_user_id
+
+ super_role = MagicMock()
+ super_role.name = 'owner'
+
+ request_data = {
+ 'name': 'Test Organization',
+ 'contact_name': 'John Doe',
+ 'contact_email': '[email protected]',
+ }
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=super_role),
+ ),
+ ):
+ client = TestClient(app)
+ response = client.post('/api/organizations', json=request_data)
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+
+
+async def test_create_org_is_not_personal(mock_app, grant_create_organization):
"""
GIVEN: Admin creates a new team organization
WHEN: POST /api/organizations is called
@@ -425,7 +613,9 @@ async def test_create_org_is_not_personal(mock_app):
@pytest.mark.asyncio
-async def test_create_org_sensitive_fields_not_exposed(mock_app):
+async def test_create_org_sensitive_fields_not_exposed(
+ mock_app, grant_create_organization
+):
"""
GIVEN: Organization is created successfully
WHEN: Response is returned
diff --git a/enterprise/tests/unit/test_authorization.py b/enterprise/tests/unit/test_authorization.py
index 4e3f329ef8..cb17137c50 100644
--- a/enterprise/tests/unit/test_authorization.py
+++ b/enterprise/tests/unit/test_authorization.py
@@ -11,13 +11,17 @@ import pytest
from fastapi import HTTPException
from server.auth.authorization import (
ROLE_PERMISSIONS,
+ SUPER_ROLE_PERMISSIONS,
Permission,
RoleName,
get_api_key_org_id_from_request,
get_role_permissions,
+ get_super_role_permissions,
get_user_org_role,
+ get_user_super_role,
has_permission,
require_permission,
+ super_role_name,
)
# =============================================================================
@@ -56,6 +60,7 @@ class TestPermission:
assert Permission.VIEW_ORG_SETTINGS.value == 'view_org_settings'
assert Permission.CHANGE_ORGANIZATION_NAME.value == 'change_organization_name'
assert Permission.DELETE_ORGANIZATION.value == 'delete_organization'
+ assert Permission.CREATE_ORGANIZATION.value == 'create_organization'
assert Permission.MANAGE_AUTOMATIONS.value == 'manage_automations'
assert Permission.VIEW_ORG_CONVERSATIONS.value == 'view_org_conversations'
@@ -198,6 +203,19 @@ class TestRolePermissions:
assert Permission.DELETE_ORGANIZATION not in member_perms
assert Permission.VIEW_ORG_CONVERSATIONS not in member_perms
+ def test_create_organization_is_not_org_scoped_for_any_role(self):
+ """
+ GIVEN: ROLE_PERMISSIONS mapping
+ WHEN: Checking CREATE_ORGANIZATION across regular roles
+ THEN: No regular org-scoped role grants CREATE_ORGANIZATION
+ (it is a super-only permission).
+ """
+ for role_name, perms in ROLE_PERMISSIONS.items():
+ assert Permission.CREATE_ORGANIZATION not in perms, (
+ f'{role_name.value} unexpectedly grants CREATE_ORGANIZATION '
+ 'at the org-scoped level'
+ )
+
# =============================================================================
# Tests for get_role_permissions function
@@ -462,6 +480,21 @@ def _create_mock_request(api_key_org_id=None):
return mock_request
+def _no_super_role():
+ """Default ``get_user_super_role`` to ``None`` for tests that don't
+ care about the super-role fallback. Individual tests can still
+ re-patch ``server.auth.authorization.get_user_super_role`` inside
+ their own ``with patch(...)`` block to override this default.
+ """
+ with patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=None),
+ ) as mocked:
+ yield mocked
+
+
[email protected]('_no_super_role')
class TestRequirePermission:
"""Tests for require_permission dependency factory."""
@@ -693,6 +726,7 @@ class TestRequirePermission:
# =============================================================================
[email protected]('_no_super_role')
class TestPermissionScenarios:
"""Tests for real-world permission scenarios."""
@@ -830,6 +864,7 @@ class TestPermissionScenarios:
# =============================================================================
[email protected]('_no_super_role')
class TestApiKeyOrgValidation:
"""Tests for API key organization binding validation in require_permission."""
@@ -1247,3 +1282,464 @@ class TestRequireFinancialDataAccess:
assert exc_info.value.status_code == 403
assert 'API key is not authorized' in exc_info.value.detail
+
+
+# =============================================================================
+# Tests for super-role helpers and fallback logic
+# =============================================================================
+
+
+class TestSuperRoleName:
+ """Tests for the ``super_role_name`` helper."""
+
+ def test_prepends_super_prefix(self):
+ """
+ GIVEN: a regular role name
+ WHEN: super_role_name is called
+ THEN: the returned label is the regular role name prefixed with "super"
+ """
+ assert super_role_name('owner') == 'superowner'
+ assert super_role_name('admin') == 'superadmin'
+ assert super_role_name('member') == 'supermember'
+
+
+class TestSuperRolePermissions:
+ """Tests for explicit super-role permission mappings."""
+
+ def test_super_role_permissions_are_explicit(self):
+ """
+ GIVEN: SUPER_ROLE_PERMISSIONS mapping
+ WHEN: comparing it to the org-scoped role mappings
+ THEN: super roles do not inherit org-scoped permissions implicitly.
+ """
+ assert SUPER_ROLE_PERMISSIONS[RoleName.OWNER] == frozenset()
+ assert SUPER_ROLE_PERMISSIONS[RoleName.ADMIN] == frozenset(
+ [Permission.CREATE_ORGANIZATION, Permission.PROVISION_USER]
+ )
+ assert SUPER_ROLE_PERMISSIONS[RoleName.MEMBER] == frozenset()
+
+ def test_super_role_keys_match_regular_role_keys(self):
+ """
+ GIVEN: super roles parallel regular roles 1:1
+ WHEN: comparing the keysets of ROLE_PERMISSIONS and SUPER_ROLE_PERMISSIONS
+ THEN: they match exactly
+ """
+ assert set(SUPER_ROLE_PERMISSIONS.keys()) == set(ROLE_PERMISSIONS.keys())
+
+ def test_get_super_role_permissions_owner_is_not_functional_yet(self):
+ """
+ GIVEN: role name 'owner'
+ WHEN: get_super_role_permissions is called
+ THEN: no instance-level permissions are currently assigned.
+ """
+ perms = get_super_role_permissions('owner')
+ assert perms == frozenset()
+
+ def test_get_super_role_permissions_invalid_role(self):
+ """
+ GIVEN: invalid role name
+ WHEN: get_super_role_permissions is called
+ THEN: an empty frozenset is returned
+ """
+ assert get_super_role_permissions('not_a_role') == frozenset()
+
+ def test_only_superadmin_grants_instance_org_management(self):
+ """
+ GIVEN: SUPER_ROLE_PERMISSIONS mapping
+ WHEN: looking up instance-level org management permissions
+ THEN: only superadmin carries CREATE_ORGANIZATION and PROVISION_USER.
+ """
+ assert (
+ Permission.CREATE_ORGANIZATION not in SUPER_ROLE_PERMISSIONS[RoleName.OWNER]
+ )
+ assert Permission.CREATE_ORGANIZATION in SUPER_ROLE_PERMISSIONS[RoleName.ADMIN]
+ assert (
+ Permission.CREATE_ORGANIZATION
+ not in SUPER_ROLE_PERMISSIONS[RoleName.MEMBER]
+ )
+ assert Permission.PROVISION_USER not in SUPER_ROLE_PERMISSIONS[RoleName.OWNER]
+ assert Permission.PROVISION_USER in SUPER_ROLE_PERMISSIONS[RoleName.ADMIN]
+ assert Permission.PROVISION_USER not in SUPER_ROLE_PERMISSIONS[RoleName.MEMBER]
+
+
+class TestHasPermissionSuper:
+ """Tests for ``has_permission`` with the ``is_super`` flag."""
+
+ def test_super_admin_has_create_organization(self):
+ """
+ GIVEN: an admin role evaluated as a super role
+ WHEN: checking CREATE_ORGANIZATION
+ THEN: the explicit instance-level permission is granted.
+ """
+ mock_role = MagicMock()
+ mock_role.name = 'admin'
+ assert (
+ has_permission(mock_role, Permission.CREATE_ORGANIZATION, is_super=True)
+ is True
+ )
+
+ def test_super_admin_does_not_inherit_org_admin_permissions(self):
+ """
+ GIVEN: an admin role evaluated as a super role
+ WHEN: checking an org-admin permission
+ THEN: the permission is not granted unless explicitly listed.
+ """
+ mock_role = MagicMock()
+ mock_role.name = 'admin'
+ assert (
+ has_permission(mock_role, Permission.MANAGE_SECRETS, is_super=True) is False
+ )
+
+ def test_super_owner_does_not_inherit_org_owner_permissions(self):
+ """
+ GIVEN: owner role evaluated as a super role
+ WHEN: checking DELETE_ORGANIZATION
+ THEN: the permission is not granted until explicitly listed.
+ """
+ mock_role = MagicMock()
+ mock_role.name = 'owner'
+ assert (
+ has_permission(mock_role, Permission.DELETE_ORGANIZATION, is_super=True)
+ is False
+ )
+
+
+class TestGetUserSuperRole:
+ """Tests for the ``get_user_super_role`` helper."""
+
+ @pytest.mark.asyncio
+ async def test_returns_role_when_user_has_role_id(self):
+ """
+ GIVEN: a user with a non-null role_id
+ WHEN: get_user_super_role is called
+ THEN: the corresponding Role is returned
+ """
+ user_id = str(uuid4())
+
+ mock_user = MagicMock()
+ mock_user.role_id = 42
+
+ mock_role = MagicMock()
+ mock_role.name = 'admin'
+
+ with (
+ patch(
+ 'server.auth.authorization.UserStore.get_user_by_id',
+ AsyncMock(return_value=mock_user),
+ ),
+ patch(
+ 'server.auth.authorization.RoleStore.get_role_by_id',
+ AsyncMock(return_value=mock_role),
+ ) as mock_get_role,
+ ):
+ result = await get_user_super_role(user_id)
+ assert result is mock_role
+ mock_get_role.assert_awaited_once_with(42)
+
+ @pytest.mark.asyncio
+ async def test_returns_none_when_user_missing(self):
+ """
+ GIVEN: no user with the given id
+ WHEN: get_user_super_role is called
+ THEN: None is returned
+ """
+ user_id = str(uuid4())
+ with patch(
+ 'server.auth.authorization.UserStore.get_user_by_id',
+ AsyncMock(return_value=None),
+ ):
+ assert await get_user_super_role(user_id) is None
+
+ @pytest.mark.asyncio
+ async def test_returns_none_when_role_id_is_none(self):
+ """
+ GIVEN: a user with role_id == None
+ WHEN: get_user_super_role is called
+ THEN: None is returned (no DB lookup for the role)
+ """
+ user_id = str(uuid4())
+
+ mock_user = MagicMock()
+ mock_user.role_id = None
+
+ with (
+ patch(
+ 'server.auth.authorization.UserStore.get_user_by_id',
+ AsyncMock(return_value=mock_user),
+ ),
+ patch(
+ 'server.auth.authorization.RoleStore.get_role_by_id',
+ AsyncMock(return_value=MagicMock()),
+ ) as mock_get_role,
+ ):
+ assert await get_user_super_role(user_id) is None
+ mock_get_role.assert_not_called()
+
+
+def _mock_role(name: str) -> MagicMock:
+ role = MagicMock()
+ role.name = name
+ return role
+
+
+class TestRequirePermissionSuperRoleFallback:
+ """Tests covering the super-role fallback in ``require_permission``."""
+
+ @pytest.mark.asyncio
+ async def test_super_role_does_not_grant_unlisted_permission(self):
+ """
+ GIVEN: a member in the org and a non-functional superowner at the user level
+ WHEN: require_permission(DELETE_ORGANIZATION) runs
+ THEN: the super role does not help because DELETE_ORGANIZATION
+ is not in the explicit super-role permission set.
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_mock_role('member')),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=_mock_role('owner')),
+ ),
+ ):
+ permission_checker = require_permission(Permission.DELETE_ORGANIZATION)
+ with pytest.raises(HTTPException) as exc_info:
+ await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+ assert exc_info.value.status_code == 403
+ assert 'delete_organization' in exc_info.value.detail.lower()
+
+ @pytest.mark.asyncio
+ async def test_super_role_grants_explicit_permission_for_non_member(self):
+ """
+ GIVEN: a user with no org membership who has a superadmin role
+ on the user record
+ WHEN: require_permission(PROVISION_USER) runs
+ THEN: the explicit super-role permission grants access.
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=_mock_role('admin')),
+ ),
+ ):
+ permission_checker = require_permission(Permission.PROVISION_USER)
+ result = await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+ assert result == user_id
+
+ @pytest.mark.asyncio
+ async def test_super_role_does_not_help_when_lacks_permission(self):
+ """
+ GIVEN: a member in the org and a supermember at the user level
+ (neither role has DELETE_ORGANIZATION)
+ WHEN: require_permission(DELETE_ORGANIZATION) runs
+ THEN: 403 Forbidden is raised with 'Requires ...' detail
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_mock_role('member')),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=_mock_role('member')),
+ ),
+ ):
+ permission_checker = require_permission(Permission.DELETE_ORGANIZATION)
+ with pytest.raises(HTTPException) as exc_info:
+ await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+ assert exc_info.value.status_code == 403
+ assert 'delete_organization' in exc_info.value.detail.lower()
+
+ @pytest.mark.asyncio
+ async def test_non_member_with_insufficient_super_role_returns_403(self):
+ """
+ GIVEN: a non-member user whose super role lacks the required permission
+ WHEN: require_permission(DELETE_ORGANIZATION) runs
+ THEN: 403 with 'not a member' detail is raised
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=_mock_role('member')),
+ ),
+ ):
+ permission_checker = require_permission(Permission.DELETE_ORGANIZATION)
+ with pytest.raises(HTTPException) as exc_info:
+ await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+ assert exc_info.value.status_code == 403
+ assert 'not a member' in exc_info.value.detail.lower()
+
+ @pytest.mark.asyncio
+ async def test_org_role_short_circuits_super_role_lookup(self):
+ """
+ GIVEN: an admin in the org who also has a super role
+ WHEN: require_permission(VIEW_LLM_SETTINGS) runs (admin has it)
+ THEN: ``get_user_super_role`` is not called -- the org role
+ already grants access
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ super_role_mock = AsyncMock(return_value=_mock_role('owner'))
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_mock_role('admin')),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ super_role_mock,
+ ),
+ ):
+ permission_checker = require_permission(Permission.VIEW_LLM_SETTINGS)
+ result = await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+ assert result == user_id
+ super_role_mock.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_implicit_org_route_super_role_grants_explicit_permission_for_non_member(
+ self,
+ ):
+ """
+ GIVEN: a route without an ``{org_id}`` path parameter, an
+ ``X-Org-Id`` header that targets an org the user is NOT
+ a member of, and a superadmin role on the user record
+ WHEN: ``require_permission(PROVISION_USER)`` runs
+ THEN: the resolver skips the membership rejection and the
+ explicit super-role permission grants access.
+ """
+ user_id = str(uuid4())
+ target_org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ # The resolver must be invoked because org_id is None on the route.
+ # It returns the target org without performing a membership check.
+ with (
+ patch(
+ 'server.auth.org_context.resolve_target_org_id_for_permission_check',
+ AsyncMock(return_value=target_org_id),
+ ) as resolver,
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=_mock_role('admin')),
+ ),
+ ):
+ permission_checker = require_permission(Permission.PROVISION_USER)
+ result = await permission_checker(
+ request=mock_request, org_id=None, user_id=user_id
+ )
+
+ assert result == user_id
+ resolver.assert_awaited_once_with(mock_request)
+
+ @pytest.mark.asyncio
+ async def test_implicit_org_route_non_member_without_super_role_returns_403(self):
+ """
+ GIVEN: a route without ``{org_id}``, the X-Org-Id header targets
+ a non-member org, and the user has no super role
+ WHEN: require_permission runs
+ THEN: the resolver returns the target org, the org-role lookup
+ returns None, the super-role lookup returns None, so 403
+ is raised
+ """
+ user_id = str(uuid4())
+ target_org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ with (
+ patch(
+ 'server.auth.org_context.resolve_target_org_id_for_permission_check',
+ AsyncMock(return_value=target_org_id),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=None),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=None),
+ ),
+ ):
+ permission_checker = require_permission(Permission.VIEW_LLM_SETTINGS)
+ with pytest.raises(HTTPException) as exc_info:
+ await permission_checker(
+ request=mock_request, org_id=None, user_id=user_id
+ )
+ assert exc_info.value.status_code == 403
+ assert 'not a member' in exc_info.value.detail.lower()
+
+ @pytest.mark.asyncio
+ async def test_log_records_super_role_label(self):
+ """
+ GIVEN: an insufficient-permission scenario where the user has a
+ supermember role (also insufficient)
+ WHEN: require_permission(DELETE_ORGANIZATION) logs the denial
+ THEN: the warning's ``extra`` dict carries the ``supermember``
+ label (i.e. uses the conceptual super-role name)
+ """
+ user_id = str(uuid4())
+ org_id = uuid4()
+ mock_request = _create_mock_request()
+
+ with (
+ patch(
+ 'server.auth.authorization.get_user_org_role',
+ AsyncMock(return_value=_mock_role('admin')),
+ ),
+ patch(
+ 'server.auth.authorization.get_user_super_role',
+ AsyncMock(return_value=_mock_role('member')),
+ ),
+ patch('server.auth.authorization.logger') as mock_logger,
+ ):
+ permission_checker = require_permission(Permission.DELETE_ORGANIZATION)
+ with pytest.raises(HTTPException):
+ await permission_checker(
+ request=mock_request, org_id=org_id, user_id=user_id
+ )
+
+ mock_logger.warning.assert_called()
+ extra = mock_logger.warning.call_args[1]['extra']
+ assert extra['user_role'] == 'admin'
+ assert extra['super_role'] == 'supermember'
diff --git a/enterprise/tests/unit/test_lite_llm_manager.py b/enterprise/tests/unit/test_lite_llm_manager.py
index b3954505bf..c198e3fd61 100644
--- a/enterprise/tests/unit/test_lite_llm_manager.py
+++ b/enterprise/tests/unit/test_lite_llm_manager.py
@@ -404,6 +404,50 @@ class TestLiteLlmManager:
mock_client.post.call_count == 4
) # create_team, add_user_to_team, delete_key_by_alias, generate_key
+ @pytest.mark.asyncio
+ async def test_create_entries_can_create_team_without_adding_user(
+ self, mock_settings, mock_response
+ ):
+ """Test org bootstrap can create a team without user membership/key."""
+ mock_404_response = MagicMock()
+ mock_404_response.status_code = 404
+ mock_404_response.is_success = False
+ mock_404_response.raise_for_status.side_effect = httpx.HTTPStatusError(
+ message='Not Found', request=MagicMock(), response=mock_404_response
+ )
+
+ mock_token_manager = MagicMock()
+ mock_token_manager.return_value.get_user_info_from_user_id = AsyncMock(
+ return_value={'email': '[email protected]'}
+ )
+
+ mock_client = AsyncMock()
+ mock_client.get.side_effect = [mock_404_response]
+ mock_client.post.return_value = mock_response
+
+ mock_client_class = MagicMock()
+ mock_client_class.return_value.__aenter__.return_value = mock_client
+
+ with (
+ patch.dict(os.environ, {'LOCAL_DEPLOYMENT': ''}),
+ patch('storage.lite_llm_manager.LITE_LLM_API_KEY', 'test-key'),
+ patch('storage.lite_llm_manager.LITE_LLM_API_URL', 'http://test.com'),
+ patch('storage.lite_llm_manager.TokenManager', mock_token_manager),
+ patch('httpx.AsyncClient', mock_client_class),
+ ):
+ result = await LiteLlmManager.create_entries(
+ 'test-org-id',
+ 'test-user-id',
+ mock_settings,
+ create_user=False,
+ add_user_to_team=False,
+ )
+
+ assert result is not None
+ assert _secret_value(result, 'llm.api_key') is None
+ assert mock_client.get.call_count == 1
+ assert mock_client.post.call_count == 1
+
@pytest.mark.asyncio
async def test_create_entries_inherits_existing_team_budget(
self, mock_settings, mock_response
diff --git a/enterprise/tests/unit/test_org_service.py b/enterprise/tests/unit/test_org_service.py
index 8bcb9d610b..3820152756 100644
--- a/enterprise/tests/unit/test_org_service.py
+++ b/enterprise/tests/unit/test_org_service.py
@@ -187,6 +187,77 @@ async def test_create_org_with_owner_success(
assert org_member.status == 'active'
+async def test_create_org_without_owner_skips_creator_membership(
+ session_maker, async_session_maker
+):
+ """
+ GIVEN: Valid organization data and add_creator_as_owner=False
+ WHEN: create_org_with_owner is called
+ THEN: The organization is created without adding the creator as a member.
+ """
+ user_id = uuid.uuid4()
+ temp_org_id = uuid.uuid4()
+
+ with session_maker() as session:
+ user = User(id=user_id, current_org_id=temp_org_id)
+ session.add(user)
+ session.commit()
+
+ mock_settings = {'team_id': 'test-team', 'user_id': str(user_id)}
+ get_owner_role_mock = AsyncMock()
+ get_member_kwargs_mock = MagicMock(return_value={'llm_api_key': 'test-key'})
+
+ with (
+ patch('storage.org_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ patch(
+ 'storage.org_service.UserStore.create_default_settings',
+ AsyncMock(return_value=mock_settings),
+ ) as create_settings_mock,
+ patch(
+ 'storage.org_service.OrgStore.get_kwargs_from_settings',
+ return_value={
+ 'agent_settings': {
+ 'llm': {'model': 'anthropic/claude-sonnet-4-5-20250929'},
+ },
+ 'conversation_settings': {},
+ },
+ ),
+ patch('storage.org_service.OrgService.get_owner_role', get_owner_role_mock),
+ patch(
+ 'storage.org_service.OrgMemberStore.get_kwargs_from_settings',
+ get_member_kwargs_mock,
+ ),
+ ):
+ result = await OrgService.create_org_with_owner(
+ name='test-org-no-owner',
+ contact_name='Jane Doe',
+ contact_email='[email protected]',
+ user_id=str(user_id),
+ add_creator_as_owner=False,
+ )
+
+ create_settings_mock.assert_awaited_once_with(
+ org_id=str(result.id),
+ user_id=str(user_id),
+ create_user=False,
+ add_user_to_litellm_team=False,
+ )
+ get_owner_role_mock.assert_not_awaited()
+ get_member_kwargs_mock.assert_not_called()
+
+ with session_maker() as session:
+ persisted_org = session.get(Org, result.id)
+ assert persisted_org is not None
+ org_member = (
+ session.query(OrgMember)
+ .filter_by(org_id=result.id, user_id=user_id)
+ .first()
+ )
+ assert org_member is None
+
+
@pytest.mark.asyncio
async def test_create_org_with_owner_duplicate_name(
session_maker, async_session_maker, owner_role, mock_litellm_api
diff --git a/enterprise/tests/unit/test_user_store.py b/enterprise/tests/unit/test_user_store.py
index 99fb610ffe..5ffb040f20 100644
--- a/enterprise/tests/unit/test_user_store.py
+++ b/enterprise/tests/unit/test_user_store.py
@@ -135,6 +135,136 @@ async def test_create_user_with_llm_profiles_does_not_crash_and_preserves_secret
assert user.llm_profiles['profiles']['work']['api_key'] == 'work-secret-key'
+# --- Tests for first-user β†’ superadmin designation ---
+
+
+async def _seed_admin_role(async_session_maker) -> int:
+ """Seed roles required by ``UserStore.create_user``.
+
+ ``owner`` is required for the user's personal-org membership, while
+ ``admin`` is the first user's explicit superadmin role. Returns the
+ seeded admin role id so tests can assert the new user's ``role_id``
+ matches it.
+ """
+ from storage.role import Role
+
+ async with async_session_maker() as session:
+ owner_role = Role(name='owner', rank=0)
+ admin_role = Role(name='admin', rank=1)
+ session.add_all([owner_role, admin_role])
+ await session.commit()
+ await session.refresh(admin_role)
+ return admin_role.id
+
+
+def _mock_create_default_settings_returning_default():
+ """Patch ``create_default_settings`` to return a minimal valid Settings.
+
+ ``UserStore.create_user`` only needs a non-None Settings to proceed
+ past the LiteLLM provisioning step; the contents are irrelevant for
+ the superadmin-designation behavior being tested here.
+ """
+ return patch(
+ 'storage.user_store.UserStore.create_default_settings',
+ new_callable=AsyncMock,
+ return_value=Settings(language='en'),
+ )
+
+
+async def test_create_user_first_user_is_designated_superadmin(async_session_maker):
+ """The very first user created must receive the ``admin`` super role.
+
+ The super role is attached via ``user.role_id`` (not the
+ ``org_member.role_id`` org-scoped role) and grants only the explicit
+ instance-level permissions defined in ``server.auth.authorization``.
+ """
+ admin_role_id = await _seed_admin_role(async_session_maker)
+
+ user_id = str(uuid.uuid4())
+ user_info = {'email': '[email protected]', 'preferred_username': 'first'}
+
+ with (
+ patch('storage.user_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ _mock_create_default_settings_returning_default(),
+ ):
+ user = await UserStore.create_user(user_id, user_info)
+
+ assert user is not None
+ assert user.role_id == admin_role_id
+
+
+async def test_create_user_subsequent_users_are_not_superadmins(async_session_maker):
+ """Only the first user gets the super role; later users do not.
+
+ Without this guard the super-role hand-out would be unbounded and
+ every newly onboarded user would silently gain workspace-wide
+ privileges.
+ """
+ await _seed_admin_role(async_session_maker)
+
+ first_user_id = str(uuid.uuid4())
+ second_user_id = str(uuid.uuid4())
+
+ with (
+ patch('storage.user_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ _mock_create_default_settings_returning_default(),
+ ):
+ first_user = await UserStore.create_user(
+ first_user_id, {'email': '[email protected]'}
+ )
+ second_user = await UserStore.create_user(
+ second_user_id, {'email': '[email protected]'}
+ )
+
+ assert first_user is not None
+ assert second_user is not None
+ assert first_user.role_id is not None
+ assert second_user.role_id is None
+
+
+async def test_create_user_explicit_role_id_is_respected_for_first_user(
+ async_session_maker,
+):
+ """Caller-supplied ``role_id`` wins over the first-user auto-designation.
+
+ This keeps the auto-promotion strictly opt-in for the default
+ onboarding path (``role_id is None``) and preserves the existing
+ contract for callers that pass an explicit super role.
+ """
+ admin_role_id = await _seed_admin_role(async_session_maker)
+
+ # Seed a second distinct role so we can pass a non-admin role_id and
+ # prove the override is honored verbatim.
+ from storage.role import Role
+
+ async with async_session_maker() as session:
+ other_role = Role(name='member', rank=10)
+ session.add(other_role)
+ await session.commit()
+ await session.refresh(other_role)
+ other_role_id = other_role.id
+
+ user_id = str(uuid.uuid4())
+
+ with (
+ patch('storage.user_store.a_session_maker', async_session_maker),
+ patch('storage.role_store.a_session_maker', async_session_maker),
+ _mock_create_default_settings_returning_default(),
+ ):
+ user = await UserStore.create_user(
+ user_id, {'email': '[email protected]'}, role_id=other_role_id
+ )
+
+ assert user is not None
+ assert user.role_id == other_role_id
+ assert user.role_id != admin_role_id
+
+
# --- Tests for create_default_settings ---
@@ -194,7 +324,9 @@ async def test_create_default_settings_v1_enabled_true_when_default_is_true(
# Track the settings passed to LiteLlmManager.create_entries
captured_settings = None
- async def capture_create_entries(_org_id, _user_id, settings, _create_user):
+ async def capture_create_entries(
+ _org_id, _user_id, settings, _create_user, *, add_user_to_team=True
+ ):
nonlocal captured_settings
captured_settings = settings
return settings
@@ -227,7 +359,9 @@ async def test_create_default_settings_v1_enabled_false_when_default_is_false(
# Track the settings passed to LiteLlmManager.create_entries
captured_settings = None
- async def capture_create_entries(_org_id, _user_id, settings, _create_user):
+ async def capture_create_entries(
+ _org_id, _user_id, settings, _create_user, *, add_user_to_team=True
+ ):
nonlocal captured_settings
captured_settings = settings
return settings