π OpenHands: AI-Driven Development
feat(enterprise): add admin user-provisioning endpoint (#14864)
chuckbutkusb0126f130191
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.pyindex a40aa7bee2..b694903b7d 100644--- a/enterprise/saas_server.py+++ b/enterprise/saas_server.py@@ -23,7 +23,10 @@ from server.auth.constants import ( # noqa: E402GITHUB_APP_CLIENT_ID,GITLAB_APP_CLIENT_ID,)-from server.constants import PERMITTED_CORS_ORIGINS # noqa: E402+from server.constants import ( # noqa: E402+ PERMITTED_CORS_ORIGINS,+ USER_PROVISIONING_ENABLED,+)from server.logger import logger # noqa: E402from server.middleware import ( # noqa: E402ApiKeyAwareCORSMiddleware,@@ -51,6 +54,9 @@ from server.routes.orgs import org_router # noqa: E402from server.routes.readiness import readiness_router # noqa: E402from server.routes.service import service_router # noqa: E402from server.routes.user_app_settings import user_app_settings_router # noqa: E402+from server.routes.user_provisioning import ( # noqa: E402+ user_provisioning_router,+)from server.routes.users_v1 import ( # noqa: E402override_users_me_endpoint,)@@ -133,6 +139,13 @@ if BITBUCKET_APP_CLIENT_ID:base_app.include_router(api_keys_router) # Add routes for API key managementbase_app.include_router(service_router) # Add routes for internal service APIbase_app.include_router(org_router) # Add routes for organization management+if USER_PROVISIONING_ENABLED:+ # Privileged admin route β registered only when the+ # USER_PROVISIONING_ENABLED env var (driven by Helm value+ # ``userProvisioning.enabled``) is truthy. Off by default in+ # staging and production; enabled per-environment via Helm.+ base_app.include_router(user_provisioning_router)+ logger.info('user_provisioning_router:enabled')base_app.include_router(org_profiles_router, prefix='/api/organizations') # Add routes for org LLM profilesdiff --git a/enterprise/server/auth/authorization.py b/enterprise/server/auth/authorization.pyindex 196b836906..469076b1d3 100644--- a/enterprise/server/auth/authorization.py+++ b/enterprise/server/auth/authorization.py@@ -90,6 +90,9 @@ class Permission(str, Enum):# Manage AutomationsMANAGE_AUTOMATIONS = 'manage_automations'+ # User provisioning (create new Keycloak/OpenHands users directly in an org)+ PROVISION_USER = 'provision_user'+class RoleName(str, Enum):"""Role names used in the system."""@@ -128,6 +131,8 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {Permission.MANAGE_ORG_CLAIMS,# Manage AutomationsPermission.MANAGE_AUTOMATIONS,+ # User provisioning+ Permission.PROVISION_USER,]),RoleName.ADMIN: frozenset(@@ -153,6 +158,8 @@ ROLE_PERMISSIONS: dict[RoleName, frozenset[Permission]] = {Permission.MANAGE_ORG_CLAIMS,# Manage AutomationsPermission.MANAGE_AUTOMATIONS,+ # User provisioning+ Permission.PROVISION_USER,]),RoleName.MEMBER: frozenset(diff --git a/enterprise/server/auth/token_manager.py b/enterprise/server/auth/token_manager.pyindex 0db26b0dcf..51b636b301 100644--- a/enterprise/server/auth/token_manager.py+++ b/enterprise/server/auth/token_manager.py@@ -812,6 +812,98 @@ class TokenManager:logger.exception(f'Unexpected error deleting Keycloak user {user_id}: {e}')return False+ @retry(+ stop=stop_after_attempt(2),+ retry=retry_if_exception_type(KeycloakConnectionError),+ before_sleep=_before_sleep_callback,+ )+ async def create_keycloak_user(+ self,+ email: str,+ password: str,+ email_verified: bool = True,+ ) -> str:+ """Create a new Keycloak user in the configured realm.++ Used by the provisioning endpoint to seed accounts on behalf of an+ org admin. The password is set as a non-temporary credential so the+ provisioned user can authenticate directly with the returned+ credentials without going through Keycloak's "update password"+ flow.++ Args:+ email: Email address. Used as both ``email`` and ``username``.+ password: Initial password to set on the account.+ email_verified: Persisted to Keycloak's ``emailVerified`` flag.++ Returns:+ The Keycloak user ID (``sub``) of the newly created user.++ Raises:+ KeycloakError: If creation fails (e.g. user already exists).+ """+ keycloak_admin = get_keycloak_admin(self.external)+ # Include the password inline in the UserRepresentation's+ # ``credentials`` array so creation and password setup are a+ # single atomic Keycloak call. If the password violates the+ # realm's password policy, Keycloak rejects the whole request+ # and no user row is created β there is no orphan window+ # between an existing user and a failed password setup.+ # See https://www.keycloak.org/docs-api/26.0.0/rest-api/index.html#UserRepresentation+ payload: dict = {+ 'email': email,+ 'username': email,+ 'enabled': True,+ 'emailVerified': email_verified,+ 'credentials': [+ {+ 'type': 'password',+ 'value': password,+ 'temporary': False,+ }+ ],+ }+ user_id = await keycloak_admin.a_create_user(payload, exist_ok=False)+ logger.info(+ 'Created Keycloak user',+ extra={'user_id': user_id, 'email': email},+ )+ return user_id++ async def request_offline_token(self, username: str, password: str) -> str:+ """Exchange password credentials for an offline refresh token.++ Uses the Resource Owner Password Credentials (ROPC) grant with the+ ``offline_access`` scope. The returned ``refresh_token`` is an+ offline token: it persists across browser sessions and is what+ ``store_offline_token`` expects.++ Args:+ username: Keycloak username (typically the email).+ password: The user's password.++ Returns:+ The offline refresh token.++ Raises:+ KeycloakError: If the token endpoint rejects the credentials+ or the realm does not have ROPC enabled.+ ValueError: If the response is missing ``refresh_token``.+ """+ token_response = await get_keycloak_openid(self.external).a_token(+ username=username,+ password=password,+ grant_type='password',+ scope='openid offline_access',+ )+ refresh_token = token_response.get('refresh_token')+ if not refresh_token:+ raise ValueError(+ 'Keycloak token response did not include a refresh_token; '+ 'offline_access scope may not be granted'+ )+ return refresh_token+async def get_user_info_from_user_id(self, user_id: str) -> dict | None:keycloak_admin = get_keycloak_admin(self.external)user = await keycloak_admin.a_get_user(user_id)diff --git a/enterprise/server/constants.py b/enterprise/server/constants.pyindex fdcc44ca76..5bee3e2558 100644--- a/enterprise/server/constants.py+++ b/enterprise/server/constants.py@@ -120,6 +120,27 @@ PERMITTED_CORS_ORIGINS = [# Controls whether new orgs/users default to V1 API (env: DEFAULT_V1_ENABLED)DEFAULT_V1_ENABLED = os.getenv('DEFAULT_V1_ENABLED', '1').lower() in ('1', 'true')+# Controls whether the admin POST /api/organizations/provision-user endpoint+# is registered on the SaaS app (env: USER_PROVISIONING_ENABLED). Defaults to+# off in staging and production via the Helm chart; deliberately env-gated so+# the privileged route can be rolled out per-environment via Helm values.+# Accepts both ``'true'`` and ``'1'`` because older Helm chart versions emit+# the latter and would otherwise silently keep the feature disabled.+USER_PROVISIONING_ENABLED = os.getenv('USER_PROVISIONING_ENABLED', 'false').lower() in (+ 'true',+ '1',+)++# Controls whether any authenticated user is allowed to create an organization+# via POST /api/organizations (env: OPEN_ORG_CREATION_ENABLED). When disabled+# (the default), org creation remains restricted to @openhands.dev admin users.+# Accepts both ``'true'`` and ``'1'`` because older Helm chart versions emit+# the latter and would otherwise silently keep the feature disabled.+OPEN_ORG_CREATION_ENABLED = os.getenv('OPEN_ORG_CREATION_ENABLED', 'false').lower() in (+ 'true',+ '1',+)+def build_litellm_proxy_model_path(model_name: str) -> str:"""Build the LiteLLM proxy model path based on model name.diff --git a/enterprise/server/email_validation.py b/enterprise/server/email_validation.pyindex 37627d32bf..e78dc1b0f1 100644--- a/enterprise/server/email_validation.py+++ b/enterprise/server/email_validation.py@@ -3,6 +3,7 @@ Email domain validation utilities for enterprise endpoints."""from fastapi import Depends, HTTPException, Request, status+from server.constants import OPEN_ORG_CREATION_ENABLEDfrom openhands.app_server.user_auth import get_user_auth, get_user_idfrom openhands.app_server.utils.logger import openhands_logger as logger@@ -66,3 +67,49 @@ async def get_admin_user_id()return user_id+++async def get_org_creator_user_id(+ request: Request, user_id: str | None = Depends(get_user_id)+) -> str:+ """+ Dependency that authorizes a user to create an organization.++ Behavior is gated by the ``OPEN_ORG_CREATION_ENABLED`` feature switch:++ - When **enabled**, any authenticated user is allowed to create an+ organization (only ``get_user_id`` is enforced).+ - When **disabled** (the default), this falls back to ``get_admin_user_id``+ so org creation remains restricted to ``@openhands.dev`` admin users.++ Args:+ request: FastAPI request object+ user_id: User ID from get_user_id dependency++ Returns:+ str: Authenticated user ID++ Raises:+ HTTPException: 401 if user is not authenticated+ HTTPException: 403 if the feature switch is disabled and the user is+ not an ``@openhands.dev`` admin++ Example:+ @router.post('/endpoint')+ async def create_resource(+ user_id: str = Depends(get_org_creator_user_id),+ ):+ # Restricted to admins unless OPEN_ORG_CREATION_ENABLED is set+ pass+ """+ if not user_id:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail='User not authenticated',+ )++ if OPEN_ORG_CREATION_ENABLED:+ return user_id++ # Feature switch is off: preserve the original admin-only behavior.+ return await get_admin_user_id(request=request, user_id=user_id)diff --git a/enterprise/server/routes/orgs.py b/enterprise/server/routes/orgs.pyindex a83abb4601..4cc893a210 100644--- a/enterprise/server/routes/orgs.py+++ b/enterprise/server/routes/orgs.py@@ -8,7 +8,7 @@ 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_admin_user_id+from server.email_validation import get_org_creator_user_idfrom server.routes.org_models import (CannotModifySelfError,GitOrgAlreadyClaimedError,@@ -152,12 +152,14 @@ 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_admin_user_id),+ user_id: str = Depends(get_org_creator_user_id),) -> OrgResponse:"""Create a new organization.- This endpoint allows authenticated users with @openhands.dev email to create- a new organization. The user who creates the organization automatically becomes+ 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 becomesits owner.Args:@@ -168,7 +170,8 @@ async def create_org(OrgResponse: The created organization detailsRaises:- HTTPException: 403 if user email domain is not @openhands.dev+ HTTPException: 403 if user email domain is not @openhands.dev and the+ ``OPEN_ORG_CREATION_ENABLED`` feature switch is disabledHTTPException: 409 if organization name already existsHTTPException: 500 if creation fails"""diff --git a/enterprise/server/routes/user_provisioning.py b/enterprise/server/routes/user_provisioning.pynew file mode 100644index 0000000000..38b7f212ac--- /dev/null+++ b/enterprise/server/routes/user_provisioning.py@@ -0,0 +1,581 @@+"""+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``).++Flow (POST ``/api/organizations/provision-user``):++1. Resolve the target org from the ``X-Org-Id`` header (validated against+ the caller's memberships by ``require_permission``).+2. Create the user in Keycloak (realm configured by+ ``KEYCLOAK_REALM_NAME``), pre-verifying the email and setting a+ non-temporary password.+3. Request an offline refresh token for the new user via ROPC and store+ it via ``TokenManager.store_offline_token`` so the account can be used+ for backend operations (e.g. SDK calls) immediately.+4. Create the OpenHands user record (mirroring the ``keycloak_callback``+ 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``).+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+API key in a single response. On failure after the Keycloak user is+created, ``_rollback_partial_provision`` compensates whatever subset of+steps already ran β see its docstring for the full unwind order.++**Compensation strategy.** Each post-Keycloak side effect is tracked by+a local progress variable so the unwind path can target exactly the+state that was created:++* ``openhands_user_id`` β set once ``UserStore.create_user`` returns,+ marking that the User row, personal Org, owner OrgMember row, default+ settings, and personal-org LiteLLM team all exist.+* ``target_membership_added`` β set once+ ``OrgMemberStore.add_user_to_org`` succeeds for the target org.++The order in the unwind matters: the personal-org cascade only+deletes the User row when the user is the sole orphan of the personal+org, so the target-org membership (if added) must be removed *before*+the cascade runs. See ``_rollback_partial_provision`` for the full+ordering and the rationale behind it.++**Known partial-cleanup gap (offline token).** Step 3a stores the+offline token before ``UserStore.create_user`` runs, mirroring the+production OAuth flow (``keycloak_offline_callback`` stores the+token before any ``UserStore`` interaction). The rollback path+removes the Keycloak user, which makes the orphaned offline token+row harmless β it is keyed by a Keycloak ``sub`` that no longer+exists, so it cannot be used to authenticate. The inverse ordering+(user-first) would leak the *entire* OpenHands cascade instead of a+single encrypted token blob, which is strictly worse. Periodic+``OfflineTokenStore`` reconciliation (if/when added) can sweep these.++**Known partial-cleanup gap (LiteLLM target-team membership).** When+``create_litellm_integration`` succeeded for the target org, the+provisioned Keycloak ``sub`` was added to the target org's LiteLLM+team and a per-user key was minted on the LiteLLM side. Removing the+OpenHands ``OrgMember`` row does not propagate to LiteLLM, so on+rollback the LiteLLM-side membership and key for that ``sub`` are+left behind. They are functionally inert (the Keycloak account is+deleted in the same unwind, so there is no way to authenticate as+the orphaned ``sub``), but they do accumulate. Cleanup should ride+on a future ``LiteLlmManager.remove_user_from_team(sub, org_id)``+helper rather than reaching into private internals from this route.+"""++from __future__ import annotations++import secrets+import string+from datetime import datetime, timezone+from uuid import UUID+from uuid import UUID as parse_uuid++from fastapi import APIRouter, Depends, HTTPException, status+from keycloak.exceptions import KeycloakError+from pydantic import BaseModel, EmailStr, Field, SecretStr+from server.auth.authorization import Permission, require_permission+from server.auth.org_context import EFFECTIVE_ORG_ID+from server.auth.token_manager import TokenManager+from sqlalchemy import select+from storage.api_key_store import ApiKeyStore+from storage.database import a_session_maker+from storage.org_member_store import OrgMemberStore+from storage.org_service import OrgService+from storage.org_store import OrgStore+from storage.role_store import RoleStore+from storage.user import User+from storage.user_store import UserStore++from openhands.app_server.utils.logger import openhands_logger as logger++# Routes that read the target org from ``X-Org-Id`` rather than the URL+# path live under ``/api/organizations`` so they sit alongside the rest+# of the org-management surface, but they are intentionally separated+# from ``org_router`` (which carries the ``REJECT_X_ORG_ID_PATH_MISMATCH``+# guard for ``/{org_id}/...`` routes β that guard would no-op here, but+# 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'++# Length of generated passwords. 24 characters from a 70-symbol alphabet+# yields well over 128 bits of entropy, which exceeds typical Keycloak+# realm password-policy minimums while staying short enough to display+# in API responses.+_GENERATED_PASSWORD_LENGTH = 24+++def _utc_now_naive() -> datetime:+ """Return the current UTC time as a naive ``datetime``.++ ``User.accepted_tos`` (and similar timestamp columns on the user+ record) are stored as naive UTC datetimes, so we strip the tzinfo+ after capturing ``now`` in UTC to avoid mixed-awareness comparisons.+ """+ return datetime.now(timezone.utc).replace(tzinfo=None)+++def _generate_password(length: int = _GENERATED_PASSWORD_LENGTH) -> str:+ """Generate a strong random password suitable for Keycloak policies.++ Mixes upper/lowercase letters, digits, and a curated set of symbols+ so the result satisfies common Keycloak password-policy rules+ (digits, special characters, mixed case) without including+ characters that complicate shell/JSON usage.+ """+ alphabet = string.ascii_letters + string.digits + '!@#$%^&*-_=+'+ # Loop until we have at least one of each character class to+ # satisfy realm password policies that mandate mixed character+ # types. With a 24-character draw from this alphabet the+ # probability of any class being absent is ~10^-9, so a bounded+ # loop guarantees termination while still effectively always+ # succeeding on the first iteration.+ for _ in range(100):+ candidate = ''.join(secrets.choice(alphabet) for _ in range(length))+ if (+ any(c.islower() for c in candidate)+ and any(c.isupper() for c in candidate)+ and any(c.isdigit() for c in candidate)+ and any(c in '!@#$%^&*-_=+' for c in candidate)+ ):+ return candidate+ # Practically unreachable: after 100 independent 24-char draws the+ # probability of never satisfying the class constraints is < 10^-87.+ raise RuntimeError(+ 'Failed to generate a password satisfying character-class '+ 'requirements after 100 attempts.'+ )+++class ProvisionUserRequest(BaseModel):+ """Payload for ``POST /api/organizations/provision-user``."""++ email: EmailStr = Field(+ ...,+ description='Email address for the new user. Used as the Keycloak username.',+ )+ password: str | None = Field(+ default=None,+ min_length=8,+ max_length=256,+ description=(+ 'Optional initial password. If omitted, a strong random '+ 'password is generated and returned in the response. '+ 'When supplied, this value is sent to Keycloak as-is and '+ 'must satisfy the realm password policy (length, character '+ 'classes, blacklist, etc.); a policy violation surfaces as '+ 'a 409 from Keycloak. Generated passwords are constructed '+ 'to satisfy common realm policies (mixed case + digit + '+ 'symbol) β caller-supplied passwords carry no such '+ 'guarantees beyond the ``min_length=8`` floor enforced here.'+ ),+ )+ api_key_name: str | None = Field(+ default=None,+ max_length=255,+ description='Optional name for the generated API key.',+ )+++class ProvisionUserResponse(BaseModel):+ """Response for ``POST /api/organizations/provision-user``.++ ``password`` is **intentionally** returned to the caller β this is+ the *only* time the plaintext is available, because the endpoint+ bypasses the normal email-based set-password flow. The admin who+ called this endpoint is expected to hand the credential to the new+ user out-of-band (e.g. an internal IT system, secrets manager, or+ direct hand-off). Callers should treat the response body as+ sensitive: do not log it, and prefer TLS-terminated transport.+ """++ email: str+ password: str = Field(+ description=(+ 'Plaintext initial password for the new user. Either the '+ "caller's supplied value or a freshly generated one. "+ 'Returned so the admin can transmit it out-of-band; this '+ 'is the only point at which it is recoverable.'+ ),+ )+ api_key: str+ user_id: str+ org_id: str+++async def _set_user_provisioned_flags(user_id: str) -> None:+ """Stamp ``email_verified``, ``accepted_tos`` and analytics consent.++ ``UserStore.create_user`` already wires up the user, personal org,+ and org-member rows. The provisioning flow then bypasses the UI+ onboarding interstitials by stamping the flags directly so the+ provisioned account is fully usable immediately. Kept as a focused+ helper to keep the route handler readable.+ """+ async with a_session_maker() as session:+ result = await session.execute(+ select(User).where(User.id == parse_uuid(user_id))+ )+ user = result.scalar_one_or_none()+ if not user:+ return+ user.email_verified = True+ user.accepted_tos = _utc_now_naive()+ user.user_consents_to_analytics = True+ # Provisioned users skip the in-product onboarding form; the+ # admin has already onboarded them out-of-band.+ user.onboarding_completed = True+ await session.commit()+++@user_provisioning_router.post(+ '/provision-user',+ response_model=ProvisionUserResponse,+ status_code=status.HTTP_201_CREATED,+)+async def provision_user(+ body: ProvisionUserRequest,+ caller_user_id: str = Depends(require_permission(Permission.PROVISION_USER)),+ target_org_id: UUID = EFFECTIVE_ORG_ID,+) -> ProvisionUserResponse:+ """Create a new user and add them to the caller's selected org.++ 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).++ Returns the email, password (generated if not supplied) and the+ new user's API key bound to the target org.+ """+ email = body.email.lower().strip()+ password = body.password or _generate_password()+ api_key_name = body.api_key_name or 'Initial API Key'++ # Confirm the target org actually exists before we mutate Keycloak.+ # ``require_permission`` has already validated that the caller is a+ # member with the right role, but the org row could have been+ # deleted between the membership check and this code path; an+ # explicit fetch produces a clean 404 instead of a confusing 500+ # later in ``OrgService.create_litellm_integration``.+ org = await OrgStore.get_org_by_id(target_org_id)+ if not org:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail='Target organization not found',+ )++ # Reject provisioning into a personal workspace.+ #+ # The personal-workspace invariant is ``Org.id == User.id == UUID(+ # keycloak.sub)`` (see ``UserStore.create_user``), so a personal+ # workspace is detected by comparing ``target_org_id`` to the+ # *caller's* user id. ``require_permission(PROVISION_USER)`` lets+ # the call through because every user is the owner of their own+ # personal org, but the *product* meaning of the permission is+ # "create members of a team org" β not "every user can mint extra+ # accounts in their personal workspace and receive credentials/+ # API keys for them". Mirrors the long-standing personal-workspace+ # rejection in ``server.services.org_invitation_service`` (and uses+ # the same 403 status code) so the two endpoints behave+ # consistently.+ if str(target_org_id) == caller_user_id:+ raise HTTPException(+ status_code=status.HTTP_403_FORBIDDEN,+ detail='Cannot provision users into a personal workspace',+ )++ token_manager = TokenManager()++ # 1. Create the Keycloak user. Any failure here is terminal β we+ # have not mutated any OpenHands state yet, so a clean error is+ # safe to return.+ try:+ kc_user_id = await token_manager.create_keycloak_user(+ email=email,+ password=password,+ email_verified=True,+ )+ except KeycloakError as e:+ logger.warning(+ 'provision_user:keycloak_create_failed',+ extra={+ 'caller_user_id': caller_user_id,+ 'target_org_id': str(target_org_id),+ 'email': email,+ 'error': str(e),+ },+ )+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail='Failed to create Keycloak user (it may already exist)',+ )+ except Exception:+ logger.exception(+ 'provision_user:keycloak_create_unexpected',+ extra={+ 'caller_user_id': caller_user_id,+ 'target_org_id': str(target_org_id),+ 'email': email,+ },+ )+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to create Keycloak user',+ )++ # Anything after this point may need to roll back partial OpenHands+ # state (DB rows, LiteLLM team, OrgMember rows) **and** the Keycloak+ # user, to avoid leaving an OpenHands ``User``/personal-``Org``+ # pointing at a Keycloak ``sub`` that no longer exists. Progress is+ # tracked by the two local variables below so the unwind path+ # targets exactly the state that was created; see+ # ``_rollback_partial_provision`` for the unwind ordering.+ openhands_user_id: UUID | None = None+ target_membership_added = False+ try:+ # 2. Get an offline token for the new user and store it. This+ # mirrors what ``keycloak_offline_callback`` does at the end of+ # the interactive flow so the user is immediately usable for+ # backend operations.+ offline_token = await token_manager.request_offline_token(+ username=email, password=password+ )+ await token_manager.store_offline_token(+ user_id=kc_user_id, offline_token=offline_token+ )++ # 3. Create the OpenHands user. Mirrors ``keycloak_callback``'s+ # ``UserStore.create_user`` call but with email_verified+ # explicitly true. ``UserStore.create_user`` creates the+ # personal org, default settings, and the owner OrgMember row+ # for that personal org.+ user_info_dict = {+ 'sub': kc_user_id,+ 'email': email,+ 'email_verified': True,+ 'preferred_username': email,+ }+ new_user = await UserStore.create_user(kc_user_id, user_info_dict)+ if new_user is None:+ raise RuntimeError('UserStore.create_user returned None')+ # From here on, an unwind must remove the User row + personal+ # org cascade in addition to the Keycloak user.+ openhands_user_id = new_user.id++ # 4. Stamp TOS / verification / consent flags so the provisioned+ # user does not get bounced to the email-verification or TOS+ # interstitials on first login.+ await _set_user_provisioned_flags(kc_user_id)++ # 5. Add the user to the *target* org (separate from their+ # auto-created personal org). Skip this step when the+ # caller-selected org happens to be the user's brand-new+ # personal org β that membership was just created by+ # ``UserStore.create_user`` and re-adding it would violate the+ # ``(org_id, user_id)`` uniqueness constraint.+ if target_org_id != openhands_user_id:+ settings = await OrgService.create_litellm_integration(+ target_org_id, kc_user_id+ )+ llm_api_key_secret = settings.agent_settings.llm.api_key+ # ``api_key`` is typed ``str | SecretStr | None`` on the+ # SDK side; org_invitation_service.py handles it the same+ # way. Defaulting to empty string lets LiteLLM-disabled+ # deployments still create memberships.+ if llm_api_key_secret is None:+ llm_api_key = ''+ elif isinstance(llm_api_key_secret, SecretStr):+ llm_api_key = llm_api_key_secret.get_secret_value()+ else:+ llm_api_key = llm_api_key_secret++ role = await RoleStore.get_role_by_name(DEFAULT_PROVISIONED_ROLE)+ if role is None:+ raise RuntimeError(+ f'Role {DEFAULT_PROVISIONED_ROLE!r} not found in database'+ )++ await OrgMemberStore.add_user_to_org(+ org_id=target_org_id,+ user_id=openhands_user_id,+ role_id=role.id,+ llm_api_key=llm_api_key,+ status='active',+ agent_settings_diff={},+ conversation_settings_diff={},+ )+ # Track separately from ``openhands_user_id`` so the unwind+ # can decide whether the personal-org cascade alone is+ # enough or whether the target-org membership has to be+ # removed first (see ``_rollback_partial_provision``).+ target_membership_added = True++ # 6. Mint an API key bound to the target org. We pass+ # ``org_id`` explicitly so the key is pinned to the org the+ # admin selected rather than the user's freshly created+ # personal org (``current_org_id`` defaults to the personal+ # org).+ api_key_store = ApiKeyStore.get_instance()+ api_key = await api_key_store.create_api_key(+ user_id=kc_user_id,+ name=api_key_name,+ org_id=target_org_id,+ )+ except HTTPException:+ # FastAPI HTTPException is intentional β surface as-is, but+ # still attempt to clean up whatever post-Keycloak state we+ # created so we do not orphan a half-created identity.+ await _rollback_partial_provision(+ token_manager=token_manager,+ kc_user_id=kc_user_id,+ openhands_user_id=openhands_user_id,+ target_org_id=target_org_id,+ target_membership_added=target_membership_added,+ )+ raise+ except Exception as e:+ logger.exception(+ 'provision_user:post_keycloak_failure',+ extra={+ 'caller_user_id': caller_user_id,+ 'target_org_id': str(target_org_id),+ 'kc_user_id': kc_user_id,+ 'email': email,+ 'error': str(e),+ },+ )+ await _rollback_partial_provision(+ token_manager=token_manager,+ kc_user_id=kc_user_id,+ openhands_user_id=openhands_user_id,+ target_org_id=target_org_id,+ target_membership_added=target_membership_added,+ )+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail='Failed to finish provisioning user',+ )++ logger.info(+ 'provision_user:success',+ extra={+ 'caller_user_id': caller_user_id,+ 'provisioned_user_id': kc_user_id,+ 'target_org_id': str(target_org_id),+ # 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.+ },+ )++ return ProvisionUserResponse(+ email=email,+ password=password,+ api_key=api_key,+ user_id=kc_user_id,+ org_id=str(target_org_id),+ )+++async def _rollback_partial_provision(+ *,+ token_manager: TokenManager,+ kc_user_id: str,+ openhands_user_id: UUID | None,+ target_org_id: UUID,+ target_membership_added: bool,+) -> None:+ """Best-effort rollback of a partially completed provision.++ Runs on the unwind path of an already-failed request. Every step is+ wrapped individually because we never want a secondary cleanup+ failure to mask the original provisioning error β the underlying+ helpers each log their own diagnostics, so swallowing here is+ intentional.++ Unwind order matters:++ 1. **Target-org membership.** If ``OrgMemberStore.add_user_to_org``+ succeeded, the user has memberships in *both* the personal org+ and the target org. ``OrgStore.delete_org_cascade`` only+ cascade-deletes the ``User`` row when the user is the sole+ orphan of the org being deleted β a surviving target-org+ membership would cause the cascade to just reassign+ ``current_org_id`` to the target org and leave the user row+ behind. So we drop the target-org membership first.++ The freshly minted API key (step 6) is bound to ``target_org_id``+ and there is no failure step *after* the API key insert: if+ ``create_api_key`` raises mid-INSERT the row is never committed,+ and if it returns successfully the route never reaches this+ unwind. So the unwind does not need an explicit+ ``ApiKeyStore.delete`` call.++ 2. **Personal-org cascade.** ``delete_org_cascade(personal_org_id,+ requester_user_id=kc_user_id)`` wipes the personal ``Org`` row,+ the owner ``OrgMember`` row, the personal-org LiteLLM team,+ org-scoped tables (``api_keys WHERE org_id =+ personal_org_id``, ``conversation_metadata_saas``,+ ``billing_sessions``, etc.) and β because the user is now sole+ orphan after step 1 β the ``User`` row itself, in a single+ transaction. ``requester_user_id`` must equal the deleted+ user's ``id`` so the cascade treats this as a personal-org+ self-service deletion rather than raising+ ``OrphanedUserError``.++ 3. **Keycloak user.** Last, so the local OpenHands identity is+ gone before we drop the upstream identity. Re-doing the+ Keycloak delete via the existing ``delete_keycloak_user``+ helper keeps that retry/logging behaviour consistent with+ interactive-flow cleanup elsewhere.+ """+ # 1. Target-org artifacts. Skip silently if the membership was+ # never inserted β there is nothing to undo.+ if openhands_user_id is not None and target_membership_added:+ try:+ await OrgMemberStore.remove_user_from_org(target_org_id, openhands_user_id)+ except Exception:+ logger.exception(+ 'provision_user:rollback_remove_target_membership_failed',+ extra={+ 'kc_user_id': kc_user_id,+ 'target_org_id': str(target_org_id),+ 'openhands_user_id': str(openhands_user_id),+ },+ )++ # 2. Personal-org cascade. Skip when ``UserStore.create_user`` had+ # not yet run β there are no DB rows to compensate, and+ # ``delete_org_cascade`` would just no-op against a missing org.+ if openhands_user_id is not None:+ try:+ await OrgStore.delete_org_cascade(+ openhands_user_id, requester_user_id=kc_user_id+ )+ except Exception:+ logger.exception(+ 'provision_user:rollback_delete_personal_org_failed',+ extra={+ 'kc_user_id': kc_user_id,+ 'openhands_user_id': str(openhands_user_id),+ },+ )++ # 3. Keycloak user. Always last; runs even when no OpenHands DB+ # state was created (e.g. failure between Keycloak create and+ # ``UserStore.create_user``).+ try:+ await token_manager.delete_keycloak_user(kc_user_id)+ except Exception:+ logger.debug(+ 'provision_user:rollback_delete_keycloak_user_failed',+ extra={'kc_user_id': kc_user_id},+ )diff --git a/enterprise/tests/unit/routes/test_user_provisioning.py b/enterprise/tests/unit/routes/test_user_provisioning.pynew file mode 100644index 0000000000..7cc0eff7f9--- /dev/null+++ b/enterprise/tests/unit/routes/test_user_provisioning.py@@ -0,0 +1,597 @@+"""Unit tests for the user-provisioning admin endpoint.++These tests exercise the route handler directly (rather than through the+FastAPI test client) so they can mock the underlying Keycloak, database,+and LiteLLM dependencies without bringing up the entire SAAS stack. The+permission wiring itself is exercised separately by asserting on+``ROLE_PERMISSIONS``.+"""++from __future__ import annotations++import contextlib+import uuid+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from fastapi import HTTPException+from keycloak.exceptions import KeycloakError+from pydantic import SecretStr+from server.auth.authorization import (+ ROLE_PERMISSIONS,+ Permission,+ RoleName,+)+from server.routes.user_provisioning import (+ DEFAULT_PROVISIONED_ROLE,+ ProvisionUserRequest,+ _generate_password,+ provision_user,+)+++class TestGeneratePassword:+ """The generated password must satisfy a basic complexity policy."""++ def test_length_and_complexity(self):+ for _ in range(5):+ pw = _generate_password()+ assert len(pw) == 24+ assert any(c.islower() for c in pw)+ assert any(c.isupper() for c in pw)+ assert any(c.isdigit() for c in pw)+ assert any(c in '!@#$%^&*-_=+' for c in pw)++ def test_custom_length(self):+ pw = _generate_password(length=32)+ assert len(pw) == 32+++class TestProvisionUserPermissionWiring:+ """The new permission must be present and assigned only to OWNER/ADMIN."""++ def test_permission_enum_includes_provision_user(self):+ assert Permission.PROVISION_USER.value == 'provision_user'++ def test_owner_has_permission(self):+ assert Permission.PROVISION_USER in ROLE_PERMISSIONS[RoleName.OWNER]++ def test_admin_has_permission(self):+ assert Permission.PROVISION_USER in ROLE_PERMISSIONS[RoleName.ADMIN]++ def test_member_does_not_have_permission(self):+ assert Permission.PROVISION_USER not in ROLE_PERMISSIONS[RoleName.MEMBER]+++class TestProvisionUserRequestValidation:+ def test_email_is_required(self):+ with pytest.raises(ValueError):+ ProvisionUserRequest(email='not-an-email') # type: ignore[arg-type]++ def test_password_min_length(self):+ with pytest.raises(ValueError):+ ProvisionUserRequest(email='[email protected]', password='short')++ def test_optional_password(self):+ req = ProvisionUserRequest(email='[email protected]')+ assert req.password is None+++class TestProvisionUserHandler:+ """End-to-end handler test with all external collaborators mocked."""++ @pytest.fixture+ def caller_user_id(self) -> str:+ return '11111111-1111-1111-1111-111111111111'++ @pytest.fixture+ def target_org_id(self) -> uuid.UUID:+ return uuid.UUID('22222222-2222-2222-2222-222222222222')++ @pytest.fixture+ def new_user_id(self) -> str:+ # Distinct from target_org_id so the route takes the+ # "add to non-personal org" branch.+ return '33333333-3333-3333-3333-333333333333'++ def _patch_dependencies(+ self,+ new_user_id: str,+ target_org_id: uuid.UUID,+ *,+ org_exists: bool = True,+ keycloak_raises: Exception | None = None,+ ):+ """Return a stack of patches as a list of context managers.++ Tests enter all of them via ``contextlib.ExitStack`` so each+ patch's mock can be asserted on individually.+ """+ token_manager_mock = MagicMock()+ token_manager_mock.create_keycloak_user = AsyncMock(+ side_effect=keycloak_raises if keycloak_raises else None,+ return_value=new_user_id,+ )+ token_manager_mock.request_offline_token = AsyncMock(+ return_value='offline-refresh-token'+ )+ token_manager_mock.store_offline_token = AsyncMock()+ token_manager_mock.delete_keycloak_user = AsyncMock(return_value=True)++ new_user = MagicMock()+ new_user.id = uuid.UUID(new_user_id)++ settings_mock = MagicMock()+ settings_mock.agent_settings.llm.api_key = SecretStr('litellm-key')++ role_mock = MagicMock()+ role_mock.id = 42++ api_key_store_mock = MagicMock()+ api_key_store_mock.create_api_key = AsyncMock(+ return_value='sk-oh-generated-api-key'+ )++ org = MagicMock() if org_exists else None++ # Rollback collaborators. We construct these as standalone+ # ``AsyncMock``s so tests can assert on call counts and+ # arguments without having to dig back into the patch object.+ delete_org_cascade_mock = AsyncMock(return_value=org)+ remove_member_mock = AsyncMock(return_value=True)+ set_flags_mock = AsyncMock()+ add_user_to_org_mock = AsyncMock()++ patches = [+ patch(+ 'server.routes.user_provisioning.TokenManager',+ return_value=token_manager_mock,+ ),+ patch(+ 'server.routes.user_provisioning.OrgStore.get_org_by_id',+ new_callable=AsyncMock,+ return_value=org,+ ),+ patch(+ 'server.routes.user_provisioning.UserStore.create_user',+ new_callable=AsyncMock,+ return_value=new_user,+ ),+ patch(+ 'server.routes.user_provisioning._set_user_provisioned_flags',+ set_flags_mock,+ ),+ patch(+ 'server.routes.user_provisioning.OrgService.create_litellm_integration',+ new_callable=AsyncMock,+ return_value=settings_mock,+ ),+ patch(+ 'server.routes.user_provisioning.RoleStore.get_role_by_name',+ new_callable=AsyncMock,+ return_value=role_mock,+ ),+ patch(+ 'server.routes.user_provisioning.OrgMemberStore.add_user_to_org',+ add_user_to_org_mock,+ ),+ patch(+ 'server.routes.user_provisioning.ApiKeyStore.get_instance',+ return_value=api_key_store_mock,+ ),+ # Rollback path: ``_rollback_partial_provision`` calls+ # ``OrgMemberStore.remove_user_from_org`` first, then+ # ``OrgStore.delete_org_cascade`` on the personal org,+ # then ``TokenManager.delete_keycloak_user``. Patch the+ # first two here so the tests can assert on the rollback+ # order without hitting a real DB.+ patch(+ 'server.routes.user_provisioning.OrgMemberStore.remove_user_from_org',+ remove_member_mock,+ ),+ patch(+ 'server.routes.user_provisioning.OrgStore.delete_org_cascade',+ delete_org_cascade_mock,+ ),+ ]+ return patches, {+ 'token_manager': token_manager_mock,+ 'api_key_store': api_key_store_mock,+ 'set_flags': set_flags_mock,+ 'add_user_to_org': add_user_to_org_mock,+ 'remove_member': remove_member_mock,+ 'delete_org_cascade': delete_org_cascade_mock,+ }++ @staticmethod+ def _enter_all(patches):+ """Enter every patch in ``patches`` via an ``ExitStack``.++ Returning the stack lets the caller use ``with stack:`` to+ guarantee tear-down. This avoids the brittle+ ``with (patches[0], patches[1], ...)`` pattern that has to be+ edited every time the patch list grows.+ """+ stack = contextlib.ExitStack()+ for p in patches:+ stack.enter_context(p)+ return stack++ @pytest.mark.asyncio+ async def test_happy_path_with_supplied_password(+ 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(+ email='[email protected]',+ password='SuperSecret-1234',+ ),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert resp.email == '[email protected]'+ assert resp.password == 'SuperSecret-1234'+ assert resp.api_key == 'sk-oh-generated-api-key'+ assert resp.user_id == new_user_id+ assert resp.org_id == str(target_org_id)++ # 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'+ )+ # 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+ assert kwargs['org_id'] == target_org_id+ assert kwargs['user_id'] == new_user_id+ # On the happy path no rollback should run.+ handles['delete_org_cascade'].assert_not_awaited()+ handles['remove_member'].assert_not_awaited()+ handles['token_manager'].delete_keycloak_user.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_generates_password_when_not_supplied(+ 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(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert len(resp.password) >= 8+ # Verify the same generated password was used for the Keycloak+ # account creation, not regenerated each time.+ kc_call = handles['token_manager'].create_keycloak_user.await_args+ assert kc_call.kwargs['password'] == resp.password++ @pytest.mark.asyncio+ async def test_target_org_not_found_returns_404(+ self, caller_user_id, target_org_id, new_user_id+ ):+ patches, handles = self._patch_dependencies(+ new_user_id, target_org_id, org_exists=False+ )+ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )+ assert exc_info.value.status_code == 404+ # Keycloak must not have been touched.+ handles['token_manager'].create_keycloak_user.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_personal_workspace_rejected_with_403(+ self, caller_user_id, new_user_id+ ):+ """``target_org_id == caller's user id`` is a personal workspace.++ Every user is the owner of their personal org (Org.id ==+ User.id == UUID(keycloak.sub)), so a bare permission check+ on ``PROVISION_USER`` would otherwise let any normal user+ provision additional Keycloak/OpenHands accounts inside+ their own personal workspace and walk away with the+ credentials. Mirrors the personal-workspace rejection in+ ``server.services.org_invitation_service`` (403 Forbidden)+ and must run *before* Keycloak is touched.+ """+ caller_personal_org_id = uuid.UUID(caller_user_id)+ patches, handles = self._patch_dependencies(new_user_id, caller_personal_org_id)+ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=caller_personal_org_id,+ )++ assert exc_info.value.status_code == 403+ assert 'personal workspace' in exc_info.value.detail.lower()+ # The rejection must short-circuit before any side effects.+ handles['token_manager'].create_keycloak_user.assert_not_awaited()+ handles['delete_org_cascade'].assert_not_awaited()+ handles['remove_member'].assert_not_awaited()+ handles['token_manager'].delete_keycloak_user.assert_not_awaited()++ @pytest.mark.asyncio+ async def test_keycloak_failure_returns_409(+ self, caller_user_id, target_org_id, new_user_id+ ):+ patches, handles = self._patch_dependencies(+ new_user_id,+ target_org_id,+ keycloak_raises=KeycloakError('user already exists'),+ )+ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )+ assert exc_info.value.status_code == 409+ # Cleanup should not run if Keycloak creation itself failed β+ # there is nothing to roll back.+ handles['token_manager'].delete_keycloak_user.assert_not_awaited()+ handles['delete_org_cascade'].assert_not_awaited()+ handles['remove_member'].assert_not_awaited()++ @pytest.mark.asyncio+ async def test_rollback_before_user_created_only_cleans_keycloak(+ self, caller_user_id, target_org_id, new_user_id+ ):+ """Failure before ``UserStore.create_user`` only undoes Keycloak.++ The offline-token step runs *before* ``UserStore.create_user``,+ so when it blows up there are no OpenHands DB rows to+ compensate. The rollback must touch only the Keycloak user+ β exercising ``delete_org_cascade`` on a never-created+ personal org would log a misleading "not found".+ """+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)+ # Make the offline-token step blow up after Keycloak succeeded+ # but before any OpenHands DB row was created.+ handles['token_manager'].request_offline_token.side_effect = RuntimeError(+ 'boom'+ )++ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )+ assert exc_info.value.status_code == 500+ # Only the Keycloak user gets removed; no DB rollback.+ handles['token_manager'].delete_keycloak_user.assert_awaited_once_with(+ new_user_id+ )+ handles['delete_org_cascade'].assert_not_awaited()+ handles['remove_member'].assert_not_awaited()++ @pytest.mark.asyncio+ async def test_rollback_when_set_flags_fails(+ self, caller_user_id, target_org_id, new_user_id+ ):+ """``_set_user_provisioned_flags`` failure cascades the personal org.++ ``UserStore.create_user`` succeeded, so the User + personal Org+ + owner OrgMember + default settings now exist. The rollback+ must wipe them via ``delete_org_cascade`` and then delete the+ Keycloak user. No target-org membership was added yet, so+ ``remove_user_from_org`` must not run.+ """+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)+ handles['set_flags'].side_effect = RuntimeError('flag update exploded')++ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert exc_info.value.status_code == 500+ handles['remove_member'].assert_not_awaited()+ handles['delete_org_cascade'].assert_awaited_once_with(+ uuid.UUID(new_user_id), requester_user_id=new_user_id+ )+ handles['token_manager'].delete_keycloak_user.assert_awaited_once_with(+ new_user_id+ )++ @pytest.mark.asyncio+ async def test_rollback_when_litellm_integration_fails(+ self, caller_user_id, target_org_id, new_user_id+ ):+ """Failure in ``create_litellm_integration`` cascades personal org.++ We have a User + personal org but no target-org membership+ yet, so the rollback should skip ``remove_user_from_org`` and+ only cascade the personal org before deleting Keycloak.+ """+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)++ with self._enter_all(patches):+ with patch(+ 'server.routes.user_provisioning.OrgService.create_litellm_integration',+ new_callable=AsyncMock,+ side_effect=RuntimeError('litellm down'),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert exc_info.value.status_code == 500+ handles['remove_member'].assert_not_awaited()+ handles['delete_org_cascade'].assert_awaited_once_with(+ uuid.UUID(new_user_id), requester_user_id=new_user_id+ )+ handles['token_manager'].delete_keycloak_user.assert_awaited_once_with(+ new_user_id+ )++ @pytest.mark.asyncio+ async def test_rollback_when_add_user_to_org_fails(+ self, caller_user_id, target_org_id, new_user_id+ ):+ """``add_user_to_org`` failure: same shape as litellm failure.++ ``add_user_to_org`` is the call that sets+ ``target_membership_added`` after returning. If it raises+ instead, the membership row was never inserted, so the+ rollback must NOT call ``remove_user_from_org`` β that would+ try to remove a row that does not exist.+ """+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)+ handles['add_user_to_org'].side_effect = RuntimeError('insert exploded')++ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert exc_info.value.status_code == 500+ handles['remove_member'].assert_not_awaited()+ handles['delete_org_cascade'].assert_awaited_once_with(+ uuid.UUID(new_user_id), requester_user_id=new_user_id+ )+ handles['token_manager'].delete_keycloak_user.assert_awaited_once_with(+ new_user_id+ )++ @pytest.mark.asyncio+ async def test_rollback_when_api_key_creation_fails(+ self, caller_user_id, target_org_id, new_user_id+ ):+ """API-key failure exercises the *full* rollback path.++ By the time ``create_api_key`` runs, the target-org membership+ has already been inserted, so the rollback must:++ 1. Remove the target-org ``OrgMember`` row, *before* calling+ ``delete_org_cascade`` β otherwise the cascade would only+ reassign ``current_org_id`` and leave the User row behind.+ 2. Cascade-delete the personal org (User + personal Org ++ settings + personal-org LiteLLM team).+ 3. Delete the Keycloak user.++ We also assert step ordering by inspecting ``mock_calls`` on+ a shared parent mock.+ """+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)+ handles['api_key_store'].create_api_key.side_effect = RuntimeError(+ 'api key insert exploded'+ )++ # Shared parent mock to assert call ordering across the three+ # rollback collaborators.+ order_tracker = MagicMock()+ order_tracker.attach_mock(handles['remove_member'], 'remove_member')+ order_tracker.attach_mock(handles['delete_org_cascade'], 'delete_org_cascade')+ order_tracker.attach_mock(+ handles['token_manager'].delete_keycloak_user,+ 'delete_keycloak_user',+ )++ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert exc_info.value.status_code == 500+ handles['remove_member'].assert_awaited_once_with(+ target_org_id, uuid.UUID(new_user_id)+ )+ handles['delete_org_cascade'].assert_awaited_once_with(+ uuid.UUID(new_user_id), requester_user_id=new_user_id+ )+ handles['token_manager'].delete_keycloak_user.assert_awaited_once_with(+ new_user_id+ )+ # Ordering: target-membership β personal-org cascade β Keycloak.+ call_names = [c[0] for c in order_tracker.mock_calls]+ assert call_names == [+ 'remove_member',+ 'delete_org_cascade',+ 'delete_keycloak_user',+ ]++ @pytest.mark.asyncio+ async def test_rollback_swallows_secondary_failures(+ self, caller_user_id, target_org_id, new_user_id+ ):+ """Each cleanup step is wrapped so secondary errors do not mask the original.++ If ``remove_user_from_org`` *and* ``delete_org_cascade`` both+ raise during rollback, the route must still surface the+ original ``HTTPException(500)`` from the provisioning+ failure, and the remaining cleanup steps must keep running.+ """+ patches, handles = self._patch_dependencies(new_user_id, target_org_id)+ handles['api_key_store'].create_api_key.side_effect = RuntimeError(+ 'api key insert exploded'+ )+ handles['remove_member'].side_effect = RuntimeError(+ 'rollback step 1 also failed'+ )+ handles['delete_org_cascade'].side_effect = RuntimeError(+ 'rollback step 2 also failed'+ )++ with self._enter_all(patches):+ with pytest.raises(HTTPException) as exc_info:+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=target_org_id,+ )++ assert exc_info.value.status_code == 500+ # Despite earlier rollback failures, the Keycloak deletion+ # must still be attempted so the upstream identity does not+ # outlive the failed provisioning attempt.+ handles['token_manager'].delete_keycloak_user.assert_awaited_once_with(+ new_user_id+ )++ @pytest.mark.asyncio+ async def test_skips_add_to_org_when_target_is_personal_org(+ self, caller_user_id, target_org_id, new_user_id+ ):+ # When the X-Org-Id matches the user's freshly-created personal+ # org (id == user_id), re-adding would violate the unique+ # constraint. The route must skip the explicit add.+ personal_org_id = uuid.UUID(new_user_id)+ patches, handles = self._patch_dependencies(new_user_id, personal_org_id)+ with self._enter_all(patches):+ await provision_user(+ body=ProvisionUserRequest(email='[email protected]'),+ caller_user_id=caller_user_id,+ target_org_id=personal_org_id,+ )+ handles['add_user_to_org'].assert_not_awaited()++ def test_default_role_is_member(self):+ # Document the policy: provisioned users are not auto-promoted.+ assert DEFAULT_PROVISIONED_ROLE == 'member'diff --git a/enterprise/tests/unit/server/routes/test_orgs.py b/enterprise/tests/unit/server/routes/test_orgs.pyindex a356a8afe7..0bf8ed21a8 100644--- a/enterprise/tests/unit/server/routes/test_orgs.py+++ b/enterprise/tests/unit/server/routes/test_orgs.py@@ -11,7 +11,7 @@ import httpximport pytestfrom fastapi import FastAPI, HTTPException, Request, statusfrom fastapi.testclient import TestClient-from server.email_validation import get_admin_user_id+from server.email_validation import get_admin_user_id, get_org_creator_user_idfrom server.routes.org_models import (CannotModifySelfError,InsufficientPermissionError,@@ -64,8 +64,12 @@ def mock_app():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_idapp.dependency_overrides[get_user_id] = mock_get_user_id+ app.dependency_overrides[get_org_creator_user_id] = mock_get_org_creator_user_idreturn app@@ -324,7 +328,7 @@ async def test_create_org_unauthorized():async def mock_unauthenticated():raise HTTPException(status_code=401, detail='User not authenticated')- app.dependency_overrides[get_admin_user_id] = mock_unauthenticated+ app.dependency_overrides[get_org_creator_user_id] = mock_unauthenticatedrequest_data = {'name': 'Test Organization',@@ -358,7 +362,7 @@ async def test_create_org_forbidden_non_openhands_email():status_code=403, detail='Access restricted to @openhands.dev users')- app.dependency_overrides[get_admin_user_id] = mock_forbidden+ app.dependency_overrides[get_org_creator_user_id] = mock_forbiddenrequest_data = {'name': 'Test Organization',diff --git a/enterprise/tests/unit/server/test_constants.py b/enterprise/tests/unit/server/test_constants.pyindex 117ccd94ac..416ef383e8 100644--- a/enterprise/tests/unit/server/test_constants.py+++ b/enterprise/tests/unit/server/test_constants.py@@ -179,3 +179,104 @@ class TestEnableAutomationsInConfig:os.environ.pop('ENABLE_AUTOMATIONS', None)importlib.reload(constants_module)assert constants_module.ENABLE_AUTOMATIONS is True+++class TestUserProvisioningEnabled:+ """Tests for the USER_PROVISIONING_ENABLED feature switch.++ The switch is driven by the ``USER_PROVISIONING_ENABLED`` env var+ (populated from the ``userProvisioning.enabled`` Helm value). It+ must accept both ``'true'`` and ``'1'`` because older Helm chart+ versions emit the latter form β accepting only one variant would+ silently disable the feature in those deployments. See AGENTS.md+ "Environment Variable Enable Toggles".+ """++ @pytest.mark.parametrize(+ 'env_value,expected',+ [+ # Truthy variants accepted by the toggle convention.+ ('true', True),+ ('True', True),+ ('TRUE', True),+ ('1', True),+ # Falsy / unset / unknown values all disable the feature.+ ('false', False),+ ('False', False),+ ('0', False),+ ('', False),+ ('yes', False), # Not part of the documented accepted set.+ ('on', False),+ ],+ )+ def test_user_provisioning_enabled_truthy_parsing(+ self, env_value: str, expected: bool+ ) -> None:+ with patch.dict('os.environ', {'USER_PROVISIONING_ENABLED': env_value}):+ import importlib++ import server.constants as constants_module++ importlib.reload(constants_module)+ assert constants_module.USER_PROVISIONING_ENABLED is expected++ def test_user_provisioning_enabled_default_is_false(self) -> None:+ """When the env var is unset, the feature must default to off."""+ with patch.dict('os.environ', {}, clear=True):+ import importlib+ import os++ os.environ.pop('USER_PROVISIONING_ENABLED', None)+ import server.constants as constants_module++ importlib.reload(constants_module)+ assert constants_module.USER_PROVISIONING_ENABLED is False+++class TestOpenOrgCreationEnabled:+ """Tests for the OPEN_ORG_CREATION_ENABLED feature switch.++ Must accept both ``'true'`` and ``'1'`` per the documented enable-toggle+ convention so that older Helm chart versions emitting ``'1'`` keep the+ feature working. See AGENTS.md "Environment Variable Enable Toggles".+ """++ @pytest.mark.parametrize(+ 'env_value,expected',+ [+ # Truthy variants accepted by the toggle convention.+ ('true', True),+ ('True', True),+ ('TRUE', True),+ ('1', True),+ # Falsy / unset / unknown values all disable the feature.+ ('false', False),+ ('False', False),+ ('0', False),+ ('', False),+ ('yes', False), # Not part of the documented accepted set.+ ('on', False),+ ],+ )+ def test_open_org_creation_enabled_truthy_parsing(+ self, env_value: str, expected: bool+ ) -> None:+ with patch.dict('os.environ', {'OPEN_ORG_CREATION_ENABLED': env_value}):+ import importlib++ import server.constants as constants_module++ importlib.reload(constants_module)+ assert constants_module.OPEN_ORG_CREATION_ENABLED is expected++ def test_open_org_creation_enabled_default_is_false(self) -> None:+ """When the env var is unset, the feature must default to off."""+ with patch.dict('os.environ', {}, clear=True):+ import importlib+ import os++ os.environ.pop('OPEN_ORG_CREATION_ENABLED', None)+ import server.constants as constants_module++ importlib.reload(constants_module)+ assert constants_module.OPEN_ORG_CREATION_ENABLED is Falsediff --git a/enterprise/tests/unit/test_email_validation_dependency.py b/enterprise/tests/unit/test_email_validation_dependency.pyindex 8ac481a6e2..a15dd342ba 100644--- a/enterprise/tests/unit/test_email_validation_dependency.py+++ b/enterprise/tests/unit/test_email_validation_dependency.py@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom fastapi import HTTPException, Request-from server.email_validation import get_admin_user_id+from server.email_validation import get_admin_user_id, get_org_creator_user_id@pytest.fixture@@ -270,3 +270,102 @@ async def test_get_openhands_user_id_empty_email(mock_request, mock_user_auth):assert exc_info.value.status_code == 401assert 'email not available' in exc_info.value.detail.lower()+++# ---------------------------------------------------------------------------+# Tests for get_org_creator_user_id (OPEN_ORG_CREATION_ENABLED feature switch)+# ---------------------------------------------------------------------------+++async def test_get_org_creator_user_id_no_user_id_raises_401(mock_request):+ """+ GIVEN: No user ID provided (None)+ WHEN: get_org_creator_user_id is called (regardless of feature switch)+ THEN: 401 Unauthorized is raised+ """+ with pytest.raises(HTTPException) as exc_info:+ await get_org_creator_user_id(mock_request, None)++ assert exc_info.value.status_code == 401+ assert 'not authenticated' in exc_info.value.detail.lower()+++async def test_get_org_creator_user_id_feature_disabled_uses_admin_check(+ mock_request, mock_user_auth+):+ """+ GIVEN: OPEN_ORG_CREATION_ENABLED is disabled and user has non-admin email+ WHEN: get_org_creator_user_id is called+ THEN: Falls back to get_admin_user_id and raises 403 Forbidden+ """+ user_id = 'test-user-123'+ mock_user_auth.get_user_email.return_value = '[email protected]'++ with (+ patch('server.email_validation.OPEN_ORG_CREATION_ENABLED', False),+ patch('server.email_validation.get_user_auth', return_value=mock_user_auth),+ ):+ with pytest.raises(HTTPException) as exc_info:+ await get_org_creator_user_id(mock_request, user_id)++ assert exc_info.value.status_code == 403+ assert 'openhands.dev' in exc_info.value.detail.lower()+++async def test_get_org_creator_user_id_feature_disabled_admin_email_succeeds(+ mock_request, mock_user_auth+):+ """+ GIVEN: OPEN_ORG_CREATION_ENABLED is disabled and user has @openhands.dev email+ WHEN: get_org_creator_user_id is called+ THEN: User ID is returned (existing admin behavior is preserved)+ """+ user_id = 'test-user-123'+ mock_user_auth.get_user_email.return_value = '[email protected]'++ with (+ patch('server.email_validation.OPEN_ORG_CREATION_ENABLED', False),+ patch('server.email_validation.get_user_auth', return_value=mock_user_auth),+ ):+ result = await get_org_creator_user_id(mock_request, user_id)++ assert result == user_id+++async def test_get_org_creator_user_id_feature_enabled_allows_non_admin(mock_request):+ """+ GIVEN: OPEN_ORG_CREATION_ENABLED is enabled and user has non-admin email+ WHEN: get_org_creator_user_id is called+ THEN: User ID is returned without consulting email/admin check+ """+ user_id = 'test-user-123'++ with patch('server.email_validation.OPEN_ORG_CREATION_ENABLED', True):+ # get_user_auth must not be invoked when the feature is enabled.+ with patch(+ 'server.email_validation.get_user_auth',+ side_effect=AssertionError('get_user_auth should not be called'),+ ):+ result = await get_org_creator_user_id(mock_request, user_id)++ assert result == user_id+++async def test_get_org_creator_user_id_feature_enabled_still_rejects_unauthenticated(+ mock_request,+):+ """+ GIVEN: OPEN_ORG_CREATION_ENABLED is enabled but no user_id is provided+ WHEN: get_org_creator_user_id is called+ THEN: 401 Unauthorized is still raised+ """+ with patch('server.email_validation.OPEN_ORG_CREATION_ENABLED', True):+ with pytest.raises(HTTPException) as exc_info:+ await get_org_creator_user_id(mock_request, None)++ assert exc_info.value.status_code == 401diff --git a/enterprise/tests/unit/test_token_manager.py b/enterprise/tests/unit/test_token_manager.pyindex 131889d22c..d225639e39 100644--- a/enterprise/tests/unit/test_token_manager.py+++ b/enterprise/tests/unit/test_token_manager.py@@ -439,3 +439,82 @@ class TestDeleteKeycloakUser:# Assertassert result is False+++class TestCreateKeycloakUser:+ """Test cases for the create_keycloak_user helper.++ The helper sets the password inline in the UserRepresentation's+ ``credentials`` array, so creation and password setup happen in a+ single atomic Keycloak call: a password-policy violation rejects the+ whole request, and there is no orphan window to clean up.+ """++ @pytest.mark.asyncio+ async def test_create_keycloak_user_success(self, token_manager):+ """Happy path: user is created with inline password credentials."""+ # Arrange+ email = '[email protected]'+ password = 'GeneratedPassword-1234'+ new_user_id = 'kc-user-id-success'++ with patch('server.auth.token_manager.get_keycloak_admin') as mock_get_admin:+ mock_admin = MagicMock()+ mock_admin.a_create_user = AsyncMock(return_value=new_user_id)+ mock_admin.a_set_user_password = AsyncMock(return_value=None)+ mock_get_admin.return_value = mock_admin++ # Act+ result = await token_manager.create_keycloak_user(+ email=email, password=password+ )++ # Assert+ assert result == new_user_id+ mock_admin.a_create_user.assert_awaited_once()+ # The password must be supplied inline via the+ # ``credentials`` array β not via a separate+ # ``a_set_user_password`` follow-up call, which would+ # re-introduce the orphan-on-failure window.+ payload = mock_admin.a_create_user.await_args.args[0]+ assert payload['email'] == email+ assert payload['username'] == email+ assert payload['enabled'] is True+ assert payload['emailVerified'] is True+ assert payload['credentials'] == [+ {'type': 'password', 'value': password, 'temporary': False}+ ]+ mock_admin.a_set_user_password.assert_not_called()++ @pytest.mark.asyncio+ async def test_create_keycloak_user_atomic_password_failure_propagates(+ self, token_manager+ ):+ """Realm password-policy failure rejects the whole create call.++ Because the password lives inside the same POST as the user+ record, Keycloak refuses to create the user at all when the+ password is rejected. The exception must propagate so the route+ can surface a clean 409/500 β and no cleanup is required+ because nothing was ever created.+ """+ # Arrange+ email = '[email protected]'+ password = 'WeakishButPassesLocalCheck-1'++ with patch('server.auth.token_manager.get_keycloak_admin') as mock_get_admin:+ mock_admin = MagicMock()+ mock_admin.a_create_user = AsyncMock(+ side_effect=KeycloakError('Password policy not met')+ )+ mock_admin.delete_user = MagicMock()+ mock_get_admin.return_value = mock_admin++ # Act / Assert+ with pytest.raises(KeycloakError):+ await token_manager.create_keycloak_user(email=email, password=password)++ # No standalone password call, and no cleanup necessary β+ # the atomic create failed, so nothing was persisted.+ mock_admin.a_set_user_password.assert_not_called()+ mock_admin.delete_user.assert_not_called()