Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-3318 [FEAT] Platform API key implementation (#1860)

Deepak K93c647dfc758
diff --git a/backend/account_v2/custom_auth_middleware.py b/backend/account_v2/custom_auth_middleware.py
index d55bbca39..59c3e85a5 100644
--- a/backend/account_v2/custom_auth_middleware.py
+++ b/backend/account_v2/custom_auth_middleware.py
@@ -1,3 +1,6 @@
+import logging
+import uuid
+
from django.conf import settings
from django.http import HttpRequest, HttpResponse, JsonResponse
from utils.constants import Account
@@ -7,9 +10,11 @@ from utils.user_session import UserSessionUtils
from account_v2.authentication_plugin_registry import AuthenticationPluginRegistry
from account_v2.authentication_service import AuthenticationService
from account_v2.constants import Common
-from backend.constants import RequestHeader
+from backend.constants import RequestHeader, RequestMethod
from backend.internal_api_constants import INTERNAL_API_PREFIX
+logger = logging.getLogger(__name__)
+
class CustomAuthMiddleware:
def __init__(self, get_response: HttpResponse):
@@ -35,6 +40,11 @@ class CustomAuthMiddleware:
): # Should API Key be in settings or just env alone?
return self.get_response(request)
+ # Authenticate with Bearer token (Platform API Key)
+ auth_header = request.headers.get("Authorization", "")
+ if auth_header.startswith("Bearer "):
+ return self._authenticate_with_platform_key(request, auth_header)
+
if AuthenticationPluginRegistry.is_plugin_available():
auth_service: AuthenticationService = (
AuthenticationPluginRegistry.get_plugin()
@@ -56,3 +66,75 @@ class CustomAuthMiddleware:
return response
return JsonResponse({"message": "Unauthorized"}, status=401)
+
+ def _authenticate_with_platform_key(
+ self, request: HttpRequest, auth_header: str
+ ) -> HttpResponse:
+ """Authenticate request using a Platform API Key Bearer token.
+
+ Resolves the token to the owning user so all downstream code sees
+ a fully authenticated request.
+ """
+ from platform_api.models import ApiKeyPermission, PlatformApiKey
+
+ token_str = auth_header[len("Bearer ") :]
+ try:
+ key_uuid = uuid.UUID(token_str)
+ except (ValueError, AttributeError):
+ return JsonResponse({"message": "Invalid API key format"}, status=401)
+
+ # Block DELETE before any DB lookup — never allowed via API key
+ if request.method == RequestMethod.DELETE:
+ return JsonResponse(
+ {"message": "DELETE operations are not allowed via API key"},
+ status=403,
+ )
+
+ try:
+ key = PlatformApiKey.objects.select_related(
+ "created_by", "api_user", "organization"
+ ).get(key=key_uuid, is_active=True)
+ except PlatformApiKey.DoesNotExist:
+ return JsonResponse({"message": "Invalid or inactive API key"}, status=401)
+
+ # Validate the key belongs to the org in the URL
+ if request.organization_id and str(key.organization.organization_id) != str(
+ request.organization_id
+ ):
+ return JsonResponse(
+ {"message": "API key does not belong to this organization"},
+ status=403,
+ )
+
+ if not key.api_user:
+ logger.error("API key %s has no linked service account", key.id)
+ return JsonResponse(
+ {
+ "message": "API key service account is missing. "
+ "Please delete and recreate the key."
+ },
+ status=401,
+ )
+
+ # Block write operations for read-only keys
+ if (
+ key.permission == ApiKeyPermission.READ
+ and request.method not in RequestMethod.SAFE_METHODS
+ ):
+ return JsonResponse(
+ {"message": "API key has read-only permission"},
+ status=403,
+ )
+
+ request.user = key.api_user
+ request.platform_api_key = key
+ # Skip CSRF for Bearer-authenticated requests
+ request.csrf_processing_done = True
+ StateStore.set(Common.LOG_EVENTS_ID, str(key.id))
+ StateStore.set(Account.ORGANIZATION_ID, key.organization.organization_id)
+
+ try:
+ return self.get_response(request)
+ finally:
+ StateStore.clear(Account.ORGANIZATION_ID)
+ StateStore.clear(Common.LOG_EVENTS_ID)
diff --git a/backend/account_v2/migrations/0004_user_is_service_account.py b/backend/account_v2/migrations/0004_user_is_service_account.py
new file mode 100644
index 000000000..5fbcb596a
--- /dev/null
+++ b/backend/account_v2/migrations/0004_user_is_service_account.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.1 on 2026-03-16 01:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("account_v2", "0003_user_is_deprecated"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="user",
+ name="is_service_account",
+ field=models.BooleanField(
+ db_comment="True for service accounts (e.g. platform API key bearer auth sessions)",
+ default=False,
+ ),
+ ),
+ ]
diff --git a/backend/account_v2/models.py b/backend/account_v2/models.py
index af2bf6592..5a3250bdd 100644
--- a/backend/account_v2/models.py
+++ b/backend/account_v2/models.py
@@ -94,6 +94,10 @@ class User(AbstractUser):
)
auth_provider = models.CharField(max_length=64, default="")
+ is_service_account = models.BooleanField(
+ default=False,
+ db_comment="True for service accounts (e.g. platform API key bearer auth sessions)",
+ )
def __str__(self): # type: ignore
return f"User({self.id}, email: {self.email}, userId: {self.user_id})"
diff --git a/backend/adapter_processor_v2/models.py b/backend/adapter_processor_v2/models.py
index 61a3fe9b0..13be07cdc 100644
--- a/backend/adapter_processor_v2/models.py
+++ b/backend/adapter_processor_v2/models.py
@@ -34,6 +34,9 @@ class AdapterInstanceModelManager(DefaultOrganizationManagerMixin, models.Manage
return super().get_queryset()
def for_user(self, user: User) -> QuerySet[Any]:
+ if getattr(user, "is_service_account", False):
+ return self.all()
+
return (
self.get_queryset()
.filter(
diff --git a/backend/adapter_processor_v2/serializers.py b/backend/adapter_processor_v2/serializers.py
index 1d931f126..482a6a9e7 100644
--- a/backend/adapter_processor_v2/serializers.py
+++ b/backend/adapter_processor_v2/serializers.py
@@ -189,7 +189,7 @@ class SharedUserListSerializer(BaseAdapterSerializer):
Used for listing adapter users
"""
- shared_users = UserSerializer(many=True)
+ shared_users = serializers.SerializerMethodField()
created_by = UserSerializer()
class Meta(BaseAdapterSerializer.Meta):
@@ -204,6 +204,11 @@ class SharedUserListSerializer(BaseAdapterSerializer):
"shared_to_org",
) # type: ignore
+ def get_shared_users(self, obj):
+ return UserSerializer(
+ obj.shared_users.filter(is_service_account=False), many=True
+ ).data
+
class UserDefaultAdapterSerializer(ModelSerializer):
class Meta:
diff --git a/backend/api_v2/models.py b/backend/api_v2/models.py
index 437015c7f..532b67d2d 100644
--- a/backend/api_v2/models.py
+++ b/backend/api_v2/models.py
@@ -30,7 +30,11 @@ class APIDeploymentModelManager(DefaultOrganizationManagerMixin, models.Manager)
- API deployments created by the user
- API deployments shared with the user
- API deployments shared with the entire organization
+ - Service accounts see all org resources
"""
+ if getattr(user, "is_service_account", False):
+ return self.all()
+
from django.db.models import Q
return self.filter(
diff --git a/backend/api_v2/serializers.py b/backend/api_v2/serializers.py
index 5a2068fd9..ef5bcb243 100644
--- a/backend/api_v2/serializers.py
+++ b/backend/api_v2/serializers.py
@@ -513,7 +513,10 @@ class SharedUserListSerializer(ModelSerializer):
def get_shared_users(self, obj):
"""Return list of shared users with id and email."""
- return [{"id": user.id, "email": user.email} for user in obj.shared_users.all()]
+ return [
+ {"id": user.id, "email": user.email}
+ for user in obj.shared_users.filter(is_service_account=False)
+ ]
def get_created_by(self, obj):
"""Return creator details."""
diff --git a/backend/backend/constants.py b/backend/backend/constants.py
index 26d944d9a..d04ce75dc 100644
--- a/backend/backend/constants.py
+++ b/backend/backend/constants.py
@@ -20,6 +20,16 @@ class FieldLengthConstants:
ADAPTER_ID_LENGTH = 128
+class RequestMethod:
+ """HTTP request method constants."""
+
+ DELETE = "DELETE"
+ GET = "GET"
+ HEAD = "HEAD"
+ OPTIONS = "OPTIONS"
+ SAFE_METHODS = frozenset({GET, HEAD, OPTIONS})
+
+
class RequestHeader:
"""Request header constants."""
diff --git a/backend/backend/serializers.py b/backend/backend/serializers.py
index 7cb429530..62a92fc8a 100644
--- a/backend/backend/serializers.py
+++ b/backend/backend/serializers.py
@@ -7,14 +7,19 @@ from backend.constants import RequestKey
class AuditSerializer(ModelSerializer):
def create(self, validated_data: dict[str, Any]) -> Any:
- if self.context.get(RequestKey.REQUEST):
- validated_data[RequestKey.CREATED_BY] = self.context.get(
- RequestKey.REQUEST
- ).user
- validated_data[RequestKey.MODIFIED_BY] = self.context.get(
- RequestKey.REQUEST
- ).user
- return super().create(validated_data)
+ request = self.context.get(RequestKey.REQUEST)
+ if request:
+ validated_data[RequestKey.CREATED_BY] = request.user
+ validated_data[RequestKey.MODIFIED_BY] = request.user
+ instance = super().create(validated_data)
+
+ # Auto-add key owner as co-owner for resources created via API key
+ if request and hasattr(request, "platform_api_key"):
+ platform_api_key = request.platform_api_key
+ if hasattr(instance, "shared_users") and platform_api_key.created_by:
+ instance.shared_users.add(platform_api_key.created_by)
+
+ return instance
def update(self, instance: Any, validated_data: dict[str, Any]) -> Any:
if self.context.get(RequestKey.REQUEST):
diff --git a/backend/backend/settings/base.py b/backend/backend/settings/base.py
index a06d63df2..b71467e43 100644
--- a/backend/backend/settings/base.py
+++ b/backend/backend/settings/base.py
@@ -344,6 +344,7 @@ SHARED_APPS = (
"tags",
"configuration",
"dashboard_metrics",
+ "platform_api",
)
TENANT_APPS = []
diff --git a/backend/backend/urls_v2.py b/backend/backend/urls_v2.py
index 05df8c58e..fd91d3cc2 100644
--- a/backend/backend/urls_v2.py
+++ b/backend/backend/urls_v2.py
@@ -64,4 +64,5 @@ urlpatterns = [
path("execution/", include("workflow_manager.execution.urls")),
path("execution/", include("workflow_manager.file_execution.urls")),
path("metrics/", include("dashboard_metrics.urls")),
+ path("platform-api/", include("platform_api.urls")),
]
diff --git a/backend/connector_v2/models.py b/backend/connector_v2/models.py
index bcd7bb597..c3d0e6108 100644
--- a/backend/connector_v2/models.py
+++ b/backend/connector_v2/models.py
@@ -27,6 +27,9 @@ class ConnectorInstanceModelManager(DefaultOrganizationManagerMixin, models.Mana
return super().get_queryset()
def for_user(self, user: User) -> models.QuerySet:
+ if getattr(user, "is_service_account", False):
+ return self.all()
+
return (
self.get_queryset()
.filter(
diff --git a/backend/permissions/permission.py b/backend/permissions/permission.py
index 5e2e45c35..a48982d9f 100644
--- a/backend/permissions/permission.py
+++ b/backend/permissions/permission.py
@@ -7,10 +7,19 @@ from rest_framework.views import APIView
from utils.user_context import UserContext
+def _is_service_account_safe_request(request: Request) -> bool:
+ """Allow service accounts through for safe (read-only) HTTP methods."""
+ return getattr(request.user, "is_service_account", False) and (
+ request.method in permissions.SAFE_METHODS
+ )
+
+
class IsOwner(permissions.BasePermission):
"""Custom permission to only allow owners of an object."""
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
+ if _is_service_account_safe_request(request):
+ return True
return True if obj.created_by == request.user else False
@@ -26,6 +35,8 @@ class IsOwnerOrSharedUser(permissions.BasePermission):
"""Custom permission to only allow owners and shared users of an object."""
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
+ if _is_service_account_safe_request(request):
+ return True
return (
True
if (
@@ -42,6 +53,8 @@ class IsOwnerOrSharedUserOrSharedToOrg(permissions.BasePermission):
"""
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
+ if _is_service_account_safe_request(request):
+ return True
return (
True
if (
diff --git a/backend/pipeline_v2/models.py b/backend/pipeline_v2/models.py
index cdd85405f..00b12c848 100644
--- a/backend/pipeline_v2/models.py
+++ b/backend/pipeline_v2/models.py
@@ -24,7 +24,11 @@ class PipelineModelManager(DefaultOrganizationManagerMixin, models.Manager):
- Pipelines created by the user
- Pipelines shared with the user
- Pipelines shared with the entire organization
+ - Service accounts see all org resources
"""
+ if getattr(user, "is_service_account", False):
+ return self.all()
+
return self.filter(
Q(created_by=user) # Owned by user
| Q(shared_users=user) # Shared with user
diff --git a/backend/pipeline_v2/serializers/sharing.py b/backend/pipeline_v2/serializers/sharing.py
index 1536745fb..0340379b5 100644
--- a/backend/pipeline_v2/serializers/sharing.py
+++ b/backend/pipeline_v2/serializers/sharing.py
@@ -26,7 +26,9 @@ class SharedUserListSerializer(serializers.ModelSerializer):
def get_shared_users(self, obj):
"""Get list of shared users with their details."""
- return UserSerializer(obj.shared_users.all(), many=True).data
+ return UserSerializer(
+ obj.shared_users.filter(is_service_account=False), many=True
+ ).data
def get_created_by(self, obj):
"""Get the creator's username."""
diff --git a/backend/platform_api/__init__.py b/backend/platform_api/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/backend/platform_api/apps.py b/backend/platform_api/apps.py
new file mode 100644
index 000000000..6c1078057
--- /dev/null
+++ b/backend/platform_api/apps.py
@@ -0,0 +1,9 @@
+from django.apps import AppConfig
+
+
+class PlatformApiConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "platform_api"
+
+ def ready(self):
+ import platform_api.signals # noqa: F401
diff --git a/backend/platform_api/migrations/0001_initial.py b/backend/platform_api/migrations/0001_initial.py
new file mode 100644
index 000000000..90d186ac8
--- /dev/null
+++ b/backend/platform_api/migrations/0001_initial.py
@@ -0,0 +1,95 @@
+# Generated by Django 4.2.1 on 2026-03-17 05:57
+
+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"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="PlatformApiKey",
+ 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.TextField(max_length=512)),
+ ("key", models.UUIDField(default=uuid.uuid4, unique=True)),
+ ("is_active", models.BooleanField(default=True)),
+ (
+ "permission",
+ models.CharField(
+ choices=[("read", "Read"), ("read_write", "Read/Write")],
+ default="read_write",
+ max_length=16,
+ ),
+ ),
+ (
+ "api_user",
+ models.OneToOneField(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="platform_api_key_identity",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="platform_api_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.",
+ default=None,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="account_v2.organization",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "platform_api_key",
+ },
+ ),
+ migrations.AddConstraint(
+ model_name="platformapikey",
+ constraint=models.UniqueConstraint(
+ fields=("name", "organization"),
+ name="unique_platform_api_key_name_per_org",
+ ),
+ ),
+ ]
diff --git a/backend/platform_api/migrations/__init__.py b/backend/platform_api/migrations/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/backend/platform_api/models.py b/backend/platform_api/models.py
new file mode 100644
index 000000000..971e0e572
--- /dev/null
+++ b/backend/platform_api/models.py
@@ -0,0 +1,56 @@
+import uuid
+
+from account_v2.models import User
+from django.db import models
+from utils.models.base_model import BaseModel
+from utils.models.organization_mixin import DefaultOrganizationMixin
+
+
+class ApiKeyPermission(models.TextChoices):
+ READ = "read", "Read"
+ READ_WRITE = "read_write", "Read/Write"
+
+
+class PlatformApiKey(DefaultOrganizationMixin, BaseModel):
+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
+ name = models.CharField(max_length=128)
+ description = models.TextField(max_length=512)
+ # TODO: Store hashed key instead of plaintext. Show plaintext only at
+ # create/rotate, then store hash. Retrieve should return masked value.
+ key = models.UUIDField(default=uuid.uuid4, unique=True)
+ is_active = models.BooleanField(default=True)
+ permission = models.CharField(
+ max_length=16,
+ choices=ApiKeyPermission.choices,
+ default=ApiKeyPermission.READ_WRITE,
+ )
+ created_by = models.ForeignKey(
+ User,
+ on_delete=models.SET_NULL,
+ null=True,
+ related_name="platform_api_keys_created",
+ )
+ modified_by = models.ForeignKey(
+ User,
+ on_delete=models.SET_NULL,
+ null=True,
+ related_name="+",
+ )
+ api_user = models.OneToOneField(
+ User,
+ on_delete=models.SET_NULL,
+ null=True,
+ related_name="platform_api_key_identity",
+ )
+
+ class Meta:
+ db_table = "platform_api_key"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["name", "organization"],
+ name="unique_platform_api_key_name_per_org",
+ ),
+ ]
+
+ def __str__(self):
+ return f"{self.name} ({self.organization})"
diff --git a/backend/platform_api/permissions.py b/backend/platform_api/permissions.py
new file mode 100644
index 000000000..12f23e63d
--- /dev/null
+++ b/backend/platform_api/permissions.py
@@ -0,0 +1,23 @@
+import logging
+
+from account_v2.authentication_controller import AuthenticationController
+from rest_framework.permissions import BasePermission
+
+logger = logging.getLogger(__name__)
+
+
+class IsOrganizationAdmin(BasePermission):
+ message = "Only organization admins can manage platform API keys."
+
+ def has_permission(self, request, view):
+ if not request.user or not request.user.is_authenticated:
+ return False
+ if getattr(request.user, "is_service_account", False):
+ return False
+ try:
+ auth_controller = AuthenticationController()
+ member = auth_controller.get_organization_members_by_user(user=request.user)
+ return auth_controller.is_admin_by_role(member.role)
+ except Exception:
+ logger.exception("Error checking admin role for user %s", request.user.id)
+ return False
diff --git a/backend/platform_api/serializers.py b/backend/platform_api/serializers.py
new file mode 100644
index 000000000..132e4feaa
--- /dev/null
+++ b/backend/platform_api/serializers.py
@@ -0,0 +1,93 @@
+import re
+
+from rest_framework import serializers
+from utils.user_context import UserContext
+
+from backend.serializers import AuditSerializer
+from platform_api.models import PlatformApiKey
+
+# Alphanumeric, spaces, hyphens, underscores, periods, commas, colons,
+# 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, 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()
+ created_by_email = serializers.SerializerMethodField()
+
+ class Meta:
+ model = PlatformApiKey
+ fields = [
+ "id",
+ "name",
+ "description",
+ "key",
+ "is_active",
+ "created_at",
+ "modified_at",
+ "permission",
+ "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 PlatformApiKeyCreateSerializer(AuditSerializer):
+ description = serializers.CharField(required=True, max_length=512)
+
+ class Meta:
+ model = PlatformApiKey
+ fields = ["name", "description", "permission"]
+
+ def validate_name(self, value):
+ value = validate_safe_text(value)
+ organization = UserContext.get_organization()
+ if PlatformApiKey.objects.filter(name=value, organization=organization).exists():
+ raise serializers.ValidationError(
+ "A key with this name already exists in your organization."
+ )
+ return value
+
+ def validate_description(self, value):
+ return validate_safe_text(value)
+
+
+class PlatformApiKeyUpdateSerializer(AuditSerializer):
+ class Meta:
+ model = PlatformApiKey
+ fields = ["description", "is_active", "permission"]
+ extra_kwargs = {
+ "description": {"required": False},
+ "is_active": {"required": False},
+ "permission": {"required": False},
+ }
+
+ def validate_description(self, value):
+ return validate_safe_text(value)
+
+
+class PlatformApiKeyDetailSerializer(serializers.ModelSerializer):
+ """Used for create/rotate responses where the full key is shown once."""
+
+ class Meta:
+ model = PlatformApiKey
+ fields = ["id", "name", "key", "is_active"]
diff --git a/backend/platform_api/services.py b/backend/platform_api/services.py
new file mode 100644
index 000000000..5eac5127f
--- /dev/null
+++ b/backend/platform_api/services.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+import re
+import uuid as _uuid
+from typing import TYPE_CHECKING
+
+from account_v2.enums import UserRole
+from account_v2.models import User
+from django.apps import apps
+from django.db import models, transaction
+from tenant_account_v2.models import OrganizationMember
+
+if TYPE_CHECKING:
+ from account_v2.models import Organization
+
+ from platform_api.models import PlatformApiKey
+
+# Business app labels whose models may have created_by / shared_users fields.
+# Restricts transfer_ownership to avoid scanning Django built-in and third-party models.
+_BUSINESS_APP_LABELS = {
+ "adapter_processor_v2",
+ "api_v2",
+ "connector_v2",
+ "pipeline_v2",
+ "workflow_v2",
+ "prompt_studio_core_v2",
+ "prompt_studio_registry_v2",
+ "agentic_studio_registry",
+}
+
+
+def _slugify_for_email(name: str) -> str:
+ """Sanitize key name to RFC 5321-safe email local part."""
+ slug = name.lower().replace(" ", "-")
+ slug = re.sub(r"[^a-z0-9\-]", "", slug)
+ return slug[:20] or "key"
+
+
+def create_api_user_for_key(
+ platform_api_key: PlatformApiKey, organization: Organization
+) -> User:
+ """Create a dedicated service account for bearer auth sessions."""
+ with transaction.atomic():
+ uid = str(_uuid.uuid4())
+ name_slug = _slugify_for_email(platform_api_key.name)
+ user = User(
+ username=f"svc-{name_slug}-{uid[:8]}",
+ email=f"{name_slug}-{uid[:8]}@platform.internal",
+ user_id=uid,
+ is_service_account=True,
+ )
+ user.set_unusable_password()
+ user.save()
+
+ OrganizationMember.objects.create(
+ user=user,
+ organization=organization,
+ role=UserRole.USER.value,
+ )
+
+ platform_api_key.api_user = user
+ platform_api_key.save(update_fields=["api_user"])
+ return user
+
+
+def _get_user_fk_fields(model: type) -> list[str]:
+ """Return names of all ForeignKey fields pointing to User."""
+ return [
+ f.name
+ for f in model._meta.get_fields()
+ if isinstance(f, models.ForeignKey) and f.related_model is User
+ ]
+
+
+def _get_user_m2m_fields(model: type) -> list[str]:
+ """Return names of all ManyToManyField fields pointing to User."""
+ return [
+ f.name
+ for f in model._meta.get_fields()
+ if isinstance(f, models.ManyToManyField) and f.related_model is User
+ ]
+
+
+def _transfer_model_ownership(model: type, from_user: User, to_user: User) -> None:
+ """Transfer ownership for a single model from one user to another.
+
+ Dynamically discovers all ForeignKey and ManyToMany fields pointing to
+ User, so custom fields like workflow_owner are handled automatically.
+
+ Uses _base_manager to bypass DefaultOrganizationManagerMixin which
+ relies on UserContext (unavailable during signal/cleanup paths).
+ """
+ # Use _base_manager to bypass org-scoped default manager filtering.
+ qs = model._base_manager.all()
+
+ user_fk_fields = _get_user_fk_fields(model)
+ user_m2m_fields = _get_user_m2m_fields(model)
+
+ # Transfer all ForeignKey fields pointing to User
+ for field_name in user_fk_fields:
+ qs.filter(**{field_name: from_user}).update(**{field_name: to_user})
+
+ # Transfer all ManyToMany fields pointing to User
+ for field_name in user_m2m_fields:
+ for instance in qs.filter(**{field_name: from_user}):
+ getattr(instance, field_name).add(to_user)
+ getattr(instance, field_name).remove(from_user)
+
+
+def transfer_ownership(from_user: User, to_user: User | None) -> None:
+ """Transfer all resource ownership from one user to another.
+
+ Replaces from_user with to_user across business models:
+ - created_by / modified_by ForeignKey fields
+ - shared_users ManyToMany fields
+
+ Also cleans up redundancy: if to_user becomes created_by (owner),
+ they are removed from shared_users on that record since ownership
+ already grants full access.
+ """
+ if not to_user:
+ return
+
+ with transaction.atomic():
+ for model in apps.get_models():
+ if model._meta.app_label not in _BUSINESS_APP_LABELS:
+ continue
+ _transfer_model_ownership(model, from_user, to_user)
+
+
+def delete_api_user_for_key(platform_api_key: PlatformApiKey) -> None:
+ """Transfer ownership to key creator, then delete the service account."""
+ api_user = platform_api_key.api_user
+ if not api_user:
+ return
+
+ with transaction.atomic():
+ transfer_ownership(from_user=api_user, to_user=platform_api_key.created_by)
+ api_user.delete()
diff --git a/backend/platform_api/signals.py b/backend/platform_api/signals.py
new file mode 100644
index 000000000..96dad5072
--- /dev/null
+++ b/backend/platform_api/signals.py
@@ -0,0 +1,22 @@
+import logging
+
+from django.db.models.signals import pre_delete
+from django.dispatch import receiver
+
+from platform_api.models import PlatformApiKey
+from platform_api.services import delete_api_user_for_key
+
+logger = logging.getLogger(__name__)
+
+
+@receiver(pre_delete, sender=PlatformApiKey)
+def cleanup_api_user_on_key_delete(sender, instance, **kwargs):
+ """Ensure service account is cleaned up when a key is deleted via any path."""
+ try:
+ delete_api_user_for_key(instance)
+ except Exception:
+ logger.exception(
+ "Failed to clean up service account for key %s — "
+ "service account may be orphaned",
+ instance.id,
+ )
diff --git a/backend/platform_api/urls.py b/backend/platform_api/urls.py
new file mode 100644
index 000000000..b691564c3
--- /dev/null
+++ b/backend/platform_api/urls.py
@@ -0,0 +1,23 @@
+from django.urls import path
+
+from platform_api.views import PlatformApiKeyViewSet
+
+urlpatterns = [
+ path(
+ "keys/",
+ PlatformApiKeyViewSet.as_view({"get": "list", "post": "create"}),
+ name="platform_api_key_list",
+ ),
+ path(
+ "keys/<uuid:pk>/",
+ PlatformApiKeyViewSet.as_view(
+ {"get": "retrieve", "patch": "partial_update", "delete": "destroy"}
+ ),
+ name="platform_api_key_detail",
+ ),
+ path(
+ "keys/<uuid:pk>/rotate/",
+ PlatformApiKeyViewSet.as_view({"post": "rotate"}),
+ name="platform_api_key_rotate",
+ ),
+]
diff --git a/backend/platform_api/views.py b/backend/platform_api/views.py
new file mode 100644
index 000000000..2abf49812
--- /dev/null
+++ b/backend/platform_api/views.py
@@ -0,0 +1,82 @@
+import uuid
+
+from django.db import transaction
+from rest_framework import status, viewsets
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+from utils.user_context import UserContext
+
+from platform_api.models import PlatformApiKey
+from platform_api.permissions import IsOrganizationAdmin
+from platform_api.serializers import (
+ PlatformApiKeyCreateSerializer,
+ PlatformApiKeyDetailSerializer,
+ PlatformApiKeyListSerializer,
+ PlatformApiKeyUpdateSerializer,
+)
+from platform_api.services import create_api_user_for_key
+
+
+class PlatformApiKeyViewSet(viewsets.ModelViewSet):
+ permission_classes = [IsAuthenticated, IsOrganizationAdmin]
+
+ def get_queryset(self):
+ return PlatformApiKey.objects.filter(
+ organization=UserContext.get_organization(),
+ )
+
+ def get_serializer_class(self):
+ if self.action == "list":
+ return PlatformApiKeyListSerializer
+ if self.action == "create":
+ return PlatformApiKeyCreateSerializer
+ if self.action == "partial_update":
+ return PlatformApiKeyUpdateSerializer
+ return PlatformApiKeyListSerializer
+
+ def create(self, request, *args, **kwargs):
+ organization = UserContext.get_organization()
+
+ serializer = PlatformApiKeyCreateSerializer(
+ data=request.data, context={"request": request}
+ )
+ serializer.is_valid(raise_exception=True)
+
+ with transaction.atomic():
+ platform_api_key = serializer.save()
+ create_api_user_for_key(platform_api_key, organization)
+
+ response_serializer = PlatformApiKeyDetailSerializer(platform_api_key)
+ return Response(response_serializer.data, status=status.HTTP_201_CREATED)
+
+ def retrieve(self, request, *args, **kwargs):
+ instance = self.get_object()
+ serializer = PlatformApiKeyDetailSerializer(instance)
+ return Response(serializer.data)
+
+ def partial_update(self, request, *args, **kwargs):
+ instance = self.get_object()
+
+ serializer = PlatformApiKeyUpdateSerializer(
+ instance, data=request.data, partial=True, context={"request": request}
+ )
+ serializer.is_valid(raise_exception=True)
+ updated_instance = serializer.save()
+
+ response_serializer = PlatformApiKeyListSerializer(updated_instance)
+ return Response(response_serializer.data)
+
+ def destroy(self, request, *args, **kwargs):
+ instance = self.get_object()
+ instance.delete()
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ 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"])
+
+ response_serializer = PlatformApiKeyDetailSerializer(instance)
+ return Response(response_serializer.data)
diff --git a/backend/prompt_studio/prompt_studio_core_v2/models.py b/backend/prompt_studio/prompt_studio_core_v2/models.py
index e125b6e50..406c157ef 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/models.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/models.py
@@ -23,6 +23,9 @@ logger = logging.getLogger(__name__)
class CustomToolModelManager(DefaultOrganizationManagerMixin, models.Manager):
def for_user(self, user: User) -> QuerySet[Any]:
+ if getattr(user, "is_service_account", False):
+ return self.all()
+
return (
self.get_queryset()
.filter(
diff --git a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
index 991adbcfc..3b15792a9 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
@@ -11,6 +11,7 @@ from account_v2.models import User
from adapter_processor_v2.constants import AdapterKeys
from adapter_processor_v2.models import AdapterInstance
from django.conf import settings
+from django.db import transaction
from django.db.models.manager import BaseManager
from plugins import get_plugin
from rest_framework.request import Request
@@ -1908,3 +1909,69 @@ class PromptStudioHelper:
return True, warning_message
return False, ""
+
+ @staticmethod
+ def sync_prompts(tool: CustomTool, import_data: dict, user) -> dict:
+ """Sync prompts from export JSON into an existing project.
+
+ Replaces all existing prompts with prompts from the export data.
+ Tool settings (preamble, postamble, etc.) are also updated.
+ Profiles and adapters are left untouched.
+
+ Args:
+ tool: Target CustomTool instance
+ import_data: Parsed export JSON
+ user: User performing the sync
+
+ Returns:
+ dict: Summary of the sync operation
+ """
+ prompts_data = import_data.get("prompts", [])
+ tool_settings = import_data.get("tool_settings", {})
+
+ # Get the target tool's default profile
+ default_profile = ProfileManager.objects.filter(
+ prompt_studio_tool=tool, is_default=True
+ ).first()
+ if not default_profile:
+ raise ValueError(
+ "Target project must have a default profile configured "
+ "before syncing prompts."
+ )
+
+ with transaction.atomic():
+ # Delete all existing prompts
+ deleted_count, _ = ToolStudioPrompt.objects.filter(tool_id=tool).delete()
+
+ # Create new prompts from export data
+ PromptStudioHelper.import_prompts(prompts_data, tool, user)
+
+ # Update tool settings
+ tool_settings_fields = [
+ "preamble",
+ "postamble",
+ "summarize_prompt",
+ "summarize_context",
+ "summarize_as_source",
+ "enable_challenge",
+ "enable_highlight",
+ "exclude_failed",
+ "single_pass_extraction_mode",
+ "prompt_grammer",
+ ]
+ update_fields = []
+ for field in tool_settings_fields:
+ if field in tool_settings:
+ setattr(tool, field, tool_settings[field])
+ update_fields.append(field)
+
+ if update_fields:
+ tool.modified_by = user
+ update_fields.append("modified_by")
+ tool.save(update_fields=update_fields)
+
+ return {
+ "prompts_deleted": deleted_count,
+ "prompts_created": len(prompts_data),
+ "tool_settings_updated": bool(update_fields),
+ }
diff --git a/backend/prompt_studio/prompt_studio_core_v2/serializers.py b/backend/prompt_studio/prompt_studio_core_v2/serializers.py
index 9a90fa358..c45367a95 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/serializers.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/serializers.py
@@ -35,7 +35,10 @@ except ImportError:
class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):
shared_users = serializers.PrimaryKeyRelatedField(
- queryset=User.objects.all(), required=False, allow_null=True, many=True
+ queryset=User.objects.filter(is_service_account=False),
+ required=False,
+ allow_null=True,
+ many=True,
)
class Meta:
@@ -117,6 +120,10 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):
tool_id=data.get(TSKeys.TOOL_ID)
).order_by("sequence_number")
+ data["created_by_email"] = (
+ instance.created_by.email if instance.created_by else ""
+ )
+
if not prompt_instances.exists():
data[TSKeys.PROMPTS] = []
return data
@@ -152,7 +159,6 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):
output.append(serialized_data)
data[TSKeys.PROMPTS] = output
- data["created_by_email"] = instance.created_by.email
return data
@@ -171,7 +177,7 @@ class SharedUserListSerializer(serializers.ModelSerializer):
"""Used for listing users of Custom tool."""
created_by = UserSerializer()
- shared_users = UserSerializer(many=True)
+ shared_users = serializers.SerializerMethodField()
class Meta:
model = CustomTool
@@ -183,6 +189,11 @@ class SharedUserListSerializer(serializers.ModelSerializer):
"shared_to_org",
)
+ def get_shared_users(self, obj):
+ return UserSerializer(
+ obj.shared_users.filter(is_service_account=False), many=True
+ ).data
+
class FileInfoIdeSerializer(serializers.Serializer):
document_id = serializers.CharField()
@@ -202,3 +213,16 @@ class FileUploadIdeSerializer(serializers.Serializer):
)
],
)
+
+
+class SyncPromptsSerializer(serializers.Serializer):
+ data = serializers.DictField(required=True)
+ create_copy = serializers.BooleanField(default=False)
+
+ def validate_data(self, value):
+ required_keys = {"prompts"}
+ if not required_keys.issubset(value.keys()):
+ raise serializers.ValidationError(
+ f"Export JSON must contain keys: {required_keys}"
+ )
+ return value
diff --git a/backend/prompt_studio/prompt_studio_core_v2/urls.py b/backend/prompt_studio/prompt_studio_core_v2/urls.py
index 228368544..f5db3bb33 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/urls.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/urls.py
@@ -55,6 +55,8 @@ prompt_studio_project_transfer = PromptStudioCoreView.as_view(
{"get": "export_project", "post": "import_project"}
)
+prompt_studio_sync_prompts = PromptStudioCoreView.as_view({"post": "sync_prompts"})
+
prompt_studio_deployment_usage = PromptStudioCoreView.as_view(
{"get": "check_deployment_usage"}
)
@@ -138,6 +140,11 @@ urlpatterns = format_suffix_patterns(
prompt_studio_project_transfer,
name="prompt_studio_project_transfer_import",
),
+ path(
+ "prompt-studio/<uuid:pk>/sync-prompts/",
+ prompt_studio_sync_prompts,
+ name="prompt_studio_sync_prompts",
+ ),
path(
"prompt-studio/<uuid:pk>/check_deployment_usage/",
prompt_studio_deployment_usage,
diff --git a/backend/prompt_studio/prompt_studio_core_v2/views.py b/backend/prompt_studio/prompt_studio_core_v2/views.py
index f9f2e7ec7..014f825d1 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py
@@ -79,6 +79,7 @@ from .serializers import (
FileUploadIdeSerializer,
PromptStudioIndexSerializer,
SharedUserListSerializer,
+ SyncPromptsSerializer,
)
logger = logging.getLogger(__name__)
@@ -718,7 +719,7 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
serializer = ExportToolRequestSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
is_shared_with_org: bool = serializer.validated_data.get("is_shared_with_org")
- user_ids = set(serializer.validated_data.get("user_id"))
+ user_ids = set(serializer.validated_data.get("user_id") or [])
force_export = serializer.validated_data.get("force_export")
# Check registry count before export for HubSpot notification
@@ -852,6 +853,59 @@ class PromptStudioCoreView(viewsets.ModelViewSet):
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
+ @action(detail=True, methods=["post"])
+ def sync_prompts(self, request: Request, pk: Any = None) -> Response:
+ """Sync prompts from export JSON into an existing project.
+
+ Rip-and-replace: deletes all existing prompts and creates new ones
+ from the export data. Tool settings are also updated.
+ Profiles and adapters are left untouched.
+
+ Request body:
+ data (dict): The export JSON containing "prompts" key
+ create_copy (bool): If true, clone the project before syncing
+ """
+ tool = self.get_object()
+
+ serializer = SyncPromptsSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ import_data = serializer.validated_data["data"]
+ create_copy = serializer.validated_data["create_copy"]
+
+ response_data = {}
+
+ # Create a backup copy if requested
+ if create_copy:
+ organization = UserContext.get_organization()
+ export_data = PromptStudioHelper.export_project_settings(tool)
+ backup_name = PromptStudioHelper.generate_unique_tool_name(
+ f"{tool.tool_name} (backup)", organization
+ )
+ backup_tool = PromptStudioHelper.create_tool_from_import_data(
+ export_data, backup_name, organization, request.user
+ )
+ # Copy profiles from original to backup
+ for profile in ProfileManager.objects.filter(prompt_studio_tool=tool):
+ profile.pk = None
+ profile.prompt_studio_tool = backup_tool
+ profile.save()
+
+ PromptStudioHelper.import_prompts(
+ export_data["prompts"], backup_tool, request.user
+ )
+ response_data["backup_tool_id"] = str(backup_tool.tool_id)
+ response_data["backup_tool_name"] = backup_name
+
+ # Sync prompts into the target tool
+ sync_result = PromptStudioHelper.sync_prompts(tool, import_data, request.user)
+ response_data.update(sync_result)
+ response_data["message"] = (
+ f"Synced {sync_result['prompts_created']} prompts " f"into '{tool.tool_name}'"
+ )
+
+ return Response(response_data, status=status.HTTP_200_OK)
+
@action(detail=True, methods=["get"])
def check_deployment_usage(self, request: Request, pk: Any = None) -> Response:
"""Check if the Prompt Studio project is used in any deployments.
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/serializers.py b/backend/prompt_studio/prompt_studio_registry_v2/serializers.py
index 059c19293..838ec7d4d 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/serializers.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/serializers.py
@@ -15,7 +15,7 @@ class PromptStudioRegistrySerializer(AuditSerializer):
class PromptStudioRegistryInfoSerializer(AuditSerializer):
- shared_users = UserSerializer(many=True)
+ shared_users = serializers.SerializerMethodField()
prompt_studio_users = serializers.SerializerMethodField()
class Meta:
@@ -27,8 +27,15 @@ class PromptStudioRegistryInfoSerializer(AuditSerializer):
"prompt_studio_users",
)
+ def get_shared_users(self, obj: PromptStudioRegistry) -> Any:
+ return UserSerializer(
+ obj.shared_users.filter(is_service_account=False), many=True
+ ).data
+
def get_prompt_studio_users(self, obj: PromptStudioRegistry) -> Any:
- prompt_studio_users = obj.custom_tool.shared_users
+ prompt_studio_users = obj.custom_tool.shared_users.filter(
+ is_service_account=False
+ )
return UserSerializer(prompt_studio_users, many=True).data
diff --git a/backend/tenant_account_v2/organization_member_service.py b/backend/tenant_account_v2/organization_member_service.py
index c85376bd3..ce1a0d987 100644
--- a/backend/tenant_account_v2/organization_member_service.py
+++ b/backend/tenant_account_v2/organization_member_service.py
@@ -29,7 +29,7 @@ class OrganizationMemberService:
@staticmethod
def get_members() -> list[OrganizationMember]:
- return OrganizationMember.objects.all()
+ return OrganizationMember.objects.filter(user__is_service_account=False)
@staticmethod
def get_members_by_role(role: str) -> list[OrganizationMember]:
@@ -41,7 +41,9 @@ class OrganizationMemberService:
Returns:
list[OrganizationMember]: list of members
"""
- return OrganizationMember.objects.filter(role=role).order_by("member_id")
+ return OrganizationMember.objects.filter(
+ role=role, user__is_service_account=False
+ ).order_by("member_id")
@staticmethod
def set_member_role(member_id: int, role: str) -> None:
diff --git a/backend/workflow_manager/workflow_v2/models/execution.py b/backend/workflow_manager/workflow_v2/models/execution.py
index 0ec5b12dd..93623118d 100644
--- a/backend/workflow_manager/workflow_v2/models/execution.py
+++ b/backend/workflow_manager/workflow_v2/models/execution.py
@@ -42,12 +42,22 @@ class WorkflowExecutionManager(models.Manager):
3. Both shared -> User can see all executions
4. Neither shared -> User cannot see executions
+ Service accounts see all executions (org-scoped by view).
+
Args:
user: The user to filter executions for
Returns:
QuerySet of executions that the user has permission to access
"""
+ if getattr(user, "is_service_account", False):
+ from utils.user_context import UserContext
+
+ org = UserContext.get_organization()
+ if org:
+ return self.filter(workflow__organization=org)
+ return self.all()
+
# Filter for workflow access
workflow_filter = Q(workflow__created_by=user) | Q(workflow__shared_users=user)
diff --git a/backend/workflow_manager/workflow_v2/models/workflow.py b/backend/workflow_manager/workflow_v2/models/workflow.py
index a286662a1..dd945fc7f 100644
--- a/backend/workflow_manager/workflow_v2/models/workflow.py
+++ b/backend/workflow_manager/workflow_v2/models/workflow.py
@@ -21,7 +21,11 @@ class WorkflowModelManager(DefaultOrganizationManagerMixin, models.Manager):
- Workflows created by the user
- Workflows shared with the user
- Workflows shared with the entire organization
+ - Service accounts see all org resources
"""
+ if getattr(user, "is_service_account", False):
+ return self.all()
+
from django.db.models import Q
return self.filter(
diff --git a/backend/workflow_manager/workflow_v2/serializers.py b/backend/workflow_manager/workflow_v2/serializers.py
index 6442d1e1f..386f9b81a 100644
--- a/backend/workflow_manager/workflow_v2/serializers.py
+++ b/backend/workflow_manager/workflow_v2/serializers.py
@@ -173,7 +173,10 @@ class SharedUserListSerializer(ModelSerializer):
def get_shared_users(self, obj):
"""Return list of shared users with id and email."""
- return [{"id": user.id, "email": user.email} for user in obj.shared_users.all()]
+ return [
+ {"id": user.id, "email": user.email}
+ for user in obj.shared_users.filter(is_service_account=False)
+ ]
def get_created_by(self, obj):
"""Return creator details."""
diff --git a/frontend/src/components/custom-tools/list-of-tools/ListOfTools.jsx b/frontend/src/components/custom-tools/list-of-tools/ListOfTools.jsx
index 6978d4e2b..ae8164e37 100644
--- a/frontend/src/components/custom-tools/list-of-tools/ListOfTools.jsx
+++ b/frontend/src/components/custom-tools/list-of-tools/ListOfTools.jsx
@@ -322,7 +322,7 @@ function ListOfTools() {
const onShare = (userIds, adapter, shareWithEveryone) => {
const requestOptions = {
method: "PATCH",
- url: `/api/v1/unstract/${sessionDetails?.orgId}/prompt-studio/${adapter?.tool_id}`,
+ url: `/api/v1/unstract/${sessionDetails?.orgId}/prompt-studio/${adapter?.tool_id}/`,
headers: {
"X-CSRFToken": sessionDetails?.csrfToken,
},
diff --git a/frontend/src/components/helpers/socket-messages/SocketMessages.js b/frontend/src/components/helpers/socket-messages/SocketMessages.js
index e2843e60d..352eebd01 100644
--- a/frontend/src/components/helpers/socket-messages/SocketMessages.js
+++ b/frontend/src/components/helpers/socket-messages/SocketMessages.js
@@ -110,9 +110,9 @@ function SocketMessages() {
if (!logId) return;
const channel = `logs:${logId}`;
- socket.on(channel, onMessage);
+ socket?.on(channel, onMessage);
return () => {
- socket.off(channel, onMessage);
+ socket?.off(channel, onMessage);
};
}, [socket, logId, onMessage]);
diff --git a/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx b/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx
index 346efa579..bb328b1a9 100644
--- a/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx
+++ b/frontend/src/components/navigations/side-nav-bar/SideNavBar.jsx
@@ -97,12 +97,21 @@ try {
// Plugin unavailable
}
-const getSettingsMenuItems = (orgName) => [
+const getSettingsMenuItems = (orgName, isAdmin) => [
{
key: "platform",
label: "Platform Settings",
path: `/${orgName}/settings/platform`,
},
+ ...(isAdmin
+ ? [
+ {
+ key: "platformApiKeys",
+ label: "Platform API Keys",
+ path: `/${orgName}/settings/platform-api-keys`,
+ },
+ ]
+ : []),
{
key: "users",
label: "User Management",
@@ -126,6 +135,9 @@ const getSettingsMenuItems = (orgName) => [
const getActiveSettingsKey = () => {
const currentPath = globalThis.location.pathname;
+ if (currentPath.includes("/settings/platform-api-keys")) {
+ return "platformApiKeys";
+ }
if (currentPath.includes("/settings/platform")) {
return "platform";
}
@@ -141,8 +153,8 @@ const getActiveSettingsKey = () => {
return "platform";
};
-const SettingsPopoverContent = ({ orgName, navigate }) => {
- const settingsMenuItems = getSettingsMenuItems(orgName);
+const SettingsPopoverContent = ({ orgName, navigate, isAdmin }) => {
+ const settingsMenuItems = getSettingsMenuItems(orgName, isAdmin);
const currentActiveKey = getActiveSettingsKey();
const handleMenuClick = (path) => {
@@ -170,6 +182,7 @@ const SettingsPopoverContent = ({ orgName, navigate }) => {
SettingsPopoverContent.propTypes = {
orgName: PropTypes.string.isRequired,
navigate: PropTypes.func.isRequired,
+ isAdmin: PropTypes.bool,
};
const HITL_MENU_ITEMS = [
@@ -442,6 +455,8 @@ const SideNavBar = ({ collapsed, setCollapsed }) => {
active:
globalThis.location.pathname === `/${orgName}/settings` ||
globalThis.location.pathname === `/${orgName}/settings/platform` ||
+ globalThis.location.pathname ===
+ `/${orgName}/settings/platform-api-keys` ||
globalThis.location.pathname === `/${orgName}/settings/triad` ||
globalThis.location.pathname === `/${orgName}/settings/review` ||
globalThis.location.pathname === `/${orgName}/users`,
@@ -672,6 +687,7 @@ const SideNavBar = ({ collapsed, setCollapsed }) => {
<SettingsPopoverContent
orgName={orgName}
navigate={navigate}
+ isAdmin={sessionDetails?.isAdmin}
/>
}
trigger="hover"
diff --git a/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.css b/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.css
new file mode 100644
index 000000000..9941aa466
--- /dev/null
+++ b/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.css
@@ -0,0 +1,38 @@
+/* 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.jsx
new file mode 100644
index 000000000..6c9b8d07f
--- /dev/null
+++ b/frontend/src/components/settings/platform-api-keys/PlatformApiKeys.jsx
@@ -0,0 +1,481 @@
+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 { 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, parentheses, and forward slashes are allowed.";
+
+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) => (
+ <Tag color={text === "read_write" ? "blue" : "default"}>
+ {text === "read_write" ? "Read/Write" : "Read"}
+ </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>
+ ),
+ },
+ ];
+
+ 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>
+ <Select.Option value="read_write">Read/Write</Select.Option>
+ <Select.Option value="read">Read</Select.Option>
+ </Select>
+ </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>
+ <Select.Option value="read_write">Read/Write</Select.Option>
+ <Select.Option value="read">Read</Select.Option>
+ </Select>
+ </Form.Item>
+ </Form>
+ </Modal>
+ </SettingsLayout>
+ );
+}
+
+export { PlatformApiKeys };
diff --git a/frontend/src/pages/PlatformApiKeysPage.jsx b/frontend/src/pages/PlatformApiKeysPage.jsx
new file mode 100644
index 000000000..6ef77eb5b
--- /dev/null
+++ b/frontend/src/pages/PlatformApiKeysPage.jsx
@@ -0,0 +1,7 @@
+import { PlatformApiKeys } from "../components/settings/platform-api-keys/PlatformApiKeys.jsx";
+
+function PlatformApiKeysPage() {
+ return <PlatformApiKeys />;
+}
+
+export { PlatformApiKeysPage };
diff --git a/frontend/src/routes/useMainAppRoutes.js b/frontend/src/routes/useMainAppRoutes.js
index 9ec8bb96e..1d5849b10 100644
--- a/frontend/src/routes/useMainAppRoutes.js
+++ b/frontend/src/routes/useMainAppRoutes.js
@@ -16,6 +16,7 @@ import { LogsPage } from "../pages/LogsPage.jsx";
import { MetricsDashboardPage } from "../pages/MetricsDashboardPage.jsx";
import { OnBoardPage } from "../pages/OnBoardPage.jsx";
import { OutputAnalyzerPage } from "../pages/OutputAnalyzerPage.jsx";
+import { PlatformApiKeysPage } from "../pages/PlatformApiKeysPage.jsx";
import { ProfilePage } from "../pages/ProfilePage.jsx";
import { SettingsPage } from "../pages/SettingsPage.jsx";
import { ToolIdePage } from "../pages/ToolIdePage.jsx";
@@ -208,6 +209,10 @@ function useMainAppRoutes() {
<Route path="users" element={<UsersPage />} />
<Route path="users/invite" element={<InviteEditUserPage />} />
<Route path="users/edit" element={<InviteEditUserPage />} />
+ <Route
+ path="settings/platform-api-keys"
+ element={<PlatformApiKeysPage />}
+ />
</Route>
<Route path="settings/triad" element={<DefaultTriad />} />
{RequirePlatformAdmin && PlatformAdminPage && (
diff --git a/unstract/connectors/src/unstract/connectors/databases/register.py b/unstract/connectors/src/unstract/connectors/databases/register.py
index f4ef0883e..28bec8a7a 100644
--- a/unstract/connectors/src/unstract/connectors/databases/register.py
+++ b/unstract/connectors/src/unstract/connectors/databases/register.py
@@ -32,7 +32,7 @@ def register_connectors(connectors: dict[str, Any]) -> None:
Common.MODULE: module,
Common.METADATA: metadata,
}
- except ModuleNotFoundError as exception:
+ except ImportError as exception:
logger.error(
f"Error while importing connectors {connector} : {exception}",
exc_info=True,