Skip to content

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

UN-3515 UN-3514 [FIX] Project shares apply to exported Prompt Studio tools; share modal keeps org-share state (#2050)

Chandrasekharan Ma611abead6a1
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/models.py b/backend/prompt_studio/prompt_studio_registry_v2/models.py
index 34478c8e7..d2eb64d8a 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/models.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/models.py
@@ -5,6 +5,7 @@ from typing import Any
from account_v2.models import User
from django.db import models
from django.db.models import QuerySet
+from tenant_account_v2.organization_member_service import OrganizationMemberService
from utils.models.base_model import BaseModel, BaseModelManager
from utils.models.organization_mixin import (
DefaultOrganizationManagerMixin,
@@ -26,12 +27,29 @@ class PromptStudioRegistryModelManager(DefaultOrganizationManagerMixin, BaseMode
return super().get_queryset()
def list_tools(self, user: User) -> QuerySet[Any]:
+ # Admins and service accounts see every row, including unlinked
+ # legacy ones — mirrors CustomTool.objects.for_user.
+ if getattr(
+ user, "is_service_account", False
+ ) or OrganizationMemberService.is_user_organization_admin(user):
+ return self.get_queryset().distinct("prompt_registry_id")
+
+ # Access derives from the linked project's current share state, so
+ # sharing applies without re-export. Unlinked legacy rows fall back
+ # to their own share fields.
+ visible_tools = CustomTool.objects.for_user(user).values("tool_id")
return (
self.get_queryset()
.filter(
- models.Q(created_by=user)
- | models.Q(shared_users=user)
- | models.Q(shared_to_org=True)
+ models.Q(custom_tool_id__in=visible_tools)
+ | (
+ models.Q(custom_tool__isnull=True)
+ & (
+ models.Q(created_by=user)
+ | models.Q(shared_users=user)
+ | models.Q(shared_to_org=True)
+ )
+ )
)
.distinct("prompt_registry_id")
)
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/tests/__init__.py b/backend/prompt_studio/prompt_studio_registry_v2/tests/__init__.py
new file mode 100644
index 000000000..0e873de84
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio_registry_v2/tests/__init__.py
@@ -0,0 +1 @@
+# Tests for prompt_studio_registry_v2.
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/tests/test_models.py b/backend/prompt_studio/prompt_studio_registry_v2/tests/test_models.py
new file mode 100644
index 000000000..890baf2ff
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio_registry_v2/tests/test_models.py
@@ -0,0 +1,150 @@
+"""Exported-tool access follows the linked project's current share state,
+not the export-time snapshot; unlinked (legacy) rows fall back to their own
+share fields.
+
+Covers ``PromptStudioRegistry.list_tools`` and its enforcement through
+``ToolInstanceHelper.validate_tool_access``. Admin resolution is patched to a
+deterministic predicate so the tests exercise share derivation, not the
+active auth plugin's role handling.
+"""
+
+import secrets
+from unittest.mock import patch
+
+from account_v2.models import Organization, User
+from django.core.exceptions import PermissionDenied
+from django.test import TestCase
+from tenant_account_v2.models import OrganizationMember
+from tool_instance_v2.tool_instance_helper import ToolInstanceHelper
+from utils.user_context import UserContext
+
+from prompt_studio.prompt_studio_core_v2.models import CustomTool
+from prompt_studio.prompt_studio_registry_v2.models import PromptStudioRegistry
+
+
+def _make_user(email: str) -> User:
+ return User.objects.create_user(
+ username=email, email=email, password=secrets.token_urlsafe()
+ )
+
+
+class RegistryShareDerivationTestBase(TestCase):
+ def setUp(self) -> None:
+ self.org = Organization.objects.create(
+ name="org-a", display_name="Org A", organization_id="org-a"
+ )
+ UserContext.set_organization_identifier(self.org.organization_id)
+
+ self.owner = _make_user("[email protected]")
+ self.other = _make_user("[email protected]")
+ self.admin = _make_user("[email protected]")
+ for user in (self.owner, self.other, self.admin):
+ OrganizationMember.objects.create(
+ organization=self.org, user=user, role="user"
+ )
+
+ patcher = patch(
+ "tenant_account_v2.organization_member_service"
+ ".OrganizationMemberService.is_user_organization_admin",
+ side_effect=lambda user: getattr(user, "email", None) == self.admin.email,
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ self.tool = CustomTool.objects.create(
+ tool_name="contract-parser",
+ description="Parses contracts",
+ author=self.owner.email,
+ created_by=self.owner,
+ organization=self.org,
+ )
+ # Owner-only snapshot, as written by an unshared export.
+ self.registry = PromptStudioRegistry.objects.create(
+ name=self.tool.tool_name,
+ custom_tool=self.tool,
+ created_by=self.owner,
+ organization=self.org,
+ )
+ self.registry.shared_users.add(self.owner)
+
+ def _visible_ids(self, user: User) -> set:
+ return set(
+ PromptStudioRegistry.objects.list_tools(user).values_list(
+ "prompt_registry_id", flat=True
+ )
+ )
+
+ def _validate(self, user: User) -> None:
+ ToolInstanceHelper.validate_tool_access(
+ user=user, tool_uid=str(self.registry.prompt_registry_id)
+ )
+
+
+class ListToolsDerivationTests(RegistryShareDerivationTestBase):
+ def test_owner_sees_own_tool(self) -> None:
+ self.assertIn(self.registry.prompt_registry_id, self._visible_ids(self.owner))
+
+ def test_unshared_tool_hidden_from_other_user(self) -> None:
+ self.assertNotIn(self.registry.prompt_registry_id, self._visible_ids(self.other))
+
+ def test_org_share_after_export_makes_tool_visible(self) -> None:
+ self.tool.shared_to_org = True
+ self.tool.save()
+ self.assertIn(self.registry.prompt_registry_id, self._visible_ids(self.other))
+
+ def test_user_share_after_export_makes_tool_visible(self) -> None:
+ self.tool.shared_users.add(self.other)
+ self.assertIn(self.registry.prompt_registry_id, self._visible_ids(self.other))
+
+ def test_unshare_after_share_hides_tool(self) -> None:
+ self.tool.shared_users.add(self.other)
+ self.tool.shared_users.remove(self.other)
+ self.assertNotIn(self.registry.prompt_registry_id, self._visible_ids(self.other))
+
+ def test_legacy_row_falls_back_to_own_share_fields(self) -> None:
+ shared = PromptStudioRegistry.objects.create(
+ name="legacy-shared",
+ custom_tool=None,
+ created_by=self.owner,
+ organization=self.org,
+ shared_to_org=True,
+ )
+ private = PromptStudioRegistry.objects.create(
+ name="legacy-private",
+ custom_tool=None,
+ created_by=self.owner,
+ organization=self.org,
+ )
+ self.assertIn(shared.prompt_registry_id, self._visible_ids(self.other))
+ self.assertNotIn(private.prompt_registry_id, self._visible_ids(self.other))
+
+ def test_admin_sees_unshared_and_legacy_rows(self) -> None:
+ legacy = PromptStudioRegistry.objects.create(
+ name="legacy-tool",
+ custom_tool=None,
+ created_by=self.owner,
+ organization=self.org,
+ )
+ visible = self._visible_ids(self.admin)
+ self.assertIn(self.registry.prompt_registry_id, visible)
+ self.assertIn(legacy.prompt_registry_id, visible)
+
+
+class ValidateToolAccessTests(RegistryShareDerivationTestBase):
+ def test_owner_allowed(self) -> None:
+ self._validate(self.owner)
+
+ def test_unshared_user_denied(self) -> None:
+ with self.assertRaises(PermissionDenied):
+ self._validate(self.other)
+
+ def test_share_after_export_allows_user(self) -> None:
+ self.tool.shared_to_org = True
+ self.tool.save()
+ self._validate(self.other)
+
+ def test_registry_snapshot_alone_does_not_grant_access(self) -> None:
+ # The project's share state wins over the registry snapshot.
+ self.registry.shared_users.add(self.other)
+ with self.assertRaises(PermissionDenied):
+ self._validate(self.other)
diff --git a/backend/tool_instance_v2/tool_instance_helper.py b/backend/tool_instance_v2/tool_instance_helper.py
index 01d99d8c0..f873b0d8b 100644
--- a/backend/tool_instance_v2/tool_instance_helper.py
+++ b/backend/tool_instance_v2/tool_instance_helper.py
@@ -534,27 +534,27 @@ class ToolInstanceHelper:
Raises:
PermissionDenied: If user doesn't have access to the tool
"""
- is_admin = OrganizationMemberService.is_user_organization_admin(user)
-
# Try to find the tool in PromptStudioRegistry first
try:
- prompt_registry_tool = PromptStudioRegistry.objects.get(pk=tool_uid)
- if (
- is_admin
- or prompt_registry_tool.created_by == user
- or prompt_registry_tool.shared_to_org
- or prompt_registry_tool.shared_users.filter(pk=user.pk).exists()
- ):
- return
- raise PermissionDenied("You don't have permission to perform this action.")
- except PromptStudioRegistry.DoesNotExist:
- # Not a prompt studio tool, try agentic studio if available
- pass
+ if PromptStudioRegistry.objects.filter(pk=tool_uid).exists():
+ # Access derives from the linked project's current share
+ # state, not the export-time snapshot.
+ if (
+ PromptStudioRegistry.objects.list_tools(user)
+ .filter(pk=tool_uid)
+ .exists()
+ ):
+ return
+ raise PermissionDenied(
+ "You don't have permission to perform this action."
+ )
except DjangoValidationError:
# Invalid UUID format, might be a static tool
logger.info(f"Not validating tool access for tool: {tool_uid}")
return
+ is_admin = OrganizationMemberService.is_user_organization_admin(user)
+
# Try to find the tool in AgenticStudioRegistry if available
if IS_AGENTIC_REGISTRY_AVAILABLE:
try:
diff --git a/frontend/src/hooks/useShareModal.js b/frontend/src/hooks/useShareModal.js
index 57ca32825..58829e4bb 100644
--- a/frontend/src/hooks/useShareModal.js
+++ b/frontend/src/hooks/useShareModal.js
@@ -76,6 +76,8 @@ function useShareModal({
...item,
shared_users: Array.isArray(sharedUsersList) ? sharedUsersList : [],
shared_groups: Array.isArray(sharedGroupsList) ? sharedGroupsList : [],
+ // List rows may omit this flag; losing it revokes org share on apply.
+ shared_to_org: sharedUsersResponse.data?.shared_to_org || false,
});
setAllUsers(userList);
const groupItems = Array.isArray(groupsResponse?.data)
diff --git a/tests/groups.yaml b/tests/groups.yaml
index ed3c161c9..357f18f30 100644
--- a/tests/groups.yaml
+++ b/tests/groups.yaml
@@ -88,7 +88,7 @@ groups:
- dashboard_metrics/tests
- file_management/tests
- project/tests
- - prompt_studio/tests
+ - prompt_studio/prompt_studio_registry_v2/tests
- tenant_account_v2/tests
- usage_v2/tests
- utils/tests