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-2407 [FEAT] Add global API deployment keys for grouped API deployments (#1881)
Deepak K6be8b555fe12
diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.pyindex 8b96bcd67..d5cfa800a 100644--- a/backend/api_v2/api_deployment_views.py+++ b/backend/api_v2/api_deployment_views.py@@ -76,7 +76,12 @@ class DeploymentExecution(views.APIView):organization = api.organizationserializer = ExecutionRequestSerializer(- data=request.data, context={"api": api, "api_key": api_key}+ data=request.data,+ context={+ "api": api,+ "api_key": api_key,+ "is_global_key": deployment_execution_dto.is_global_key,+ },)serializer.is_valid(raise_exception=True)file_objs = serializer.validated_data.get(ApiExecution.FILES_FORM_DATA, [])diff --git a/backend/api_v2/deployment_helper.py b/backend/api_v2/deployment_helper.pyindex b6b3a8d16..5fbec7999 100644--- a/backend/api_v2/deployment_helper.py+++ b/backend/api_v2/deployment_helper.py@@ -9,6 +9,7 @@ from configuration.config_registry import ConfigurationRegistryfrom configuration.models import Configurationfrom django.conf import settingsfrom django.core.files.uploadedfile import InMemoryUploadedFile, UploadedFile+from global_api_deployment_key.models import GlobalApiDeploymentKeyfrom plugins.workflow_manager.workflow_v2.api_hub_usage_utils import APIHubUsageUtilfrom rest_framework.request import Requestfrom rest_framework.serializers import Serializer@@ -33,6 +34,7 @@ from api_v2.exceptions import (InactiveAPI,InvalidAPIRequest,PresignedURLFetchError,+ UnauthorizedKey,)from api_v2.key_helper import KeyHelperfrom api_v2.models import APIDeployment, APIKey@@ -61,31 +63,63 @@ class DeploymentHelper(BaseAPIKeyValidator):"""Fetch API deployment and validate API key."""api_name = kwargs.get("api_name") or request.data.get("api_name")api_deployment = DeploymentHelper.get_deployment_by_api_name(api_name=api_name)- DeploymentHelper.validate_api(api_deployment=api_deployment, api_key=api_key)+ global_key = DeploymentHelper.validate_api(+ api_deployment=api_deployment, api_key=api_key+ )deployment_execution_dto = DeploymentExecutionDTO(- api=api_deployment, api_key=api_key+ api=api_deployment, api_key=api_key, global_key=global_key)kwargs["deployment_execution_dto"] = deployment_execution_dtoreturn func(self, request, *args, **kwargs)@staticmethod- def validate_api(api_deployment: APIDeployment | None, api_key: str) -> None:- """Validating API and API key.+ def validate_api(+ api_deployment: APIDeployment | None, api_key: str+ ) -> GlobalApiDeploymentKey | None:+ """Validate API deployment and API key.++ Tries deployment-specific key first. If that fails, falls back to+ Global API Deployment Key validation.Args:- api_deployment (Optional[APIDeployment]): _description_- api_key (str): _description_+ api_deployment: The API deployment instance+ api_key: The bearer token value++ Returns:+ The authorizing ``GlobalApiDeploymentKey`` when the request was+ authenticated via a global key, else ``None`` (deployment-specific+ key). Returning the key (not a bool) preserves audit identity.Raises:- APINotFound: _description_- InactiveAPI: _description_+ APINotFound: If deployment not found+ InactiveAPI: If deployment is inactive+ UnauthorizedKey: If key validation fails"""if not api_deployment:raise APINotFound()if not api_deployment.is_active:raise InactiveAPI()- KeyHelper.validate_api_key(api_key=api_key, instance=api_deployment)++ try:+ KeyHelper.validate_api_key(api_key=api_key, instance=api_deployment)+ return None+ except UnauthorizedKey:+ logger.debug(+ "Deployment-specific key auth failed for API '%s'; falling back "+ "to global API deployment key validation.",+ api_deployment.api_name,+ )+ global_key = KeyHelper.validate_global_api_deployment_key(+ api_key=api_key, api_deployment=api_deployment+ )+ logger.info(+ "API '%s' authorized via global API deployment key '%s' (%s).",+ api_deployment.api_name,+ global_key.name,+ global_key.id,+ )+ return global_key@staticmethoddef validate_and_get_workflow(workflow_id: str) -> Workflow:diff --git a/backend/api_v2/dto.py b/backend/api_v2/dto.pyindex 93df13e44..e7fb9203c 100644--- a/backend/api_v2/dto.py+++ b/backend/api_v2/dto.py@@ -1,11 +1,30 @@-from dataclasses import dataclass+from dataclasses import dataclass, field+from typing import TYPE_CHECKINGfrom api_v2.models import APIDeployment+if TYPE_CHECKING:+ from global_api_deployment_key.models import GlobalApiDeploymentKey-@dataclass++@dataclass(frozen=True)class DeploymentExecutionDTO:- """DTO for deployment execution viewset."""+ """DTO for deployment execution viewset.++ Frozen: built once per request in ``DeploymentHelper.validate_api_key`` and+ only read downstream.+ """api: APIDeployment- api_key: str+ # repr=False: this is the live bearer credential. Without it the generated+ # __repr__ writes the raw key into any ``logger.debug("...%s", dto)`` or+ # exception repr that touches this object.+ api_key: str = field(repr=False)+ # The global API deployment key that authorized this execution, if any.+ # Carrying the resolved key (not just a bool) preserves audit identity —+ # "which named key authorized this?" — for downstream logging/incidents.+ global_key: "GlobalApiDeploymentKey | None" = None++ @property+ def is_global_key(self) -> bool:+ return self.global_key is not Nonediff --git a/backend/api_v2/key_helper.py b/backend/api_v2/key_helper.pyindex b1c9244de..cacf40faf 100644--- a/backend/api_v2/key_helper.py+++ b/backend/api_v2/key_helper.py@@ -1,6 +1,9 @@+from __future__ import annotations+import loggingfrom django.core.exceptions import ValidationError+from global_api_deployment_key.models import GlobalApiDeploymentKeyfrom pipeline_v2.models import Pipelinefrom rest_framework.request import Requestfrom workflow_manager.workflow_v2.workflow_helper import WorkflowHelper@@ -61,6 +64,56 @@ class KeyHelper:return api_key.pipeline == instancereturn False+ @staticmethod+ def validate_global_api_deployment_key(+ api_key: str, api_deployment: APIDeployment+ ) -> GlobalApiDeploymentKey:+ """Validate a Global API Deployment Key for deployment execution.++ Checks:+ 1. Key exists and is active+ 2. Key belongs to the same organization as the deployment+ 3. Key has access to the specific deployment (allow_all or listed)++ Args:+ api_key: The bearer token value+ api_deployment: The API deployment being accessed++ Returns:+ GlobalApiDeploymentKey: The validated key instance++ Raises:+ UnauthorizedKey: If validation fails+ """+ try:+ # UUIDField coerces/validates the key string via to_python, raising+ # ValidationError for a malformed value — the same pattern+ # ``validate_api_key`` relies on, so no manual uuid parsing is needed.+ global_key = GlobalApiDeploymentKey.objects.get(key=api_key, is_active=True)+ except (GlobalApiDeploymentKey.DoesNotExist, ValidationError):+ # Unknown, inactive, or malformed key. Log the reason for+ # observability; the client still gets a generic 401 (we don't+ # leak which condition failed).+ logger.warning(+ "Global API key rejected (unknown/inactive/malformed) for "+ "deployment %s (key ...%s).",+ api_deployment.id,+ str(api_key)[-4:],+ )+ raise UnauthorizedKey() from None++ if not global_key.has_access_to_deployment(api_deployment):+ logger.warning(+ "Global API key '%s' (%s) rejected: no access to deployment %s "+ "(out of scope or different organization).",+ global_key.name,+ global_key.id,+ api_deployment.id,+ )+ raise UnauthorizedKey()++ return global_key+@staticmethoddef validate_workflow_exists(workflow_id: str) -> None:"""Validate that the specified workflow_id exists in the Workflowdiff --git a/backend/api_v2/serializers.py b/backend/api_v2/serializers.pyindex 0eb99f1bc..3db7f53db 100644--- a/backend/api_v2/serializers.py+++ b/backend/api_v2/serializers.py@@ -401,6 +401,7 @@ class ExecutionRequestSerializer(TagParamsSerializer):# Get context from serializerapi = self.context.get("api")api_key = self.context.get("api_key")+ is_global_key = self.context.get("is_global_key", False)if not api or not api_key:raise ValidationError("Unable to validate LLM profile ownership")@@ -411,6 +412,29 @@ class ExecutionRequestSerializer(TagParamsSerializer):except ProfileManager.DoesNotExist:raise ValidationError("Profile not found")+ # Global API Keys are org-level (not tied to a single user), so the+ # per-user ownership check below does not apply. We must still confirm+ # the profile belongs to the same organization as the deployment,+ # otherwise a caller could reference another org's profile by UUID.+ # ``ProfileManager.objects`` is not org-scoped by default, so this+ # check is load-bearing, not merely defense-in-depth.+ if is_global_key:+ # A profile's org is only derivable through its prompt studio tool.+ # That FK is nullable, and an unattached profile therefore has no+ # org to compare against — ``None`` never equals a real org id, so+ # such a profile is rejected. That is deliberate: with no way to+ # attribute the profile to an organization, the org-scoped key must+ # fail closed rather than accept it.+ profile_org_id = (+ profile.prompt_studio_tool.organization_id+ if profile.prompt_studio_tool_id+ else None+ )+ if profile_org_id != api.organization_id:+ # Generic error avoids confirming another org's profile exists.+ raise ValidationError("Profile not found")+ return value+# Get the specific API key being usedtry:active_api_key = api.api_keys.get(api_key=api_key, is_active=True)diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.pyindex 179e62593..2f2809024 100644--- a/backend/backend/settings/base.py+++ b/backend/backend/settings/base.py@@ -392,6 +392,7 @@ SHARED_APPS = ("configuration","dashboard_metrics","platform_api",+ "global_api_deployment_key",)TENANT_APPS = []diff --git a/backend/backend/urls_v2.py b/backend/backend/urls_v2.pyindex fd91d3cc2..7c0ead02a 100644--- a/backend/backend/urls_v2.py+++ b/backend/backend/urls_v2.py@@ -65,4 +65,5 @@ urlpatterns = [path("execution/", include("workflow_manager.file_execution.urls")),path("metrics/", include("dashboard_metrics.urls")),path("platform-api/", include("platform_api.urls")),+ path("global-api-deployment/", include("global_api_deployment_key.urls")),]diff --git a/backend/global_api_deployment_key/__init__.py b/backend/global_api_deployment_key/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/global_api_deployment_key/apps.py b/backend/global_api_deployment_key/apps.pynew file mode 100644index 000000000..1d3924167--- /dev/null+++ b/backend/global_api_deployment_key/apps.py@@ -0,0 +1,6 @@+from django.apps import AppConfig+++class GlobalApiDeploymentKeyConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "global_api_deployment_key"diff --git a/backend/global_api_deployment_key/migrations/0001_initial.py b/backend/global_api_deployment_key/migrations/0001_initial.pynew file mode 100644index 000000000..469960791--- /dev/null+++ b/backend/global_api_deployment_key/migrations/0001_initial.py@@ -0,0 +1,94 @@+# Generated by Django 4.2.1 on 2026-03-25 18:22++import uuid++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("account_v2", "0004_user_is_service_account"),+ ("api_v2", "0003_add_organization_rate_limit"),+ ]++ operations = [+ migrations.CreateModel(+ name="GlobalApiDeploymentKey",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("modified_at", models.DateTimeField(auto_now=True)),+ (+ "id",+ models.UUIDField(+ default=uuid.uuid4,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("name", models.CharField(max_length=128)),+ ("description", models.CharField(max_length=512)),+ ("key", models.UUIDField(default=uuid.uuid4, unique=True)),+ ("is_active", models.BooleanField(default=True)),+ (+ "allow_all_deployments",+ models.BooleanField(+ db_comment="If True, this key can authenticate any API deployment in the org",+ default=False,+ ),+ ),+ (+ "api_deployments",+ models.ManyToManyField(+ blank=True,+ related_name="global_api_deployment_keys",+ to="api_v2.apideployment",+ ),+ ),+ (+ "created_by",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="global_api_deployment_keys_created",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "modified_by",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ blank=True,+ db_comment="Foreign key reference to the Organization model.",+ editable=False,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="account_v2.organization",+ ),+ ),+ ],+ options={+ "db_table": "global_api_deployment_key",+ },+ ),+ migrations.AddConstraint(+ model_name="globalapideploymentkey",+ constraint=models.UniqueConstraint(+ fields=("name", "organization"),+ name="unique_global_api_deployment_key_name_per_org",+ ),+ ),+ ]diff --git a/backend/global_api_deployment_key/migrations/__init__.py b/backend/global_api_deployment_key/migrations/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/global_api_deployment_key/models.py b/backend/global_api_deployment_key/models.pynew file mode 100644index 000000000..f77330ecd--- /dev/null+++ b/backend/global_api_deployment_key/models.py@@ -0,0 +1,70 @@+import uuid++from account_v2.models import User+from api_v2.models import APIDeployment+from django.db import models+from utils.models.base_model import BaseModel+from utils.models.organization_mixin import DefaultOrganizationMixin+++class GlobalApiDeploymentKey(DefaultOrganizationMixin, BaseModel):+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ name = models.CharField(max_length=128)+ # CharField (not TextField) so the 512 cap is a real varchar(512) DB+ # invariant, not just a Python-layer serializer validator.+ description = models.CharField(max_length=512)+ key = models.UUIDField(default=uuid.uuid4, unique=True)+ is_active = models.BooleanField(default=True)+ allow_all_deployments = models.BooleanField(+ default=False,+ db_comment="If True, this key can authenticate any API deployment in the org",+ )+ api_deployments = models.ManyToManyField(+ APIDeployment,+ blank=True,+ related_name="global_api_deployment_keys",+ )+ created_by = models.ForeignKey(+ User,+ on_delete=models.SET_NULL,+ null=True,+ related_name="global_api_deployment_keys_created",+ )+ modified_by = models.ForeignKey(+ User,+ on_delete=models.SET_NULL,+ null=True,+ related_name="+",+ )++ class Meta:+ db_table = "global_api_deployment_key"+ constraints = [+ models.UniqueConstraint(+ fields=["name", "organization"],+ name="unique_global_api_deployment_key_name_per_org",+ ),+ ]++ def __str__(self):+ return f"{self.name} ({self.organization})"++ def has_access_to_deployment(self, api_deployment: APIDeployment) -> bool:+ """Check if this key can authenticate the given API deployment."""+ if not self.is_active:+ return False+ # Load-bearing, not defensive: validate_global_api_deployment_key looks+ # the key up by ``key`` + ``is_active`` with NO org filter, so this is+ # the only thing preventing a key from authenticating another org's+ # deployment.+ if self.organization_id != api_deployment.organization_id:+ return False+ # ``allow_all_deployments`` deliberately wins over ``api_deployments``:+ # the pair is a mode switch, not a union. The coherent pair can't be+ # enforced structurally (a CheckConstraint can't span an M2M, and+ # ``clean()`` runs before M2M rows exist), so the serializers own the+ # invariant — see ``_GlobalApiDeploymentKeyWriteSerializer`` subclasses,+ # which reject/clear a list whenever allow-all is set.+ if self.allow_all_deployments:+ return True+ return self.api_deployments.filter(id=api_deployment.id).exists()diff --git a/backend/global_api_deployment_key/permissions.py b/backend/global_api_deployment_key/permissions.pynew file mode 100644index 000000000..5af1675ba--- /dev/null+++ b/backend/global_api_deployment_key/permissions.py@@ -0,0 +1,8 @@+from platform_api.permissions import IsOrganizationAdmin as PlatformIsOrganizationAdmin+++class IsOrganizationAdmin(PlatformIsOrganizationAdmin):+ message = "Only organization admins can manage global API deployment keys."+++__all__ = ["IsOrganizationAdmin"]diff --git a/backend/global_api_deployment_key/serializers.py b/backend/global_api_deployment_key/serializers.pynew file mode 100644index 000000000..0f22f83f7--- /dev/null+++ b/backend/global_api_deployment_key/serializers.py@@ -0,0 +1,195 @@+from api_v2.models import APIDeployment+from rest_framework import serializers+from utils.input_sanitizer import validate_safe_text+from utils.user_context import UserContext++from backend.serializers import AuditSerializer+from global_api_deployment_key.models import GlobalApiDeploymentKey++ALLOW_ALL_WITH_LIST_ERROR = {+ "api_deployments": "Leave empty when 'allow all deployments' is enabled."+}+NO_DEPLOYMENTS_SELECTED_ERROR = {+ "api_deployments": (+ "Select at least one deployment or enable 'allow all deployments'."+ )+}+++class ApiDeploymentMinimalSerializer(serializers.ModelSerializer):+ """Minimal serializer for API deployments used in key assignment."""++ class Meta:+ model = APIDeployment+ fields = ["id", "display_name", "api_name", "is_active"]+++class GlobalApiDeploymentKeyListSerializer(serializers.ModelSerializer):+ key = serializers.SerializerMethodField()+ created_by_email = serializers.SerializerMethodField()+ api_deployments = ApiDeploymentMinimalSerializer(many=True, read_only=True)++ class Meta:+ model = GlobalApiDeploymentKey+ fields = [+ "id",+ "name",+ "description",+ "key",+ "is_active",+ "allow_all_deployments",+ "api_deployments",+ "created_at",+ "modified_at",+ "created_by_email",+ ]++ def get_key(self, obj):+ key_str = str(obj.key)+ return f"****-{key_str[-4:]}"++ def get_created_by_email(self, obj):+ return obj.created_by.email if obj.created_by else "Deleted user"+++class GlobalApiDeploymentKeyDetailSerializer(serializers.ModelSerializer):+ """Exposes the full plaintext key.++ Used by the create/rotate responses and by ``retrieve`` (GET keys/<pk>/),+ so the full key stays retrievable by an org admin for the key's lifetime —+ consistent with the platform_api key flow (not a one-time reveal).+ """++ class Meta:+ model = GlobalApiDeploymentKey+ fields = ["id", "name", "key", "is_active"]+++class _GlobalApiDeploymentKeyWriteSerializer(AuditSerializer):+ """Shared write-side surface for the create and update serializers.++ Owns the org-scoped ``api_deployments`` field and the description+ sanitiser; subclasses bring their own ``Meta`` and ``validate``.+ """++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ # Built here rather than declared as a class attribute: any queryset+ # expression on ``APIDeployment.objects`` runs the org-scoped manager's+ # ``get_queryset``, which resolves ``UserContext.get_organization()`` —+ # so a class-level declaration issues a DB query at *import* time, and+ # blows up wherever the module is imported without a database.+ #+ # The org filter is the guard that stops an admin attaching another+ # org's deployment by UUID.+ self.fields["api_deployments"] = serializers.PrimaryKeyRelatedField(+ many=True,+ required=False,+ queryset=APIDeployment.objects.filter(+ organization=UserContext.get_organization()+ ),+ )++ def validate_description(self, value):+ return validate_safe_text(value)+++class GlobalApiDeploymentKeyCreateSerializer(_GlobalApiDeploymentKeyWriteSerializer):+ description = serializers.CharField(required=True, max_length=512)++ class Meta:+ model = GlobalApiDeploymentKey+ fields = ["name", "description", "allow_all_deployments", "api_deployments"]++ def validate_name(self, value):+ value = validate_safe_text(value)+ organization = UserContext.get_organization()+ if GlobalApiDeploymentKey.objects.filter(+ name=value, organization=organization+ ).exists():+ raise serializers.ValidationError(+ "A key with this name already exists in your organization."+ )+ return value++ def validate(self, attrs):+ """Reject incoherent scopes.++ Both fields are always present on create, so an incoherent pair is a+ caller mistake worth surfacing rather than silently normalising:+ ``allow_all`` with a list (the list would be ignored at auth time), or+ neither (a live key that authenticates nothing).+ """+ allow_all = attrs.get("allow_all_deployments", False)+ deployments = attrs.get("api_deployments") or []+ if allow_all and deployments:+ raise serializers.ValidationError(ALLOW_ALL_WITH_LIST_ERROR)+ if not allow_all and not deployments:+ raise serializers.ValidationError(NO_DEPLOYMENTS_SELECTED_ERROR)+ return attrs+++class GlobalApiDeploymentKeyUpdateSerializer(_GlobalApiDeploymentKeyWriteSerializer):+ class Meta:+ model = GlobalApiDeploymentKey+ fields = [+ "description",+ "is_active",+ "allow_all_deployments",+ "api_deployments",+ ]+ extra_kwargs = {+ "description": {"required": False},+ "is_active": {"required": False},+ "allow_all_deployments": {"required": False},+ }++ def validate(self, attrs):+ """Validate the effective scope without trapping partial updates.++ Updates are PATCH-only, so a caller may touch one scope field, both, or+ neither. Validating the stored list unconditionally makes two legitimate+ requests fail: flipping a scoped key to allow-all in one field, and+ editing (or deactivating) a key whose only deployment was deleted.+ """+ allow_all = attrs.get(+ "allow_all_deployments",+ self.instance.allow_all_deployments if self.instance else False,+ )+ scope_sent = "api_deployments" in attrs++ if allow_all:+ # ``allow_all`` wins at auth time (see+ # ``GlobalApiDeploymentKey.has_access_to_deployment``), so a list is+ # dead weight. Reject one the caller explicitly sent — they believe+ # they scoped the key — and clear a stale stored one otherwise, so+ # PATCH {"allow_all_deployments": true} works on its own.+ if scope_sent and attrs["api_deployments"]:+ raise serializers.ValidationError(ALLOW_ALL_WITH_LIST_ERROR)+ attrs["api_deployments"] = []+ return attrs++ if scope_sent:+ if not attrs["api_deployments"]:+ raise serializers.ValidationError(NO_DEPLOYMENTS_SELECTED_ERROR)+ return attrs++ if (+ "allow_all_deployments" in attrs+ and not self.instance.api_deployments.exists()+ ):+ # Turning allow-all off without naming deployments would leave a key+ # that authenticates nothing.+ raise serializers.ValidationError(NO_DEPLOYMENTS_SELECTED_ERROR)++ # Scope untouched (e.g. PATCH {"is_active": false}) — deliberately not+ # re-validated, so a key stranded by a deleted deployment stays editable+ # and, more importantly, deactivatable.+ return attrs++ def update(self, instance, validated_data):+ api_deployments = validated_data.pop("api_deployments", None)+ instance = super().update(instance, validated_data)+ if api_deployments is not None:+ instance.api_deployments.set(api_deployments)+ return instancediff --git a/backend/global_api_deployment_key/tests/__init__.py b/backend/global_api_deployment_key/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/global_api_deployment_key/tests/test_global_key_auth.py b/backend/global_api_deployment_key/tests/test_global_key_auth.pynew file mode 100644index 000000000..cf17a5cab--- /dev/null+++ b/backend/global_api_deployment_key/tests/test_global_key_auth.py@@ -0,0 +1,329 @@+"""Guard: a global API deployment key never authenticates another org's API.++``KeyHelper.validate_global_api_deployment_key`` looks a key up by ``key`` ++``is_active`` with **no organization filter**, so the org comparison inside+``GlobalApiDeploymentKey.has_access_to_deployment`` is the only thing standing+between a valid Org A key and an Org B deployment. These tests pin that guard,+the rest of the authorization matrix, and the deployment-key -> global-key+fallback ordering in ``DeploymentHelper.validate_api``.++No test database: every case runs on unsaved model instances with the M2M+descriptor and ``objects`` manager patched, mirroring the mock-collaborator+style of ``api_v2/tests/test_deployment_helper.py``.+"""++from __future__ import annotations++import os+from unittest import mock++import django+from django.apps import apps++os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings.test")+if not apps.ready:+ django.setup()++import api_v2.deployment_helper as dh # noqa: E402+import pytest # noqa: E402+from api_v2.exceptions import APINotFound, InactiveAPI, UnauthorizedKey # noqa: E402+from api_v2.key_helper import KeyHelper # noqa: E402+from api_v2.models import APIDeployment # noqa: E402+from api_v2.serializers import ExecutionRequestSerializer # noqa: E402+from django.core.exceptions import ValidationError # noqa: E402+from prompt_studio.prompt_profile_manager_v2.models import ( # noqa: E402+ ProfileManager,+)+from rest_framework.serializers import ( # noqa: E402+ ValidationError as DRFValidationError,+)+from utils.user_context import UserContext # noqa: E402++from global_api_deployment_key.models import GlobalApiDeploymentKey # noqa: E402+from global_api_deployment_key.serializers import ( # noqa: E402+ GlobalApiDeploymentKeyUpdateSerializer,+)++ORG_A = 1+ORG_B = 2+# A syntactically valid UUID — the bearer value under test, not a real key.+WELL_FORMED_UUID = "3f1d9c4e-6b2a-4c8d-9e77-1a2b3c4d5e6f"+++def _deployment(organization_id: int = ORG_A) -> APIDeployment:+ """An unsaved deployment; the auth path only reads id/org/is_active."""+ deployment = APIDeployment(api_name="my-api", is_active=True)+ deployment.id = "8c1f0b6a-0000-4000-8000-000000000001"+ deployment.organization_id = organization_id+ return deployment+++def _key(+ *,+ organization_id: int = ORG_A,+ is_active: bool = True,+ allow_all: bool = False,+) -> GlobalApiDeploymentKey:+ key = GlobalApiDeploymentKey(+ name="prod-key",+ description="prod",+ is_active=is_active,+ allow_all_deployments=allow_all,+ )+ key.organization_id = organization_id+ return key+++def m2m():+ """Patch the ``api_deployments`` relation so no database is needed.++ ``ManyToManyDescriptor`` is a data descriptor, so it can only be shadowed on+ the class — hence ``PropertyMock`` rather than an instance attribute.+ """+ with mock.patch.object(+ GlobalApiDeploymentKey, "api_deployments", new_callable=mock.PropertyMock+ ) as prop:+ yield prop+++def no_org():+ """No organization in context.++ Org resolution is a DB read, and it runs inside the org-scoped model+ manager as well as the serializer, so it is patched on the class both share.+ """+ with mock.patch.object(UserContext, "get_organization", return_value=None):+ yield+++def _scope(m2m, *, contains: bool) -> None:+ """Make the key's deployment list report whether it holds the deployment."""+ manager = mock.MagicMock()+ manager.filter.return_value.exists.return_value = contains+ m2m.return_value = manager+++class TestHasAccessToDeployment:+ """The authorization matrix on the model."""++ def test_cross_org_key_is_rejected_even_when_allow_all(self, m2m) -> None:+ """The load-bearing tenant guard: Org A key, Org B deployment."""+ key = _key(organization_id=ORG_A, allow_all=True)+ assert key.has_access_to_deployment(_deployment(ORG_B)) is False++ def test_cross_org_key_is_rejected_when_scoped(self, m2m) -> None:+ """Org mismatch wins even if the M2M somehow lists the deployment."""+ _scope(m2m, contains=True)+ key = _key(organization_id=ORG_A, allow_all=False)+ assert key.has_access_to_deployment(_deployment(ORG_B)) is False++ def test_same_org_allow_all_authorizes(self, m2m) -> None:+ key = _key(organization_id=ORG_A, allow_all=True)+ assert key.has_access_to_deployment(_deployment(ORG_A)) is True++ def test_inactive_key_is_rejected(self, m2m) -> None:+ key = _key(organization_id=ORG_A, allow_all=True, is_active=False)+ assert key.has_access_to_deployment(_deployment(ORG_A)) is False++ def test_scoped_key_authorizes_listed_deployment(self, m2m) -> None:+ _scope(m2m, contains=True)+ key = _key(organization_id=ORG_A, allow_all=False)+ assert key.has_access_to_deployment(_deployment(ORG_A)) is True++ def test_scoped_key_rejects_unlisted_deployment(self, m2m) -> None:+ _scope(m2m, contains=False)+ key = _key(organization_id=ORG_A, allow_all=False)+ assert key.has_access_to_deployment(_deployment(ORG_A)) is False+++class TestValidateGlobalApiDeploymentKey:+ """The lookup wrapper: what reaches the caller for each failure mode."""++ def test_unknown_key_raises_unauthorized(self) -> None:+ deployment = _deployment()+ with mock.patch.object(GlobalApiDeploymentKey, "objects") as objects:+ objects.get.side_effect = GlobalApiDeploymentKey.DoesNotExist+ with pytest.raises(UnauthorizedKey):+ KeyHelper.validate_global_api_deployment_key(+ api_key=WELL_FORMED_UUID, api_deployment=deployment+ )++ def test_malformed_key_raises_unauthorized_not_server_error(self) -> None:+ """A non-UUID bearer token must 401, not 500 — UUIDField coercion."""+ deployment = _deployment()+ with mock.patch.object(GlobalApiDeploymentKey, "objects") as objects:+ objects.get.side_effect = ValidationError("badly formed UUID")+ with pytest.raises(UnauthorizedKey):+ KeyHelper.validate_global_api_deployment_key(+ api_key="not-a-uuid", api_deployment=deployment+ )++ def test_out_of_scope_key_raises_unauthorized(self) -> None:+ key = mock.MagicMock()+ key.has_access_to_deployment.return_value = False+ deployment = _deployment()+ with mock.patch.object(GlobalApiDeploymentKey, "objects") as objects:+ objects.get.return_value = key+ with pytest.raises(UnauthorizedKey):+ KeyHelper.validate_global_api_deployment_key(+ api_key=WELL_FORMED_UUID, api_deployment=deployment+ )++ def test_authorized_key_is_returned_for_audit(self) -> None:+ key = mock.MagicMock()+ key.has_access_to_deployment.return_value = True+ with mock.patch.object(GlobalApiDeploymentKey, "objects") as objects:+ objects.get.return_value = key+ returned = KeyHelper.validate_global_api_deployment_key(+ api_key=WELL_FORMED_UUID, api_deployment=_deployment()+ )+ assert returned is key+ # Inactive keys are excluded by the lookup itself, not a later check.+ objects.get.assert_called_once_with(key=WELL_FORMED_UUID, is_active=True)+++class TestValidateApiFallbackOrdering:+ """Deployment-specific key first; the global key is strictly a fallback."""++ def test_missing_deployment_raises_api_not_found(self) -> None:+ with pytest.raises(APINotFound):+ dh.DeploymentHelper.validate_api(api_deployment=None, api_key=WELL_FORMED_UUID)++ def test_inactive_deployment_raises_inactive_api(self) -> None:+ deployment = _deployment()+ deployment.is_active = False+ with pytest.raises(InactiveAPI):+ dh.DeploymentHelper.validate_api(+ api_deployment=deployment, api_key=WELL_FORMED_UUID+ )++ def test_valid_deployment_key_never_hits_global_lookup(self) -> None:+ with mock.patch.object(dh, "KeyHelper") as key_helper:+ key_helper.validate_api_key.return_value = None+ result = dh.DeploymentHelper.validate_api(+ api_deployment=_deployment(), api_key=WELL_FORMED_UUID+ )+ key_helper.validate_global_api_deployment_key.assert_not_called()+ assert result is None++ def test_falls_back_to_global_key_and_returns_it(self) -> None:+ global_key = mock.MagicMock()+ with mock.patch.object(dh, "KeyHelper") as key_helper:+ key_helper.validate_api_key.side_effect = UnauthorizedKey+ key_helper.validate_global_api_deployment_key.return_value = global_key+ result = dh.DeploymentHelper.validate_api(+ api_deployment=_deployment(), api_key=WELL_FORMED_UUID+ )+ assert result is global_key++ def test_both_paths_failing_propagates_unauthorized(self) -> None:+ deployment = _deployment()+ with mock.patch.object(dh, "KeyHelper") as key_helper:+ key_helper.validate_api_key.side_effect = UnauthorizedKey+ key_helper.validate_global_api_deployment_key.side_effect = UnauthorizedKey+ with pytest.raises(UnauthorizedKey):+ dh.DeploymentHelper.validate_api(+ api_deployment=deployment, api_key=WELL_FORMED_UUID+ )+++class TestGlobalKeyLlmProfileScoping:+ """``llm_profile_id`` must stay org-scoped when a global key is used.++ The per-user ownership check that guards deployment-specific keys cannot+ apply to an org-level key, so the organization comparison in+ ``ExecutionRequestSerializer.validate_llm_profile_id`` is what stops a+ caller referencing another org's profile by UUID.+ """++ PROFILE_ID = "b7c2f1de-0000-4000-8000-000000000002"++ def _serializer(self, organization_id: int = ORG_A):+ return ExecutionRequestSerializer(+ context={+ "api": _deployment(organization_id),+ "api_key": WELL_FORMED_UUID,+ "is_global_key": True,+ }+ )++ def _profile(self, organization_id: int | None) -> mock.MagicMock:+ profile = mock.MagicMock()+ profile.prompt_studio_tool_id = (+ None if organization_id is None else "tool-id"+ )+ profile.prompt_studio_tool.organization_id = organization_id+ return profile++ def test_same_org_profile_is_accepted(self) -> None:+ with mock.patch.object(ProfileManager, "objects") as objects:+ objects.get.return_value = self._profile(ORG_A)+ assert (+ self._serializer().validate_llm_profile_id(self.PROFILE_ID)+ == self.PROFILE_ID+ )++ def test_cross_org_profile_is_rejected(self) -> None:+ serializer = self._serializer()+ with mock.patch.object(ProfileManager, "objects") as objects:+ objects.get.return_value = self._profile(ORG_B)+ with pytest.raises(DRFValidationError, match="Profile not found"):+ serializer.validate_llm_profile_id(self.PROFILE_ID)++ def test_profile_without_a_tool_fails_closed(self) -> None:+ """No prompt studio tool means no derivable org — reject, don't guess."""+ serializer = self._serializer()+ with mock.patch.object(ProfileManager, "objects") as objects:+ objects.get.return_value = self._profile(None)+ with pytest.raises(DRFValidationError, match="Profile not found"):+ serializer.validate_llm_profile_id(self.PROFILE_ID)++ def test_unknown_profile_is_rejected(self) -> None:+ serializer = self._serializer()+ with mock.patch.object(ProfileManager, "objects") as objects:+ objects.get.side_effect = ProfileManager.DoesNotExist+ with pytest.raises(DRFValidationError, match="Profile not found"):+ serializer.validate_llm_profile_id(self.PROFILE_ID)+++class TestUpdateSerializerScopeValidation:+ """PATCH must not trap callers into an unrepresentable scope.++ Updates are partial, so the effective scope is a mix of payload and stored+ state. These pin the two cases where validating the stored list would+ reject a legitimate request.+ """++ def _serializer(self, instance, data):+ return GlobalApiDeploymentKeyUpdateSerializer(instance, data=data, partial=True)++ def test_flipping_a_scoped_key_to_allow_all_clears_the_list(+ self, m2m, no_org+ ) -> None:+ """PATCH {"allow_all_deployments": true} alone must succeed."""+ _scope(m2m, contains=True)+ instance = _key(allow_all=False)+ serializer = self._serializer(instance, {"allow_all_deployments": True})+ assert serializer.is_valid(), serializer.errors+ # Cleared, so the stored list can't misrepresent what the key reaches.+ assert serializer.validated_data["api_deployments"] == []++ def test_key_stranded_by_a_deleted_deployment_stays_deactivatable(+ self, m2m, no_org+ ) -> None:+ """Its only deployment was deleted; deactivating it must still work."""+ m2m.return_value.exists.return_value = False+ instance = _key(allow_all=False)+ serializer = self._serializer(instance, {"is_active": False})+ assert serializer.is_valid(), serializer.errors++ def test_turning_allow_all_off_without_deployments_is_rejected(+ self, m2m, no_org+ ) -> None:+ m2m.return_value.exists.return_value = False+ instance = _key(allow_all=True)+ serializer = self._serializer(instance, {"allow_all_deployments": False})+ assert not serializer.is_valid()+ assert "api_deployments" in serializer.errorsdiff --git a/backend/global_api_deployment_key/urls.py b/backend/global_api_deployment_key/urls.pynew file mode 100644index 000000000..33185bed6--- /dev/null+++ b/backend/global_api_deployment_key/urls.py@@ -0,0 +1,28 @@+from django.urls import path++from global_api_deployment_key.views import GlobalApiDeploymentKeyViewSet++urlpatterns = [+ path(+ "keys/",+ GlobalApiDeploymentKeyViewSet.as_view({"get": "list", "post": "create"}),+ name="global_api_deployment_key_list",+ ),+ path(+ "keys/<uuid:pk>/",+ GlobalApiDeploymentKeyViewSet.as_view(+ {"get": "retrieve", "patch": "partial_update", "delete": "destroy"}+ ),+ name="global_api_deployment_key_detail",+ ),+ path(+ "keys/<uuid:pk>/rotate/",+ GlobalApiDeploymentKeyViewSet.as_view({"post": "rotate"}),+ name="global_api_deployment_key_rotate",+ ),+ path(+ "deployments/",+ GlobalApiDeploymentKeyViewSet.as_view({"get": "deployments"}),+ name="global_api_deployment_key_deployments",+ ),+]diff --git a/backend/global_api_deployment_key/views.py b/backend/global_api_deployment_key/views.pynew file mode 100644index 000000000..b2405f525--- /dev/null+++ b/backend/global_api_deployment_key/views.py@@ -0,0 +1,80 @@+import uuid++from api_v2.models import APIDeployment+from rest_framework import status, viewsets+from rest_framework.decorators import action+from rest_framework.permissions import IsAuthenticated+from rest_framework.response import Response+from utils.user_context import UserContext++from global_api_deployment_key.models import GlobalApiDeploymentKey+from global_api_deployment_key.permissions import IsOrganizationAdmin+from global_api_deployment_key.serializers import (+ ApiDeploymentMinimalSerializer,+ GlobalApiDeploymentKeyCreateSerializer,+ GlobalApiDeploymentKeyDetailSerializer,+ GlobalApiDeploymentKeyListSerializer,+ GlobalApiDeploymentKeyUpdateSerializer,+)+++class GlobalApiDeploymentKeyViewSet(viewsets.ModelViewSet):+ permission_classes = [IsAuthenticated, IsOrganizationAdmin]++ def get_queryset(self):+ # ``created_by`` is select_related because the list serializer reads+ # ``created_by.email`` per row; without it the unpaginated list costs+ # one extra query per key.+ return (+ GlobalApiDeploymentKey.objects.filter(+ organization=UserContext.get_organization(),+ )+ .select_related("created_by")+ .prefetch_related("api_deployments")+ )++ def get_serializer_class(self):+ # create/retrieve/partial_update/rotate are overridden and instantiate+ # their serializers directly, so only ``list``/``destroy`` (and DRF's+ # default fallback) route through here — all use the list serializer.+ return GlobalApiDeploymentKeyListSerializer++ def create(self, request, *args, **kwargs):+ serializer = GlobalApiDeploymentKeyCreateSerializer(+ data=request.data, context={"request": request}+ )+ serializer.is_valid(raise_exception=True)+ instance = serializer.save()+ response_serializer = GlobalApiDeploymentKeyDetailSerializer(instance)+ return Response(response_serializer.data, status=status.HTTP_201_CREATED)++ def retrieve(self, request, *args, **kwargs):+ instance = self.get_object()+ serializer = GlobalApiDeploymentKeyDetailSerializer(instance)+ return Response(serializer.data)++ def partial_update(self, request, *args, **kwargs):+ instance = self.get_object()+ serializer = GlobalApiDeploymentKeyUpdateSerializer(+ instance, data=request.data, partial=True, context={"request": request}+ )+ serializer.is_valid(raise_exception=True)+ updated_instance = serializer.save()+ response_serializer = GlobalApiDeploymentKeyListSerializer(updated_instance)+ return Response(response_serializer.data)++ def rotate(self, request, *args, **kwargs):+ instance = self.get_object()+ instance.key = uuid.uuid4()+ instance.modified_by = request.user+ instance.save(update_fields=["key", "modified_by", "modified_at"])+ response_serializer = GlobalApiDeploymentKeyDetailSerializer(instance)+ return Response(response_serializer.data)++ @action(detail=False, methods=["get"])+ def deployments(self, request):+ """List all API deployments in the org for admins to assign to keys."""+ organization = UserContext.get_organization()+ deployments = APIDeployment.objects.filter(organization=organization)+ serializer = ApiDeploymentMinimalSerializer(deployments, many=True)+ return Response(serializer.data)diff --git a/backend/platform_api/serializers.py b/backend/platform_api/serializers.pyindex 7962e7572..e3edadabd 100644--- a/backend/platform_api/serializers.py+++ b/backend/platform_api/serializers.py@@ -1,30 +1,10 @@-import re-from rest_framework import serializers+from utils.input_sanitizer import validate_safe_textfrom utils.user_context import UserContextfrom backend.serializers import AuditSerializerfrom platform_api.models import PlatformApiKey-# Alphanumeric, spaces, hyphens, underscores, periods, commas, colons,-# apostrophes, parentheses, forward slashes. No HTML tags or angle brackets.-SAFE_TEXT_PATTERN = re.compile(r"^[a-zA-Z0-9 \-_.,:'()/]+$")-SAFE_TEXT_ERROR = (- "Only alphanumeric characters, spaces, hyphens, underscores, "- "periods, commas, colons, apostrophes, parentheses, and forward slashes "- "are allowed."-)---def validate_safe_text(value):- """Reject HTML tags and restrict to safe characters."""- stripped = value.strip()- if not stripped:- raise serializers.ValidationError("This field cannot be empty.")- if not SAFE_TEXT_PATTERN.match(stripped):- raise serializers.ValidationError(SAFE_TEXT_ERROR)- return stripped-class PlatformApiKeyListSerializer(serializers.ModelSerializer):key = serializers.SerializerMethodField()diff --git a/backend/utils/input_sanitizer.py b/backend/utils/input_sanitizer.pyindex 36772727e..227dbc95c 100644--- a/backend/utils/input_sanitizer.py+++ b/backend/utils/input_sanitizer.py@@ -43,3 +43,38 @@ def validate_name_field(value: str, field_name: str = "This field") -> str:if not value:raise ValidationError(f"{field_name} must not be empty.")return validate_no_html_tags(value, field_name)+++# Allow-list of characters permitted in user-facing free text (names,+# descriptions). Unlike ``validate_no_html_tags`` (which block-lists known+# dangerous constructs), this is a strict allow-list: alphanumerics, spaces and+# a small set of common punctuation. Angle brackets (``<``/``>``), double+# quotes, ampersands and backticks are rejected, so a stored value cannot start+# a tag or break out of a double-quoted HTML attribute when rendered in+# non-React contexts (emails, PDFs, logs).+#+# The apostrophe IS allowed (names like "Client's Prod Key" are legitimate), so+# a single-quoted attribute context — ``title='{value}'`` — is NOT covered by+# this validator and must still escape the value at render time.+SAFE_TEXT_PATTERN = re.compile(r"^[a-zA-Z0-9 \-_.,:'()/]+$")+SAFE_TEXT_ERROR = (+ "Only alphanumeric characters, spaces, hyphens, underscores, "+ "periods, commas, colons, apostrophes, parentheses, and forward slashes "+ "are allowed."+)+++def validate_safe_text(value: str) -> str:+ """Restrict free text to the safe allow-list in ``SAFE_TEXT_PATTERN``.++ Strips surrounding whitespace, rejects empty/whitespace-only input, and+ rejects any character outside the allow-list (which excludes ``<``, ``>``,+ double quotes, ``&``, backticks and similar injection-prone characters —+ but not the apostrophe). Returns the stripped value on success.+ """+ stripped = value.strip()+ if not stripped:+ raise ValidationError("This field cannot be empty.")+ if not SAFE_TEXT_PATTERN.match(stripped):+ raise ValidationError(SAFE_TEXT_ERROR)+ return strippeddiff --git a/backend/utils/tests/test_input_sanitizer.py b/backend/utils/tests/test_input_sanitizer.pyindex fe3634e72..159690488 100644--- a/backend/utils/tests/test_input_sanitizer.py+++ b/backend/utils/tests/test_input_sanitizer.py@@ -1,7 +1,11 @@import pytestfrom rest_framework.serializers import ValidationError-from utils.input_sanitizer import validate_name_field, validate_no_html_tags+from utils.input_sanitizer import (+ validate_name_field,+ validate_no_html_tags,+ validate_safe_text,+)class TestValidateNoHtmlTags:@@ -148,3 +152,46 @@ class TestValidateNameField:def test_custom_field_name_in_error(self):with pytest.raises(ValidationError, match="Tool name"):validate_name_field(" ", field_name="Tool name")++class TestValidateSafeText:+ """The strict allow-list used for key names/descriptions.++ Unlike its block-listing siblings above, anything outside+ ``SAFE_TEXT_PATTERN`` is rejected — so these cases pin what the allow-list+ actually permits, including the apostrophe it deliberately keeps.+ """++ def test_clean_text_passes(self):+ assert validate_safe_text("Prod deployment key") == "Prod deployment key"++ def test_strips_whitespace(self):+ assert validate_safe_text(" x ") == "x"++ def test_rejects_whitespace_only(self):+ with pytest.raises(ValidationError, match="cannot be empty"):+ validate_safe_text(" ")++ def test_rejects_html_tags(self):+ with pytest.raises(ValidationError, match="Only alphanumeric characters"):+ validate_safe_text("<script>alert(1)</script>")++ def test_rejects_ampersand(self):+ with pytest.raises(ValidationError, match="Only alphanumeric characters"):+ validate_safe_text("Billing & Ops")++ def test_rejects_double_quote(self):+ with pytest.raises(ValidationError, match="Only alphanumeric characters"):+ validate_safe_text('Say "hi"')++ def test_rejects_backtick(self):+ with pytest.raises(ValidationError, match="Only alphanumeric characters"):+ validate_safe_text("`whoami`")++ def test_allows_apostrophe(self):+ # Documented carve-out: real names contain it, so single-quoted HTML+ # attribute contexts must escape at render time (see module comment).+ assert validate_safe_text("Client's Prod Key") == "Client's Prod Key"++ def test_allows_punctuation_subset(self):+ value = "Key-1_v2 (prod), region: us/west."+ assert validate_safe_text(value) == valuediff --git a/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx b/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsxindex eee4f0623..799ce3c61 100644--- a/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx+++ b/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx@@ -116,6 +116,11 @@ const getSettingsMenuItems = (orgName, isAdmin) => [label: "Platform API Keys",path: `/${orgName}/settings/platform-api-keys`,},+ {+ key: "globalApiDeploymentKeys",+ label: "Global API Deployment Keys",+ path: `/${orgName}/settings/global-api-deployment-keys`,+ },]: []),{@@ -150,6 +155,9 @@ const getSettingsMenuItems = (orgName, isAdmin) => [const getActiveSettingsKey = () => {const currentPath = globalThis.location.pathname;+ if (currentPath.includes("/settings/global-api-deployment-keys")) {+ return "globalApiDeploymentKeys";+ }if (currentPath.includes("/settings/platform-api-keys")) {return "platformApiKeys";}@@ -475,6 +483,8 @@ const SideNavBar = ({ collapsed, setCollapsed }) => {globalThis.location.pathname === `/${orgName}/settings/platform` ||globalThis.location.pathname ===`/${orgName}/settings/platform-api-keys` ||+ globalThis.location.pathname ===+ `/${orgName}/settings/global-api-deployment-keys` ||globalThis.location.pathname === `/${orgName}/settings/triad` ||globalThis.location.pathname === `/${orgName}/settings/review` ||globalThis.location.pathname === `/${orgName}/users` ||diff --git a/frontend/src/components/settings/api-key-manager/ApiKeyManager.css b/frontend/src/components/settings/api-key-manager/ApiKeyManager.cssnew file mode 100644index 000000000..fe2081a45--- /dev/null+++ b/frontend/src/components/settings/api-key-manager/ApiKeyManager.css@@ -0,0 +1,46 @@+/* Shared styles for the API key management screens (platform + global). */++.api-key-manager__content {+ padding: 20px;+}++.api-key-manager__header-actions {+ display: flex;+ justify-content: flex-end;+ margin-bottom: 16px;+}++.api-key-manager__key-cell {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 0;+ cursor: pointer;+}++.api-key-manager__key-text {+ font-family: monospace;+ font-size: 13px;+ pointer-events: none;+ /* Theme-aware (respects dark mode) instead of a hardcoded rgba. */+ color: var(--ant-color-text-secondary, rgba(0, 0, 0, 0.65));+}++.api-key-manager__copy-icon {+ font-size: 12px;+ color: var(--ant-color-text-tertiary, rgba(0, 0, 0, 0.45));+}++.api-key-manager__key-cell:hover .api-key-manager__copy-icon {+ color: var(--ant-color-text, rgba(0, 0, 0, 0.88));+}++.api-key-manager__actions {+ display: flex;+ gap: 8px;+}++.api-key-manager__deployment-select {+ width: 100%;+ margin-top: 8px;+}diff --git a/frontend/src/components/settings/api-key-manager/ApiKeyManager.jsx b/frontend/src/components/settings/api-key-manager/ApiKeyManager.jsxnew file mode 100644index 000000000..fc77ba5ea--- /dev/null+++ b/frontend/src/components/settings/api-key-manager/ApiKeyManager.jsx@@ -0,0 +1,488 @@+import {+ ArrowLeftOutlined,+ CopyOutlined,+ DeleteOutlined,+ EditOutlined,+ PlusOutlined,+ SyncOutlined,+} from "@ant-design/icons";+import {+ Button,+ Form,+ Input,+ Modal,+ Switch,+ Table,+ Tooltip,+ Typography,+} from "antd";+import PropTypes from "prop-types";+import { useCallback, useEffect, useState } from "react";+import { useNavigate } from "react-router-dom";++import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";+import { useCopyToClipboard } from "../../../hooks/useCopyToClipboard";+import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";+import { IslandLayout } from "../../../layouts/island-layout/IslandLayout.jsx";+import { useAlertStore } from "../../../store/alert-store";+import { useSessionStore } from "../../../store/session-store";+import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal.jsx";+import { SettingsLayout } from "../settings-layout/SettingsLayout.jsx";+import "../platform/PlatformSettings.css";+import "./ApiKeyManager.css";++// Allow-list for user-facing free text (key name/description). Matches the+// backend's utils.input_sanitizer.SAFE_TEXT_PATTERN — alphanumerics, spaces and+// a small set of punctuation. Angle brackets, double quotes, & and backticks+// are rejected so a stored value can't start a tag or break out of a+// double-quoted attribute in emails/PDFs/logs. The apostrophe IS allowed, so+// single-quoted attribute contexts must still escape at render time.+const SAFE_TEXT_REGEX = /^[a-zA-Z0-9 \-_.,:'()/]+$/;+const SAFE_TEXT_MESSAGE =+ "Only alphanumeric characters, spaces, hyphens, underscores, periods, commas, colons, apostrophes, parentheses, and forward slashes are allowed.";++// Static: no props, state or closures, so it lives outside the component+// (unlike `columns`, which closes over the row handlers).+const NAME_AND_DESCRIPTION_RULES = {+ name: [+ { required: true, message: "Name is required" },+ { max: 128, message: "Name cannot exceed 128 characters" },+ { pattern: SAFE_TEXT_REGEX, message: SAFE_TEXT_MESSAGE },+ ],+ description: [+ { required: true, message: "Description is required" },+ { max: 512, message: "Description cannot exceed 512 characters" },+ { pattern: SAFE_TEXT_REGEX, message: SAFE_TEXT_MESSAGE },+ ],+};++const identity = (v) => v;++/**+ * Shared key-management screen for platform API keys and global API deployment+ * keys. Owns the common table + create/edit/rotate/delete/copy flows; callers+ * inject the feature-specific bits (extra column, extra form fields, payload+ * shaping, edit initial values) via props.+ */+function ApiKeyManager({+ title,+ entityLabel,+ resourcePath,+ extraColumns = [],+ renderCreateFields,+ renderEditFields,+ getEditInitialValues = () => ({}),+ transformCreatePayload = identity,+ transformEditPayload = identity,+}) {+ const [keys, setKeys] = useState([]);+ const [isLoading, setIsLoading] = useState(false);+ const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);+ const [isEditModalOpen, setIsEditModalOpen] = useState(false);+ const [selectedKey, setSelectedKey] = useState(null);+ const [isSaving, setIsSaving] = useState(false);++ const [createForm] = Form.useForm();+ const [editForm] = Form.useForm();++ const { sessionDetails } = useSessionStore();+ const { setAlertDetails } = useAlertStore();+ const axiosPrivate = useAxiosPrivate();+ const navigate = useNavigate();+ const handleException = useExceptionHandler();+ const copyToClipboard = useCopyToClipboard();++ const basePath = `/api/v1/unstract/${sessionDetails?.orgId}/${resourcePath}`;++ const fetchKeys = useCallback(() => {+ if (!sessionDetails?.orgId) {+ return;+ }+ setIsLoading(true);+ axiosPrivate({ method: "GET", url: `${basePath}/keys/` })+ .then((res) => setKeys(res?.data || []))+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to load API keys")),+ )+ .finally(() => setIsLoading(false));+ }, [basePath, sessionDetails?.orgId]);++ useEffect(() => {+ fetchKeys();+ }, [fetchKeys]);++ const handleCreate = () => {+ createForm+ .validateFields()+ .then((values) => {+ setIsSaving(true);+ axiosPrivate({+ method: "POST",+ url: `${basePath}/keys/`,+ headers: {+ "X-CSRFToken": sessionDetails?.csrfToken,+ "Content-Type": "application/json",+ },+ data: transformCreatePayload(values),+ })+ .then((res) => {+ setIsCreateModalOpen(false);+ createForm.resetFields();+ fetchKeys();+ copyToClipboard(res?.data?.key, "API key");+ })+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to create API key")),+ )+ .finally(() => setIsSaving(false));+ })+ .catch((err) => {+ // validateFields rejects with `errorFields`, which antd already renders+ // inline. Anything else escaped the .then body (payload shaping) after+ // isSaving was set, so surface it and release the modal.+ if (err?.errorFields) {+ return;+ }+ setIsSaving(false);+ setAlertDetails(handleException(err, "Failed to create API key"));+ });+ };++ const handleEdit = () => {+ editForm+ .validateFields()+ .then((values) => {+ setIsSaving(true);+ axiosPrivate({+ method: "PATCH",+ url: `${basePath}/keys/${selectedKey?.id}/`,+ headers: {+ "X-CSRFToken": sessionDetails?.csrfToken,+ "Content-Type": "application/json",+ },+ data: transformEditPayload(values),+ })+ .then(() => {+ setIsEditModalOpen(false);+ editForm.resetFields();+ setSelectedKey(null);+ fetchKeys();+ setAlertDetails({+ type: "success",+ content: "API key updated successfully",+ });+ })+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to update API key")),+ )+ .finally(() => setIsSaving(false));+ })+ .catch((err) => {+ // See handleCreate: only antd's validation reject is silent.+ if (err?.errorFields) {+ return;+ }+ setIsSaving(false);+ setAlertDetails(handleException(err, "Failed to update API key"));+ });+ };++ const handleToggleStatus = (record) => {+ axiosPrivate({+ method: "PATCH",+ url: `${basePath}/keys/${record?.id}/`,+ headers: {+ "X-CSRFToken": sessionDetails?.csrfToken,+ "Content-Type": "application/json",+ },+ data: { is_active: !record?.is_active },+ })+ .then(() => fetchKeys())+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to update key status")),+ );+ };++ const handleRotate = (record) => {+ axiosPrivate({+ method: "POST",+ url: `${basePath}/keys/${record?.id}/rotate/`,+ headers: { "X-CSRFToken": sessionDetails?.csrfToken },+ })+ .then((res) => {+ fetchKeys();+ copyToClipboard(res?.data?.key, "API key");+ })+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to rotate API key")),+ );+ };++ const handleDelete = (record) => {+ axiosPrivate({+ method: "DELETE",+ url: `${basePath}/keys/${record?.id}/`,+ headers: { "X-CSRFToken": sessionDetails?.csrfToken },+ })+ .then(() => {+ fetchKeys();+ setAlertDetails({+ type: "success",+ content: "API key deleted successfully",+ });+ })+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to delete API key")),+ );+ };++ const openEditModal = (record) => {+ setSelectedKey(record);+ editForm.setFieldsValue({+ description: record?.description,+ ...getEditInitialValues(record),+ });+ setIsEditModalOpen(true);+ };++ const handleCopyKey = (record) => {+ axiosPrivate({ method: "GET", url: `${basePath}/keys/${record?.id}/` })+ .then((res) => copyToClipboard(res?.data?.key, "API key"))+ .catch((err) =>+ setAlertDetails(handleException(err, "Failed to copy API key")),+ );+ };++ const formatDate = (dateStr) =>+ dateStr ? new Date(dateStr).toLocaleString() : "";++ const columns = [+ {+ title: "Name",+ dataIndex: "name",+ key: "name",+ width: "13%",+ ellipsis: true,+ },+ {+ title: "Description",+ dataIndex: "description",+ key: "description",+ // Base columns total 86%, leaving room for one injected column (14%).+ width: "13%",+ ellipsis: true,+ },+ {+ title: "API Key",+ dataIndex: "key",+ key: "key",+ width: "14%",+ render: (_, record) => (+ <Tooltip title="Click to copy">+ <Button+ type="text"+ className="api-key-manager__key-cell"+ onClick={() => handleCopyKey(record)}+ aria-label={`Copy API key ${record?.name}`}+ >+ <Typography.Text className="api-key-manager__key-text">+ {record?.key}+ </Typography.Text>+ <CopyOutlined className="api-key-manager__copy-icon" />+ </Button>+ </Tooltip>+ ),+ },+ ...extraColumns,+ {+ title: "Active",+ dataIndex: "is_active",+ key: "is_active",+ width: "7%",+ render: (_, record) => (+ <Switch+ size="small"+ checked={record?.is_active}+ onChange={() => handleToggleStatus(record)}+ />+ ),+ },+ {+ title: "Created By",+ dataIndex: "created_by_email",+ key: "created_by_email",+ width: "15%",+ ellipsis: true,+ },+ {+ title: "Created",+ dataIndex: "created_at",+ key: "created_at",+ width: "12%",+ render: (text) => formatDate(text),+ },+ {+ title: "Actions",+ key: "actions",+ width: "12%",+ render: (_, record) => (+ <div className="api-key-manager__actions">+ <ConfirmModal+ handleConfirm={() => handleRotate(record)}+ title="Rotate Key"+ content="This will generate a new key and invalidate the current one. Continue?"+ okText="Rotate"+ >+ <Tooltip title="Rotate key">+ <Button size="small" icon={<SyncOutlined />} />+ </Tooltip>+ </ConfirmModal>+ <Tooltip title="Edit">+ <Button+ size="small"+ icon={<EditOutlined />}+ onClick={() => openEditModal(record)}+ />+ </Tooltip>+ <ConfirmModal+ handleConfirm={() => handleDelete(record)}+ title="Delete Key"+ content="Are you sure you want to delete this key? This action cannot be undone."+ okText="Delete"+ >+ <Tooltip title="Delete">+ <Button size="small" danger icon={<DeleteOutlined />} />+ </Tooltip>+ </ConfirmModal>+ </div>+ ),+ },+ ];++ return (+ <SettingsLayout>+ <div>+ <div className="plt-set-head">+ <Button+ size="small"+ type="text"+ onClick={() =>+ navigate(`/${sessionDetails?.orgName}/settings/platform`)+ }+ >+ <ArrowLeftOutlined />+ </Button>+ <Typography.Text className="plt-set-head-typo">+ {title}+ </Typography.Text>+ </div>+ <div className="plt-set-layout">+ <IslandLayout>+ <div className="api-key-manager__content">+ <div className="api-key-manager__header-actions">+ <Button+ type="primary"+ icon={<PlusOutlined />}+ onClick={() => setIsCreateModalOpen(true)}+ >+ New Key+ </Button>+ </div>+ <Table+ columns={columns}+ dataSource={keys}+ rowKey="id"+ loading={isLoading}+ pagination={false}+ size="small"+ />+ </div>+ </IslandLayout>+ </div>+ </div>++ {/* Create Modal */}+ <Modal+ title={`Create ${entityLabel}`}+ open={isCreateModalOpen}+ onOk={handleCreate}+ onCancel={() => {+ setIsCreateModalOpen(false);+ createForm.resetFields();+ }}+ okText="Create"+ confirmLoading={isSaving}+ centered+ >+ <Form form={createForm} layout="vertical">+ <Form.Item+ name="name"+ label="Name"+ rules={NAME_AND_DESCRIPTION_RULES.name}+ >+ <Input placeholder="Enter key name" maxLength={128} />+ </Form.Item>+ <Form.Item+ name="description"+ label="Description"+ rules={NAME_AND_DESCRIPTION_RULES.description}+ >+ <Input.TextArea+ placeholder="Enter description"+ rows={3}+ maxLength={512}+ />+ </Form.Item>+ {renderCreateFields?.(createForm)}+ </Form>+ </Modal>++ {/* Edit Modal */}+ <Modal+ title={`Edit ${entityLabel}`}+ open={isEditModalOpen}+ onOk={handleEdit}+ onCancel={() => {+ setIsEditModalOpen(false);+ editForm.resetFields();+ setSelectedKey(null);+ }}+ okText="Save"+ confirmLoading={isSaving}+ centered+ >+ <Form form={editForm} layout="vertical">+ <Form.Item label="Name">+ <Input value={selectedKey?.name} disabled />+ </Form.Item>+ <Form.Item+ name="description"+ label="Description"+ rules={NAME_AND_DESCRIPTION_RULES.description}+ >+ <Input.TextArea+ placeholder="Enter description"+ rows={3}+ maxLength={512}+ />+ </Form.Item>+ {renderEditFields?.(editForm)}+ </Form>+ </Modal>+ </SettingsLayout>+ );+}++ApiKeyManager.propTypes = {+ title: PropTypes.string.isRequired,+ entityLabel: PropTypes.string.isRequired,+ resourcePath: PropTypes.string.isRequired,+ extraColumns: PropTypes.array,+ renderCreateFields: PropTypes.func,+ renderEditFields: PropTypes.func,+ getEditInitialValues: PropTypes.func,+ transformCreatePayload: PropTypes.func,+ transformEditPayload: PropTypes.func,+};++export { ApiKeyManager };diff --git a/frontend/src/components/settings/global-api-deployment-keys/GlobalApiDeploymentKeys.jsx b/frontend/src/components/settings/global-api-deployment-keys/GlobalApiDeploymentKeys.jsxnew file mode 100644index 000000000..1b0326fe0--- /dev/null+++ b/frontend/src/components/settings/global-api-deployment-keys/GlobalApiDeploymentKeys.jsx@@ -0,0 +1,135 @@+import { Checkbox, Form, Select, Tag, Tooltip } from "antd";+import PropTypes from "prop-types";+import { useCallback, useEffect, useState } from "react";++import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";+import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";+import { useAlertStore } from "../../../store/alert-store";+import { useSessionStore } from "../../../store/session-store";+import { ApiKeyManager } from "../api-key-manager/ApiKeyManager.jsx";++function DeploymentScopeFields({ form, deployments }) {+ const allowAll = Form.useWatch("allow_all_deployments", form);+ return (+ <>+ <Form.Item+ name="allow_all_deployments"+ valuePropName="checked"+ initialValue={false}+ >+ <Checkbox>Allow all API deployments</Checkbox>+ </Form.Item>+ <Form.Item+ name="api_deployments"+ label="Select API Deployments"+ rules={+ allowAll === false+ ? [{ required: true, message: "Select at least one deployment" }]+ : []+ }+ >+ <Select+ mode="multiple"+ placeholder="Search and select deployments"+ optionFilterProp="children"+ className="api-key-manager__deployment-select"+ showSearch+ disabled={allowAll !== false}+ >+ {deployments?.map((d) => (+ <Select.Option key={d?.id} value={d?.id}>+ {d?.display_name || d?.api_name}+ {!d?.is_active && " (inactive)"}+ </Select.Option>+ ))}+ </Select>+ </Form.Item>+ </>+ );+}++DeploymentScopeFields.propTypes = {+ form: PropTypes.object.isRequired,+ deployments: PropTypes.array,+};++const scopeColumn = {+ title: "Scope",+ key: "scope",+ width: "14%",+ render: (_, record) =>+ record?.allow_all_deployments ? (+ <Tag color="blue">All Deployments</Tag>+ ) : (+ <Tooltip+ title={record?.api_deployments+ ?.map((d) => d?.display_name || d?.api_name)+ ?.join(", ")}+ >+ <Tag>{record?.api_deployments?.length || 0} deployment(s)</Tag>+ </Tooltip>+ ),+};++// Scoped keys carry an explicit deployment list; org-wide keys must not (the+// backend rejects an incoherent pair). Mirror that shaping on the client. The+// `?? false` default only bites on create — the edit form seeds the checkbox+// from the record — so one transform serves both.+const transformPayload = (values) => {+ const allowAll = values?.allow_all_deployments ?? false;+ return {+ ...values,+ allow_all_deployments: allowAll,+ api_deployments: allowAll ? [] : values?.api_deployments || [],+ };+};++function GlobalApiDeploymentKeys() {+ const [deployments, setDeployments] = useState([]);+ const { sessionDetails } = useSessionStore();+ const { setAlertDetails } = useAlertStore();+ const axiosPrivate = useAxiosPrivate();+ const handleException = useExceptionHandler();++ const basePath = `/api/v1/unstract/${sessionDetails?.orgId}/global-api-deployment`;++ const fetchDeployments = useCallback(() => {+ if (!sessionDetails?.orgId) {+ return;+ }+ axiosPrivate({ method: "GET", url: `${basePath}/deployments/` })+ .then((res) => setDeployments(res?.data || []))+ .catch((err) =>+ // Surface it: a scoped key requires picking from this list, so a silent+ // empty picker would leave the admin unable to create one with no clue why.+ setAlertDetails(handleException(err, "Failed to load API deployments")),+ );+ }, [basePath, sessionDetails?.orgId]);++ useEffect(() => {+ fetchDeployments();+ }, [fetchDeployments]);++ const renderScopeFields = (form) => (+ <DeploymentScopeFields form={form} deployments={deployments} />+ );++ return (+ <ApiKeyManager+ title="Global API Deployment Keys"+ entityLabel="Global API Deployment Key"+ resourcePath="global-api-deployment"+ extraColumns={[scopeColumn]}+ renderCreateFields={renderScopeFields}+ renderEditFields={renderScopeFields}+ getEditInitialValues={(record) => ({+ allow_all_deployments: record?.allow_all_deployments,+ api_deployments: record?.api_deployments?.map((d) => d?.id) || [],+ })}+ transformCreatePayload={transformPayload}+ transformEditPayload={transformPayload}+ />+ );+}++export { GlobalApiDeploymentKeys };diff --git a/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.css b/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.cssdeleted file mode 100644index 9941aa466..000000000--- a/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.css+++ /dev/null@@ -1,38 +0,0 @@-/* Styles for PlatformApiKeys */--.platform-api-keys__content {- padding: 20px;-}--.platform-api-keys__header-actions {- display: flex;- justify-content: flex-end;- margin-bottom: 16px;-}--.platform-api-keys__key-cell {- display: inline-flex;- align-items: center;- gap: 6px;- cursor: pointer;-}--.platform-api-keys__key-text {- font-family: monospace;- font-size: 13px;- pointer-events: none;-}--.platform-api-keys__copy-icon {- font-size: 12px;- color: rgba(0, 0, 0, 0.45);-}--.platform-api-keys__key-cell:hover .platform-api-keys__copy-icon {- color: rgba(0, 0, 0, 0.88);-}--.platform-api-keys__actions {- display: flex;- gap: 8px;-}diff --git a/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.jsx b/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.jsxindex d578d12f6..d7bac1316 100644--- a/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.jsx+++ b/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.jsx@@ -1,40 +1,6 @@-import {- ArrowLeftOutlined,- CopyOutlined,- DeleteOutlined,- EditOutlined,- PlusOutlined,- SyncOutlined,-} from "@ant-design/icons";-import {- Button,- Form,- Input,- Modal,- Select,- Switch,- Table,- Tag,- Tooltip,- Typography,-} from "antd";-import { useCallback, useEffect, useState } from "react";-import { useNavigate } from "react-router-dom";+import { Form, Select, Tag } from "antd";-import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";-import { useCopyToClipboard } from "../../../hooks/useCopyToClipboard";-import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";-import { IslandLayout } from "../../../layouts/island-layout/IslandLayout.jsx";-import { useAlertStore } from "../../../store/alert-store";-import { useSessionStore } from "../../../store/session-store";-import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal.jsx";-import { SettingsLayout } from "../settings-layout/SettingsLayout.jsx";-import "../platform/PlatformSettings.css";-import "./PlatformApiKeys.css";--const SAFE_TEXT_REGEX = /^[a-zA-Z0-9 \-_.,:'()/]+$/;-const SAFE_TEXT_MESSAGE =- "Only alphanumeric characters, spaces, hyphens, underscores, periods, commas, colons, apostrophes, parentheses, and forward slashes are allowed.";+import { ApiKeyManager } from "../api-key-manager/ApiKeyManager.jsx";const PERMISSION_OPTIONS = [{ value: "read_write", label: "Read/Write", color: "blue" },@@ -48,443 +14,43 @@ const PERMISSION_CONFIG = Object.fromEntries(]),);-function PlatformApiKeys() {- const [keys, setKeys] = useState([]);- const [isLoading, setIsLoading] = useState(false);- const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);- const [isEditModalOpen, setIsEditModalOpen] = useState(false);- const [selectedKey, setSelectedKey] = useState(null);- const [isSaving, setIsSaving] = useState(false);-- const [createForm] = Form.useForm();- const [editForm] = Form.useForm();-- const { sessionDetails } = useSessionStore();- const { setAlertDetails } = useAlertStore();- const axiosPrivate = useAxiosPrivate();- const navigate = useNavigate();- const handleException = useExceptionHandler();- const copyToClipboard = useCopyToClipboard();-- const basePath = `/api/v1/unstract/${sessionDetails?.orgId}/platform-api`;-- const fetchKeys = useCallback(() => {- if (!sessionDetails?.orgId) {- return;- }- setIsLoading(true);- axiosPrivate({- method: "GET",- url: `${basePath}/keys/`,- })- .then((res) => {- setKeys(res?.data || []);- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to load API keys"));- })- .finally(() => {- setIsLoading(false);- });- }, [basePath, sessionDetails?.orgId]);-- useEffect(() => {- fetchKeys();- }, [fetchKeys]);-- const handleCreate = () => {- createForm.validateFields().then((values) => {- setIsSaving(true);- axiosPrivate({- method: "POST",- url: `${basePath}/keys/`,- headers: {- "X-CSRFToken": sessionDetails?.csrfToken,- "Content-Type": "application/json",- },- data: values,- })- .then((res) => {- setIsCreateModalOpen(false);- createForm.resetFields();- fetchKeys();- copyToClipboard(res?.data?.key, "API key");- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to create API key"));- })- .finally(() => {- setIsSaving(false);- });- });- };-- const handleEdit = () => {- editForm.validateFields().then((values) => {- setIsSaving(true);- axiosPrivate({- method: "PATCH",- url: `${basePath}/keys/${selectedKey?.id}/`,- headers: {- "X-CSRFToken": sessionDetails?.csrfToken,- "Content-Type": "application/json",- },- data: values,- })- .then(() => {- setIsEditModalOpen(false);- editForm.resetFields();- setSelectedKey(null);- fetchKeys();- setAlertDetails({- type: "success",- content: "API key updated successfully",- });- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to update API key"));- })- .finally(() => {- setIsSaving(false);- });- });- };-- const handleToggleStatus = (record) => {- axiosPrivate({- method: "PATCH",- url: `${basePath}/keys/${record?.id}/`,- headers: {- "X-CSRFToken": sessionDetails?.csrfToken,- "Content-Type": "application/json",- },- data: { is_active: !record?.is_active },- })- .then(() => {- fetchKeys();- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to update key status"));- });- };-- const handleRotate = (record) => {- axiosPrivate({- method: "POST",- url: `${basePath}/keys/${record?.id}/rotate/`,- headers: {- "X-CSRFToken": sessionDetails?.csrfToken,- },- })- .then((res) => {- fetchKeys();- copyToClipboard(res?.data?.key, "API key");- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to rotate API key"));- });- };-- const handleDelete = (record) => {- axiosPrivate({- method: "DELETE",- url: `${basePath}/keys/${record?.id}/`,- headers: {- "X-CSRFToken": sessionDetails?.csrfToken,- },- })- .then(() => {- fetchKeys();- setAlertDetails({- type: "success",- content: "API key deleted successfully",- });- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to delete API key"));- });- };-- const openEditModal = (record) => {- setSelectedKey(record);- editForm.setFieldsValue({- description: record?.description,- permission: record?.permission,- });- setIsEditModalOpen(true);- };-- const handleCopyKey = (record) => {- axiosPrivate({- method: "GET",- url: `${basePath}/keys/${record?.id}/`,- })- .then((res) => {- copyToClipboard(res?.data?.key, "API key");- })- .catch((err) => {- setAlertDetails(handleException(err, "Failed to copy API key"));- });- };-- const formatDate = (dateStr) => {- if (!dateStr) {- return "";- }- return new Date(dateStr).toLocaleString();- };-- const columns = [- {- title: "Name",- dataIndex: "name",- key: "name",- width: "14%",- ellipsis: true,- },- {- title: "Description",- dataIndex: "description",- key: "description",- width: "18%",- ellipsis: true,- },- {- title: "API Key",- dataIndex: "key",- key: "key",- width: "14%",- render: (_, record) => (- <Tooltip title="Click to copy">- <Button- type="text"- className="platform-api-keys__key-cell"- onClick={() => handleCopyKey(record)}- aria-label={`Copy API key ${record?.name}`}- >- <Typography.Text className="platform-api-keys__key-text">- {record?.key}- </Typography.Text>- <CopyOutlined className="platform-api-keys__copy-icon" />- </Button>- </Tooltip>- ),- },- {- title: "Permission",- dataIndex: "permission",- key: "permission",- width: "10%",- render: (text) => {- const { color, label } = PERMISSION_CONFIG[text] ?? {- color: "default",- label: `Unknown: ${text}`,- };- return <Tag color={color}>{label}</Tag>;- },- },- {- title: "Active",- dataIndex: "is_active",- key: "is_active",- width: "7%",- render: (_, record) => (- <Switch- size="small"- checked={record?.is_active}- onChange={() => handleToggleStatus(record)}- />- ),- },- {- title: "Created By",- dataIndex: "created_by_email",- key: "created_by_email",- width: "17%",- ellipsis: true,- },- {- title: "Created",- dataIndex: "created_at",- key: "created_at",- width: "15%",- render: (text) => formatDate(text),- },- {- title: "Actions",- key: "actions",- width: "15%",- render: (_, record) => (- <div className="platform-api-keys__actions">- <ConfirmModal- handleConfirm={() => handleRotate(record)}- title="Rotate API Key"- content="This will generate a new key and invalidate the current one. Continue?"- okText="Rotate"- >- <Tooltip title="Rotate key">- <Button size="small" icon={<SyncOutlined />} />- </Tooltip>- </ConfirmModal>- <Tooltip title="Edit">- <Button- size="small"- icon={<EditOutlined />}- onClick={() => openEditModal(record)}- />- </Tooltip>- <ConfirmModal- handleConfirm={() => handleDelete(record)}- title="Delete API Key"- content="Are you sure you want to delete this API key? This action cannot be undone."- okText="Delete"- >- <Tooltip title="Delete">- <Button size="small" danger icon={<DeleteOutlined />} />- </Tooltip>- </ConfirmModal>- </div>- ),- },- ];+const permissionColumn = {+ title: "Permission",+ dataIndex: "permission",+ key: "permission",+ width: "10%",+ render: (text) => {+ const { color, label } = PERMISSION_CONFIG[text] ?? {+ color: "default",+ label: `Unknown: ${text}`,+ };+ return <Tag color={color}>{label}</Tag>;+ },+};+function PlatformApiKeys() {return (- <SettingsLayout>- <div>- <div className="plt-set-head">- <Button- size="small"- type="text"- onClick={() =>- navigate(`/${sessionDetails?.orgName}/settings/platform`)- }- >- <ArrowLeftOutlined />- </Button>- <Typography.Text className="plt-set-head-typo">- Platform API Keys- </Typography.Text>- </div>- <div className="plt-set-layout">- <IslandLayout>- <div className="platform-api-keys__content">- <div className="platform-api-keys__header-actions">- <Button- type="primary"- icon={<PlusOutlined />}- onClick={() => setIsCreateModalOpen(true)}- >- New Key- </Button>- </div>- <Table- columns={columns}- dataSource={keys}- rowKey="id"- loading={isLoading}- pagination={false}- size="small"- />- </div>- </IslandLayout>- </div>- </div>-- {/* Create Modal */}- <Modal- title="Create API Key"- open={isCreateModalOpen}- onOk={handleCreate}- onCancel={() => {- setIsCreateModalOpen(false);- createForm.resetFields();- }}- okText="Create"- confirmLoading={isSaving}- centered- >- <Form form={createForm} layout="vertical">- <Form.Item- name="name"- label="Name"- rules={[- { required: true, message: "Name is required" },- { max: 128, message: "Name cannot exceed 128 characters" },- { pattern: SAFE_TEXT_REGEX, message: SAFE_TEXT_MESSAGE },- ]}- >- <Input placeholder="Enter key name" maxLength={128} />- </Form.Item>- <Form.Item- name="description"- label="Description"- rules={[- { required: true, message: "Description is required" },- {- max: 512,- message: "Description cannot exceed 512 characters",- },- { pattern: SAFE_TEXT_REGEX, message: SAFE_TEXT_MESSAGE },- ]}- >- <Input.TextArea- placeholder="Enter description"- rows={3}- maxLength={512}- />- </Form.Item>- <Form.Item- name="permission"- label="Permission"- initialValue="read_write"- >- <Select options={PERMISSION_OPTIONS} />- </Form.Item>- </Form>- </Modal>-- {/* Edit Modal */}- <Modal- title="Edit API Key"- open={isEditModalOpen}- onOk={handleEdit}- onCancel={() => {- setIsEditModalOpen(false);- editForm.resetFields();- setSelectedKey(null);- }}- okText="Save"- confirmLoading={isSaving}- centered- >- <Form form={editForm} layout="vertical">- <Form.Item label="Name">- <Input value={selectedKey?.name} disabled />- </Form.Item>- <Form.Item- name="description"- label="Description"- rules={[- { required: true, message: "Description is required" },- {- max: 512,- message: "Description cannot exceed 512 characters",- },- { pattern: SAFE_TEXT_REGEX, message: SAFE_TEXT_MESSAGE },- ]}- >- <Input.TextArea- placeholder="Enter description"- rows={3}- maxLength={512}- />- </Form.Item>- <Form.Item name="permission" label="Permission">- <Select options={PERMISSION_OPTIONS} />- </Form.Item>- </Form>- </Modal>- </SettingsLayout>+ <ApiKeyManager+ title="Platform API Keys"+ entityLabel="API Key"+ resourcePath="platform-api"+ extraColumns={[permissionColumn]}+ renderCreateFields={() => (+ <Form.Item+ name="permission"+ label="Permission"+ initialValue="read_write"+ >+ <Select options={PERMISSION_OPTIONS} />+ </Form.Item>+ )}+ renderEditFields={() => (+ <Form.Item name="permission" label="Permission">+ <Select options={PERMISSION_OPTIONS} />+ </Form.Item>+ )}+ getEditInitialValues={(record) => ({ permission: record?.permission })}+ />);}diff --git a/frontend/src/pages/GlobalApiDeploymentKeysPage.jsx b/frontend/src/pages/GlobalApiDeploymentKeysPage.jsxnew file mode 100644index 000000000..9f589265c--- /dev/null+++ b/frontend/src/pages/GlobalApiDeploymentKeysPage.jsx@@ -0,0 +1,7 @@+import { GlobalApiDeploymentKeys } from "../components/settings/global-api-deployment-keys/GlobalApiDeploymentKeys.jsx";++function GlobalApiDeploymentKeysPage() {+ return <GlobalApiDeploymentKeys />;+}++export { GlobalApiDeploymentKeysPage };diff --git a/frontend/src/routes/useMainAppRoutes.js b/frontend/src/routes/useMainAppRoutes.jsindex b6a4c4c49..6d3d245a1 100644--- a/frontend/src/routes/useMainAppRoutes.js+++ b/frontend/src/routes/useMainAppRoutes.js@@ -41,6 +41,10 @@ const DeploymentsPage = lazyNamed(() => import("../pages/DeploymentsPage.jsx"),"DeploymentsPage",);+const GlobalApiDeploymentKeysPage = lazyNamed(+ () => import("../pages/GlobalApiDeploymentKeysPage.jsx"),+ "GlobalApiDeploymentKeysPage",+);const GroupsPage = lazyNamed(() => import("../pages/GroupsPage.jsx"),"GroupsPage",@@ -307,6 +311,10 @@ function useMainAppRoutes() {path="settings/platform-api-keys"element={<PlatformApiKeysPage />}/>+ <Route+ path="settings/global-api-deployment-keys"+ element={<GlobalApiDeploymentKeysPage />}+ /></Route><Route path="settings/triad" element={<DefaultTriad />} />{RequirePlatformAdmin && PlatformAdminPage && (