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-4399 [FEAT] Organisation capability permissions API (#2344)
Ritwik Gabc0ccec12fd
diff --git a/backend/account_v2/migrations/0008_organization_capability_settings.py b/backend/account_v2/migrations/0008_organization_capability_settings.pynew file mode 100644index 000000000..4be2eac47--- /dev/null+++ b/backend/account_v2/migrations/0008_organization_capability_settings.py@@ -0,0 +1,65 @@+# Generated by Django 4.2.30 on 2026-10-14 23:16++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("account_v2", "0007_organization_restrict_connector_creation"),+ ]++ # Django 4.2 drops a column's database default after backfilling it. Keep+ # one, so an older image still running during a rollout (or after an+ # image-only rollback) can insert organizations without these columns.+ operations = [+ migrations.AddField(+ model_name="organization",+ name="restrict_api_key_management",+ field=models.BooleanField(+ db_comment="Capability: when True, only organization admins may create and rotate platform and global deployment keys. Default True is today's admin-only behaviour.",+ default=True,+ ),+ ),+ migrations.AddField(+ model_name="organization",+ name="restrict_member_management",+ field=models.BooleanField(+ db_comment="Capability: when True, only organization admins may invite members and change roles. Default True is today's admin-only behaviour.",+ default=True,+ ),+ ),+ migrations.AddField(+ model_name="organization",+ name="restrict_other_adapter_creation",+ field=models.BooleanField(+ db_comment="Capability: when True, only organization admins may create non-LLM adapters. Default False preserves open creation.",+ default=False,+ ),+ ),+ migrations.AddField(+ model_name="organization",+ name="restrict_platform_defaults",+ field=models.BooleanField(+ db_comment="Capability: when True, only organization admins may change organization-wide platform settings. Default True is today's behaviour.",+ default=True,+ ),+ ),+ migrations.AddField(+ model_name="organization",+ name="restrict_resource_deletion",+ field=models.BooleanField(+ db_comment="Capability: when True, only organization admins may delete workflows, API deployments and pipelines. Default False keeps today's owner-or-admin rule.",+ default=False,+ ),+ ),+ migrations.RunSQL(+ sql=[+ "ALTER TABLE organization ALTER COLUMN restrict_other_adapter_creation SET DEFAULT false",+ "ALTER TABLE organization ALTER COLUMN restrict_api_key_management SET DEFAULT true",+ "ALTER TABLE organization ALTER COLUMN restrict_member_management SET DEFAULT true",+ "ALTER TABLE organization ALTER COLUMN restrict_platform_defaults SET DEFAULT true",+ "ALTER TABLE organization ALTER COLUMN restrict_resource_deletion SET DEFAULT false",+ ],+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/backend/account_v2/models.py b/backend/account_v2/models.pyindex e532a9a45..447aa9947 100644--- a/backend/account_v2/models.py+++ b/backend/account_v2/models.py@@ -53,6 +53,46 @@ class Organization(models.Model):"connectors in this org. Default False preserves open creation."),)+ # Capability permissions (UN-4399): True means admins only. Defaults keep+ # today's behaviour for each capability.+ restrict_other_adapter_creation = models.BooleanField(+ default=False,+ db_comment=(+ "Capability: when True, only organization admins may create non-LLM "+ "adapters. Default False preserves open creation."+ ),+ )+ restrict_api_key_management = models.BooleanField(+ default=True,+ db_comment=(+ "Capability: when True, only organization admins may create and "+ "rotate platform and global deployment keys. Default True is "+ "today's admin-only behaviour."+ ),+ )+ restrict_member_management = models.BooleanField(+ default=True,+ db_comment=(+ "Capability: when True, only organization admins may invite members "+ "and change roles. Default True is today's admin-only behaviour."+ ),+ )+ restrict_platform_defaults = models.BooleanField(+ default=True,+ db_comment=(+ "Capability: when True, only organization admins may change "+ "organization-wide platform settings. Default True is today's "+ "behaviour."+ ),+ )+ restrict_resource_deletion = models.BooleanField(+ default=False,+ db_comment=(+ "Capability: when True, only organization admins may delete "+ "workflows, API deployments and pipelines. Default False keeps "+ "today's owner-or-admin rule."+ ),+ )class Meta:verbose_name = "Organization"diff --git a/backend/adapter_processor_v2/serializers.py b/backend/adapter_processor_v2/serializers.pyindex 02bd3982c..f59b32dff 100644--- a/backend/adapter_processor_v2/serializers.py+++ b/backend/adapter_processor_v2/serializers.py@@ -20,6 +20,7 @@ from adapter_processor_v2.deprecated_adapters import (get_deprecation_metadata,is_adapter_deprecated,)+from adapter_processor_v2.exceptions import InValidAdapterIdfrom adapter_processor_v2.image_output_gating import validate_image_output_allowedfrom backend.constants import FieldLengthConstants as FLCfrom backend.serializers import AuditSerializer@@ -111,8 +112,42 @@ class AdapterInstanceSerializer(BaseAdapterSerializer):raise ValidationError({AdapterKeys.ADAPTER_ID: get_deprecation_message(adapter_id)})+ self._reject_type_mismatch(attrs)return attrs+ def _reject_type_mismatch(self, attrs: dict[str, Any]) -> None:+ """Reject an ``adapter_type`` that is not the type of ``adapter_id``.++ The create capability is chosen from ``adapter_type`` (UN-4399), so a+ mislabelled pair would let a member past "Create LLM adapters" or+ "Create other adapters". On update either field may be absent, so each+ falls back to the stored one. An id the registry does not know is left+ to the existing paths, which already fail it when it is used.+ """+ instance = self.instance+ adapter_id = attrs.get(AdapterKeys.ADAPTER_ID) or getattr(+ instance, "adapter_id", None+ )+ declared = attrs.get(AdapterKeys.ADAPTER_TYPE) or getattr(+ instance, "adapter_type", None+ )+ if not adapter_id or not declared:+ return+ try:+ actual = AdapterProcessor.get_adapter_data_with_key(+ adapter_id, AdapterKeys.ADAPTER_TYPE+ )+ except InValidAdapterId:+ return+ if actual and actual != declared:+ raise ValidationError(+ {+ AdapterKeys.ADAPTER_TYPE: (+ f"Adapter '{adapter_id}' has type {actual}, not {declared}."+ )+ }+ )+def to_internal_value(self, data: dict[str, Any]) -> dict[str, Any]:if data.get(AdapterKeys.ADAPTER_METADATA, None):# Reject image output mode on deployments without the clouddiff --git a/backend/adapter_processor_v2/views.py b/backend/adapter_processor_v2/views.pyindex 656988231..81f537f61 100644--- a/backend/adapter_processor_v2/views.py+++ b/backend/adapter_processor_v2/views.py@@ -25,12 +25,12 @@ from platform_audit.recorder import (from 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 ModelSerializerfrom rest_framework.versioning import URLPathVersioningfrom rest_framework.viewsets import GenericViewSet, ModelViewSet+from tenant_account_v2.capabilities import Capability, enforce_capabilityfrom tenant_account_v2.organization_member_service import OrganizationMemberServicefrom tool_instance_v2.models import ToolInstancefrom utils.filtering import FilterHelper@@ -227,26 +227,17 @@ class AdapterInstanceViewSet(return 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.+ def _enforce_adapter_creation_capability(request: Any, adapter_type: str) -> None:+ """Capability permissions (UN-3584, UN-4399): LLM adapters fall under+ "Create LLM adapters", every other type under "Create other adapters".+ Service accounts bypass; the defaults keep 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."- )+ enforce_capability(+ request,+ Capability.CREATE_LLM_ADAPTERS+ if adapter_type == AdapterKeys.LLM+ else Capability.CREATE_OTHER_ADAPTERS,+ )def create(self, request: Any) -> Response:serializer = self.get_serializer(data=request.data)@@ -262,7 +253,7 @@ class AdapterInstanceViewSet(# which also covers update/partial_update.serializer.is_valid(raise_exception=True)adapter_type = serializer.validated_data.get(AdapterKeys.ADAPTER_TYPE)- self._enforce_llm_creation_restriction(request, adapter_type)+ self._enforce_adapter_creation_capability(request, adapter_type)try:if adapter_type == AdapterKeys.X2TEXT and use_platform_unstract_key:@@ -532,6 +523,11 @@ class AdapterInstanceViewSet(# Get the adapter instance for updateadapter = self.get_object()+ # Changing an adapter's type amounts to creating one of the new type,+ # so it needs the same capability as creating it would.+ new_type = request.data.get(AdapterKeys.ADAPTER_TYPE)+ if new_type and new_type != adapter.adapter_type:+ self._enforce_adapter_creation_capability(request, new_type)if use_platform_unstract_key:logger.error("Processing adapter with platform key")diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.pyindex 7440ab45f..739fc2e70 100644--- a/backend/api_v2/api_deployment_views.py+++ b/backend/api_v2/api_deployment_views.py@@ -21,6 +21,7 @@ from rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import Serializer+from tenant_account_v2.capabilities import Capability, RequiresCapabilityfrom tool_instance_v2.models import ToolInstancefrom utils.enums import CeleryTaskStatefrom utils.hubspot_notify import notify_hubspot_event@@ -291,8 +292,13 @@ class APIDeploymentViewSet(self.request, flag="is_active"):return [IsOwnerOrSharedUserOrSharedToOrg()]+ if self.action == "destroy":+ # Ownership as before, narrowed by the org's deletion capability.+ return [+ IsOwner(),+ RequiresCapability(Capability.DELETE_WORKFLOWS_AND_DEPLOYMENTS),+ ]if self.action in [- "destroy","partial_update","update","add_co_owner",diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.pyindex 05d970218..76f8f4b05 100644--- a/backend/backend/settings/base.py+++ b/backend/backend/settings/base.py@@ -1096,6 +1096,8 @@ SPECTACULAR_SETTINGS = {"ENUM_NAME_OVERRIDES": {"ErrorType": "api_v2.openapi_schema.ERROR_TYPES","ApiKeyPermission": "platform_api.models.ApiKeyPermission.choices",+ "CapabilityKey": "tenant_account_v2.capabilities.CAPABILITY_KEY_VALUES",+ "CapabilitySetting": "tenant_account_v2.capabilities.CAPABILITY_SETTING_VALUES",},# Group descriptions generated clients show in their help; without this# the spec has no root `tags` array for the text to live in.diff --git a/backend/connector_v2/views.py b/backend/connector_v2/views.pyindex ac60db475..3a869e500 100644--- a/backend/connector_v2/views.py+++ b/backend/connector_v2/views.py@@ -14,11 +14,10 @@ from permissions.resource_share_views import ResourceShareManagementMixinfrom plugins import get_pluginfrom rest_framework import status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.versioning import URLPathVersioning-from tenant_account_v2.organization_member_service import OrganizationMemberService+from tenant_account_v2.capabilities import Capability, enforce_capabilityfrom utils.filtering import FilterHelperfrom utils.pagination import OptionalPaginationfrom utils.user_context import UserContext@@ -75,18 +74,7 @@ class ConnectorInstanceViewSet(for everyone. Applies to all connector types (all connect to externalsystems)."""- if getattr(request.user, "is_service_account", False):- return- organization = UserContext.get_organization()- if (- organization- and organization.restrict_connector_creation- and not OrganizationMemberService.is_user_organization_admin(request.user)- ):- raise PermissionDenied(- "Connector creation is restricted to organization admins. "- "Please contact your organization admin."- )+ enforce_capability(request, Capability.CREATE_CONNECTORS)def get_queryset(self) -> QuerySet | None:# Avoid per-row queries for owner/co-owner + creator fields in list viewsdiff --git a/backend/pipeline_v2/views.py b/backend/pipeline_v2/views.pyindex 6ac0597e0..2171472e9 100644--- a/backend/pipeline_v2/views.py+++ b/backend/pipeline_v2/views.py@@ -23,6 +23,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.versioning import URLPathVersioningfrom scheduler.helper import SchedulerHelper+from tenant_account_v2.capabilities import Capability, RequiresCapabilityfrom utils.filters.ordering_filter import DeterministicOrderingFilterfrom utils.pagination import CustomPagination@@ -74,8 +75,13 @@ class PipelineViewSet(self.request, flag="active", ignore=("pipeline_id",)):return [IsOwnerOrSharedUserOrSharedToOrg()]+ if self.action == "destroy":+ # Ownership as before, narrowed by the org's deletion capability.+ return [+ IsOwner(),+ RequiresCapability(Capability.DELETE_WORKFLOWS_AND_DEPLOYMENTS),+ ]if self.action in [- "destroy","partial_update","update","add_co_owner",diff --git a/backend/platform_audit/README.md b/backend/platform_audit/README.mdindex 09a9d1f00..03f7f1339 100644--- a/backend/platform_audit/README.md+++ b/backend/platform_audit/README.md@@ -196,7 +196,6 @@ Expected emitters outside this PR:| Task | Action | Notes ||---|---|---|-| PB-T04 (UN-4399) | `capability.changed` | target `capability`, id = capability key, `changes` before/after audience || PB-T05 (UN-4360) | `key.expiry_set` | target per key type; cloud review keys may register their own `review_key.*` actions || PB-T08 (UN-4318) | `execution.aborted` | target `execution`; actor is the owner or admin who aborted |@@ -221,8 +220,8 @@ Expected emitters outside this PR:| `key.changed` | Key changed | keys | any other key field || `key.expiry_set` | Key expiry set | keys | PB-T05 || `default_profile.changed` | Default changed | defaults | `adapter/default_triad/`; per member, before→after adapter names per slot |-| `platform_setting.changed` | Setting changed | settings | `organization/settings` PATCH and `notifications/settings/` PATCH, one event per changed setting |-| `capability.changed` | Capability changed | capabilities | PB-T04 |+| `platform_setting.changed` | Setting changed | settings | `notifications/settings/` PATCH |+| `capability.changed` | Capability changed | capabilities | `organization/capabilities/` PATCH and `organization/settings` PATCH (its two flags are the storage of two capabilities), one event per changed capability; target `capability`, id = capability key, name = label, `changes` `{"before": {"setting": …}, "after": {"setting": …}}` with values `admins_only`/`any_member` || `execution.aborted` | Execution aborted | executions | PB-T08 |Target types: `member`, `invitation`, `group`, `platform_api_key`,diff --git a/backend/platform_audit/tests/test_events.py b/backend/platform_audit/tests/test_events.pyindex 5b82b6cad..643325a7d 100644--- a/backend/platform_audit/tests/test_events.py+++ b/backend/platform_audit/tests/test_events.py@@ -684,24 +684,23 @@ class DefaultProfileEventTests(AuditTestBase):class PlatformSettingEventTests(AuditTestBase):def test_organization_setting_changed(self) -> None:+ """Its flags are the storage of two capabilities (UN-4399), so a change+ is recorded once, as the capability changing."""response = self.call(organization_settings,"patch",data={"restrict_llm_adapter_creation": True},)self.assertEqual(response.status_code, 200)- event = self.only_event(action="platform_setting.changed")+ event = self.only_event(action="capability.changed")self.assert_admin_actor(event)self.assertEqual(- (event.target_type, event.target_id),- ("platform_setting", "restrict_llm_adapter_creation"),+ (event.target_type, event.target_id, event.target_name),+ ("capability", "create_llm_adapters", "Create LLM adapters"),)self.assertEqual(event.changes,- {- "before": {"restrict_llm_adapter_creation": False},- "after": {"restrict_llm_adapter_creation": True},- },+ {"before": {"setting": "any_member"}, "after": {"setting": "admins_only"}},)# Re-sending the same value is not a change.self.call(diff --git a/backend/tenant_account_v2/CAPABILITIES.md b/backend/tenant_account_v2/CAPABILITIES.mdnew file mode 100644index 000000000..ddc464a7b--- /dev/null+++ b/backend/tenant_account_v2/CAPABILITIES.md@@ -0,0 +1,139 @@+# Organisation capability permissions++An organisation admin decides, per capability, whether **any member** or+**only admins** may use it (UN-4399, Frontend v1 PB-T04). This README and the+`@extend_schema` annotations on `organization_capabilities` are the published+contract; the convention is the one PB-T01 set (`platform_audit/README.md`).++## Endpoint++`/api/v1/unstract/{org_id}/organization/capabilities/`++| Method | Who | Does |+|---|---|---|+| GET | any authenticated member, and platform-key service accounts | every capability, its setting, and whether it lets the caller use it |+| PATCH | organisation admins on a session (not service accounts) | sets any subset; returns the same shape as GET |++### GET++```json+{+ "capabilities": [+ {+ "key": "create_connectors",+ "label": "Create connectors",+ "description": "Add new source and destination connectors.",+ "setting": "any_member",+ "allowed_for_me": true,+ "configurable": true+ }+ ]+}+```++Always all seven, in this order:++| `key` | Default | Governs |+|---|---|---|+| `create_llm_adapters` | `any_member` | creating an LLM adapter |+| `create_connectors` | `any_member` | creating a connector |+| `create_other_adapters` | `any_member` | creating any non-LLM adapter (embedding, vector DB, text extractor, OCR) |+| `manage_api_keys` | `admins_only` | creating and rotating platform keys and global deployment keys (not per-deployment keys, which their owners manage) — **not yet enforced, see below** |+| `manage_members` | `admins_only` | inviting members and changing roles — **not yet enforced** |+| `change_platform_defaults` | `admins_only` | organisation-wide platform settings — **not yet enforced** |+| `delete_workflows_and_deployments` | `any_member` | deleting a workflow, API deployment or pipeline |++`allowed_for_me` means *the setting does not block you* — nothing more. It is+always true for admins and for service accounts (platform API keys), which no+capability setting governs. The endpoint's own rules still apply on top and+can refuse a caller this reports as allowed: deleting needs the caller to own+(or co-own) the resource; the key, member and settings endpoints keep their+existing admin and key-permission checks (for example, a `full_access`+platform key can rotate keys, a lower-tier key cannot). With `admins_only`,+owners who are not admins are refused.++`configurable` says whether PATCH accepts `any_member` for that capability. It+is false for the three marked *not yet enforced* above: setting them to+`any_member` answers 400 "Not configurable yet". A settings UI can lock those+rows from it instead of hard-coding the keys.++Only creation is governed for adapters. Changing an existing adapter's type+counts as creating one of the new type, and that check runs before the request+is validated, so a refused type change answers 403 even when the body has+other errors. An `adapter_type` that is not the registry type of `adapter_id` is+refused with 400, on create and on update (where a missing field falls back to+the stored one), so a provider cannot be filed under the other capability. Any+other edit of an existing adapter, including pointing it at a different+provider of the same type, is not governed.++### PATCH++```json+{"create_connectors": "admins_only", "delete_workflows_and_deployments": "admins_only"}+```++Any subset of keys, at least one; each value `admins_only` or `any_member`.+Every key and value is validated before anything is saved. Errors use the+standard envelope (`{type, errors[{code, detail, attr}]}`):++| Status | When |+|---|---|+| 400 | unknown key (`attr` = the key), bad value, empty body, or `any_member` for a capability that is not enforced yet |+| 403 | not an organisation admin, or a service account |+| 404 | no organisation in the request context (GET too) |++`manage_api_keys`, `manage_members` and `change_platform_defaults` accept only+`admins_only` until their enforcement lands (PR-2 of UN-4399, which waits on+the product decision about what "any member" may do there). Their endpoints+are admin-only today, so storing `any_member` would promise members something+nothing grants.++## Refusals++A governed endpoint refuses with **403** in the standard envelope. The detail+is `<label> is restricted to organisation admins.`; the two original+capabilities keep their existing messages ("LLM adapter creation is restricted+to organization admins. …", "Connector creation is restricted to organization+admins. …").++## Storage and the legacy endpoint++Each capability is a `restrict_*` boolean on `Organization` (True = admins+only). `restrict_llm_adapter_creation` and `restrict_connector_creation` are the+storage for the first two, so `organization/settings` (its request and+response unchanged; its audit events are now `capability.changed`) and this+endpoint always agree.++## Audit++Every changed capability writes one `capability.changed` platform audit event+(target `capability`, id = key, name = label, `changes`+`{"before": {"setting": …}, "after": {"setting": …}}`), from either endpoint.++## TypeScript++```ts+type CapabilityKey =+ | "create_llm_adapters" | "create_connectors" | "create_other_adapters"+ | "manage_api_keys" | "manage_members" | "change_platform_defaults"+ | "delete_workflows_and_deployments";+type CapabilitySetting = "admins_only" | "any_member";+interface Capability {+ key: CapabilityKey;+ label: string;+ description: string;+ setting: CapabilitySetting;+ allowed_for_me: boolean;+ configurable: boolean;+}+interface CapabilitiesResponse { capabilities: Capability[] }+// At least one key; an empty object is a 400.+type CapabilitiesPatchRequest = Partial<Record<CapabilityKey, CapabilitySetting>>;+```++## For emitters of new enforcement++`tenant_account_v2.capabilities.enforce_capability(request, Capability.X)`+raises the refusal; `RequiresCapability(Capability.X)` is the DRF permission+form. Neither applies to service accounts. Set the spec's `enforced=True` in the same+change that adds the enforcement.diff --git a/backend/tenant_account_v2/capabilities.py b/backend/tenant_account_v2/capabilities.pynew file mode 100644index 000000000..a86d7f086--- /dev/null+++ b/backend/tenant_account_v2/capabilities.py@@ -0,0 +1,172 @@+"""Organisation capability permissions (UN-4399).++An org admin decides, per capability, whether any member or only admins may+use it. Each setting is a ``restrict_<...>`` boolean on ``Organization``+(True = admins only); the two legacy controlled-mode flags are the storage for+the first two capabilities, so ``organization/settings`` and+``organization/capabilities/`` stay in step by construction.++Service accounts (platform API keys) are never subject to a capability+setting. That is all a capability decides: each endpoint's own rules (admin+checks, key permission levels, ownership) still apply on top, unchanged.+"""++from dataclasses import dataclass+from enum import StrEnum+from typing import Any++from account_v2.models import Organization+from rest_framework.exceptions import PermissionDenied+from rest_framework.permissions import BasePermission+from utils.user_context import UserContext++from tenant_account_v2.organization_member_service import OrganizationMemberService+++class Capability(StrEnum):+ """In the design's order."""++ CREATE_LLM_ADAPTERS = "create_llm_adapters"+ CREATE_CONNECTORS = "create_connectors"+ CREATE_OTHER_ADAPTERS = "create_other_adapters"+ MANAGE_API_KEYS = "manage_api_keys"+ MANAGE_MEMBERS = "manage_members"+ CHANGE_PLATFORM_DEFAULTS = "change_platform_defaults"+ DELETE_WORKFLOWS_AND_DEPLOYMENTS = "delete_workflows_and_deployments"+++class CapabilitySetting(StrEnum):+ ADMINS_ONLY = "admins_only"+ ANY_MEMBER = "any_member"+++# The serializers' choices, and the targets of the schema's enum-name overrides+# (drf-spectacular matches overrides on the choice set, not on the Enum).+CAPABILITY_KEY_VALUES = [capability.value for capability in Capability]+CAPABILITY_SETTING_VALUES = [setting.value for setting in CapabilitySetting]+++@dataclass(frozen=True)+class CapabilitySpec:+ key: Capability+ label: str+ description: str+ field: str # the Organization BooleanField; True means admins only+ # False while the endpoints that the capability governs do not enforce+ # it yet; such a capability can only be "admins_only" (today's behaviour).+ enforced: bool+ # A refusal's message. Legacy capabilities keep their existing wording so+ # existing responses do not change.+ denied_message: str = ""++ def message(self) -> str:+ return self.denied_message or (+ f"{self.label} is restricted to organisation admins."+ )+++SPECS: tuple[CapabilitySpec, ...] = (+ CapabilitySpec(+ Capability.CREATE_LLM_ADAPTERS,+ "Create LLM adapters",+ "Add new LLM provider connections.",+ "restrict_llm_adapter_creation",+ enforced=True,+ denied_message=(+ "LLM adapter creation is restricted to organization admins. "+ "Please contact your organization admin."+ ),+ ),+ CapabilitySpec(+ Capability.CREATE_CONNECTORS,+ "Create connectors",+ "Add new source and destination connectors.",+ "restrict_connector_creation",+ enforced=True,+ denied_message=(+ "Connector creation is restricted to organization admins. "+ "Please contact your organization admin."+ ),+ ),+ CapabilitySpec(+ Capability.CREATE_OTHER_ADAPTERS,+ "Create other adapters",+ "Add embedding, vector database, text extractor and OCR adapters.",+ "restrict_other_adapter_creation",+ enforced=True,+ ),+ CapabilitySpec(+ Capability.MANAGE_API_KEYS,+ "Manage API keys",+ "Create and rotate platform keys and global deployment keys "+ "(not per-deployment keys, which their owners manage).",+ "restrict_api_key_management",+ enforced=False,+ ),+ CapabilitySpec(+ Capability.MANAGE_MEMBERS,+ "Manage members",+ "Invite members and change their roles.",+ "restrict_member_management",+ enforced=False,+ ),+ CapabilitySpec(+ Capability.CHANGE_PLATFORM_DEFAULTS,+ "Change platform defaults",+ "Change organisation-wide platform settings.",+ "restrict_platform_defaults",+ enforced=False,+ ),+ CapabilitySpec(+ Capability.DELETE_WORKFLOWS_AND_DEPLOYMENTS,+ "Delete workflows and deployments",+ "Delete workflows, API deployments and pipelines the member owns.",+ "restrict_resource_deletion",+ enforced=True,+ ),+)++SPECS_BY_KEY: dict[str, CapabilitySpec] = {spec.key.value: spec for spec in SPECS}+++def setting_of(organization: Organization, spec: CapabilitySpec) -> CapabilitySetting:+ if getattr(organization, spec.field):+ return CapabilitySetting.ADMINS_ONLY+ return CapabilitySetting.ANY_MEMBER+++def is_allowed(user: Any, organization: Organization | None, key: Capability) -> bool:+ """Whether the setting lets ``user`` use the capability.++ It says only that the setting does not block them: the endpoint's own+ rules (for example, deleting needs ownership) still apply on top.+ """+ spec = SPECS_BY_KEY[key]+ if getattr(user, "is_service_account", False) or organization is None:+ return True+ if setting_of(organization, spec) == CapabilitySetting.ANY_MEMBER:+ return True+ return OrganizationMemberService.is_user_organization_admin(user)+++def enforce_capability(request: Any, key: Capability) -> None:+ """Raise ``PermissionDenied`` when the org restricts ``key`` to admins and+ the caller is not one.+ """+ if not is_allowed(request.user, UserContext.get_organization(), key):+ raise PermissionDenied(SPECS_BY_KEY[key].message())+++class RequiresCapability(BasePermission):+ """A DRF permission that applies ``enforce_capability`` for one key.++ Use it beside an endpoint's existing permission classes; it narrows, never+ widens, what they allow.+ """++ def __init__(self, key: Capability) -> None:+ self.key = key++ def has_permission(self, request: Any, view: Any) -> bool:+ enforce_capability(request, self.key)+ return Truediff --git a/backend/tenant_account_v2/serializer.py b/backend/tenant_account_v2/serializer.pyindex 6851d88d0..8b1789e0e 100644--- a/backend/tenant_account_v2/serializer.py+++ b/backend/tenant_account_v2/serializer.py@@ -6,6 +6,13 @@ from rest_framework import serializersfrom rest_framework.exceptions import ValidationErrorfrom rest_framework.serializers import ModelSerializer+from tenant_account_v2.capabilities import (+ CAPABILITY_KEY_VALUES,+ CAPABILITY_SETTING_VALUES,+ SPECS,+ SPECS_BY_KEY,+ CapabilitySetting,+)from tenant_account_v2.models import OrganizationMember@@ -161,3 +168,58 @@ class UpdateFlagSerializer(ModelSerializer):class Meta:model = OrganizationMemberfields = ("is_login_onboarding_msg", "is_prompt_studio_onboarding_msg")+++class CapabilitySerializer(serializers.Serializer):+ key = serializers.ChoiceField(choices=CAPABILITY_KEY_VALUES)+ label = serializers.CharField()+ description = serializers.CharField()+ setting = serializers.ChoiceField(choices=CAPABILITY_SETTING_VALUES)+ allowed_for_me = serializers.BooleanField(+ help_text="The setting does not block the caller. The endpoint's own "+ "rules (admin checks, platform-key permission level, ownership) still "+ "apply. Always true for admins and service accounts."+ )+ configurable = serializers.BooleanField(+ help_text="Whether PATCH accepts any_member for this capability. False "+ "while the endpoints it governs still allow only admins; setting "+ "any_member then answers 400."+ )+++class CapabilitiesResponseSerializer(serializers.Serializer):+ capabilities = CapabilitySerializer(many=True)+++class CapabilitiesPatchSerializer(serializers.Serializer):+ """A ``{capability: setting}`` map; any subset, at least one key.++ Every key and value is checked before anything is saved. A capability+ whose endpoints do not enforce it yet only accepts ``admins_only``.+ """++ def get_fields(self) -> dict[str, serializers.Field]:+ return {+ spec.key.value: serializers.ChoiceField(+ choices=CAPABILITY_SETTING_VALUES, required=False+ )+ for spec in SPECS+ }++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ unknown = sorted(set(self.initial_data or {}) - set(SPECS_BY_KEY))+ if unknown:+ raise ValidationError(dict.fromkeys(unknown, "Unknown capability."))+ if not attrs:+ raise ValidationError("Provide at least one capability.")+ not_yet = {+ key: (+ "Not configurable yet: the endpoints it governs still allow "+ "only organisation admins."+ )+ for key, value in attrs.items()+ if value == CapabilitySetting.ANY_MEMBER and not SPECS_BY_KEY[key].enforced+ }+ if not_yet:+ raise ValidationError(not_yet)+ return attrsdiff --git a/backend/tenant_account_v2/test_capabilities.py b/backend/tenant_account_v2/test_capabilities.pynew file mode 100644index 000000000..16fc9d86f--- /dev/null+++ b/backend/tenant_account_v2/test_capabilities.py@@ -0,0 +1,528 @@+"""Organisation capability permissions (UN-4399).++The OSS auth service treats the ``admin`` role as admin, so the fixtures'+roles drive ``is_user_organization_admin`` directly.+"""++import importlib+import re+from types import SimpleNamespace+from unittest.mock import patch++from account_v2.models import Organization+from adapter_processor_v2.models import AdapterInstance+from adapter_processor_v2.views import AdapterInstanceViewSet+from api_v2.api_deployment_views import APIDeploymentViewSet+from connector_v2.models import ConnectorInstance+from connector_v2.views import ConnectorInstanceViewSet+from django.test import SimpleTestCase+from drf_spectacular.generators import SchemaGenerator+from permissions.permission import IsOwner+from permissions.roles import ResourceRole+from pipeline_v2.views import PipelineViewSet+from platform_audit.tests.base import AuditTestBase, make_user+from rest_framework.exceptions import PermissionDenied+from workflow_manager.workflow_v2.models.workflow import Workflow+from workflow_manager.workflow_v2.views import WorkflowViewSet++from tenant_account_v2 import urls as tenant_urls+from tenant_account_v2.capabilities import (+ SPECS,+ Capability,+ CapabilitySetting,+)+from tenant_account_v2.views import organization_capabilities, organization_settings++ENFORCED = [spec for spec in SPECS if spec.enforced]+++class CapabilityRegistryTests(SimpleTestCase):+ def test_every_capability_has_one_spec_in_design_order(self) -> None:+ self.assertEqual([s.key for s in SPECS], list(Capability))++ def test_every_spec_is_stored_on_organization(self) -> None:+ fields = {f.name for f in Organization._meta.get_fields()}+ for spec in SPECS:+ with self.subTest(key=spec.key.value):+ self.assertIn(spec.field, fields)++ def test_new_capabilities_use_the_standard_message(self) -> None:+ spec = next(s for s in SPECS if s.key == Capability.CREATE_OTHER_ADAPTERS)+ self.assertEqual(+ spec.message(), "Create other adapters is restricted to organisation admins."+ )++ def test_migration_database_defaults_match_the_model(self) -> None:+ # Django drops a column's database default after AddField, so the+ # migration sets them by hand; they must agree with the model.+ migration = importlib.import_module(+ "account_v2.migrations.0008_organization_capability_settings"+ ).Migration+ sql = " ".join(+ statement+ for op in migration.operations+ if op.__class__.__name__ == "RunSQL"+ for statement in op.sql+ )+ found = dict(re.findall(r"ALTER COLUMN (\w+) SET DEFAULT (true|false)", sql))+ new_fields = {+ spec.field+ for spec in SPECS+ if spec.field+ not in ("restrict_llm_adapter_creation", "restrict_connector_creation")+ }+ self.assertEqual(set(found), new_fields)+ for column, default in found.items():+ with self.subTest(column=column):+ self.assertEqual(+ default == "true",+ Organization._meta.get_field(column).default,+ )++ def test_schema_names_the_capability_enums_as_the_contract_does(self) -> None:+ schema = SchemaGenerator(patterns=tenant_urls.urlpatterns).get_schema(+ request=None, public=True+ )+ components = schema["components"]["schemas"]+ self.assertEqual(+ components["CapabilityKey"]["enum"], [c.value for c in Capability]+ )+ self.assertEqual(+ components["CapabilitySetting"]["enum"], ["admins_only", "any_member"]+ )+ # No field-named duplicate (KeyEnum, SettingEnum) of either.+ duplicated = [+ name+ for name, component in components.items()+ if name.endswith("Enum")+ and component.get("enum")+ in ([c.value for c in Capability], ["admins_only", "any_member"])+ ]+ self.assertEqual(duplicated, [])+++class CapabilityTestBase(AuditTestBase):+ def setUp(self) -> None:+ super().setUp()+ self.service_account = make_user("[email protected]", is_service_account=True)++ def restrict(self, key: Capability, restricted: bool) -> None:+ spec = next(s for s in SPECS if s.key == key)+ Organization.objects.filter(pk=self.org.pk).update(**{spec.field: restricted})+ self.org.refresh_from_db()++ def capabilities(self, user) -> dict[str, dict]:+ response = self.call(organization_capabilities, "get", user=user)+ self.assertEqual(response.status_code, 200)+ return {row["key"]: row for row in response.data["capabilities"]}+++class CapabilitiesApiTests(CapabilityTestBase):+ def test_defaults_are_todays_behaviour(self) -> None:+ rows = self.capabilities(self.member)+ expected = {+ "create_llm_adapters": ("any_member", True),+ "create_connectors": ("any_member", True),+ "create_other_adapters": ("any_member", True),+ "manage_api_keys": ("admins_only", False),+ "manage_members": ("admins_only", False),+ "change_platform_defaults": ("admins_only", False),+ "delete_workflows_and_deployments": ("any_member", True),+ }+ self.assertEqual(+ {k: (r["setting"], r["allowed_for_me"]) for k, r in rows.items()},+ expected,+ )+ self.assertEqual(list(rows), [s.key.value for s in SPECS])+ self.assertEqual(rows["create_connectors"]["label"], "Create connectors")+ self.assertEqual(+ {k for k, r in rows.items() if not r["configurable"]},+ {"manage_api_keys", "manage_members", "change_platform_defaults"},+ )++ def test_admins_are_always_allowed(self) -> None:+ rows = self.capabilities(self.admin)+ self.assertTrue(all(r["allowed_for_me"] for r in rows.values()))++ def test_no_setting_blocks_service_accounts(self) -> None:+ for spec in SPECS:+ self.restrict(spec.key, True)+ rows = self.capabilities(self.service_account)+ self.assertTrue(all(r["allowed_for_me"] for r in rows.values()))++ def test_no_organization_is_a_404_in_the_standard_envelope(self) -> None:+ with patch(+ "tenant_account_v2.views.UserContext.get_organization", return_value=None+ ):+ for method, data in (+ ("get", None),+ ("patch", {"create_connectors": "admins_only"}),+ ):+ with self.subTest(method=method):+ response = self.call(+ organization_capabilities, method, user=self.admin, data=data+ )+ self.assertEqual(response.status_code, 404)+ self.assertEqual(response.data["type"], "client_error")++ def test_service_account_cannot_patch(self) -> None:+ response = self.call(+ organization_capabilities,+ "patch",+ user=self.service_account,+ data={"create_connectors": "admins_only"},+ )+ self.assertEqual(response.status_code, 403)++ def test_member_cannot_patch(self) -> None:+ response = self.call(+ organization_capabilities,+ "patch",+ user=self.member,+ data={"create_connectors": "admins_only"},+ )+ self.assertEqual(response.status_code, 403)+ self.org.refresh_from_db()+ self.assertFalse(self.org.restrict_connector_creation)++ def test_admin_patch_saves_and_returns_the_full_list(self) -> None:+ response = self.call(+ organization_capabilities,+ "patch",+ data={+ "create_connectors": "admins_only",+ "delete_workflows_and_deployments": "admins_only",+ },+ )+ self.assertEqual(response.status_code, 200, response.data)+ self.assertEqual(len(response.data["capabilities"]), len(SPECS))+ self.org.refresh_from_db()+ self.assertTrue(self.org.restrict_connector_creation)+ self.assertTrue(self.org.restrict_resource_deletion)+ rows = self.capabilities(self.member)+ self.assertFalse(rows["create_connectors"]["allowed_for_me"])++ def test_patch_rejects_bad_input_and_saves_nothing(self) -> None:+ for body, attr in (+ ({"create_connectors": "admins_only", "nope": "admins_only"}, "nope"),+ ({"create_connectors": "admins_only", "create_llm_adapters": "x"}, None),+ ({"manage_members": "any_member", "create_connectors": "admins_only"}, None),+ ({}, None),+ ):+ with self.subTest(body=str(body)):+ response = self.call(organization_capabilities, "patch", data=body)+ self.assertEqual(response.status_code, 400, response.data)+ self.org.refresh_from_db()+ self.assertFalse(self.org.restrict_connector_creation)++ def test_unenforced_capabilities_accept_only_admins_only(self) -> None:+ for spec in SPECS:+ if spec.enforced:+ continue+ with self.subTest(key=spec.key.value):+ ok = self.call(+ organization_capabilities,+ "patch",+ data={spec.key.value: "admins_only"},+ )+ self.assertEqual(ok.status_code, 200)+ refused = self.call(+ organization_capabilities,+ "patch",+ data={spec.key.value: "any_member"},+ )+ self.assertEqual(refused.status_code, 400)++ def test_legacy_settings_and_capabilities_stay_in_step(self) -> None:+ self.call(+ organization_settings, "patch", data={"restrict_llm_adapter_creation": True}+ )+ self.assertEqual(+ self.capabilities(self.admin)["create_llm_adapters"]["setting"],+ CapabilitySetting.ADMINS_ONLY,+ )+ self.call(+ organization_capabilities, "patch", data={"create_connectors": "admins_only"}+ )+ response = self.call(organization_settings, "get")+ self.assertEqual(+ response.data,+ {"restrict_llm_adapter_creation": True, "restrict_connector_creation": True},+ )++ def test_each_change_is_audited_once(self) -> None:+ self.call(+ organization_capabilities,+ "patch",+ data={+ "create_connectors": "admins_only",+ "create_llm_adapters": "any_member",+ },+ )+ event = self.only_event(action="capability.changed")+ self.assert_admin_actor(event)+ self.assertEqual(+ (event.target_type, event.target_id, event.target_name),+ ("capability", "create_connectors", "Create connectors"),+ )+ self.assertEqual(+ event.changes,+ {"before": {"setting": "any_member"}, "after": {"setting": "admins_only"}},+ )++ def test_before_is_read_from_the_row_not_the_requests_copy(self) -> None:+ # A concurrent request saved admins_only after this one loaded the+ # org, so this one's copy is stale. Lifting the restriction must still+ # be audited, from both endpoints.+ lifted = {+ "before": {"setting": "admins_only"},+ "after": {"setting": "any_member"},+ }+ for count, (view, data) in enumerate(+ (+ (organization_capabilities, {"create_connectors": "any_member"}),+ (organization_settings, {"restrict_connector_creation": False}),+ ),+ start=1,+ ):+ with self.subTest(view=view.__name__):+ stale = Organization.objects.get(pk=self.org.pk)+ self.restrict(Capability.CREATE_CONNECTORS, True)+ with patch(+ "tenant_account_v2.views.UserContext.get_organization",+ return_value=stale,+ ):+ response = self.call(view, "patch", data=data)+ self.assertEqual(response.status_code, 200)+ events = self.events(action="capability.changed")+ self.assertEqual([e.changes for e in events], [lifted] * count)+++class EnforcementMatrixTests(CapabilityTestBase):+ """Each enforced capability x {admins_only, any_member} x {admin, member,+ service account}.+ """++ def _allowed(self, key: Capability, user) -> bool:+ if key == Capability.CREATE_CONNECTORS:+ response = self._create_connector(user)+ if response.status_code == 403:+ return False+ self.assertEqual(response.status_code, 201, response.data)+ return True+ if key in (Capability.CREATE_LLM_ADAPTERS, Capability.CREATE_OTHER_ADAPTERS):+ adapter_type = "LLM" if key == Capability.CREATE_LLM_ADAPTERS else "EMBEDDING"+ response = self._create_adapter(user, adapter_type)+ if response.status_code == 403:+ return False+ self.assertEqual(response.status_code, 201, response.data)+ return True+ return self._may_delete_owned_workflow(user)++ def _create_connector(self, user):+ # The connector and payload shape of connector_v2's register test.+ # Creating stores the metadata without contacting the storage.+ view = ConnectorInstanceViewSet.as_view({"post": "create"})+ payload = {+ "connector_id": "minio|c799f6e3-2b57-434e-aaac-b5daa415da19",+ "connector_name": f"minio-{user.pk}-{ConnectorInstance.objects.count()}",+ "connector_metadata": {+ "connectorName": "minio",+ "key": "access-key",+ "secret": "secret-key",+ "endpoint_url": "http://minio.invalid:9000",+ "region_name": "",+ "bucket": "bucket",+ "path": "/",+ },+ }+ return self.call(view, "post", user=user, data=payload)++ def _create_adapter(self, user, adapter_type: str):+ view = AdapterInstanceViewSet.as_view({"post": "create"})+ payload = {+ "adapter_id": "openai|test",+ "adapter_name": f"{adapter_type}-{user.pk}-{AdapterInstance.objects.count()}",+ "adapter_type": adapter_type,+ "adapter_metadata": {"api_key": "sk-test", "model": "gpt-4o-mini"},+ }+ with patch.object(AdapterInstance, "get_context_window_size", return_value=4096):+ return self.call(view, "post", user=user, data=payload)++ def _may_delete_owned_workflow(self, user) -> bool:+ workflow = Workflow.objects.create(+ workflow_name=f"wf-{user.pk}-{Workflow.objects.count()}",+ organization=self.org,+ created_by=user,+ )+ workflow.memberships.create(user=user, role=ResourceRole.OWNER)+ view = WorkflowViewSet.as_view({"delete": "destroy"})+ response = self.call(view, "delete", user=user, pk=workflow.pk)+ if response.status_code == 403:+ return False+ self.assertIn(response.status_code, (200, 204), getattr(response, "data", None))+ return True++ def test_matrix(self) -> None:+ for spec in ENFORCED:+ for restricted in (True, False):+ self.restrict(spec.key, restricted)+ for name, user, expected in (+ ("admin", self.admin, True),+ ("member", self.member, not restricted),+ ("service account", self.service_account, True),+ ):+ with self.subTest(+ key=spec.key.value, restricted=restricted, user=name+ ):+ self.assertEqual(self._allowed(spec.key, user), expected)++ def test_refusal_messages(self) -> None:+ self.restrict(Capability.CREATE_CONNECTORS, True)+ self.restrict(Capability.CREATE_LLM_ADAPTERS, True)+ self.restrict(Capability.CREATE_OTHER_ADAPTERS, True)+ view = ConnectorInstanceViewSet.as_view({"post": "create"})+ response = self.call(view, "post", user=self.member, data={})+ self.assertIn(+ "Connector creation is restricted to organization admins",+ str(response.data),+ )+ response = self._create_adapter(self.member, "LLM")+ self.assertIn(+ "LLM adapter creation is restricted to organization admins",+ str(response.data),+ )+ response = self._create_adapter(self.member, "EMBEDDING")+ self.assertIn(+ "Create other adapters is restricted to organisation admins",+ str(response.data),+ )++ def test_changing_an_adapters_type_needs_the_new_types_capability(self) -> None:+ created = self._create_adapter(self.member, "EMBEDDING")+ self.assertEqual(created.status_code, 201, created.data)+ self.restrict(Capability.CREATE_LLM_ADAPTERS, True)+ view = AdapterInstanceViewSet.as_view({"patch": "partial_update"})+ response = self.call(+ view,+ "patch",+ user=self.member,+ data={"adapter_type": "LLM"},+ pk=created.data["id"],+ )+ self.assertEqual(response.status_code, 403)+ self.assertEqual(+ AdapterInstance.objects.get(pk=created.data["id"]).adapter_type, "EMBEDDING"+ )++ def test_editing_an_adapter_without_changing_its_type_stays_allowed(self) -> None:+ # The frontend always sends adapter_type on an edit.+ created = self._create_adapter(self.member, "LLM")+ self.assertEqual(created.status_code, 201, created.data)+ self.restrict(Capability.CREATE_LLM_ADAPTERS, True)+ view = AdapterInstanceViewSet.as_view({"patch": "partial_update"})+ with patch.object(AdapterInstance, "get_context_window_size", return_value=4096):+ response = self.call(+ view,+ "patch",+ user=self.member,+ data={"adapter_type": "LLM", "adapter_name": "renamed"},+ pk=created.data["id"],+ )+ self.assertEqual(response.status_code, 200, response.data)+ self.assertEqual(+ AdapterInstance.objects.get(pk=created.data["id"]).adapter_name, "renamed"+ )++ # Real registry ids (unstract.sdk1 Adapterkit): the OpenAI LLM and the+ # OpenAI embedding adapter.+ OPENAI_LLM = "openai|502ecf49-e47c-445c-9907-6d4b90c5cd17"+ OPENAI_EMBEDDING = "openai|717a0b0e-3bbc-41dc-9f0c-5689437a1151"++ def _create_adapter_as(self, user, adapter_id: str, adapter_type: str):+ view = AdapterInstanceViewSet.as_view({"post": "create"})+ payload = {+ "adapter_id": adapter_id,+ "adapter_name": f"mislabelled-{AdapterInstance.objects.count()}",+ "adapter_type": adapter_type,+ "adapter_metadata": {"api_key": "sk-test", "model": "gpt-4o-mini"},+ }+ with patch.object(AdapterInstance, "get_context_window_size", return_value=4096):+ return self.call(view, "post", user=user, data=payload)++ def test_a_mislabelled_adapter_type_is_refused_both_ways(self) -> None:+ # Each label would pass the open capability while the id belongs to+ # the restricted one.+ for restricted, adapter_id, label in (+ (Capability.CREATE_LLM_ADAPTERS, self.OPENAI_LLM, "EMBEDDING"),+ (Capability.CREATE_OTHER_ADAPTERS, self.OPENAI_EMBEDDING, "LLM"),+ ):+ with self.subTest(restricted=restricted.value):+ self.restrict(Capability.CREATE_LLM_ADAPTERS, False)+ self.restrict(Capability.CREATE_OTHER_ADAPTERS, False)+ self.restrict(restricted, True)+ before = AdapterInstance.objects.count()+ response = self._create_adapter_as(self.member, adapter_id, label)+ self.assertEqual(response.status_code, 400, response.data)+ self.assertEqual(response.data["errors"][0]["attr"], "adapter_type")+ self.assertEqual(AdapterInstance.objects.count(), before)++ def test_a_correctly_labelled_registry_adapter_is_created(self) -> None:+ response = self._create_adapter_as(self.member, self.OPENAI_LLM, "LLM")+ self.assertEqual(response.status_code, 201, response.data)++ def test_switching_adapter_id_to_another_types_provider_is_refused(self) -> None:+ created = self._create_adapter_as(self.member, self.OPENAI_EMBEDDING, "EMBEDDING")+ self.assertEqual(created.status_code, 201, created.data)+ self.restrict(Capability.CREATE_LLM_ADAPTERS, True)+ view = AdapterInstanceViewSet.as_view({"patch": "partial_update"})+ with patch.object(AdapterInstance, "get_context_window_size", return_value=4096):+ response = self.call(+ view,+ "patch",+ user=self.member,+ data={"adapter_id": self.OPENAI_LLM},+ pk=created.data["id"],+ )+ self.assertEqual(response.status_code, 400, response.data)+ self.assertEqual(+ AdapterInstance.objects.get(pk=created.data["id"]).adapter_id,+ self.OPENAI_EMBEDDING,+ )++ def test_deleting_still_needs_ownership(self) -> None:+ stranger_owned = Workflow.objects.create(+ workflow_name="not-yours", organization=self.org, created_by=self.admin+ )+ stranger_owned.memberships.create(user=self.admin, role=ResourceRole.OWNER)+ # Shared with the member, so they can see it but do not own it.+ stranger_owned.memberships.create(user=self.member, role=ResourceRole.VIEWER)+ view = WorkflowViewSet.as_view({"delete": "destroy"})+ for restricted in (False, True):+ self.restrict(Capability.DELETE_WORKFLOWS_AND_DEPLOYMENTS, restricted)+ with self.subTest(restricted=restricted):+ response = self.call(+ view, "delete", user=self.member, pk=stranger_owned.pk+ )+ self.assertEqual(response.status_code, 403)+ for viewset in (APIDeploymentViewSet, PipelineViewSet, WorkflowViewSet):+ with self.subTest(viewset=viewset.__name__):+ view = viewset()+ view.action = "destroy"+ self.assertTrue(+ any(isinstance(p, IsOwner) for p in view.get_permissions())+ )++ def test_deletion_capability_applies_to_deployments_and_pipelines(self) -> None:+ self.restrict(Capability.DELETE_WORKFLOWS_AND_DEPLOYMENTS, True)+ for viewset in (APIDeploymentViewSet, PipelineViewSet, WorkflowViewSet):+ with self.subTest(viewset=viewset.__name__):+ view = viewset()+ view.action = "destroy"+ request = SimpleNamespace(user=self.member, method="DELETE")+ with self.assertRaisesMessage(+ PermissionDenied,+ "Delete workflows and deployments is restricted to organisation admins.",+ ):+ for permission in view.get_permissions():+ permission.has_permission(request, view)diff --git a/backend/tenant_account_v2/urls.py b/backend/tenant_account_v2/urls.pyindex 4b7aec849..e0b1d7721 100644--- a/backend/tenant_account_v2/urls.py+++ b/backend/tenant_account_v2/urls.py@@ -4,6 +4,7 @@ from tenant_account_v2 import groups_urls, invitation_urls, users_urlsfrom tenant_account_v2.views import (get_organization,get_roles,+ organization_capabilities,organization_settings,reset_password,)@@ -18,6 +19,11 @@ urlpatterns = [organization_settings,name="organization_settings",),+ path(+ "organization/capabilities/",+ organization_capabilities,+ name="organization_capabilities",+ ),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 e2744e3ec..d7806ccbb 100644--- a/backend/tenant_account_v2/views.py+++ b/backend/tenant_account_v2/views.py@@ -4,19 +4,36 @@ from typing import Anyfrom account_v2.authentication_controller import AuthenticationControllerfrom account_v2.dto import UserRoleDatafrom account_v2.models import Organization+from django.db import transaction+from drf_spectacular.utils import extend_schema+from drf_standardized_errors.openapi_serializers import (+ ErrorResponse403Serializer,+ ErrorResponse404Serializer,+ ValidationErrorResponseSerializer,+)from platform_api.permissions import IsOrganizationAdminfrom platform_audit.actions import Action, TargetType-from platform_audit.recorder import record_platform_event+from platform_audit.recorder import best_effort, record_platform_eventfrom rest_framework import statusfrom rest_framework.decorators import api_view, permission_classes+from rest_framework.exceptions import NotFound, PermissionDeniedfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom utils.user_context import UserContextfrom utils.user_session import UserSessionUtils+from tenant_account_v2.capabilities import (+ SPECS,+ SPECS_BY_KEY,+ CapabilitySetting,+ is_allowed,+ setting_of,+)from tenant_account_v2.dto import OrganizationLoginResponse, ResetUserPasswordDtofrom tenant_account_v2.serializer import (+ CapabilitiesPatchSerializer,+ CapabilitiesResponseSerializer,GetRolesResponseSerializer,OrganizationLoginResponseSerializer,)@@ -105,12 +122,10 @@ def organization_settings(request: Request) -> Response:status=status.HTTP_400_BAD_REQUEST,data={"message": f"{flag} must be a boolean"},)- before = {flag: getattr(organization, flag) for flag in provided}- for flag, value in provided.items():- setattr(organization, flag, value)- organization.modified_by = request.user- organization.save(update_fields=[*provided, "modified_by", "modified_at"])- _record_setting_changes(request, before, provided)+ organization, before = _save_restrictions(request, organization, provided)+ # These flags are the storage of two capabilities, so a change here is+ # recorded as that capability changing, once, as from the new endpoint.+ _record_capability_changes(request, organization, before)return Response(status=status.HTTP_200_OK,@@ -118,20 +133,6 @@ def organization_settings(request: Request) -> Response:)-def _record_setting_changes(request: Request, before: dict, provided: dict) -> None:- for flag, value in provided.items():- if before[flag] != value:- record_platform_event(- action=Action.PLATFORM_SETTING_CHANGED,- target_type=TargetType.PLATFORM_SETTING,- target_id=flag,- target_name=flag,- changes={"before": {flag: before[flag]}, "after": {flag: value}},- summary=f"{flag}: {before[flag]} → {value}",- request=request,- )--@api_view(["GET"])def get_organization(request: Request) -> Response:auth_controller = AuthenticationController()@@ -168,3 +169,119 @@ def makeSignupResponse(organization.created_at,)).data+++def _capabilities_payload(request: Request, organization: Organization) -> dict:+ return {+ "capabilities": [+ {+ "key": spec.key.value,+ "label": spec.label,+ "description": spec.description,+ "setting": setting_of(organization, spec).value,+ "allowed_for_me": is_allowed(request.user, organization, spec.key),+ "configurable": spec.enforced,+ }+ for spec in SPECS+ ]+ }+++@extend_schema(+ methods=["GET"],+ operation_id="organization_capabilities_retrieve",+ tags=["organization-capabilities"],+ responses={+ 200: CapabilitiesResponseSerializer,+ 403: ErrorResponse403Serializer,+ 404: ErrorResponse404Serializer,+ },+ description="Every capability, its setting, and whether it lets the caller "+ "use it. Any member may read it.",+)+@extend_schema(+ methods=["PATCH"],+ operation_id="organization_capabilities_partial_update",+ tags=["organization-capabilities"],+ request=CapabilitiesPatchSerializer,+ responses={+ 200: CapabilitiesResponseSerializer,+ 400: ValidationErrorResponseSerializer,+ 403: ErrorResponse403Serializer,+ 404: ErrorResponse404Serializer,+ },+ description="Set any subset of capabilities. Organisation admins only. "+ "Every key and value is validated before anything is saved.",+)+@api_view(["GET", "PATCH"])+@permission_classes([IsAuthenticated])+def organization_capabilities(request: Request) -> Response:+ """Read capability settings (any member) or change them (admins only)."""+ organization = UserContext.get_organization()+ if not organization:+ raise NotFound("Organization not found.")+ if request.method == "PATCH":+ if not IsOrganizationAdmin().has_permission(request, None):+ raise PermissionDenied(+ "Only organization admins can change capability settings."+ )+ serializer = CapabilitiesPatchSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ changed = {+ SPECS_BY_KEY[key].field: value == CapabilitySetting.ADMINS_ONLY+ for key, value in serializer.validated_data.items()+ }+ organization, before = _save_restrictions(request, organization, changed)+ _record_capability_changes(request, organization, before)+ return Response(+ status=status.HTTP_200_OK, data=_capabilities_payload(request, organization)+ )+++def _save_restrictions(+ request: Request, organization: Organization, values: dict[str, bool]+) -> tuple[Organization, dict[str, bool]]:+ """Save ``restrict_*`` fields and return the row with its values before.++ The row is locked while it is read and written, so of two concurrent+ changes the second sees the first's result as its "before" and the audit+ records every change. Both settings endpoints write through here.+ """+ with transaction.atomic():+ locked = Organization.objects.select_for_update().get(pk=organization.pk)+ before = {field: getattr(locked, field) for field in values}+ for field, value in values.items():+ setattr(locked, field, value)+ locked.modified_by = request.user+ locked.save(update_fields=[*values, "modified_by", "modified_at"])+ return locked, before+++@best_effort+def _record_capability_changes(+ request: Request, organization: Organization, before: dict[str, bool]+) -> None:+ """One ``capability.changed`` per capability whose setting changed."""+ for spec in SPECS:+ if spec.field not in before:+ continue+ old = _as_setting(before[spec.field])+ new = setting_of(organization, spec).value+ if old == new:+ continue+ record_platform_event(+ action=Action.CAPABILITY_CHANGED,+ target_type=TargetType.CAPABILITY,+ target_id=spec.key.value,+ target_name=spec.label,+ changes={"before": {"setting": old}, "after": {"setting": new}},+ summary=f"{old} → {new}",+ request=request,+ organization=organization,+ )+++def _as_setting(restricted: bool) -> str:+ return (+ CapabilitySetting.ADMINS_ONLY if restricted else CapabilitySetting.ANY_MEMBER+ ).valuediff --git a/backend/workflow_manager/workflow_v2/views.py b/backend/workflow_manager/workflow_v2/views.pyindex 938ed6c53..e2eb0a8be 100644--- a/backend/workflow_manager/workflow_v2/views.py+++ b/backend/workflow_manager/workflow_v2/views.py@@ -19,6 +19,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.versioning import URLPathVersioningfrom rest_framework.views import APIView+from tenant_account_v2.capabilities import Capability, RequiresCapabilityfrom utils.filtering import FilterHelperfrom utils.organization_utils import filter_queryset_by_organization, resolve_organizationfrom utils.pagination import OptionalPagination@@ -87,8 +88,13 @@ class WorkflowViewSet(return ResourceType.WORKFLOW.valuedef get_permissions(self) -> list[Any]:+ if self.action == "destroy":+ # Ownership as before, narrowed by the org's deletion capability.+ return [+ IsOwner(),+ RequiresCapability(Capability.DELETE_WORKFLOWS_AND_DEPLOYMENTS),+ ]if self.action in [- "destroy","partial_update","update","add_co_owner",