LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-3584 [FEAT] Restrict LLM adapter creation to org admins (controlled mode) (#2132)
Deepak K5f9589cac06a
diff --git a/backend/account_v2/migrations/0006_organization_restrict_llm_adapter_creation.py b/backend/account_v2/migrations/0006_organization_restrict_llm_adapter_creation.pynew file mode 100644index 000000000..591b7a4f1--- /dev/null+++ b/backend/account_v2/migrations/0006_organization_restrict_llm_adapter_creation.py@@ -0,0 +1,22 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("account_v2", "0005_alter_platformkey_organization"),+ ]++ operations = [+ migrations.AddField(+ model_name="organization",+ name="restrict_llm_adapter_creation",+ field=models.BooleanField(+ db_comment=(+ "Controlled mode: when True, only organization admins may "+ "create LLM adapters in this org. Default False preserves "+ "open creation."+ ),+ default=False,+ ),+ ),+ ]diff --git a/backend/account_v2/models.py b/backend/account_v2/models.pyindex eb6b81d8b..def009cd2 100644--- a/backend/account_v2/models.py+++ b/backend/account_v2/models.py@@ -39,6 +39,13 @@ class Organization(models.Model):default=-1,db_comment="token limit set in case of frition less onbaoarded org",)+ restrict_llm_adapter_creation = models.BooleanField(+ default=False,+ db_comment=(+ "Controlled mode: when True, only organization admins may create "+ "LLM adapters in this org. Default False preserves open creation."+ ),+ )class Meta:verbose_name = "Organization"diff --git a/backend/adapter_processor_v2/views.py b/backend/adapter_processor_v2/views.pyindex 4cfee77d0..2d500588e 100644--- a/backend/adapter_processor_v2/views.py+++ b/backend/adapter_processor_v2/views.py@@ -16,6 +16,7 @@ from permissions.resource_share_views import ResourceShareManagementMixinfrom plugins import get_pluginfrom rest_framework import statusfrom rest_framework.decorators import action+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import ModelSerializer@@ -24,6 +25,7 @@ from rest_framework.viewsets import GenericViewSet, ModelViewSetfrom tenant_account_v2.organization_member_service import OrganizationMemberServicefrom tool_instance_v2.models import ToolInstancefrom utils.filtering import FilterHelper+from utils.user_context import UserContextfrom adapter_processor_v2.adapter_processor import AdapterProcessorfrom adapter_processor_v2.constants import AdapterKeys@@ -173,6 +175,28 @@ class AdapterInstanceViewSet(ResourceShareManagementMixin, ModelViewSet):return AdapterListSerializerreturn AdapterInstanceSerializer+ @staticmethod+ def _enforce_llm_creation_restriction(request: Any, adapter_type: str) -> None:+ """Controlled mode (UN-3584): only org admins may create LLM adapters+ when the org has enabled the restriction. Service accounts (platform+ API-key sessions) and non-LLM adapter types bypass; the default+ (flag off) keeps creation open for everyone.+ """+ if adapter_type != AdapterKeys.LLM:+ return+ if getattr(request.user, "is_service_account", False):+ return+ organization = UserContext.get_organization()+ if (+ organization+ and organization.restrict_llm_adapter_creation+ and not OrganizationMemberService.is_user_organization_admin(request.user)+ ):+ raise PermissionDenied(+ "LLM adapter creation is restricted to organization admins. "+ "Please contact your organization admin."+ )+def create(self, request: Any) -> Response:serializer = self.get_serializer(data=request.data)@@ -184,9 +208,10 @@ class AdapterInstanceViewSet(ResourceShareManagementMixin, ModelViewSet):use_platform_unstract_key = Trueserializer.is_valid(raise_exception=True)- try:- adapter_type = serializer.validated_data.get(AdapterKeys.ADAPTER_TYPE)+ adapter_type = serializer.validated_data.get(AdapterKeys.ADAPTER_TYPE)+ self._enforce_llm_creation_restriction(request, adapter_type)+ try:if adapter_type == AdapterKeys.X2TEXT and use_platform_unstract_key:adapter_metadata_b = serializer.validated_data.get(AdapterKeys.ADAPTER_METADATA_B@@ -199,7 +224,12 @@ class AdapterInstanceViewSet(ResourceShareManagementMixin, ModelViewSet):adapter_metadata_b)- instance = serializer.save()+ # Bind the adapter to the request-scoped organization, overriding any+ # client-supplied `organization` in the payload (the serializer+ # exposes it via fields="__all__"). This keeps the row's org+ # consistent with the org the controlled-mode check above evaluated,+ # so the per-org restriction can't be sidestepped via the payload.+ instance = serializer.save(organization=UserContext.get_organization())organization_member = OrganizationMemberService.get_user_by_id(request.user.id)diff --git a/backend/tenant_account_v2/urls.py b/backend/tenant_account_v2/urls.pyindex 91831b8c1..4b7aec849 100644--- a/backend/tenant_account_v2/urls.py+++ b/backend/tenant_account_v2/urls.py@@ -1,13 +1,23 @@from django.urls import include, pathfrom tenant_account_v2 import groups_urls, invitation_urls, users_urls-from tenant_account_v2.views import get_organization, get_roles, reset_password+from tenant_account_v2.views import (+ get_organization,+ get_roles,+ organization_settings,+ reset_password,+)urlpatterns = [path("roles", get_roles, name="roles"),path("users/", include(users_urls)),path("invitation/", include(invitation_urls)),path("organization", get_organization, name="get_organization"),+ path(+ "organization/settings",+ organization_settings,+ name="organization_settings",+ ),path("reset_password", reset_password, name="reset_password"),path("", include(groups_urls)),]diff --git a/backend/tenant_account_v2/views.py b/backend/tenant_account_v2/views.pyindex 838e6adff..7cbce0f5a 100644--- a/backend/tenant_account_v2/views.py+++ b/backend/tenant_account_v2/views.py@@ -4,10 +4,13 @@ from typing import Anyfrom account_v2.authentication_controller import AuthenticationControllerfrom account_v2.dto import UserRoleDatafrom account_v2.models import Organization+from platform_api.permissions import IsOrganizationAdminfrom rest_framework import status-from rest_framework.decorators import api_view+from rest_framework.decorators import api_view, permission_classes+from rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from utils.user_context import UserContextfrom utils.user_session import UserSessionUtilsfrom tenant_account_v2.dto import OrganizationLoginResponse, ResetUserPasswordDto@@ -52,6 +55,46 @@ def reset_password(request: Request) -> Response:)+@api_view(["GET", "PATCH"])+@permission_classes([IsAuthenticated, IsOrganizationAdmin])+def organization_settings(request: Request) -> Response:+ """Read or update org-level settings. Admin-only.++ Currently exposes the ``restrict_llm_adapter_creation`` controlled-mode+ flag. GET returns the current value; PATCH updates it.+ """+ organization = UserContext.get_organization()+ if not organization:+ return Response(+ status=status.HTTP_404_NOT_FOUND,+ data={"message": "Org Not Found"},+ )++ if request.method == "PATCH":+ value = request.data.get("restrict_llm_adapter_creation")+ if not isinstance(value, bool):+ return Response(+ status=status.HTTP_400_BAD_REQUEST,+ data={"message": "restrict_llm_adapter_creation must be a boolean"},+ )+ organization.restrict_llm_adapter_creation = value+ organization.modified_by = request.user+ organization.save(+ update_fields=[+ "restrict_llm_adapter_creation",+ "modified_by",+ "modified_at",+ ]+ )++ return Response(+ status=status.HTTP_200_OK,+ data={+ "restrict_llm_adapter_creation": (organization.restrict_llm_adapter_creation)+ },+ )++@api_view(["GET"])def get_organization(request: Request) -> Response:auth_controller = AuthenticationController()diff --git a/frontend/src/components/settings/platform/PlatformSettings.jsx b/frontend/src/components/settings/platform/PlatformSettings.jsxindex e62b48a91..e7ee22dda 100644--- a/frontend/src/components/settings/platform/PlatformSettings.jsx+++ b/frontend/src/components/settings/platform/PlatformSettings.jsx@@ -10,6 +10,7 @@ import {Input,InputNumber,Row,+ Switch,Tag,Typography,} from "antd";@@ -28,6 +29,19 @@ import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";import usePostHogEvents from "../../../hooks/usePostHogEvents.js";import { SettingsLayout } from "../settings-layout/SettingsLayout.jsx";+// The "restrict LLM creation" control is enterprise/cloud-only: org admin+// roles and user management don't exist in OSS, so this setting is meaningless+// there. Detect the enterprise build by probing for an enterprise-only plugin+// (absent in OSS) and hide the control entirely otherwise. Mirrors the+// plugin-gating idiom used in SideNavBar.+let isEnterpriseBuild = false;+try {+ await import("../../../plugins/store/unstract-subscription-plan-store");+ isEnterpriseBuild = true;+} catch {+ // OSS build — enterprise plugins are not bundled.+}+const defaultKeys = [{id: null,@@ -85,6 +99,9 @@ function PlatformSettings() {// UI shows minutes; wire format (and ConfigSpec.value) is seconds.const [batchIntervalMinutes, setBatchIntervalMinutes] = useState(null);const [isSavingInterval, setIsSavingInterval] = useState(false);+ // Controlled-mode flag: only admins can create LLM adapters when true.+ const [restrictLlmCreation, setRestrictLlmCreation] = useState(false);+ const [isSavingRestriction, setIsSavingRestriction] = useState(false);const { sessionDetails } = useSessionStore();const { setAlertDetails } = useAlertStore();const axiosPrivate = useAxiosPrivate();@@ -119,6 +136,62 @@ function PlatformSettings() {});}, [sessionDetails?.orgId]);+ useEffect(() => {+ // Enterprise/cloud-only + admin-only setting; skip the call in OSS and for+ // non-admins (the endpoint is admin-gated and would 403) and before+ // session hydration.+ if (+ !isEnterpriseBuild ||+ !sessionDetails?.orgId ||+ !sessionDetails?.isAdmin+ ) {+ return;+ }+ axiosPrivate({+ method: "GET",+ url: `/api/v1/unstract/${sessionDetails?.orgId}/organization/settings`,+ })+ .then((res) => {+ setRestrictLlmCreation(+ Boolean(res?.data?.restrict_llm_adapter_creation),+ );+ })+ .catch((err) => {+ console.warn("Failed to load LLM adapter creation setting", err);+ });+ }, [sessionDetails?.orgId, sessionDetails?.isAdmin]);++ const handleToggleRestriction = (checked) => {+ const previous = restrictLlmCreation;+ setRestrictLlmCreation(checked); // optimistic+ setIsSavingRestriction(true);+ axiosPrivate({+ method: "PATCH",+ url: `/api/v1/unstract/${sessionDetails?.orgId}/organization/settings`,+ headers: {+ "X-CSRFToken": sessionDetails?.csrfToken,+ "Content-Type": "application/json",+ },+ data: { restrict_llm_adapter_creation: checked },+ })+ .then((res) => {+ setRestrictLlmCreation(+ Boolean(res?.data?.restrict_llm_adapter_creation),+ );+ setAlertDetails({+ type: "success",+ content: "LLM adapter creation setting updated.",+ });+ })+ .catch((err) => {+ setRestrictLlmCreation(previous); // revert on failure+ setAlertDetails(handleException(err, "Failed to update setting"));+ })+ .finally(() => {+ setIsSavingRestriction(false);+ });+ };+const handleSaveInterval = () => {if (!batchIntervalMinutes ||@@ -483,6 +556,32 @@ function PlatformSettings() {</Typography.Text></div></div>+ {isEnterpriseBuild && sessionDetails?.isAdmin && (+ <div className="plt-set-section">+ <Typography.Title level={5}>+ LLM Adapter Creation+ </Typography.Title>+ <Typography.Text+ type="secondary"+ className="plt-set-section-subtitle"+ >+ Restrict creation of LLM connections to organization admins.+ When enabled, non-admin users cannot create LLM adapters.+ </Typography.Text>+ <div className="plt-set-inner-card">+ <div className="plt-set-notif-field-row">+ <Switch+ checked={restrictLlmCreation}+ loading={isSavingRestriction}+ onChange={handleToggleRestriction}+ />+ <Typography.Text>+ Only admins can create LLM adapters+ </Typography.Text>+ </div>+ </div>+ </div>+ )}</div></IslandLayout></div>