Skip to content

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

UN-2868 [FIX] Make settings read-only and block deletion on resources shared with a user (#2273)

Kirtiman Mishra1f1b28ae7ea2
diff --git a/backend/adapter_processor_v2/serializers.py b/backend/adapter_processor_v2/serializers.py
index 8209dd75c..3fee1f0ce 100644
--- a/backend/adapter_processor_v2/serializers.py
+++ b/backend/adapter_processor_v2/serializers.py
@@ -173,6 +173,7 @@ class AdapterListSerializer(BaseAdapterSerializer):
"created_at",
"modified_at",
"description",
+ "is_friction_less",
) # type: ignore
def to_representation(self, instance: AdapterInstance) -> dict[str, str]:
diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.py
index 33d7844b9..891ed1c57 100644
--- a/backend/api_v2/api_deployment_views.py
+++ b/backend/api_v2/api_deployment_views.py
@@ -7,7 +7,11 @@ from django.db.models import Count, F, IntegerField, OuterRef, QuerySet, Subquer
from django.db.models.functions import Coalesce
from django.http import HttpResponse
from permissions.membership_views import OwnerManagementMixin
-from permissions.permission import IsOwner, IsOwnerOrSharedUserOrSharedToOrg
+from permissions.permission import (
+ IsOwner,
+ IsOwnerOrSharedUserOrSharedToOrg,
+ is_activation_only_patch,
+)
from permissions.resource_share_views import ResourceShareManagementMixin
from platform_api.openapi_schema import PlatformKeyAutoSchema
from plugins import get_plugin
@@ -269,6 +273,12 @@ class APIDeploymentViewSet(
return ResourceType.API_DEPLOYMENT.value
def get_permissions(self) -> list[Any]:
+ # Enabling or disabling is use, not configuration, so it follows
+ # sharing. Everything else on these verbs stays with the owner.
+ if self.action == "partial_update" and is_activation_only_patch(
+ self.request, flag="is_active"
+ ):
+ return [IsOwnerOrSharedUserOrSharedToOrg()]
if self.action in [
"destroy",
"partial_update",
diff --git a/backend/api_v2/serializers.py b/backend/api_v2/serializers.py
index d9d8c9638..5bd5dc982 100644
--- a/backend/api_v2/serializers.py
+++ b/backend/api_v2/serializers.py
@@ -8,6 +8,7 @@ from django.apps import apps
from django.core.validators import RegexValidator
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
+from permissions.permission import mutable_workflows_for
from pipeline_v2.models import Pipeline
from prompt_studio.prompt_profile_manager_v2.models import ProfileManager
from rest_framework import serializers
@@ -34,6 +35,7 @@ from utils.serializer.integrity_error_mixin import IntegrityErrorMixin
from workflow_manager.endpoint_v2.models import WorkflowEndpoint
from workflow_manager.workflow_v2.exceptions import ExecutionDoesNotExistError
from workflow_manager.workflow_v2.models.execution import WorkflowExecution
+from workflow_manager.workflow_v2.models.workflow import Workflow
from api_v2.constants import ApiExecution
from api_v2.models import APIDeployment, APIKey
@@ -45,6 +47,9 @@ class APIDeploymentSerializer(IntegrityErrorMixin, AuditSerializer):
# explicitly so ``fields = "__all__"`` continues to expose it. Share
# mutations go through ``POST /api/<id>/share/`` (UN-2977 plan §B).
shared_groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
+ # Also on the list serializer; a detail response without it reads as
+ # editable to the UI.
+ is_owner = serializers.SerializerMethodField()
class Meta:
model = APIDeployment
@@ -56,6 +61,10 @@ class APIDeploymentSerializer(IntegrityErrorMixin, AuditSerializer):
"shared_to_org": {"read_only": True},
}
+ def get_is_owner(self, obj) -> bool:
+ request = self.context.get("request")
+ return obj.is_owner(request.user) if request else False
+
unique_error_message_map: dict[str, dict[str, str]] = {
"unique_api_name": {
"field": "api_name",
@@ -84,8 +93,36 @@ class APIDeploymentSerializer(IntegrityErrorMixin, AuditSerializer):
def validate_display_name(self, value: str) -> str:
return validate_name_field(value, field_name="Display name")
+ def get_fields(self) -> dict[str, Any]:
+ """Scope ``workflow`` to the requester, as the endpoint serializer does.
+
+ The default manager is only org-scoped, so an unscoped field lets any
+ member deploy a colleague's workflow -- executing it with its
+ connectors and adapters, at the owner's cost. Deploying is an owner
+ act: a deployment is a persistent execution surface its creator then
+ owns and can share onward.
+ """
+ fields = super().get_fields()
+ request = self.context.get("request")
+ queryset = mutable_workflows_for(request) if request else Workflow.objects.none()
+ # An update resends the bound workflow unchanged, so keep it
+ # selectable: a co-owner of this resource need not own the workflow.
+ # ``validate_workflow`` still refuses an actual change.
+ if self.instance is not None:
+ queryset = queryset | Workflow.objects.filter(pk=self.instance.workflow_id)
+ fields["workflow"].queryset = queryset
+ # Same code, readable text: the default names a pk the user never
+ # typed. Tests discriminate on the code, which is unchanged.
+ fields["workflow"].error_messages["does_not_exist"] = (
+ "You can only deploy a workflow you own. Ask its owner to add "
+ "you as a co-owner."
+ )
+ return fields
+
def validate_workflow(self, workflow):
- """Validate that the workflow has properly configured source and destination endpoints."""
+ """Refuse reparenting, then validate the endpoint configuration."""
+ if self.instance and workflow != self.instance.workflow:
+ raise ValidationError("A deployment cannot be moved to another workflow.")
# Get all endpoints for this workflow with related data
endpoints = WorkflowEndpoint.objects.filter(workflow=workflow).select_related(
"connector_instance"
@@ -171,6 +208,18 @@ class APIDeploymentSerializer(IntegrityErrorMixin, AuditSerializer):
class APIKeySerializer(AuditSerializer):
+ def validate_api(self, value):
+ """Refuse reparenting: the gate authorises against the stored parent."""
+ if self.instance and value != self.instance.api:
+ raise ValidationError("A key cannot be moved to another deployment.")
+ return value
+
+ def validate_pipeline(self, value):
+ """Refuse reparenting: the gate authorises against the stored parent."""
+ if self.instance and value != self.instance.pipeline:
+ raise ValidationError("A key cannot be moved to another pipeline.")
+ return value
+
class Meta:
model = APIKey
fields = "__all__"
diff --git a/backend/api_v2/tests/test_deployment_provision.py b/backend/api_v2/tests/test_deployment_provision.py
index 5f5963019..50859aafb 100644
--- a/backend/api_v2/tests/test_deployment_provision.py
+++ b/backend/api_v2/tests/test_deployment_provision.py
@@ -14,6 +14,7 @@ import secrets
import pytest
from account_v2.models import Organization, User
from django.test import TestCase
+from permissions.roles import ResourceRole
from rest_framework import status
from rest_framework.test import APIRequestFactory, force_authenticate
from tenant_account_v2.models import OrganizationMember
@@ -42,7 +43,12 @@ class APIDeploymentProvisionTest(TestCase):
OrganizationMember.objects.create(
organization=self.org, user=self.user, role="user"
)
- self.workflow = Workflow.objects.create(workflow_name="wf-deploy", is_active=True)
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-deploy", is_active=True, created_by=self.user
+ )
+ # The real create path grants this row, and deploying is owner-only:
+ # ``created_by`` is audit-only, so ownership comes from the membership.
+ self.workflow.memberships.create(user=self.user, role=ResourceRole.OWNER)
for endpoint_type in WorkflowEndpoint.EndpointType:
WorkflowEndpoint.objects.create(
workflow=self.workflow,
diff --git a/backend/permissions/permission.py b/backend/permissions/permission.py
index 18db6827a..dc6b6c4d7 100644
--- a/backend/permissions/permission.py
+++ b/backend/permissions/permission.py
@@ -3,6 +3,7 @@ from typing import Any
from adapter_processor_v2.models import AdapterInstance
from rest_framework import permissions
+from rest_framework.exceptions import PermissionDenied
from rest_framework.request import Request
from rest_framework.views import APIView
from tenant_account_v2.organization_member_service import OrganizationMemberService
@@ -79,9 +80,9 @@ def _is_resource_owner(user: Any, obj: Any) -> bool:
memberships = getattr(obj, "memberships", None)
if memberships is None:
return obj.created_by == user
- from permissions.roles import ResourceRole
-
- return memberships.filter(user=user, role=ResourceRole.OWNER).exists()
+ # ``is_owner`` walks ``memberships.all()``, so a caller that prefetched
+ # them pays nothing per row. Same rule as filtering for an OWNER row.
+ return obj.is_owner(user)
def _is_resource_viewer(user: Any, obj: Any) -> bool:
@@ -135,6 +136,44 @@ def is_workflow_mutator(request: Request, workflow: Any) -> bool:
return _is_organization_admin(request)
+def is_activation_only_patch(
+ request: Request, *, flag: str, ignore: tuple[str, ...] = ()
+) -> bool:
+ """Whether this PATCH changes nothing but the enable/disable flag.
+
+ Sharing grants run and watch, and starting or stopping a shared pipeline
+ or deployment is part of that. Editing its settings is not -- so the
+ relaxation holds only when no other field rides along.
+ """
+ if request.method != "PATCH":
+ return False
+ keys = set(request.data)
+ return flag in keys and not (keys - {flag} - set(ignore))
+
+
+def mutable_workflows_for(request: Request) -> Any:
+ """Workflows ``request.user`` may mutate or build on.
+
+ Queryset counterpart of :func:`is_workflow_mutator`, for scoping writable
+ ``workflow`` fields. A shared workflow grants read and run, so it is not
+ here: deploying one is an owner act, not a use of it.
+ """
+ from tenant_account_v2.sharing_helpers import resources_visible_via_memberships
+ from workflow_manager.workflow_v2.models.workflow import Workflow
+
+ from permissions.roles import ResourceRole
+
+ # ``Workflow.objects`` is org-scoped by its manager, so this needs no
+ # organization filter of its own. The subquery casts the membership
+ # table's varchar ``object_id``; a direct join does not compare.
+ if _is_service_account(request) or _is_organization_admin(request):
+ return Workflow.objects.all()
+ owned = resources_visible_via_memberships(
+ Workflow, request.user, role=ResourceRole.OWNER
+ )
+ return Workflow.objects.filter(pk__in=owned)
+
+
class IsParentWorkflowOwner(permissions.BasePermission):
"""Mutation gate for nested workflow sub-resources.
@@ -148,24 +187,34 @@ class IsParentWorkflowOwner(permissions.BasePermission):
return is_workflow_mutator(request, obj.workflow)
-class IsParentToolOwner(permissions.BasePermission):
- """Mutation gate for Prompt Studio sub-resources owned via the parent tool.
+class WorkflowOwnerMutationMixin:
+ """Viewset mixin gating mutation of a workflow sub-resource.
+
+ Shared access to the parent workflow -- direct, via group, or org-wide --
+ grants read only. Admits owners, co-owners, org admins and service
+ accounts, via :func:`is_workflow_mutator`. Requires the resource to carry
+ a ``workflow`` FK.
- A ``ProfileManager`` is not a membership resource, so its access is
- inherited from the parent ``CustomTool``. Admits the tool's owner (creator +
- co-owners), org admin, or service account -- mirrors ``IsParentWorkflowOwner``
- (UN-2202). Falls back to the object's own owner when it has no parent tool
- (``prompt_studio_tool`` is nullable) to preserve legacy behaviour for
- orphan rows.
+ ``create`` is handled separately from the rest: it is collection-level, so
+ DRF never calls ``get_object()`` and ``IsParentWorkflowOwner`` cannot run.
"""
- def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
- if _is_service_account(request):
- return True
- owner_resource = obj.prompt_studio_tool or obj
- if _is_resource_owner(request.user, owner_resource):
- return True
- return _is_organization_admin(request)
+ mutation_denied_message = (
+ "Only the workflow owner or an organization admin can change this."
+ )
+
+ def get_permissions(self) -> list[Any]:
+ if self.action in ("update", "partial_update", "destroy"):
+ return [IsParentWorkflowOwner()]
+ return list(super().get_permissions())
+
+ def perform_create(self, serializer: Any) -> None:
+ # Fails closed: this mixin only guards resources that carry a parent
+ # workflow, so a payload without one cannot be authorised at all.
+ workflow = serializer.validated_data.get("workflow")
+ if not workflow or not is_workflow_mutator(self.request, workflow):
+ raise PermissionDenied(self.mutation_denied_message)
+ serializer.save()
class IsParentDeploymentOwner(permissions.BasePermission):
@@ -174,7 +223,7 @@ class IsParentDeploymentOwner(permissions.BasePermission):
An ``APIKey`` is not a membership resource, so its access is inherited
from the parent ``APIDeployment`` or ``Pipeline`` (both nullable — exactly
one is set). Admits the parent's owner (creator + co-owners), org admin,
- or service account -- mirrors ``IsParentToolOwner`` (UN-2202). Falls back
+ or service account -- mirrors ``IsParentWorkflowOwner`` (UN-2202). Falls back
to the key's own ``created_by`` when both parents are null.
``obj`` may also be the parent itself. ``create`` is a collection-level
diff --git a/backend/permissions/resource_share_views.py b/backend/permissions/resource_share_views.py
index 122756253..a38ff400f 100644
--- a/backend/permissions/resource_share_views.py
+++ b/backend/permissions/resource_share_views.py
@@ -84,9 +84,8 @@ class ResourceShareManagementMixin:
def share(self, request: Request, pk: str | None = None) -> Response:
"""Apply a replace-style share state for the resource.
- HTTP entry gate is the host viewset's ``get_permissions`` (currently
- ``IsOwnerOrSharedUserOrSharedToOrg`` on all 7 resources — see
- UN-2977 plan §B). Per-axis authorization (owner / org admin /
+ HTTP entry gate is the host viewset's ``get_permissions``, which
+ differs per host. Per-axis authorization (owner / org admin /
shared user / group member) and scope checks (org-membership for
users, group-membership for groups) live in
``ShareAuthorizationService``.
diff --git a/backend/permissions/tests/test_owner_management.py b/backend/permissions/tests/test_owner_management.py
index 85a36ad8f..1b1b124a9 100644
--- a/backend/permissions/tests/test_owner_management.py
+++ b/backend/permissions/tests/test_owner_management.py
@@ -18,6 +18,8 @@ from account_v2.models import User
from django.test import TestCase
from permissions.roles import ResourceRole
from rest_framework import status
+from rest_framework.parsers import JSONParser
+from rest_framework.request import Request as DRFRequest
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory, force_authenticate
from rest_framework.views import APIView
@@ -25,7 +27,7 @@ from workflow_manager.workflow_v2.models.workflow import Workflow
from workflow_manager.workflow_v2.views import WorkflowViewSet
from permissions.membership_serializers import AddOwnerSerializer
-from permissions.permission import IsParentToolOwner
+from prompt_studio.permission import ParentToolAccess
from permissions.tests.base import (
RESOURCE_SPECS,
CoOwnerOrgTestMixin,
@@ -323,10 +325,12 @@ class OwnerNotificationWiringTests(CoOwnerOrgTestMixin, TestCase):
self.assertIn(self.coowner.pk, owner_ids)
-class IsParentToolOwnerTests(CoOwnerOrgTestMixin, TestCase):
- """``IsParentToolOwner`` inherits access from the parent ``CustomTool``
- (owner/co-owner/admin/service-account allow; viewer/outsider deny) and falls
- back to the object's own ``created_by`` when there is no parent tool.
+class ParentToolAccessTests(CoOwnerOrgTestMixin, TestCase):
+ """``ParentToolAccess`` inherits access from the parent ``CustomTool``.
+
+ A Prompt Studio project is shared for collaboration, so a viewer manages
+ its profiles alongside its owner; only an outsider is refused. Falls back
+ to the object's own ``created_by`` when there is no parent tool.
"""
def setUp(self) -> None:
@@ -346,7 +350,7 @@ class IsParentToolOwnerTests(CoOwnerOrgTestMixin, TestCase):
def _perm(self, user: User, obj: object) -> bool:
request = APIRequestFactory().get("/")
request.user = user
- return IsParentToolOwner().has_object_permission(request, APIView(), obj)
+ return ParentToolAccess().has_object_permission(request, APIView(), obj)
def test_parent_tool_owners_admin_service_account_allowed(self) -> None:
child = SimpleNamespace(prompt_studio_tool=self.tool)
@@ -356,17 +360,39 @@ class IsParentToolOwnerTests(CoOwnerOrgTestMixin, TestCase):
self.assertTrue(self._perm(self.admin, child))
self.assertTrue(self._perm(svc, child))
- def test_parent_tool_viewer_and_outsider_denied(self) -> None:
+ def test_parent_tool_viewer_allowed_outsider_denied(self) -> None:
+ # The collaboration rule: a shared viewer manages the project's
+ # profiles; someone with no access to the project does not.
child = SimpleNamespace(prompt_studio_tool=self.tool)
- self.assertFalse(self._perm(self.viewer, child))
+ self.assertTrue(self._perm(self.viewer, child))
self.assertFalse(self._perm(self.outsider, child))
- def test_null_parent_falls_back_to_object_owner(self) -> None:
+ def test_null_parent_falls_back_to_object_creator(self) -> None:
# No parent tool → access derives from the object's own ``created_by``.
- orphan = SimpleNamespace(prompt_studio_tool=None, created_by=self.owner)
+ orphan = SimpleNamespace(
+ prompt_studio_tool=None, created_by_id=self.owner.pk
+ )
self.assertTrue(self._perm(self.owner, orphan))
self.assertFalse(self._perm(self.coowner, orphan))
+ def test_create_resolves_the_parent_from_the_payload(self) -> None:
+ # ``create`` is collection-level, so DRF never calls get_object();
+ # the parent is read from the request body instead.
+ def can_create(user: User, tool_id: object) -> bool:
+ # A DRF Request, not the raw WSGI one: the gate reads ``.data``.
+ raw = APIRequestFactory().post(
+ "/", {"prompt_studio_tool": str(tool_id)}, format="json"
+ )
+ request = DRFRequest(raw, parsers=[JSONParser()])
+ request.user = user
+ return ParentToolAccess().has_permission(
+ request, SimpleNamespace(action="create")
+ )
+
+ self.assertTrue(can_create(self.owner, self.tool.tool_id))
+ self.assertTrue(can_create(self.viewer, self.tool.tool_id))
+ self.assertFalse(can_create(self.outsider, self.tool.tool_id))
+
class AdapterShareOwnerExemptionTests(CoOwnerOrgTestMixin, TestCase):
"""A co-owner keeps their default-adapter link when a share-axis change
@@ -510,9 +536,13 @@ class CreateEndpointGrantsCreatorOwnershipTests(CoOwnerOrgTestMixin, TestCase):
self.assertIn(created, model.objects.for_user(self.coowner))
def _build_workflow_fixture(self) -> Workflow:
- return Workflow.objects.create(
+ workflow = Workflow.objects.create(
workflow_name="wf-parent", organization=self.org, created_by=self.coowner
)
+ # The real create path grants this row, and ``created_by`` is
+ # audit-only -- without it the creator does not own the parent.
+ workflow.memberships.create(user=self.coowner, role=ResourceRole.OWNER)
+ return workflow
@pytest.mark.critical_path("co-owner-manage")
def test_workflow_create_grants_creator_ownership(self) -> None:
diff --git a/backend/permissions/tests/test_shared_user_gates.py b/backend/permissions/tests/test_shared_user_gates.py
new file mode 100644
index 000000000..bac545e04
--- /dev/null
+++ b/backend/permissions/tests/test_shared_user_gates.py
@@ -0,0 +1,758 @@
+"""What a shared user may and may not do on someone else's resource (UN-2868).
+
+Sharing is not one rule. A Prompt Studio project is shared *for
+collaboration* -- prompts, settings and LLM profiles stay editable. Every
+other resource is shared *for use*. On all of them, renaming, deleting and
+changing who else has access stay with the owner.
+
+These exercise the real viewsets through DRF's request factory, so a gate
+that exists only in a permission class -- and never reaches the route -- is
+still caught.
+"""
+
+from typing import Any
+
+from account_v2.models import User
+from connector_v2.models import ConnectorInstance
+from django.test import TestCase
+from permissions.roles import ResourceRole
+from permissions.tests.base import CoOwnerOrgTestMixin
+from rest_framework import status
+from rest_framework.response import Response
+from rest_framework.test import APIRequestFactory, force_authenticate
+from django.contrib.contenttypes.models import ContentType
+from tenant_account_v2.models import (
+ GroupMembership,
+ OrganizationGroup,
+ ResourceGroupShare,
+)
+from tool_instance_v2.views import ToolInstanceViewSet
+from workflow_manager.workflow_v2.enums import ExecutionStatus
+from workflow_manager.workflow_v2.file_history_views import FileHistoryViewSet
+from workflow_manager.workflow_v2.models.file_history import FileHistory
+from workflow_manager.workflow_v2.views import WorkflowViewSet
+from workflow_manager.endpoint_v2.models import WorkflowEndpoint
+from workflow_manager.endpoint_v2.views import WorkflowEndpointViewSet
+from workflow_manager.workflow_v2.models.workflow import Workflow
+
+
+class SharedWorkflowEndpointTests(CoOwnerOrgTestMixin, TestCase):
+ """A workflow is shared for use: its connector config is owner-only."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-endpoint", organization=self.org, created_by=self.owner
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.workflow.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.connector = ConnectorInstance.objects.create(
+ connector_name="dest-conn",
+ connector_id="minio|c799f6e3-2b57-434e-aaac-b5daa415da19",
+ connector_metadata={"key": "AKIA-SECRET", "secret": "s3cr3t"},
+ organization=self.org,
+ created_by=self.owner,
+ )
+ self.endpoint = WorkflowEndpoint.objects.create(
+ workflow=self.workflow,
+ endpoint_type=WorkflowEndpoint.EndpointType.DESTINATION,
+ connection_type=WorkflowEndpoint.ConnectionType.FILESYSTEM,
+ connector_instance=self.connector,
+ )
+ self.factory = APIRequestFactory()
+
+ def _patch(self, actor: User) -> Response:
+ view = WorkflowEndpointViewSet.as_view({"patch": "partial_update"})
+ request = self.factory.patch(
+ "/x/", {"configuration": {"path": "/changed"}}, format="json"
+ )
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.endpoint.pk))
+
+ def _delete(self, actor: User) -> Response:
+ view = WorkflowEndpointViewSet.as_view({"delete": "destroy"})
+ request = self.factory.delete("/x/")
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.endpoint.pk))
+
+ def _read(self, actor: User) -> Response:
+ view = WorkflowEndpointViewSet.as_view({"get": "retrieve"})
+ request = self.factory.get("/x/")
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.endpoint.pk))
+
+ def test_shared_viewer_cannot_change_connector_config(self) -> None:
+ self.assertEqual(self._patch(self.viewer).status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_shared_viewer_cannot_delete_the_endpoint(self) -> None:
+ self.assertEqual(
+ self._delete(self.viewer).status_code, status.HTTP_403_FORBIDDEN
+ )
+ self.assertTrue(WorkflowEndpoint.objects.filter(pk=self.endpoint.pk).exists())
+
+ def test_shared_viewer_can_still_read_it(self) -> None:
+ # Refusing the write must not also hide the resource.
+ self.assertEqual(self._read(self.viewer).status_code, status.HTTP_200_OK)
+
+ def test_shared_viewer_does_not_receive_the_connector_credentials(self) -> None:
+ # Sharing grants read; the connector's secrets are not part of it.
+ rep = self._read(self.viewer).data
+ self.assertEqual(rep["connector_instance"]["connector_metadata"], {})
+
+ def test_redacting_credentials_does_not_query_per_endpoint(self) -> None:
+ """The redaction must ride the queryset's prefetch, not re-ask per row.
+
+ Measured: 44 queries for 7 endpoints both with and without
+ ``to_representation``, so the redaction itself costs nothing. Losing
+ the ``workflow__memberships`` prefetch, or making the owner check
+ query again, shows up as roughly one more query per endpoint.
+ """
+ from django.db import connection
+ from django.test.utils import CaptureQueriesContext
+
+ for n in range(6):
+ wf = Workflow.objects.create(
+ workflow_name=f"wf-bulk-{n}",
+ organization=self.org,
+ created_by=self.owner,
+ )
+ wf.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ WorkflowEndpoint.objects.create(
+ workflow=wf,
+ endpoint_type=WorkflowEndpoint.EndpointType.DESTINATION,
+ connection_type=WorkflowEndpoint.ConnectionType.FILESYSTEM,
+ connector_instance=self.connector,
+ )
+
+ view = WorkflowEndpointViewSet.as_view({"get": "list"})
+ request = self.factory.get("/x/")
+ force_authenticate(request, user=self.owner)
+ with CaptureQueriesContext(connection) as ctx:
+ response = view(request)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(len(response.data), 7)
+ for row in response.data:
+ self.assertEqual(
+ row["connector_instance"]["connector_metadata"],
+ {"key": "AKIA-SECRET", "secret": "s3cr3t"},
+ )
+ self.assertLess(len(ctx.captured_queries), 48)
+
+ def test_owner_still_receives_the_connector_credentials(self) -> None:
+ rep = self._read(self.owner).data
+ self.assertEqual(
+ rep["connector_instance"]["connector_metadata"],
+ {"key": "AKIA-SECRET", "secret": "s3cr3t"},
+ )
+
+ def test_owner_and_co_owner_can_change_it(self) -> None:
+ self.workflow.memberships.create(user=self.coowner, role=ResourceRole.OWNER)
+ for actor in (self.owner, self.coowner):
+ self.assertEqual(self._patch(actor).status_code, status.HTTP_200_OK)
+
+ def _endpoint_list(self, actor: User) -> Response:
+ view = WorkflowEndpointViewSet.as_view({"get": "workflow_endpoint_list"})
+ request = self.factory.get("/x/")
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.workflow.pk))
+
+ def test_endpoint_list_refuses_a_user_with_no_access(self) -> None:
+ # Pins the list scoping: unscoped, this returned another user's
+ # endpoints with their connector configuration.
+ self.assertEqual(
+ self._endpoint_list(self.outsider).status_code, status.HTTP_404_NOT_FOUND
+ )
+
+ def test_endpoint_list_redacts_credentials_for_a_shared_viewer(self) -> None:
+ response = self._endpoint_list(self.viewer)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ for row in response.data:
+ self.assertEqual(row["connector_instance"]["connector_metadata"], {})
+
+ def test_a_user_with_no_access_gets_404_not_403(self) -> None:
+ # 403 would confirm the endpoint exists to someone who cannot see it.
+ self.assertEqual(
+ self._patch(self.outsider).status_code, status.HTTP_404_NOT_FOUND
+ )
+
+
+class SharedWorkflowToolInstanceTests(CoOwnerOrgTestMixin, TestCase):
+ """Attaching a tool mutates the workflow -- and activates it."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-tools",
+ organization=self.org,
+ created_by=self.owner,
+ is_active=False,
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.workflow.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def _create(self, actor: User) -> Response:
+ view = ToolInstanceViewSet.as_view({"post": "create"})
+ request = self.factory.post(
+ "/x/",
+ {"workflow_id": str(self.workflow.pk), "tool_id": "tool-uid"},
+ format="json",
+ )
+ force_authenticate(request, user=actor)
+ return view(request)
+
+ def test_shared_viewer_cannot_add_a_tool(self) -> None:
+ response = self._create(self.viewer)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_a_user_with_no_access_gets_404(self) -> None:
+ self.assertEqual(
+ self._create(self.outsider).status_code, status.HTTP_404_NOT_FOUND
+ )
+
+ def test_a_tool_cannot_be_moved_to_another_workflow(self) -> None:
+ """Pins both reparent guards, including the ``workflow_id`` alias.
+
+ The gate authorises against the stored parent, so a writable parent
+ FK would let an owner of workflow B pull a tool off workflow A.
+ """
+ from tool_instance_v2.models import ToolInstance
+
+ other = Workflow.objects.create(
+ workflow_name="wf-other", organization=self.org, created_by=self.owner
+ )
+ other.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ tool = ToolInstance.objects.create(
+ workflow=self.workflow,
+ tool_id="tool-uid",
+ step=1,
+ version="",
+ metadata={},
+ created_by=self.owner,
+ )
+ view = ToolInstanceViewSet.as_view({"patch": "partial_update"})
+ for payload in ({"workflow": str(other.pk)}, {"workflow_id": str(other.pk)}):
+ request = self.factory.patch("/x/", payload, format="json")
+ force_authenticate(request, user=self.owner)
+ response = view(request, pk=str(tool.pk))
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ tool.refresh_from_db()
+ self.assertEqual(tool.workflow_id, self.workflow.pk)
+
+
+class SharedPromptStudioProjectTests(CoOwnerOrgTestMixin, TestCase):
+ """Prompt Studio is shared for collaboration; only the name is owner-only."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ from prompt_studio.prompt_studio_core_v2.models import CustomTool
+
+ self.tool = CustomTool.objects.create(
+ tool_name="ps-project",
+ description="collaboration test",
+ organization=self.org,
+ created_by=self.owner,
+ )
+ self.tool.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.tool.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def _patch(self, actor: User, payload: dict[str, Any]) -> Response:
+ from prompt_studio.prompt_studio_core_v2.views import PromptStudioCoreView
+
+ view = PromptStudioCoreView.as_view({"patch": "partial_update"})
+ request = self.factory.patch("/x/", payload, format="json")
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.tool.pk))
+
+ def test_shared_user_cannot_rename_the_project(self) -> None:
+ response = self._patch(self.viewer, {"tool_name": "renamed-by-viewer"})
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.tool.refresh_from_db()
+ self.assertEqual(self.tool.tool_name, "ps-project")
+
+ def test_shared_user_can_change_a_settings_field(self) -> None:
+ # Same endpoint as the rename, so the gate has to be per-field.
+ response = self._patch(self.viewer, {"preamble": "set by a collaborator"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.tool.refresh_from_db()
+ self.assertEqual(self.tool.preamble, "set by a collaborator")
+
+ def test_owner_can_rename(self) -> None:
+ response = self._patch(self.owner, {"tool_name": "renamed-by-owner"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.tool.refresh_from_db()
+ self.assertEqual(self.tool.tool_name, "renamed-by-owner")
+
+ def test_resending_the_same_name_is_not_a_rename(self) -> None:
+ # A settings PATCH that echoes the current name must not be refused.
+ response = self._patch(
+ self.viewer, {"tool_name": "ps-project", "postamble": "echoed"}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+
+class PromptStudioChildCreateTests(CoOwnerOrgTestMixin, TestCase):
+ """Adding a prompt or an LLM profile is gated by access to the project."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ from prompt_studio.prompt_studio_core_v2.models import CustomTool
+
+ self.tool = CustomTool.objects.create(
+ tool_name="ps-child-create",
+ description="create gate test",
+ organization=self.org,
+ created_by=self.owner,
+ )
+ self.tool.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.tool.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def _create_prompt(self, actor: User, **extra: Any) -> Response:
+ from prompt_studio.prompt_studio_core_v2.views import PromptStudioCoreView
+
+ view = PromptStudioCoreView.as_view({"post": "create_prompt"})
+ payload: dict[str, Any] = {
+ "prompt_key": "p1",
+ "prompt": "extract something",
+ "tool_id": str(self.tool.pk),
+ }
+ payload.update(extra)
+ request = self.factory.post("/x/", payload, format="json")
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.tool.pk))
+
+ def test_an_outsider_cannot_add_a_prompt(self) -> None:
+ from prompt_studio.prompt_studio_v2.models import ToolStudioPrompt
+
+ self.assertEqual(
+ self._create_prompt(self.outsider).status_code, status.HTTP_404_NOT_FOUND
+ )
+ self.assertFalse(ToolStudioPrompt.objects.filter(tool_id=self.tool).exists())
+
+ def test_the_payload_cannot_redirect_the_prompt_to_another_project(self) -> None:
+ # The URL is authoritative: a body naming someone else's project must
+ # not decide where the row lands.
+ from prompt_studio.prompt_studio_core_v2.models import CustomTool
+ from prompt_studio.prompt_studio_v2.models import ToolStudioPrompt
+
+ other = CustomTool.objects.create(
+ tool_name="not-mine",
+ description="owned by the outsider",
+ organization=self.org,
+ created_by=self.outsider,
+ )
+ other.memberships.create(user=self.outsider, role=ResourceRole.OWNER)
+
+ response = self._create_prompt(self.owner, tool_id=str(other.pk))
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertFalse(ToolStudioPrompt.objects.filter(tool_id=other).exists())
+ self.assertTrue(ToolStudioPrompt.objects.filter(tool_id=self.tool).exists())
+
+ def test_a_collaborator_can_add_a_prompt(self) -> None:
+ # Prompt Studio is shared for collaboration: prompts stay editable.
+ self.assertEqual(
+ self._create_prompt(self.viewer).status_code, status.HTTP_201_CREATED
+ )
+
+ def test_a_malformed_parent_id_is_refused_not_a_server_error(self) -> None:
+ # The gate filters a UUID column on raw request data, ahead of any
+ # serializer: an unparseable id must miss the lookup, not raise.
+ from prompt_studio.prompt_profile_manager_v2.views import ProfileManagerView
+
+ view = ProfileManagerView.as_view({"post": "create"})
+ request = self.factory.post(
+ "/x/", {"profile_name": "p", "prompt_studio_tool": "not-a-uuid"}, format="json"
+ )
+ force_authenticate(request, user=self.owner)
+ self.assertEqual(view(request).status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_a_malformed_prompt_id_on_reorder_is_not_a_server_error(self) -> None:
+ from prompt_studio.prompt_studio_v2.views import ToolStudioPromptView
+
+ view = ToolStudioPromptView.as_view({"post": "reorder_prompts"})
+ # Complete payload on purpose: omitting a required field 400s before
+ # the id is ever parsed, which is not what this pins.
+ request = self.factory.post(
+ "/x/",
+ {
+ "prompt_id": "not-a-uuid",
+ "start_sequence_number": 1,
+ "end_sequence_number": 2,
+ },
+ format="json",
+ )
+ force_authenticate(request, user=self.owner)
+ self.assertEqual(view(request).status_code, status.HTTP_400_BAD_REQUEST)
+
+
+class GroupSharedWorkflowFileHistoryTests(CoOwnerOrgTestMixin, TestCase):
+ """Reaching a workflow through a group grants its sub-pages too.
+
+ ``Workflow.objects.for_user`` has always included group shares, so a
+ group-shared workflow is visible in the list. Its file history was gated
+ on a check that stopped at direct viewers, so opening the workflow worked
+ and the File History tab returned 403.
+ """
+
+ def setUp(self) -> None:
+ self._seed_org()
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-group", organization=self.org, created_by=self.owner
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+
+ group = OrganizationGroup.objects.create(
+ name="team-fh", organization=self.org, created_by=self.owner
+ )
+ GroupMembership.objects.create(group=group, user=self.viewer)
+ ResourceGroupShare.objects.create(
+ group=group,
+ content_type=ContentType.objects.get_for_model(Workflow),
+ object_id=str(self.workflow.pk),
+ organization=self.org,
+ )
+ self.factory = APIRequestFactory()
+
+ def _list(self, actor: User) -> Response:
+ view = FileHistoryViewSet.as_view({"get": "list"})
+ request = self.factory.get("/x/")
+ force_authenticate(request, user=actor)
+ return view(request, workflow_id=str(self.workflow.pk))
+
+ def test_group_member_can_view_file_history(self) -> None:
+ self.assertEqual(self._list(self.viewer).status_code, status.HTTP_200_OK)
+
+ def test_owner_can_view_file_history(self) -> None:
+ self.assertEqual(self._list(self.owner).status_code, status.HTTP_200_OK)
+
+ def test_a_user_with_no_access_still_cannot(self) -> None:
+ # Widening to groups must not widen to everyone in the org.
+ self.assertEqual(
+ self._list(self.outsider).status_code, status.HTTP_403_FORBIDDEN
+ )
+
+
+class FileHistoryWriteGateTests(CoOwnerOrgTestMixin, TestCase):
+ """Deleting a workflow's execution history is the owner's."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-fh-write", organization=self.org, created_by=self.owner
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.workflow.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.history = FileHistory.objects.create(
+ workflow=self.workflow,
+ cache_key=f"ck-{self.workflow.pk}",
+ provider_file_uuid="pf-1",
+ status=ExecutionStatus.COMPLETED.value,
+ )
+ self.factory = APIRequestFactory()
+
+ def test_shared_viewer_cannot_delete_one_row(self) -> None:
+ view = FileHistoryViewSet.as_view({"delete": "destroy"})
+ request = self.factory.delete("/x/")
+ force_authenticate(request, user=self.viewer)
+ response = view(
+ request, workflow_id=str(self.workflow.pk), id=str(self.history.pk)
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertTrue(FileHistory.objects.filter(pk=self.history.pk).exists())
+
+ def test_shared_viewer_cannot_clear_the_history(self) -> None:
+ view = FileHistoryViewSet.as_view({"post": "clear"})
+ request = self.factory.post("/x/", {"ids": [str(self.history.pk)]}, format="json")
+ force_authenticate(request, user=self.viewer)
+ response = view(request, workflow_id=str(self.workflow.pk))
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertTrue(FileHistory.objects.filter(pk=self.history.pk).exists())
+
+ def test_owner_can_clear_the_history(self) -> None:
+ view = FileHistoryViewSet.as_view({"post": "clear"})
+ request = self.factory.post("/x/", {"ids": [str(self.history.pk)]}, format="json")
+ force_authenticate(request, user=self.owner)
+ response = view(request, workflow_id=str(self.workflow.pk))
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+
+class ClearFileMarkerMethodTests(CoOwnerOrgTestMixin, TestCase):
+ """Clearing execution markers is a POST, and an owner action."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-marker", organization=self.org, created_by=self.owner
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.workflow.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def test_the_action_accepts_post_only(self) -> None:
+ """Pins the GET->POST move: a GET is reachable by prefetch or a
+ pasted URL, with no CSRF in the way.
+
+ Asserts the action's own mapping. Driving ``as_view({"post": ...})``
+ and sending a GET proves nothing -- the 405 comes from that map, so
+ it passes with the decorator back on ``methods=["get"]``.
+ """
+ mapping = WorkflowViewSet.clear_file_marker.mapping
+ self.assertEqual(set(mapping), {"post"})
+ self.assertEqual(mapping["post"], "clear_file_marker")
+
+ def test_the_route_binds_post_only(self) -> None:
+ """The URLconf and the decorator have to agree, or one silently wins."""
+ from workflow_manager.workflow_v2.urls.workflow import urlpatterns
+
+ matched = [
+ p for p in urlpatterns if "clear-file-marker" in str(p.pattern)
+ ]
+ # More than one: DRF adds a format-suffix twin. Every one must agree.
+ self.assertTrue(matched)
+ for pattern in matched:
+ self.assertEqual(set(pattern.callback.actions), {"post"})
+
+ def test_shared_viewer_cannot_post_it(self) -> None:
+ view = WorkflowViewSet.as_view({"post": "clear_file_marker"})
+ request = self.factory.post("/x/")
+ force_authenticate(request, user=self.viewer)
+ response = view(request, pk=str(self.workflow.pk))
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+
+class DeployAnothersWorkflowTests(CoOwnerOrgTestMixin, TestCase):
+ """Deploying a workflow is an owner act, not a use of a shared one.
+
+ ``workflow`` is writable on both the deployment and pipeline serializers
+ and was bound through a merely org-scoped manager, so any member could
+ point a new deployment at a colleague's private workflow -- then execute
+ it, with its connectors and adapters, at the owner's cost, and mint API
+ keys against it.
+ """
+
+ def setUp(self) -> None:
+ self._seed_org()
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-private", organization=self.org, created_by=self.owner
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.workflow.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def _deploy(self, actor: User) -> Response:
+ from api_v2.api_deployment_views import DeploymentExecution # noqa: F401
+ from api_v2.api_deployment_views import APIDeploymentViewSet
+
+ view = APIDeploymentViewSet.as_view({"post": "create"})
+ request = self.factory.post(
+ "/x/",
+ {
+ "workflow": str(self.workflow.pk),
+ "display_name": "stolen",
+ "api_name": "stolen",
+ },
+ format="json",
+ )
+ force_authenticate(request, user=actor)
+ return view(request)
+
+ def _schedule(self, actor: User) -> Response:
+ from pipeline_v2.views import PipelineViewSet
+
+ view = PipelineViewSet.as_view({"post": "create"})
+ request = self.factory.post(
+ "/x/",
+ {
+ "workflow": str(self.workflow.pk),
+ "pipeline_name": "stolen",
+ "pipeline_type": "ETL",
+ "cron_string": "0 0 * * *",
+ },
+ format="json",
+ )
+ force_authenticate(request, user=actor)
+ return view(request)
+
+ def _assert_workflow_refused(self, response: Response) -> None:
+ """Refused because the workflow is not in the field's queryset.
+
+ The code matters: this serializer also rejects a workflow whose
+ endpoints are unconfigured, on the same ``workflow`` attr. Only the
+ scoping produces ``does_not_exist``, so asserting the attr alone
+ passes with the gate removed.
+ """
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ codes = {
+ e.get("code")
+ for e in response.data.get("errors", [])
+ if e.get("attr") == "workflow"
+ }
+ self.assertIn("does_not_exist", codes)
+
+ def test_an_outsider_cannot_deploy_it(self) -> None:
+ self._assert_workflow_refused(self._deploy(self.outsider))
+
+ def test_a_shared_viewer_cannot_deploy_it(self) -> None:
+ # Shared for use: running it is fine, standing up a permanent
+ # execution surface on it is the owner's.
+ self._assert_workflow_refused(self._deploy(self.viewer))
+
+ def test_an_outsider_cannot_schedule_it(self) -> None:
+ self._assert_workflow_refused(self._schedule(self.outsider))
+
+ def test_a_shared_viewer_cannot_schedule_it(self) -> None:
+ self._assert_workflow_refused(self._schedule(self.viewer))
+
+ def test_the_owner_is_not_blocked(self) -> None:
+ # The scoping must not lock the owner out of their own workflow.
+ response = self._schedule(self.owner)
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ def test_a_pipeline_co_owner_can_still_save_it(self) -> None:
+ """Co-owning the pipeline is not co-owning its workflow.
+
+ The edit modal PUTs the whole form back, ``workflow`` included, so a
+ queryset holding only workflows the requester owns refuses a write
+ that changes nothing about the parent.
+ """
+ from pipeline_v2.models import Pipeline
+ from pipeline_v2.views import PipelineViewSet
+
+ pipeline = Pipeline.objects.create(
+ pipeline_name="shared-etl",
+ pipeline_type="ETL",
+ workflow=self.workflow,
+ organization=self.org,
+ created_by=self.owner,
+ cron_string="0 0 * * *",
+ )
+ pipeline.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ pipeline.memberships.create(user=self.coowner, role=ResourceRole.OWNER)
+
+ view = PipelineViewSet.as_view({"put": "update"})
+ request = self.factory.put(
+ "/x/",
+ {
+ "workflow": str(self.workflow.pk),
+ "pipeline_name": "shared-etl-renamed",
+ "pipeline_type": "ETL",
+ "cron_string": "0 0 * * *",
+ },
+ format="json",
+ )
+ force_authenticate(request, user=self.coowner)
+ response = view(request, pk=str(pipeline.pk))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ pipeline.refresh_from_db()
+ self.assertEqual(pipeline.pipeline_name, "shared-etl-renamed")
+ self.assertEqual(pipeline.workflow_id, self.workflow.pk)
+
+ def test_a_co_owner_still_cannot_repoint_it(self) -> None:
+ """Keeping the bound workflow selectable must not reopen reparenting."""
+ from pipeline_v2.models import Pipeline
+ from pipeline_v2.views import PipelineViewSet
+
+ other = Workflow.objects.create(
+ workflow_name="wf-elsewhere", organization=self.org, created_by=self.owner
+ )
+ other.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ pipeline = Pipeline.objects.create(
+ pipeline_name="shared-etl-2",
+ pipeline_type="ETL",
+ workflow=self.workflow,
+ organization=self.org,
+ created_by=self.owner,
+ cron_string="0 0 * * *",
+ )
+ pipeline.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ pipeline.memberships.create(user=self.coowner, role=ResourceRole.OWNER)
+
+ view = PipelineViewSet.as_view({"put": "update"})
+ request = self.factory.put(
+ "/x/",
+ {
+ "workflow": str(other.pk),
+ "pipeline_name": "shared-etl-2",
+ "pipeline_type": "ETL",
+ "cron_string": "0 0 * * *",
+ },
+ format="json",
+ )
+ force_authenticate(request, user=self.coowner)
+ self.assertEqual(
+ view(request, pk=str(pipeline.pk)).status_code,
+ status.HTTP_400_BAD_REQUEST,
+ )
+ pipeline.refresh_from_db()
+ self.assertEqual(pipeline.workflow_id, self.workflow.pk)
+
+
+class SharedPipelineActivationTests(CoOwnerOrgTestMixin, TestCase):
+ """Starting and stopping a shared pipeline is use, not configuration."""
+
+ def setUp(self) -> None:
+ self._seed_org()
+ from pipeline_v2.models import Pipeline
+
+ self.workflow = Workflow.objects.create(
+ workflow_name="wf-toggle", organization=self.org, created_by=self.owner
+ )
+ self.workflow.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.pipeline = Pipeline.objects.create(
+ pipeline_name="etl-toggle",
+ pipeline_type="ETL",
+ workflow=self.workflow,
+ organization=self.org,
+ created_by=self.owner,
+ cron_string="0 0 * * *",
+ active=False,
+ )
+ self.pipeline.memberships.create(user=self.owner, role=ResourceRole.OWNER)
+ self.pipeline.memberships.create(user=self.viewer, role=ResourceRole.VIEWER)
+ self.factory = APIRequestFactory()
+
+ def _patch(self, actor: User, payload: dict[str, Any]) -> Response:
+ from pipeline_v2.views import PipelineViewSet
+
+ view = PipelineViewSet.as_view({"patch": "partial_update"})
+ request = self.factory.patch("/x/", payload, format="json")
+ force_authenticate(request, user=actor)
+ return view(request, pk=str(self.pipeline.pk))
+
+ def test_a_shared_viewer_can_enable_it(self) -> None:
+ response = self._patch(
+ self.viewer, {"active": True, "pipeline_id": str(self.pipeline.pk)}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.pipeline.refresh_from_db()
+ self.assertTrue(self.pipeline.active)
+
+ def test_a_shared_viewer_cannot_smuggle_another_field_alongside(self) -> None:
+ """The relaxation is activation-only; one extra key and it is gone."""
+ response = self._patch(
+ self.viewer, {"active": True, "pipeline_name": "renamed-by-viewer"}
+ )
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+ self.pipeline.refresh_from_db()
+ self.assertFalse(self.pipeline.active)
+ self.assertEqual(self.pipeline.pipeline_name, "etl-toggle")
+
+ def test_a_shared_viewer_still_cannot_rename_it(self) -> None:
+ response = self._patch(self.viewer, {"pipeline_name": "renamed"})
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_an_outsider_cannot_enable_it(self) -> None:
+ response = self._patch(
+ self.outsider, {"active": True, "pipeline_id": str(self.pipeline.pk)}
+ )
+ self.assertIn(
+ response.status_code,
+ (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND),
+ )
+ self.pipeline.refresh_from_db()
+ self.assertFalse(self.pipeline.active)
diff --git a/backend/pipeline_v2/serializers/crud.py b/backend/pipeline_v2/serializers/crud.py
index acc45a333..590e4bb48 100644
--- a/backend/pipeline_v2/serializers/crud.py
+++ b/backend/pipeline_v2/serializers/crud.py
@@ -6,17 +6,19 @@ from typing import Any
from croniter import croniter
from django.conf import settings
from django.utils import timezone
+from permissions.permission import mutable_workflows_for
from pipeline_v2.constants import PipelineConstants as PC
from pipeline_v2.constants import PipelineKey as PK
from pipeline_v2.constants import PipelineScheduling
from pipeline_v2.models import Pipeline
from rest_framework import serializers
-from rest_framework.serializers import SerializerMethodField
+from rest_framework.serializers import SerializerMethodField, ValidationError
from scheduler.helper import SchedulerHelper
from utils.serializer.integrity_error_mixin import IntegrityErrorMixin
from utils.serializer_utils import SerializerUtils
from workflow_manager.endpoint_v2.models import WorkflowEndpoint
from workflow_manager.workflow_v2.models.execution import WorkflowExecution
+from workflow_manager.workflow_v2.models.workflow import Workflow
from backend.serializers import AuditSerializer
from unstract.connectors.connectorkit import Connectorkit
@@ -48,6 +50,36 @@ class PipelineSerializer(IntegrityErrorMixin, AuditSerializer):
"shared_to_org": {"read_only": True},
}
+ def get_fields(self) -> dict[str, Any]:
+ """Scope ``workflow`` to the requester.
+
+ The default manager is only org-scoped, so an unscoped field lets any
+ member schedule a colleague's workflow -- running it with its
+ connectors and adapters, at the owner's cost.
+ """
+ fields = super().get_fields()
+ request = self.context.get("request")
+ queryset = mutable_workflows_for(request) if request else Workflow.objects.none()
+ # An update resends the bound workflow unchanged, so keep it
+ # selectable: a co-owner of this resource need not own the workflow.
+ # ``validate_workflow`` still refuses an actual change.
+ if self.instance is not None:
+ queryset = queryset | Workflow.objects.filter(pk=self.instance.workflow_id)
+ fields["workflow"].queryset = queryset
+ # Same code, readable text: the default names a pk the user never
+ # typed. Tests discriminate on the code, which is unchanged.
+ fields["workflow"].error_messages["does_not_exist"] = (
+ "You can only schedule a workflow you own. Ask its owner to add "
+ "you as a co-owner."
+ )
+ return fields
+
+ def validate_workflow(self, value):
+ """Refuse reparenting: the gate authorises against the stored parent."""
+ if self.instance and value != self.instance.workflow:
+ raise ValidationError("A pipeline cannot be moved to another workflow.")
+ return value
+
unique_error_message_map: dict[str, dict[str, str]] = {
"unique_pipeline_name": {
"field": "pipeline_name",
diff --git a/backend/pipeline_v2/views.py b/backend/pipeline_v2/views.py
index 2bf502c90..27c800518 100644
--- a/backend/pipeline_v2/views.py
+++ b/backend/pipeline_v2/views.py
@@ -10,7 +10,11 @@ from django.db import IntegrityError, transaction
from django.db.models import F, QuerySet
from django.http import HttpResponse
from permissions.membership_views import OwnerManagementMixin
-from permissions.permission import IsOwner, IsOwnerOrSharedUserOrSharedToOrg
+from permissions.permission import (
+ IsOwner,
+ IsOwnerOrSharedUserOrSharedToOrg,
+ is_activation_only_patch,
+)
from permissions.resource_share_views import ResourceShareManagementMixin
from plugins import get_plugin
from rest_framework import serializers, status, viewsets
@@ -65,6 +69,12 @@ class PipelineViewSet(
return None
def get_permissions(self) -> list[Any]:
+ # Enabling or disabling is use, not configuration, so it follows
+ # sharing. ``pipeline_id`` is echoed by the client and changes nothing.
+ if self.action == "partial_update" and is_activation_only_patch(
+ self.request, flag="active", ignore=("pipeline_id",)
+ ):
+ return [IsOwnerOrSharedUserOrSharedToOrg()]
if self.action in [
"destroy",
"partial_update",
diff --git a/backend/prompt_studio/permission.py b/backend/prompt_studio/permission.py
index 43eb9c75d..cb987c3a5 100644
--- a/backend/prompt_studio/permission.py
+++ b/backend/prompt_studio/permission.py
@@ -1,3 +1,4 @@
+import uuid
from typing import Any
from permissions.permission import (
@@ -11,36 +12,93 @@ from rest_framework.views import APIView
from tenant_account_v2.organization_member_service import OrganizationMemberService
+def parse_uuid(value: Any) -> uuid.UUID | None:
+ """Coerce a raw payload value to a UUID, or ``None`` when it is not one.
+
+ Gates below filter a ``UUIDField`` on unvalidated request data, ahead of
+ any serializer. Django raises on a malformed string there, which surfaces
+ as a 500 rather than a 400, so coerce first and let the lookup miss.
+ """
+ try:
+ return uuid.UUID(str(value))
+ except (ValueError, TypeError, AttributeError):
+ return None
+
+
+def _can_access_tool(user: Any, tool: Any) -> bool:
+ """Whether ``user`` may work on ``tool``.
+
+ Prompt Studio is shared for collaboration: a shared user edits the
+ project's prompts and settings, the same as its owner. Renaming, deleting
+ and removing access stay with the owner; sharing onward does not.
+ """
+ if _is_resource_owner(user, tool):
+ return True
+ if _is_resource_viewer(user, tool):
+ return True
+ if tool.shared_to_org:
+ return True
+ if has_group_access(user, tool):
+ return True
+ # Left last: the admin lookup is uncached, so shared users resolve without it.
+ return OrganizationMemberService.is_user_organization_admin(user)
+
+
class PromptAcesssToUser(permissions.BasePermission):
"""Is the crud to Prompt/Notes allowed to user.
- A user qualifies when they own the parent ``CustomTool``, are a direct
- viewer (VIEWER membership, UN-2202), reach the project via group sharing
- (``ResourceGroupShare`` on the parent tool), or are an org admin
- (org-wide admin override, UN-3479).
+ Qualifying is :func:`_can_access_tool` on the parent ``CustomTool`` --
+ stated there rather than restated here, since an enumeration on the caller
+ has already gone stale once.
"""
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
if getattr(request.user, "is_service_account", False):
return True
- tool = obj.tool_id
- if _is_resource_owner(request.user, tool):
+ return _can_access_tool(request.user, obj.tool_id)
+
+
+class ParentToolAccess(permissions.BasePermission):
+ """Gate for Prompt Studio sub-resources keyed to a project.
+
+ A ``ProfileManager`` carries no membership of its own, so access follows
+ the parent ``CustomTool`` -- anyone the project is shared with manages its
+ profiles as they do its prompts. ``create`` is collection-level, so DRF
+ never calls the object check for it and the parent is resolved from the
+ payload instead.
+ """
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if getattr(view, "action", None) != "create":
return True
- if _is_resource_viewer(request.user, tool):
+ if getattr(request.user, "is_service_account", False):
return True
- if has_group_access(request.user, tool):
+ from prompt_studio.prompt_profile_manager_v2.constants import ProfileManagerKeys
+ from prompt_studio.prompt_studio_core_v2.models import CustomTool
+
+ tool = CustomTool.objects.filter(
+ tool_id=parse_uuid(request.data.get(ProfileManagerKeys.PROMPT_STUDIO_TOOL))
+ ).first()
+ return bool(tool and _can_access_tool(request.user, tool))
+
+ def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
+ if getattr(request.user, "is_service_account", False):
return True
- return OrganizationMemberService.is_user_organization_admin(request.user)
+ tool = obj.prompt_studio_tool
+ if not tool:
+ # Orphan row: the parent FK is nullable, so fall back to its creator.
+ return obj.created_by_id == request.user.id
+ return _can_access_tool(request.user, tool)
class IsRegistryToolOwner(permissions.BasePermission):
"""Is unpublishing an exported tool allowed to user.
A ``PromptStudioRegistry`` row is not itself a membership resource, so
- ownership is inherited from the linked ``CustomTool`` -- mirroring
- ``IsParentToolOwner``, which does the same for ``ProfileManager``. Falls
- back to the row's own owner for unlinked legacy rows (``custom_tool`` is
- nullable).
+ ownership is inherited from the linked ``CustomTool``. Unlike
+ ``ParentToolAccess``, which lets collaborators manage a project's
+ profiles, unpublishing stays with the owner. Falls back to the row's own
+ owner for unlinked legacy rows (``custom_tool`` is nullable).
Read access is deliberately broader (see
``PromptStudioRegistry.objects.list_tools``); deleting is restricted to
diff --git a/backend/prompt_studio/prompt_profile_manager_v2/serializers.py b/backend/prompt_studio/prompt_profile_manager_v2/serializers.py
index 5fa6d3bf9..e26b20fd1 100644
--- a/backend/prompt_studio/prompt_profile_manager_v2/serializers.py
+++ b/backend/prompt_studio/prompt_profile_manager_v2/serializers.py
@@ -28,6 +28,12 @@ class ProfileManagerSerializer(AuditSerializer):
# Dropped so a duplicate create surfaces the view's DuplicateData.
validators = []
+ def validate_prompt_studio_tool(self, value):
+ """Refuse reparenting: the gate authorises against the stored parent."""
+ if self.instance and value != self.instance.prompt_studio_tool:
+ raise ValidationError("A profile cannot be moved to another project.")
+ return value
+
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
"""Reject a change to an adapter the requester cannot access.
diff --git a/backend/prompt_studio/prompt_profile_manager_v2/views.py b/backend/prompt_studio/prompt_profile_manager_v2/views.py
index 907a137e4..8d3b3dd09 100644
--- a/backend/prompt_studio/prompt_profile_manager_v2/views.py
+++ b/backend/prompt_studio/prompt_profile_manager_v2/views.py
@@ -4,15 +4,13 @@ from account_v2.custom_exceptions import DuplicateData
from django.db import IntegrityError
from django.db.models import QuerySet
from django.http import HttpRequest
-from permissions.permission import (
- IsOwnerOrSharedUserOrSharedToOrg,
- IsParentToolOwner,
-)
+from permissions.permission import IsOwnerOrSharedUserOrSharedToOrg
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from utils.filtering import FilterHelper
+from prompt_studio.permission import ParentToolAccess
from prompt_studio.prompt_profile_manager_v2.constants import (
ProfileManagerErrors,
ProfileManagerKeys,
@@ -29,10 +27,10 @@ class ProfileManagerView(viewsets.ModelViewSet):
serializer_class = ProfileManagerSerializer
def get_permissions(self) -> list[Any]:
- # Mutations require ownership of the parent tool (creator + co-owners);
- # reads honor sharing.
+ # A profile is part of the project's design, so anyone the project is
+ # shared with manages it (UN-2868); reads honor sharing.
if self.action in ("create", "destroy", "partial_update", "update"):
- return [IsParentToolOwner()]
+ return [ParentToolAccess()]
return [IsOwnerOrSharedUserOrSharedToOrg()]
def get_queryset(self) -> QuerySet | None:
diff --git a/backend/prompt_studio/prompt_studio_core_v2/serializers.py b/backend/prompt_studio/prompt_studio_core_v2/serializers.py
index 8525b7f08..3ee929106 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/serializers.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/serializers.py
@@ -5,8 +5,9 @@ from account_v2.serializer import UserSerializer
from adapter_processor_v2.models import AdapterInstance
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from tenant_account_v2.sharing_helpers import (
+ is_org_admin,
serialize_group_refs,
serialize_owner_refs,
)
@@ -99,6 +100,9 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):
# groups axis is read-only here (UN-2977 plan §B). Direct viewers live in
# the membership table (UN-2202) and surface via the share-modal serializer.
shared_groups = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
+ # The editor needs to know whether to offer edit controls at all; the list
+ # serializer already carries this.
+ is_owner = serializers.SerializerMethodField()
class Meta:
model = CustomTool
@@ -114,6 +118,10 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):
"output",
)
+ def get_is_owner(self, instance: CustomTool) -> bool:
+ request = self.context.get("request")
+ return instance.is_owner(request.user) if request else False
+
unique_error_message_map: dict[str, dict[str, str]] = {
"unique_tool_name": {
"field": "tool_name",
@@ -124,7 +132,19 @@ class CustomToolSerializer(IntegrityErrorMixin, AuditSerializer):
}
def validate_tool_name(self, value: str) -> str:
- return validate_name_field(value, field_name="Tool name")
+ value = validate_name_field(value, field_name="Tool name")
+ # Settings and the project's name share this endpoint, and settings are
+ # collaborative -- so the rename is gated here rather than on the view
+ # (UN-2868).
+ request = self.context.get("request")
+ if not self.instance or not request or value == self.instance.tool_name:
+ return value
+ user = request.user
+ if getattr(user, "is_service_account", False):
+ return value
+ if not self.instance.is_owner(user) and not is_org_admin(user):
+ raise PermissionDenied("Only the owner can rename this project.")
+ return value
def validate_summarize_llm_adapter(self, value):
"""Validate that the adapter type is LLM and is accessible to the user."""
diff --git a/backend/prompt_studio/prompt_studio_core_v2/views.py b/backend/prompt_studio/prompt_studio_core_v2/views.py
index 86a739efc..2179253ec 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py
@@ -151,6 +151,10 @@ class PromptStudioCoreView(
return CustomToolSerializer
def get_permissions(self) -> list[Any]:
+ # Settings are collaborative (UN-2868); only the project's existence
+ # and who it is shared with stay with the owner. Renaming is blocked
+ # per-field in the serializer, since it shares an endpoint with
+ # every settings write.
if self.action in ["destroy", "add_co_owner", "remove_co_owner"]:
return [IsOwner()]
@@ -929,9 +933,15 @@ class PromptStudioCoreView(
@action(detail=True, methods=["post"])
def create_prompt(self, request: HttpRequest, pk: Any = None) -> Response:
+ # A custom @action, so DRF never calls get_object() on its own even
+ # though the route carries a pk -- the object gate would not run.
+ # Resolve the parent from the URL and pin it, so the payload cannot
+ # name a project the caller cannot reach.
+ prompt_studio_tool = self.get_object()
context = super().get_serializer_context()
serializer = ToolStudioPromptSerializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
+ serializer.validated_data[ToolStudioPromptKeys.TOOL_ID] = prompt_studio_tool
try:
# serializer.save()
self.perform_create(serializer)
@@ -948,18 +958,15 @@ class PromptStudioCoreView(
context = super().get_serializer_context()
serializer = ProfileManagerSerializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
- # Check for the maximum number of profiles constraint
- prompt_studio_tool = serializer.validated_data.get(
- ProfileManagerKeys.PROMPT_STUDIO_TOOL
+ # The URL is authoritative for the parent: resolving it here is what
+ # runs the object gate, and pinning it stops the payload naming another
+ # project. Also keeps perform_create() from persisting NULL and
+ # orphaning the profile from every ``filter(prompt_studio_tool=...)``.
+ prompt_studio_tool = self.get_object()
+ serializer.validated_data[ProfileManagerKeys.PROMPT_STUDIO_TOOL] = (
+ prompt_studio_tool
)
- if not prompt_studio_tool:
- # Write back into validated_data so perform_create() doesn't
- # persist NULL and orphan the profile from every
- # ``filter(prompt_studio_tool=...)`` query.
- prompt_studio_tool = self.get_object()
- serializer.validated_data[ProfileManagerKeys.PROMPT_STUDIO_TOOL] = (
- prompt_studio_tool
- )
+ # Check for the maximum number of profiles constraint
profile_count = ProfileManager.objects.filter(
prompt_studio_tool=prompt_studio_tool
).count()
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/tests/test_registry_tool_delete_guards.py b/backend/prompt_studio/prompt_studio_registry_v2/tests/test_registry_tool_delete_guards.py
index acb772e65..52429f868 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/tests/test_registry_tool_delete_guards.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/tests/test_registry_tool_delete_guards.py
@@ -172,7 +172,7 @@ class TestRegistryToolDeleteAuthorization:
)
def test_ownership_follows_the_parent_project_not_the_row(self) -> None:
- """Ownership is inherited from ``custom_tool``, mirroring IsParentToolOwner.
+ """Ownership is inherited from ``custom_tool``.
The row's own ``owner`` must be ignored while a parent exists, otherwise
a stale export-time owner could outrank the project's current owner.
diff --git a/backend/prompt_studio/prompt_studio_v2/serializers.py b/backend/prompt_studio/prompt_studio_v2/serializers.py
index f0fe082d6..82d11dac8 100644
--- a/backend/prompt_studio/prompt_studio_v2/serializers.py
+++ b/backend/prompt_studio/prompt_studio_v2/serializers.py
@@ -1,4 +1,5 @@
from rest_framework import serializers
+from rest_framework.serializers import ValidationError
from backend.serializers import AuditSerializer
@@ -23,6 +24,12 @@ class ToolStudioPromptListSerializer(serializers.ModelSerializer):
class ToolStudioPromptSerializer(AuditSerializer):
+ def validate_tool_id(self, value):
+ """Refuse reparenting: the gate authorises against the stored parent."""
+ if self.instance and value != self.instance.tool_id:
+ raise ValidationError("A prompt cannot be moved to another project.")
+ return value
+
class Meta:
model = ToolStudioPrompt
fields = "__all__"
@@ -46,7 +53,9 @@ class ToolStudioIndexSerializer(serializers.Serializer):
class ReorderPromptsSerializer(serializers.Serializer):
start_sequence_number = serializers.IntegerField(required=True)
end_sequence_number = serializers.IntegerField(required=True)
- prompt_id = serializers.CharField(required=True)
+ # UUID, not CharField: the controller feeds this straight to objects.get,
+ # where a malformed id is a 500 rather than a 400.
+ prompt_id = serializers.UUIDField(required=True)
def validate(self, data):
start_sequence_number = data.get("start_sequence_number")
diff --git a/backend/prompt_studio/prompt_studio_v2/views.py b/backend/prompt_studio/prompt_studio_v2/views.py
index a54048027..b1dcb7657 100644
--- a/backend/prompt_studio/prompt_studio_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_v2/views.py
@@ -6,7 +6,7 @@ from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from utils.filtering import FilterHelper
-from prompt_studio.permission import PromptAcesssToUser
+from prompt_studio.permission import PromptAcesssToUser, parse_uuid
from prompt_studio.prompt_studio_v2.constants import ToolStudioPromptKeys
from prompt_studio.prompt_studio_v2.controller import PromptStudioController
from prompt_studio.prompt_studio_v2.models import ToolStudioPrompt
@@ -60,5 +60,12 @@ class ToolStudioPromptView(viewsets.ModelViewSet):
Returns:
Response: The HTTP response indicating the status of the reorder operation.
"""
+ # Routed without a pk, so DRF runs no object check of its own; resolve
+ # the prompt so reordering is gated like every other write here.
+ prompt = ToolStudioPrompt.objects.filter(
+ prompt_id=parse_uuid(request.data.get(ToolStudioPromptKeys.PROMPT_ID))
+ ).first()
+ if prompt:
+ self.check_object_permissions(request, prompt)
prompt_studio_controller = PromptStudioController()
return prompt_studio_controller.reorder_prompts(request, ToolStudioPrompt)
diff --git a/backend/tenant_account_v2/shareable_resources.py b/backend/tenant_account_v2/shareable_resources.py
index f528e2959..80e735608 100644
--- a/backend/tenant_account_v2/shareable_resources.py
+++ b/backend/tenant_account_v2/shareable_resources.py
@@ -22,8 +22,8 @@ class ShareableResource:
id_field: str # primary-key field name
-# ``agentic_studio_v1`` is cloud-only; consumers resolve it lazily and skip it
-# when the app is not installed.
+# ``agentic_studio_v1`` and ``lookups`` are cloud-only; consumers resolve them
+# lazily and skip them when the app is not installed.
SHAREABLE_RESOURCES: tuple[ShareableResource, ...] = (
ShareableResource("workflow_v2", "Workflow", "workflow", "workflow_name", "id"),
ShareableResource("pipeline_v2", "Pipeline", "pipeline", "pipeline_name", "id"),
@@ -48,4 +48,5 @@ SHAREABLE_RESOURCES: tuple[ShareableResource, ...] = (
"name",
"id",
),
+ ShareableResource("lookups", "LookupDefinition", "lookup", "name", "lookup_id"),
)
diff --git a/backend/tenant_account_v2/sharing_helpers.py b/backend/tenant_account_v2/sharing_helpers.py
index 36887b133..e7035e59d 100644
--- a/backend/tenant_account_v2/sharing_helpers.py
+++ b/backend/tenant_account_v2/sharing_helpers.py
@@ -194,7 +194,10 @@ def resources_visible_via_groups(
def resources_visible_via_memberships(
- model: type[Model], user: Any, organization: Organization | None = None
+ model: type[Model],
+ user: Any,
+ organization: Organization | None = None,
+ role: str | None = None,
) -> QuerySet[Any]:
"""Subquery of ``model`` PKs on which ``user`` holds a ``ResourceMembership``
(OWNER or VIEWER), scoped to ``organization``.
@@ -211,6 +214,9 @@ def resources_visible_via_memberships(
org-scoped. Falls back to ``UserContext`` so request paths need no change;
pass ``organization`` explicitly on worker/management paths where
``UserContext`` is empty.
+
+ Pass ``role`` to narrow to one role -- OWNER for "may mutate", where a
+ VIEWER row must not count.
"""
organization = organization or UserContext.get_organization()
qs = ResourceMembership.objects.filter(
@@ -219,6 +225,8 @@ def resources_visible_via_memberships(
)
if organization is not None:
qs = qs.filter(organization=organization)
+ if role is not None:
+ qs = qs.filter(role=role)
return _object_id_subquery(qs, model)
diff --git a/backend/tool_instance_v2/serializers.py b/backend/tool_instance_v2/serializers.py
index 049effe52..3edffea8b 100644
--- a/backend/tool_instance_v2/serializers.py
+++ b/backend/tool_instance_v2/serializers.py
@@ -52,6 +52,20 @@ class ToolInstanceSerializer(AuditSerializer):
},
}
+ def validate_workflow(self, value):
+ """Refuse reparenting: the gate authorises against the stored parent."""
+ if self.instance and value != self.instance.workflow:
+ raise ValidationError("A tool cannot be moved to another workflow.")
+ return value
+
+ def validate_workflow_id(self, value):
+ """Same guard for the declared alias -- ``workflow_id`` is the FK's
+ attname, so DRF writes the column through it directly.
+ """
+ if self.instance and str(value) != str(self.instance.workflow_id):
+ raise ValidationError("A tool cannot be moved to another workflow.")
+ return value
+
def to_representation(self, instance: ToolInstance) -> dict[str, str]:
rep: dict[str, Any] = super().to_representation(instance)
tool_function = rep.get(TIKey.TOOL_ID)
diff --git a/backend/tool_instance_v2/views.py b/backend/tool_instance_v2/views.py
index f37388ece..0488354a6 100644
--- a/backend/tool_instance_v2/views.py
+++ b/backend/tool_instance_v2/views.py
@@ -132,6 +132,21 @@ class ToolInstanceViewSet(viewsets.ModelViewSet):
"""
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
+
+ # Adding a tool mutates the workflow -- it also activates it -- so
+ # require owner / org-admin / service-account, parity with reorder.
+ # Collection-level, so IsParentWorkflowOwner cannot gate it; the
+ # for_user() fetch scopes out cross-org workflow ids (404).
+ workflow = get_object_or_404(
+ Workflow.objects.for_user(request.user),
+ pk=serializer.validated_data[WorkflowKey.WF_ID],
+ )
+ if not is_workflow_mutator(request, workflow):
+ raise PermissionDenied(
+ "Only the workflow owner or an organization admin can "
+ "add a tool to it."
+ )
+
try:
self.perform_create(serializer)
except IntegrityError:
diff --git a/backend/workflow_manager/endpoint_v2/endpoint_utils.py b/backend/workflow_manager/endpoint_v2/endpoint_utils.py
index 33b06f7b6..b6c4ae272 100644
--- a/backend/workflow_manager/endpoint_v2/endpoint_utils.py
+++ b/backend/workflow_manager/endpoint_v2/endpoint_utils.py
@@ -21,14 +21,6 @@ class WorkflowEndpointUtils:
SourceConnector.create_endpoint_for_workflow(workflow)
DestinationConnector.create_endpoint_for_workflow(workflow)
- @staticmethod
- def get_endpoints_for_workflow(workflow_id: str) -> list[WorkflowEndpoint]:
- workflow = WorkflowHelper.get_workflow_by_id(workflow_id)
- endpoints: list[WorkflowEndpoint] = WorkflowEndpoint.objects.filter(
- workflow=workflow
- )
- return endpoints
-
@staticmethod
def get_endpoint_for_workflow_by_type(
workflow_id: str, endpoint_type: WorkflowEndpoint.EndpointType
diff --git a/backend/workflow_manager/endpoint_v2/serializers.py b/backend/workflow_manager/endpoint_v2/serializers.py
index de3fb12a6..2e99d0e48 100644
--- a/backend/workflow_manager/endpoint_v2/serializers.py
+++ b/backend/workflow_manager/endpoint_v2/serializers.py
@@ -1,8 +1,10 @@
import logging
from typing import Any
+from connector_v2.constants import ConnectorInstanceKey as CIKey
from connector_v2.models import ConnectorInstance
from connector_v2.serializers import ConnectorInstanceSerializer
+from permissions.permission import is_workflow_mutator
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from workflow_manager.endpoint_v2.models import WorkflowEndpoint
@@ -31,5 +33,27 @@ class WorkflowEndpointSerializer(ModelSerializer):
context is available.
"""
fields = super().get_fields()
- fields["connector_instance_id"].queryset = ConnectorInstance.objects.all()
+ # User-scoped, so an endpoint cannot be pointed at a connector the
+ # requester has no access to. The nested read is redacted separately,
+ # in to_representation.
+ request = self.context.get("request")
+ fields["connector_instance_id"].queryset = (
+ ConnectorInstance.objects.for_user(request.user)
+ if request
+ else ConnectorInstance.objects.none()
+ )
return fields
+
+ def to_representation(self, instance: WorkflowEndpoint) -> dict[str, Any]:
+ """Blank the connector's credentials for anyone who may only read.
+
+ Sharing grants read, and the nested serializer returns
+ ``connector_metadata`` decrypted. Fails closed without a request.
+ """
+ rep = super().to_representation(instance)
+ connector = rep.get("connector_instance")
+ if connector:
+ request = self.context.get("request")
+ if not request or not is_workflow_mutator(request, instance.workflow):
+ connector[CIKey.CONNECTOR_METADATA] = {}
+ return rep
diff --git a/backend/workflow_manager/endpoint_v2/views.py b/backend/workflow_manager/endpoint_v2/views.py
index 67c5f012a..8b37d3926 100644
--- a/backend/workflow_manager/endpoint_v2/views.py
+++ b/backend/workflow_manager/endpoint_v2/views.py
@@ -1,18 +1,30 @@
from django.db.models import QuerySet
+from permissions.permission import WorkflowOwnerMutationMixin
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from workflow_manager.endpoint_v2.destination import DestinationConnector
-from workflow_manager.endpoint_v2.endpoint_utils import WorkflowEndpointUtils
from workflow_manager.endpoint_v2.models import WorkflowEndpoint
from workflow_manager.endpoint_v2.serializers import WorkflowEndpointSerializer
from workflow_manager.endpoint_v2.source import SourceConnector
+from workflow_manager.workflow_v2.exceptions import WorkflowDoesNotExistError
from workflow_manager.workflow_v2.models.workflow import Workflow
-class WorkflowEndpointViewSet(viewsets.ModelViewSet):
+class WorkflowEndpointViewSet(WorkflowOwnerMutationMixin, viewsets.ModelViewSet):
+ """Workflow source / destination endpoints.
+
+ Config here selects the connector and its settings -- the destination
+ folder for filesystem, the table for database. Shared users may read
+ it; only owners and org admins may change it.
+ """
+
serializer_class = WorkflowEndpointSerializer
+ mutation_denied_message = (
+ "Only the workflow owner or an organization admin can change its "
+ "connector configuration."
+ )
def get_queryset(self) -> QuerySet:
# Get workflows accessible to the user (owned or shared)
@@ -21,7 +33,10 @@ class WorkflowEndpointViewSet(viewsets.ModelViewSet):
# Get endpoints for those workflows
queryset = (
WorkflowEndpoint.objects.all()
- .select_related("workflow")
+ .select_related("workflow", "connector_instance")
+ # The serializer redacts credentials per row by asking whether the
+ # reader owns the workflow; without this that is a query each time.
+ .prefetch_related("workflow__memberships")
.filter(workflow__in=accessible_workflows)
)
workflow_filter = self.request.query_params.get("workflow", None)
@@ -85,6 +100,10 @@ class WorkflowEndpointViewSet(viewsets.ModelViewSet):
Response: The HTTP response containing the serialized list of
endpoints.
"""
- endpoints = WorkflowEndpointUtils.get_endpoints_for_workflow(pk)
- serializer = WorkflowEndpointSerializer(endpoints, many=True)
+ # Scoped to workflows the requester can reach; the serializer redacts
+ # connector_metadata for anyone who may only read.
+ if not Workflow.objects.for_user(request.user).filter(pk=pk).exists():
+ raise WorkflowDoesNotExistError
+ endpoints = self.get_queryset().filter(workflow_id=pk)
+ serializer = self.get_serializer(endpoints, many=True)
return Response(serializer.data)
diff --git a/backend/workflow_manager/internal_views.py b/backend/workflow_manager/internal_views.py
index 8c919551c..66b22d321 100644
--- a/backend/workflow_manager/internal_views.py
+++ b/backend/workflow_manager/internal_views.py
@@ -1615,12 +1615,12 @@ class WorkflowEndpointAPIView(APIView):
"usercontext_org_name": organization_from_context.display_name
if organization_from_context
else None,
- "headers": dict(request.headers),
"internal_service": getattr(request, "internal_service", False),
"authenticated_via": getattr(request, "authenticated_via", None),
"path": request.path,
}
- logger.info(f"WorkflowEndpointAPIView debug - {request_debug}")
+ # Headers omitted: they carry the internal service bearer key.
+ logger.debug("WorkflowEndpointAPIView debug - %s", request_debug)
# Get workflow using the DefaultOrganizationManagerMixin which automatically filters by organization
try:
diff --git a/backend/workflow_manager/workflow_v2/file_history_views.py b/backend/workflow_manager/workflow_v2/file_history_views.py
index 6a1562194..229a5d16e 100644
--- a/backend/workflow_manager/workflow_v2/file_history_views.py
+++ b/backend/workflow_manager/workflow_v2/file_history_views.py
@@ -1,4 +1,5 @@
import logging
+from typing import Any
from django.shortcuts import get_object_or_404
from rest_framework import status, viewsets
@@ -10,7 +11,10 @@ from utils.pagination import CustomPagination
from workflow_manager.workflow_v2.models.file_history import FileHistory
from workflow_manager.workflow_v2.models.workflow import Workflow
-from workflow_manager.workflow_v2.permissions import IsWorkflowOwnerOrShared
+from workflow_manager.workflow_v2.permissions import (
+ IsWorkflowOwnerForFileHistoryWrite,
+ IsWorkflowOwnerOrShared,
+)
from workflow_manager.workflow_v2.serializers import FileHistorySerializer
logger = logging.getLogger(__name__)
@@ -26,6 +30,11 @@ class FileHistoryViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [IsAuthenticated, IsWorkflowOwnerOrShared]
pagination_class = CustomPagination
+ def get_permissions(self) -> list[Any]:
+ if self.action in ("destroy", "clear"):
+ return [IsAuthenticated(), IsWorkflowOwnerForFileHistoryWrite()]
+ return list(super().get_permissions())
+
def _validate_execution_count(self, value, param_name):
"""Validate execution count parameter is a non-negative integer.
diff --git a/backend/workflow_manager/workflow_v2/permissions.py b/backend/workflow_manager/workflow_v2/permissions.py
index d133ed441..6e9c38b24 100644
--- a/backend/workflow_manager/workflow_v2/permissions.py
+++ b/backend/workflow_manager/workflow_v2/permissions.py
@@ -1,5 +1,10 @@
from django.shortcuts import get_object_or_404
-from permissions.permission import _is_resource_owner, _is_resource_viewer
+from permissions.permission import (
+ _is_resource_owner,
+ _is_resource_viewer,
+ has_group_access,
+ is_workflow_mutator,
+)
from rest_framework.permissions import BasePermission
from tenant_account_v2.organization_member_service import OrganizationMemberService
@@ -12,7 +17,11 @@ class IsWorkflowOwnerOrShared(BasePermission):
Checks:
1. User owns the workflow (OWNER membership; ``created_by`` is audit-only).
2. User is a direct viewer (VIEWER membership).
- 3. Workflow is shared to user's organization (shared_to_org).
+ 3. User reaches it through a group it is shared with.
+ 4. Workflow is shared to user's organization (shared_to_org).
+
+ Mirrors ``Workflow.objects.for_user``: a gate that admits less than the
+ queryset makes a resource visible but its sub-pages 403.
Caches the workflow on request object to avoid duplicate fetching.
"""
@@ -42,8 +51,20 @@ class IsWorkflowOwnerOrShared(BasePermission):
getattr(user, "is_service_account", False)
or _is_resource_owner(user, workflow)
or _is_resource_viewer(user, workflow)
+ or has_group_access(user, workflow)
or (workflow.shared_to_org and workflow.organization == user.organization)
or OrganizationMemberService.is_user_organization_admin(user)
)
return has_access
+
+
+class IsWorkflowOwnerForFileHistoryWrite(IsWorkflowOwnerOrShared):
+ """Owner-only gate for deleting a workflow's file history."""
+
+ message = "Only the workflow owner or an organization admin can delete file history"
+
+ def has_permission(self, request, view):
+ return super().has_permission(request, view) and is_workflow_mutator(
+ request, request._workflow_cache
+ )
diff --git a/backend/workflow_manager/workflow_v2/urls/workflow.py b/backend/workflow_manager/workflow_v2/urls/workflow.py
index 7eee26821..6bf13a677 100644
--- a/backend/workflow_manager/workflow_v2/urls/workflow.py
+++ b/backend/workflow_manager/workflow_v2/urls/workflow.py
@@ -22,7 +22,7 @@ execution_entity = WorkflowExecutionViewSet.as_view({"get": "retrieve"})
execution_list = WorkflowExecutionViewSet.as_view({"get": "list"})
execution_log_list = WorkflowExecutionLogViewSet.as_view({"get": "list"})
execution_log_export = WorkflowExecutionLogViewSet.as_view({"get": "export"})
-workflow_clear_file_marker = WorkflowViewSet.as_view({"get": "clear_file_marker"})
+workflow_clear_file_marker = WorkflowViewSet.as_view({"post": "clear_file_marker"})
workflow_schema = WorkflowViewSet.as_view({"get": "get_schema"})
can_update = WorkflowViewSet.as_view({"get": "can_update"})
list_shared_users = WorkflowViewSet.as_view({"get": "list_of_shared_users"})
diff --git a/backend/workflow_manager/workflow_v2/views.py b/backend/workflow_manager/workflow_v2/views.py
index e8f6d2272..845b25417 100644
--- a/backend/workflow_manager/workflow_v2/views.py
+++ b/backend/workflow_manager/workflow_v2/views.py
@@ -93,6 +93,7 @@ class WorkflowViewSet(
"update",
"add_co_owner",
"remove_co_owner",
+ "clear_file_marker",
]:
return [IsOwner()]
@@ -349,7 +350,9 @@ class WorkflowViewSet(
response: dict[str, Any] = WorkflowHelper.can_update_workflow(pk)
return Response(response, status=status.HTTP_200_OK)
- @action(detail=True, methods=["get"])
+ # POST, not GET: this clears execution markers, so a GET made it reachable
+ # by prefetch or a pasted URL with no CSRF in the way.
+ @action(detail=True, methods=["post"])
def clear_file_marker(self, request: Request, *args: Any, **kwargs: Any) -> Response:
workflow = self.get_object()
response: dict[str, Any] = WorkflowHelper.clear_file_marker(
diff --git a/frontend/src/components/agency/agency/Agency.jsx b/frontend/src/components/agency/agency/Agency.jsx
index 10735cb67..bb008b1bc 100644
--- a/frontend/src/components/agency/agency/Agency.jsx
+++ b/frontend/src/components/agency/agency/Agency.jsx
@@ -15,6 +15,7 @@ import useClearFileHistory from "../../../hooks/useClearFileHistory";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
import usePostHogEvents from "../../../hooks/usePostHogEvents.js";
import useRequestUrl from "../../../hooks/useRequestUrl";
+import { useWorkflowCanEdit } from "../../../hooks/useWorkflowCanEdit";
import { IslandLayout } from "../../../layouts/island-layout/IslandLayout.jsx";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
@@ -56,6 +57,7 @@ function Agency() {
} = workflowStore;
const { sessionDetails } = useSessionStore();
const { orgName } = sessionDetails;
+ const canEdit = useWorkflowCanEdit();
const { getUrl } = useRequestUrl();
const axiosPrivate = useAxiosPrivate();
const { setAlertDetails } = useAlertStore();
@@ -1146,14 +1148,22 @@ function Agency() {
{selectedTool ? (
<div className="selected-tool-info">
<span className="selected-tool-name">
+ {/* exportedTools holds only the viewer's own
+ projects, so a shared workflow misses; the
+ tool instance carries the name either way. */}
{exportedTools.find(
(t) => t.function_name === selectedTool,
- )?.name || selectedTool}
+ )?.name ||
+ details?.tool_instances?.find(
+ (ti) => ti.tool_id === selectedTool,
+ )?.name ||
+ selectedTool}
</span>
<Button
type="link"
onClick={() => setShowToolSelectionSidebar(true)}
size="small"
+ disabled={!canEdit}
>
Change Prompt Studio project
</Button>
@@ -1163,6 +1173,7 @@ function Agency() {
type="default"
onClick={() => setShowToolSelectionSidebar(true)}
className="select-tool-btn"
+ disabled={!canEdit}
>
Select Prompt Studio project
</Button>
diff --git a/frontend/src/components/agency/configure-connector-modal/ConfigureConnectorModal.jsx b/frontend/src/components/agency/configure-connector-modal/ConfigureConnectorModal.jsx
index 1c90a2d81..d91a205e5 100644
--- a/frontend/src/components/agency/configure-connector-modal/ConfigureConnectorModal.jsx
+++ b/frontend/src/components/agency/configure-connector-modal/ConfigureConnectorModal.jsx
@@ -15,10 +15,12 @@ import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
import usePostHogEvents from "../../../hooks/usePostHogEvents";
import useRequestUrl from "../../../hooks/useRequestUrl";
+import { useWorkflowCanEdit } from "../../../hooks/useWorkflowCanEdit";
import { useAlertStore } from "../../../store/alert-store";
import { AddSourceModal } from "../../input-output/add-source-modal/AddSourceModal";
import { ManageFiles } from "../../input-output/manage-files/ManageFiles";
import { CustomButton } from "../../widgets/custom-button/CustomButton";
+import { ReadOnlyNotice } from "../../widgets/read-only-notice/ReadOnlyNotice";
import { ConfigureFormsLayout } from "../configure-forms-layout/ConfigureFormsLayout";
import "./ConfigureConnectorModal.css";
@@ -72,6 +74,11 @@ function ConfigureConnectorModal({
const [hasInitializedFormData, setHasInitializedFormData] = useState(false);
const [schemaLoadedForSession, setSchemaLoadedForSession] = useState(false);
const [ruleEngineHasChanges, setRuleEngineHasChanges] = useState(false);
+ const canEdit = useWorkflowCanEdit();
+ // Grey out a region without touching each third-party widget inside it.
+ const roClass = canEdit ? undefined : "uneditable";
+ // Lets the single footer Save flush the HITL plugin's rules too.
+ const ruleEngineRef = useRef(null);
const fileExplorerRef = useRef(null);
const formRef = useRef(null);
@@ -280,6 +287,10 @@ function ConfigureConnectorModal({
folderSectionConfig[connType] || folderSectionConfig.input;
const hasUnsavedChanges = () => {
+ // A view-only user cannot have changed anything, so never prompt them.
+ if (!canEdit) {
+ return false;
+ }
// For API mode, only check RuleEngine's dirty state
if (connMode === "API") {
return ruleEngineHasChanges;
@@ -293,7 +304,10 @@ function ConfigureConnectorModal({
return hasConfigChanges || hasConnectorChanged || ruleEngineHasChanges;
};
- const handleValidateAndSubmit = async (validatedFormData) => {
+ const handleValidateAndSubmit = async (
+ validatedFormData,
+ notifySuccess = true,
+ ) => {
const hasConfigChanges = !isEqual(validatedFormData, initialFormDataConfig);
const hasConnectorChanged = connDetails?.id !== initialConnectorId;
const hasChanges = hasConfigChanges || hasConnectorChanged;
@@ -314,40 +328,73 @@ function ConfigureConnectorModal({
// Update initial values after successful save
setInitialFormDataConfig(cloneDeep(validatedFormData));
setInitialConnectorId(connDetails?.id);
- setAlertDetails({
- type: "success",
- content: "Configuration saved successfully.",
- });
+ if (notifySuccess) {
+ setAlertDetails({
+ type: "success",
+ content: "Configuration saved successfully.",
+ });
+ }
+ return true;
} catch (error) {
setAlertDetails({
type: "error",
content:
error?.message || "Failed to save changes. Please try again.",
});
+ return false;
} finally {
setIsSavingEndpoint(false);
}
}
+ // Nothing to write.
+ return true;
};
- const handleSave = async () => {
- const hasConfigChanges = !isEqual(formDataConfig, initialFormDataConfig);
+ const handleSave = async (validatedFormData) => {
+ // RJSF hands its own validated data to the submit path; the Save button
+ // has none and the state is current for it.
+ const formData = validatedFormData ?? formDataConfig;
+ const hasConfigChanges = !isEqual(formData, initialFormDataConfig);
- if (hasConfigChanges && formRef?.current) {
- if (formRef?.current?.validateForm()) {
- await handleValidateAndSubmit(formDataConfig);
- return true;
- } else {
- // RJSF shows validation errors
- return false;
+ if (
+ hasConfigChanges &&
+ formRef?.current &&
+ !formRef.current.validateForm()
+ ) {
+ // RJSF shows validation errors
+ return false;
+ }
+ // HITL rules live in the plugin and used to need their own button. One
+ // Save now writes everything the modal shows. Only when they actually
+ // changed -- otherwise every connector save would write a rule too.
+ const writesRules = ruleEngineHasChanges && !!ruleEngineRef.current?.save;
+ // Stop here if the endpoint write failed, rather than writing half the
+ // configuration and closing as though everything saved. Stay quiet on
+ // success when rules follow: the rule write reports the real outcome, and
+ // a success toast ahead of its failure would read as though both landed.
+ if (!(await handleValidateAndSubmit(formData, !writesRules))) {
+ return false;
+ }
+ if (writesRules) {
+ setIsSavingEndpoint(true);
+ try {
+ // Keep the modal open on failure so the edit is not lost.
+ if (!(await ruleEngineRef.current.save())) {
+ return false;
+ }
+ } finally {
+ setIsSavingEndpoint(false);
}
- } else {
- // No config changes, just save connector changes if any
- await handleValidateAndSubmit(formDataConfig);
- return true;
}
+ return true;
};
+ // Both ways of submitting take the same path. Enter used to reach the
+ // endpoint-only route, so a rule edit made alongside a config edit was
+ // reported saved and silently dropped. The read-only styling stops the
+ // mouse but not the keyboard, so this is still cut when canEdit is false.
+ const submitIfEditable = canEdit ? handleSave : undefined;
+
const handleModalClose = () => {
if (hasUnsavedChanges()) {
setShowUnsavedChangesModal(true);
@@ -532,12 +579,16 @@ function ConfigureConnectorModal({
footer={
connDetails?.id || connMode === "API" ? (
<div className="conn-modal-footer">
- <Button onClick={handleModalClose}>Cancel</Button>
- {connMode !== "API" && (
+ <Button onClick={handleModalClose}>
+ {canEdit ? "Cancel" : "Close"}
+ </Button>
+ {canEdit && (
<Button
type="primary"
loading={isSavingEndpoint}
- onClick={handleSave}
+ // Wrapped: a bare reference would hand the click event to
+ // handleSave's validated-data parameter.
+ onClick={() => handleSave()}
disabled={!hasUnsavedChanges()}
>
Save
@@ -554,9 +605,11 @@ function ConfigureConnectorModal({
{connMode === "API" ? "Configure HITL Rules" : "Configure Connector"}
</Typography.Text>
+ {!canEdit && <ReadOnlyNotice />}
+
{/* Connector Selection Dropdown (not shown for API connectors) */}
{connMode !== "API" && (
- <div className="connector-selection-section">
+ <div className={`connector-selection-section ${roClass ?? ""}`}>
<Typography.Text strong className="connector-selection-label">
Select Connector
</Typography.Text>
@@ -622,11 +675,14 @@ function ConfigureConnectorModal({
{/* API connectors: Show only HITL rules (no connector selection needed) */}
{connMode === "API" && RuleEngine && (
- <RuleEngine
- workflowDetails={workflowDetails}
- ruleType="API"
- onDirtyStateChange={setRuleEngineHasChanges}
- />
+ <div className={roClass}>
+ <RuleEngine
+ ref={ruleEngineRef}
+ workflowDetails={workflowDetails}
+ ruleType="API"
+ onDirtyStateChange={setRuleEngineHasChanges}
+ />
+ </div>
)}
{/* Only show configuration form and file browser after a connector is selected */}
@@ -645,7 +701,7 @@ function ConfigureConnectorModal({
label: item.label,
disabled: item.disabled,
children: (
- <>
+ <div className={roClass}>
{item.key === "1" && (
<ConfigureFormsLayout
specConfig={specConfig}
@@ -653,23 +709,24 @@ function ConfigureConnectorModal({
setFormDataConfig={setFormDataConfig}
isSpecConfigLoading={isSpecConfigLoading}
formRef={formRef}
- validateAndSubmit={handleValidateAndSubmit}
+ validateAndSubmit={submitIfEditable}
/>
)}
{item.key === "MANUALREVIEW" && RuleEngine && (
<RuleEngine
+ ref={ruleEngineRef}
workflowDetails={workflowDetails}
ruleType="DB"
onDirtyStateChange={setRuleEngineHasChanges}
/>
)}
- </>
+ </div>
),
}))}
/>
) : (
/* Other connector types: Show existing layout */
- <Row className="conn-modal-row" gutter={24}>
+ <Row className={`conn-modal-row ${roClass ?? ""}`} gutter={24}>
{/* Left side - Configuration Form */}
<Col span={12} className="conn-modal-col">
<div className="conn-modal-fs-config">
@@ -679,7 +736,7 @@ function ConfigureConnectorModal({
setFormDataConfig={setFormDataConfig}
isSpecConfigLoading={isSpecConfigLoading}
formRef={formRef}
- validateAndSubmit={handleValidateAndSubmit}
+ validateAndSubmit={submitIfEditable}
/>
</div>
</Col>
diff --git a/frontend/src/components/agency/ds-settings-card/DsSettingsCard.jsx b/frontend/src/components/agency/ds-settings-card/DsSettingsCard.jsx
index 342459475..2ca1c4d08 100644
--- a/frontend/src/components/agency/ds-settings-card/DsSettingsCard.jsx
+++ b/frontend/src/components/agency/ds-settings-card/DsSettingsCard.jsx
@@ -10,6 +10,7 @@ import { Typography } from "@/components/ui/shims/antd-typography";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
import useRequestUrl from "../../../hooks/useRequestUrl";
+import { useWorkflowCanEdit } from "../../../hooks/useWorkflowCanEdit";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
import { useWorkflowStore } from "../../../store/workflow-store";
@@ -20,6 +21,7 @@ import "./DsSettingsCard.css";
function DsSettingsCard({ connType, endpointDetails, message }) {
const workflowStore = useWorkflowStore();
const { source, destination, allowChangeEndpoint, details } = workflowStore;
+ const canEdit = useWorkflowCanEdit();
const [options, setOptions] = useState([]);
const [openModal, setOpenModal] = useState(false);
@@ -231,8 +233,9 @@ function DsSettingsCard({ connType, endpointDetails, message }) {
<Space>
<Tooltip
title={
- !allowChangeEndpoint &&
- "Workflow used in API/Task/ETL deployment"
+ (!canEdit && "Only the owner can change this") ||
+ (!allowChangeEndpoint &&
+ "Workflow used in API/Task/ETL deployment")
}
>
<Select
@@ -240,7 +243,7 @@ function DsSettingsCard({ connType, endpointDetails, message }) {
options={options}
placeholder="Select Connector Type"
value={endpointDetails?.connection_type || undefined}
- disabled={!allowChangeEndpoint}
+ disabled={!allowChangeEndpoint || !canEdit}
onChange={(value) => {
handleEndpointUpdate({
connection_type: value,
diff --git a/frontend/src/components/agency/tool-settings/ToolSettings.jsx b/frontend/src/components/agency/tool-settings/ToolSettings.jsx
index 436eb90ff..7a3f30fbf 100644
--- a/frontend/src/components/agency/tool-settings/ToolSettings.jsx
+++ b/frontend/src/components/agency/tool-settings/ToolSettings.jsx
@@ -4,12 +4,14 @@ import { Empty } from "@/components/ui/shims/antd-leaves";
import { Typography } from "@/components/ui/shims/antd-typography";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
+import { useWorkflowCanEdit } from "../../../hooks/useWorkflowCanEdit";
import { RjsfFormLayout } from "../../../layouts/rjsf-form-layout/RjsfFormLayout.jsx";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
import { useToolSettingsStore } from "../../../store/tool-settings";
import { useWorkflowStore } from "../../../store/workflow-store";
import { CustomButton } from "../../widgets/custom-button/CustomButton.jsx";
+import { ReadOnlyNotice } from "../../widgets/read-only-notice/ReadOnlyNotice";
import "./ToolSettings.css";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";
@@ -22,6 +24,7 @@ function ToolSettings({ spec, isSpecLoading }) {
const { updateMetadata, getMetadata, isLoading } = useWorkflowStore();
const axiosPrivate = useAxiosPrivate();
const handleException = useExceptionHandler();
+ const canEdit = useWorkflowCanEdit();
// Transform adapter names to IDs for validation compatibility
const transformAdapterNamesToIds = (metadata, schema) => {
@@ -66,6 +69,11 @@ function ToolSettings({ spec, isSpecLoading }) {
};
const validateAndSubmit = (updatedFormData) => {
+ // The read-only styling stops the mouse but not the keyboard, so refuse
+ // here too rather than let Enter fire a request the backend will reject.
+ if (!canEdit) {
+ return;
+ }
if (formRef && !formRef.current?.validateForm()) {
return;
}
@@ -125,26 +133,31 @@ function ToolSettings({ spec, isSpecLoading }) {
return (
<div className="tool-settings-layout">
- <RjsfFormLayout
- schema={spec}
- formData={formData}
- setFormData={setFormData}
- isLoading={isSpecLoading}
- validateAndSubmit={validateAndSubmit}
- formRef={formRef}
- isStateUpdateRequired={true}
- >
- <div className="display-flex-right tool-settings-submit-btn">
- <CustomButton
- type="primary"
- block
- htmlType="submit"
- disabled={isLoading}
- >
- Save
- </CustomButton>
- </div>
- </RjsfFormLayout>
+ {!canEdit && <ReadOnlyNotice />}
+ <div className={canEdit ? undefined : "uneditable"}>
+ <RjsfFormLayout
+ schema={spec}
+ formData={formData}
+ setFormData={setFormData}
+ isLoading={isSpecLoading}
+ validateAndSubmit={validateAndSubmit}
+ formRef={formRef}
+ isStateUpdateRequired={true}
+ >
+ {canEdit && (
+ <div className="display-flex-right tool-settings-submit-btn">
+ <CustomButton
+ type="primary"
+ block
+ htmlType="submit"
+ disabled={isLoading}
+ >
+ Save
+ </CustomButton>
+ </div>
+ )}
+ </RjsfFormLayout>
+ </div>
</div>
);
}
diff --git a/frontend/src/components/custom-tools/header/Header.jsx b/frontend/src/components/custom-tools/header/Header.jsx
index 34bae4dd8..bae4bbdc4 100644
--- a/frontend/src/components/custom-tools/header/Header.jsx
+++ b/frontend/src/components/custom-tools/header/Header.jsx
@@ -9,6 +9,7 @@ import { ExportToolIcon } from "../../../assets";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
import usePostHogEvents from "../../../hooks/usePostHogEvents";
+import { usePromptStudioCanEdit } from "../../../hooks/usePromptStudioCanEdit";
import { useAlertStore } from "../../../store/alert-store";
import { useCustomToolStore } from "../../../store/custom-tool-store";
import { useSessionStore } from "../../../store/session-store";
@@ -53,6 +54,8 @@ function Header({
const { details, isPublicSource, markChangesAsExported } =
useCustomToolStore();
const { sessionDetails } = useSessionStore();
+ // Renaming a shared project is an edit, so it follows the same rule.
+ const canEdit = usePromptStudioCanEdit();
const { setAlertDetails } = useAlertStore();
const axiosPrivate = useAxiosPrivate();
const handleException = useExceptionHandler();
@@ -444,6 +447,7 @@ function Header({
onEditTitle={
isPublicSource || !details?.tool_id ? undefined : handleOpenEditModal
}
+ editTitleDisabled={!canEdit}
customButtons={actionButtons}
/>
<Modal
diff --git a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
index 62867bacb..21ff2a44c 100644
--- a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
+++ b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
@@ -233,7 +233,7 @@ function ApiDeployment() {
updateItemStatus(record.id, newStatus);
apiDeploymentsApiService
- .updateApiDeployment({ ...record, is_active: newStatus })
+ .setApiDeploymentActive(record.id, newStatus)
.catch((err) => {
updateItemStatus(record.id, !newStatus);
setAlertDetails(handleException(err));
diff --git a/frontend/src/components/deployments/api-deployment/ApiDeploymentCardConfig.jsx b/frontend/src/components/deployments/api-deployment/ApiDeploymentCardConfig.jsx
index fde548844..341d7c6ed 100644
--- a/frontend/src/components/deployments/api-deployment/ApiDeploymentCardConfig.jsx
+++ b/frontend/src/components/deployments/api-deployment/ApiDeploymentCardConfig.jsx
@@ -11,6 +11,7 @@ import { Switch } from "@/components/ui/shims/antd-inputs";
import { Flex, Space } from "@/components/ui/shims/antd-layout";
import { Tooltip } from "@/components/ui/shims/antd-overlays";
import { Typography } from "@/components/ui/shims/antd-typography";
+import { canEditResource } from "../../../helpers/resourceAccess";
import { StatusPills } from "../../pipelines-or-deployments/pipelines/PipelineCardConfig";
import {
@@ -88,6 +89,13 @@ function createApiDeploymentCardConfig({
],
};
+ // Enabling or disabling is use, not configuration, so anyone the
+ // deployment is shared with may do it -- the backend admits an
+ // activation-only PATCH for exactly this.
+ const toggleTitle = deployment.is_active
+ ? "Disable API deployment"
+ : "Enable API deployment";
+
return (
<div className="card-list-content">
<CardHeaderRow
@@ -95,13 +103,7 @@ function createApiDeploymentCardConfig({
description={deployment.description}
>
<Space size={16} className="card-list-actions">
- <Tooltip
- title={
- deployment.is_active
- ? "Disable API deployment"
- : "Enable API deployment"
- }
- >
+ <Tooltip title={toggleTitle}>
<Switch
size="small"
checked={deployment.is_active}
diff --git a/frontend/src/components/deployments/api-deployment/api-deployments-service.js b/frontend/src/components/deployments/api-deployment/api-deployments-service.js
index b562d551a..cc933677c 100644
--- a/frontend/src/components/deployments/api-deployment/api-deployments-service.js
+++ b/frontend/src/components/deployments/api-deployment/api-deployments-service.js
@@ -39,6 +39,17 @@ function apiDeploymentsService() {
};
return axiosPrivate(options);
},
+ setApiDeploymentActive: (id, isActive) => {
+ // Only the flag: the gate admits shared users for an activation-only
+ // PATCH, and a full PUT would carry fields they may not change.
+ options = {
+ url: `${path}/api/deployment/${id}/`,
+ method: "PATCH",
+ headers: requestHeaders,
+ data: { is_active: isActive },
+ };
+ return axiosPrivate(options);
+ },
updateApiDeployment: (record) => {
options = {
url: `${path}/api/deployment/${record?.id}/`,
diff --git a/frontend/src/components/deployments/manage-keys/ManageKeys.css b/frontend/src/components/deployments/manage-keys/ManageKeys.css
index 8a15a8d84..3fa9de859 100644
--- a/frontend/src/components/deployments/manage-keys/ManageKeys.css
+++ b/frontend/src/components/deployments/manage-keys/ManageKeys.css
@@ -15,3 +15,9 @@
.actions {
margin-right: 10px;
}
+
+/* API keys are credentials: a shared user sees the controls, greyed. */
+.actions[aria-disabled="true"] {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
diff --git a/frontend/src/components/deployments/manage-keys/ManageKeys.jsx b/frontend/src/components/deployments/manage-keys/ManageKeys.jsx
index e13621b0f..dbc83f3df 100644
--- a/frontend/src/components/deployments/manage-keys/ManageKeys.jsx
+++ b/frontend/src/components/deployments/manage-keys/ManageKeys.jsx
@@ -7,6 +7,7 @@ import { Modal, Tooltip } from "@/components/ui/shims/antd-overlays";
import { Table } from "@/components/ui/shims/antd-structure";
import { Typography } from "@/components/ui/shims/antd-typography";
+import { canEditResource } from "../../../helpers/resourceAccess";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useAlertStore } from "../../../store/alert-store";
import { useSessionStore } from "../../../store/session-store";
@@ -27,6 +28,10 @@ const ManageKeys = ({
type,
}) => {
const { sessionDetails } = useSessionStore();
+ // Keys are managed by the deployment's owner, so a shared user reads them
+ // but cannot add one or change its state (UN-2868).
+ const canEdit = canEditResource(selectedApiRow, sessionDetails);
+ const ownerOnlyTitle = canEdit ? "" : "Only the owner can change this";
const axiosPrivate = useAxiosPrivate();
const handleException = useExceptionHandler();
const [isTableLoading, setIsTableLoading] = useState(false);
@@ -256,13 +261,16 @@ const ManageKeys = ({
dataIndex: "is_active",
align: "center",
render: (_, record) => (
- <Switch
- size="small"
- checked={record.is_active}
- onChange={(e) => {
- updateKeyStatus(record);
- }}
- />
+ <Tooltip title={ownerOnlyTitle}>
+ <Switch
+ size="small"
+ checked={record.is_active}
+ disabled={!canEdit}
+ onChange={(e) => {
+ updateKeyStatus(record);
+ }}
+ />
+ </Tooltip>
),
},
{
@@ -271,13 +279,24 @@ const ManageKeys = ({
align: "center",
render: (_, record) => (
<>
- <Space className="actions" onClick={() => openEditModal(record)}>
- <Tooltip title="edit" className="cursorPointer">
+ <Space
+ className="actions"
+ aria-disabled={!canEdit}
+ onClick={() => canEdit && openEditModal(record)}
+ >
+ <Tooltip title={ownerOnlyTitle || "edit"} className="cursorPointer">
<Pencil />
</Tooltip>
</Space>
- <Space className="actions" onClick={() => showDeleteModal(record)}>
- <Tooltip title="delete" className="cursorPointer">
+ <Space
+ className="actions"
+ aria-disabled={!canEdit}
+ onClick={() => canEdit && showDeleteModal(record)}
+ >
+ <Tooltip
+ title={ownerOnlyTitle || "delete"}
+ className="cursorPointer"
+ >
<Trash2 />
</Tooltip>
</Space>
@@ -298,14 +317,17 @@ const ManageKeys = ({
footer={null}
>
<div className="display-flex-right new-key-btn">
- <CustomButton
- type="primary"
- size="small"
- icon={<Plus />}
- onClick={openAddModal}
- >
- New Key
- </CustomButton>
+ <Tooltip title={ownerOnlyTitle}>
+ <CustomButton
+ type="primary"
+ size="small"
+ icon={<Plus />}
+ disabled={!canEdit}
+ onClick={openAddModal}
+ >
+ New Key
+ </CustomButton>
+ </Tooltip>
</div>
<div className="keys-table">
<Table
diff --git a/frontend/src/components/navigations/tool-nav-bar/ToolNavBar.jsx b/frontend/src/components/navigations/tool-nav-bar/ToolNavBar.jsx
index cb138897f..f13ba1de4 100644
--- a/frontend/src/components/navigations/tool-nav-bar/ToolNavBar.jsx
+++ b/frontend/src/components/navigations/tool-nav-bar/ToolNavBar.jsx
@@ -5,6 +5,7 @@ import { useEffect, useMemo, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/shims/antd-button";
import { Input } from "@/components/ui/shims/antd-inputs";
+import { Tooltip } from "@/components/ui/shims/antd-overlays";
import { Segmented } from "@/components/ui/shims/antd-structure";
import { Typography } from "@/components/ui/shims/antd-typography";
@@ -15,6 +16,7 @@ function ToolNavBar({
titleAdornment,
subtitle,
onEditTitle,
+ editTitleDisabled = false,
enableSearch,
customButtons,
setSearchList,
@@ -80,14 +82,23 @@ function ToolNavBar({
</Typography.Text>
{titleAdornment}
{onEditTitle && (
- <Button
- type="text"
- size="small"
- icon={<Pencil />}
- className="tool-nav-bar__edit-icon"
- onClick={onEditTitle}
- aria-label="Edit title"
- />
+ <Tooltip
+ title={
+ editTitleDisabled
+ ? "Only the owner can change this"
+ : undefined
+ }
+ >
+ <Button
+ type="text"
+ size="small"
+ icon={<Pencil />}
+ className="tool-nav-bar__edit-icon"
+ onClick={onEditTitle}
+ disabled={editTitleDisabled}
+ aria-label="Edit title"
+ />
+ </Tooltip>
)}
</div>
{subtitle && (
@@ -134,6 +145,7 @@ ToolNavBar.propTypes = {
titleAdornment: PropTypes.node,
subtitle: PropTypes.string,
onEditTitle: PropTypes.func,
+ editTitleDisabled: PropTypes.bool,
enableSearch: PropTypes.bool,
customButtons: PropTypes.node,
setSearchList: PropTypes.func,
diff --git a/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx b/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx
index 7bfbd6517..9b3076ab5 100644
--- a/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx
+++ b/frontend/src/components/pipelines-or-deployments/etl-task-deploy/EtlTaskDeploy.jsx
@@ -8,7 +8,7 @@ import { Input, Select } from "@/components/ui/shims/antd-inputs";
import { Space } from "@/components/ui/shims/antd-layout";
import { Modal } from "@/components/ui/shims/antd-overlays";
import { Typography } from "@/components/ui/shims/antd-typography";
-
+import { canEditResource } from "../../../helpers/resourceAccess.js";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate.js";
import { useAlertStore } from "../../../store/alert-store";
import { usePromptStudioStore } from "../../../store/prompt-studio-store";
@@ -88,7 +88,11 @@ const EtlTaskDeploy = ({
workflowApiService
.getWorkflowList()
.then((workflows) => {
- setWorkflowList(workflows);
+ // Deploying is an owner act, and the serializer refuses the rest.
+ // Offering them anyway produces an unexplained rejection on save.
+ setWorkflowList(
+ workflows?.filter((wf) => canEditResource(wf, sessionDetails)) || [],
+ );
})
.catch(() => {
console.error("Unable to get workflow list");
diff --git a/frontend/src/components/pipelines-or-deployments/pipelines/PipelineCardConfig.jsx b/frontend/src/components/pipelines-or-deployments/pipelines/PipelineCardConfig.jsx
index 9dfa69a97..3e7cfb832 100644
--- a/frontend/src/components/pipelines-or-deployments/pipelines/PipelineCardConfig.jsx
+++ b/frontend/src/components/pipelines-or-deployments/pipelines/PipelineCardConfig.jsx
@@ -21,6 +21,7 @@ import { Avatar, Tag } from "@/components/ui/shims/antd-leaves";
import { Tooltip } from "@/components/ui/shims/antd-overlays";
import { Typography } from "@/components/ui/shims/antd-typography";
import { formattedDateTime } from "../../../helpers/GetStaticData";
+import { canEditResource } from "../../../helpers/resourceAccess";
import { useSessionStore } from "../../../store/session-store";
import {
ApiEndpointSection,
@@ -312,6 +313,13 @@ function createPipelineCardConfig({
],
};
+ // Enabling or disabling is use, not configuration, so anyone the
+ // pipeline is shared with may do it -- the backend admits an
+ // activation-only PATCH for exactly this.
+ const toggleTitle = pipeline.active
+ ? "Disable pipeline"
+ : "Enable pipeline";
+
return (
<div className="card-list-content">
{/* Header Row: Name + Actions */}
@@ -323,9 +331,7 @@ function createPipelineCardConfig({
</Tooltip>
<Space size={16} className="card-list-actions">
- <Tooltip
- title={pipeline.active ? "Disable pipeline" : "Enable pipeline"}
- >
+ <Tooltip title={toggleTitle}>
<Switch
size="small"
checked={pipeline.active}
diff --git a/frontend/src/components/ui/shims/antd-overlays.tsx b/frontend/src/components/ui/shims/antd-overlays.tsx
index 31bacaca5..b45bedb8f 100644
--- a/frontend/src/components/ui/shims/antd-overlays.tsx
+++ b/frontend/src/components/ui/shims/antd-overlays.tsx
@@ -565,7 +565,22 @@ const Tooltip = React.forwardRef<HTMLDivElement, TooltipProps>(function Tooltip(
* for the same reason.
*/}
<TooltipTrigger asChild {...anchorProps}>
- {children}
+ {/*
+ * A disabled control swallows pointer events, so the trigger never
+ * receives mouseenter and the tooltip explaining WHY it is disabled
+ * never opens. Wrap it, and stop the child hit-testing, so the
+ * events land on the wrapper. Hover only -- a focusable wrapper
+ * would need a role and a name to be worth anything to a screen
+ * reader, which is a larger change than this.
+ */}
+ {React.isValidElement(children) &&
+ (children.props as { disabled?: boolean })?.disabled ? (
+ <span className="inline-flex [&>*]:pointer-events-none">
+ {children}
+ </span>
+ ) : (
+ children
+ )}
</TooltipTrigger>
<TooltipContent
side={
diff --git a/frontend/src/components/widgets/card-grid-view/CardFieldComponents.jsx b/frontend/src/components/widgets/card-grid-view/CardFieldComponents.jsx
index 4ea6ae090..25282aead 100644
--- a/frontend/src/components/widgets/card-grid-view/CardFieldComponents.jsx
+++ b/frontend/src/components/widgets/card-grid-view/CardFieldComponents.jsx
@@ -27,6 +27,8 @@ import {
formattedDateTime,
shortenApiEndpoint,
} from "../../../helpers/GetStaticData";
+import { canEditResource } from "../../../helpers/resourceAccess";
+import { useSessionStore } from "../../../store/session-store";
import { resolveOwnerDisplay } from "../owner-display";
/**
@@ -48,6 +50,12 @@ function CardActionBox({
*/
testIdPrefix,
}) {
+ const { sessionDetails } = useSessionStore();
+ // Edit and delete are the owner's on every resource this renders. What
+ // else sharing allows differs per resource, so it is not stated here.
+ // Sharing onward stays available -- see the Share button below.
+ const canEdit = canEditResource(item, sessionDetails);
+ const lockedTitle = canEdit ? undefined : "Only the owner can change this";
const testId = (suffix) =>
testIdPrefix ? `${testIdPrefix}-${suffix}-${item?.id}` : undefined;
const handleEditAction = (e) => {
@@ -64,13 +72,18 @@ function CardActionBox({
return (
<Space className="card-list-action-box">
- <Button
- type="text"
- className="action-icon-btn edit-icon"
- data-testid={testId("edit")}
- icon={<Pencil />}
- onClick={handleEditAction}
- />
+ <Tooltip title={lockedTitle}>
+ <Button
+ type="text"
+ className="action-icon-btn edit-icon"
+ data-testid={testId("edit")}
+ icon={<Pencil />}
+ disabled={!canEdit}
+ onClick={handleEditAction}
+ />
+ </Tooltip>
+ {/* Sharing stays open to shared users: they may pass access on to a
+ group they belong to, or to a user in the same organisation. */}
<Button
type="text"
className="action-icon-btn share-icon"
@@ -79,6 +92,7 @@ function CardActionBox({
onClick={handleShareAction}
/>
<Popconfirm
+ disabled={!canEdit}
title={deleteTitle}
description="This action cannot be undone."
onConfirm={() => {
@@ -98,13 +112,16 @@ function CardActionBox({
testIdPrefix ? `${testIdPrefix}-delete-confirm` : undefined
}
>
- <Button
- type="text"
- className="action-icon-btn delete-icon"
- data-testid={testId("delete")}
- icon={<Trash2 />}
- onClick={(e) => e.stopPropagation()}
- />
+ <Tooltip title={lockedTitle}>
+ <Button
+ type="text"
+ className="action-icon-btn delete-icon"
+ data-testid={testId("delete")}
+ icon={<Trash2 />}
+ disabled={!canEdit}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </Tooltip>
</Popconfirm>
<Dropdown
menu={kebabMenuItems}
diff --git a/frontend/src/components/widgets/read-only-notice/ReadOnlyNotice.css b/frontend/src/components/widgets/read-only-notice/ReadOnlyNotice.css
new file mode 100644
index 000000000..5cf657e69
--- /dev/null
+++ b/frontend/src/components/widgets/read-only-notice/ReadOnlyNotice.css
@@ -0,0 +1,25 @@
+.read-only-notice {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px;
+ margin-bottom: 12px;
+ border: 1px solid var(--border-color, #e0e0e0);
+ border-radius: 6px;
+ background: var(--bg-subtle, #fafafa);
+ font-size: 13px;
+}
+
+.read-only-notice__icon {
+ flex-shrink: 0;
+}
+
+/* Blanket read-only for a form region. Covers third-party form widgets that
+ expose no single disabled prop.
+ ponytail: keyboard focus can still reach inputs; the backend gate and the
+ absent Save button are what actually prevent writes. Swap for per-input
+ `disabled` if that ever needs to be airtight visually. */
+.uneditable {
+ pointer-events: none;
+ opacity: 0.6;
+}
diff --git a/frontend/src/components/widgets/read-only-notice/ReadOnlyNotice.jsx b/frontend/src/components/widgets/read-only-notice/ReadOnlyNotice.jsx
new file mode 100644
index 000000000..efc7ca2b6
--- /dev/null
+++ b/frontend/src/components/widgets/read-only-notice/ReadOnlyNotice.jsx
@@ -0,0 +1,22 @@
+import { Lock } from "lucide-react";
+import PropTypes from "prop-types";
+
+import "./ReadOnlyNotice.css";
+
+/** Tells a shared user, up front, that this workflow is not theirs to change. */
+function ReadOnlyNotice({
+ message = "Shared with you — view only. Only the owner can change this.",
+}) {
+ return (
+ <div className="read-only-notice">
+ <Lock className="read-only-notice__icon" size={14} />
+ <span>{message}</span>
+ </div>
+ );
+}
+
+ReadOnlyNotice.propTypes = {
+ message: PropTypes.string,
+};
+
+export { ReadOnlyNotice };
diff --git a/frontend/src/components/widgets/resource-table/ResourceTable.jsx b/frontend/src/components/widgets/resource-table/ResourceTable.jsx
index d218b5107..e9aaa0c1e 100644
--- a/frontend/src/components/widgets/resource-table/ResourceTable.jsx
+++ b/frontend/src/components/widgets/resource-table/ResourceTable.jsx
@@ -22,6 +22,7 @@ import { Table } from "@/components/ui/shims/antd-structure";
import { Typography } from "@/components/ui/shims/antd-typography";
import { formattedDateTime, timeAgo } from "../../../helpers/GetStaticData";
+import { canEditResource } from "../../../helpers/resourceAccess";
import { resolveOwnerDisplay } from "../owner-display";
import "./ResourceTable.css";
@@ -280,6 +281,16 @@ function ResourceTable({
const renderActions = (item) => {
const deprecated = item?.is_deprecated;
const disabledTitle = deprecated ? "This adapter is deprecated" : "";
+ // Edit and delete are the owner's on every resource this renders. What
+ // else sharing allows differs per resource, so it is not stated here.
+ // Both controls stay on screen but disabled, so it is obvious they exist
+ // and why they are not available. Sharing onward stays open.
+ const canEdit = canEditResource(item, sessionDetails);
+ const locked = !canEdit;
+ // Frictionless adapters are platform-provisioned: any org member may
+ // delete them, so the ownership lock covers Edit but not Delete.
+ const deleteLocked = locked && !item?.is_friction_less;
+ const lockedTitle = "Only the owner can change this";
return (
<Space
size={18}
@@ -287,14 +298,16 @@ function ResourceTable({
onClick={(event) => event.stopPropagation()}
role="none"
>
- <Tooltip title={disabledTitle}>
+ <Tooltip title={locked ? lockedTitle : disabledTitle}>
<button
type="button"
className="action-icon-btn"
aria-label={`Edit ${type}`}
data-testid={rowTestId(item, "edit")}
- aria-disabled={deprecated}
- onClick={(event) => !deprecated && handleEdit?.(event, item)}
+ aria-disabled={deprecated || locked}
+ onClick={(event) =>
+ !deprecated && canEdit && handleEdit?.(event, item)
+ }
>
<Pencil className="action-icon-buttons edit-icon" />
</button>
@@ -320,6 +333,7 @@ function ResourceTable({
* because every row has one.
*/}
<Popconfirm
+ disabled={deleteLocked}
title={`Delete the ${type}`}
description={`Are you sure to delete ${item?.[titleProp]}`}
okText="Yes"
@@ -333,6 +347,8 @@ function ResourceTable({
className="action-icon-btn"
aria-label={`Delete ${type}`}
data-testid={rowTestId(item, "delete")}
+ aria-disabled={deleteLocked}
+ title={deleteLocked ? lockedTitle : undefined}
>
<Trash2 className="action-icon-buttons delete-icon" />
</button>
diff --git a/frontend/src/components/workflows/new-workflow/NewWorkflow.jsx b/frontend/src/components/workflows/new-workflow/NewWorkflow.jsx
index 34772c173..44f7ebba7 100644
--- a/frontend/src/components/workflows/new-workflow/NewWorkflow.jsx
+++ b/frontend/src/components/workflows/new-workflow/NewWorkflow.jsx
@@ -24,7 +24,7 @@ function NewWorkflow({
backendErrors,
setBackendErrors,
}) {
- const [disableCreation, setDisableCreation] = useState(true);
+ const [disableCreation, setDisableCreation] = useState(!name || !description);
const nameRef = useRef(name);
const descriptionRef = useRef(description);
const [form] = Form.useForm();
@@ -88,6 +88,10 @@ function NewWorkflow({
name="workflowForm"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
+ initialValues={{
+ workflow_name: name,
+ workflow_description: description,
+ }}
onValuesChange={handleInputChange}
>
<Form.Item
@@ -101,7 +105,7 @@ function NewWorkflow({
}
help={getBackendErrorDetail("workflow_name", backendErrors)}
>
- <Input defaultValue={nameRef.current} onChange={updateName} />
+ <Input onChange={updateName} />
</Form.Item>
<Form.Item
label="Description"
@@ -117,7 +121,6 @@ function NewWorkflow({
help={getBackendErrorDetail("workflow_description", backendErrors)}
>
<TextArea
- defaultValue={descriptionRef.current}
autoSize={{ minRows: 4, maxRows: 6 }}
onChange={updateDescription}
/>
diff --git a/frontend/src/components/workflows/workflow/workflow-service.js b/frontend/src/components/workflows/workflow/workflow-service.js
index ed6c43067..0b771bf48 100644
--- a/frontend/src/components/workflows/workflow/workflow-service.js
+++ b/frontend/src/components/workflows/workflow/workflow-service.js
@@ -60,7 +60,7 @@ function workflowService() {
clearFileMarkers: (id) => {
options = {
url: `${path}/workflow/${id}/clear-file-marker/`,
- method: "GET",
+ method: "POST",
headers: {
"X-CSRFToken": csrfToken,
},
diff --git a/frontend/src/helpers/resourceAccess.js b/frontend/src/helpers/resourceAccess.js
new file mode 100644
index 000000000..e91a54821
--- /dev/null
+++ b/frontend/src/helpers/resourceAccess.js
@@ -0,0 +1,23 @@
+/**
+ * Whether the current user owns a shared resource.
+ *
+ * True for owners, co-owners and org admins. What that unlocks is per
+ * resource and the backend is the authority: on most resources sharing grants
+ * read only, while Prompt Studio and Agentic Prompt Studio are shared for
+ * collaboration and hold back only the name, delete and access changes.
+ * This only decides what the UI offers, so nobody fills in a form that can
+ * only fail — it is not itself the rule.
+ *
+ * `is_owner` is set by every shareable resource's serializer.
+ */
+function canEditResource(resource, sessionDetails) {
+ // Payload not in yet. The backend still refuses the write, so assume
+ // editable rather than flash a read-only view at the resource's own owner
+ // while the request is in flight.
+ if (resource?.is_owner === undefined) {
+ return true;
+ }
+ return Boolean(resource.is_owner || sessionDetails?.isAdmin);
+}
+
+export { canEditResource };
diff --git a/frontend/src/hooks/usePromptStudioCanEdit.js b/frontend/src/hooks/usePromptStudioCanEdit.js
new file mode 100644
index 000000000..74fdecd19
--- /dev/null
+++ b/frontend/src/hooks/usePromptStudioCanEdit.js
@@ -0,0 +1,21 @@
+import { canEditResource } from "../helpers/resourceAccess";
+import { useCustomToolStore } from "../store/custom-tool-store";
+import { useSessionStore } from "../store/session-store";
+
+/**
+ * Whether the current user owns the Prompt Studio project being viewed.
+ *
+ * Gates the owner-only controls, which for Prompt Studio is the project name:
+ * prompts and settings stay editable for everyone it is shared with.
+ *
+ * Pairs with the existing `isPublicSource` flag rather than replacing it:
+ * that one means "opened through a public read-only link" and also selects
+ * API paths.
+ */
+function usePromptStudioCanEdit() {
+ const { details } = useCustomToolStore();
+ const { sessionDetails } = useSessionStore();
+ return canEditResource(details, sessionDetails);
+}
+
+export { usePromptStudioCanEdit };
diff --git a/frontend/src/hooks/useWorkflowCanEdit.js b/frontend/src/hooks/useWorkflowCanEdit.js
new file mode 100644
index 000000000..d183b8b1d
--- /dev/null
+++ b/frontend/src/hooks/useWorkflowCanEdit.js
@@ -0,0 +1,17 @@
+import { canEditResource } from "../helpers/resourceAccess";
+import { useSessionStore } from "../store/session-store";
+import { useWorkflowStore } from "../store/workflow-store";
+
+/**
+ * Whether the current user may change the workflow being viewed.
+ *
+ * Thin wrapper over `canEditResource` for the workflow builder, which reads
+ * its resource from the workflow store rather than a list row.
+ */
+function useWorkflowCanEdit() {
+ const { details } = useWorkflowStore();
+ const { sessionDetails } = useSessionStore();
+ return canEditResource(details, sessionDetails);
+}
+
+export { useWorkflowCanEdit };
diff --git a/frontend/src/layouts/menu-layout/MenuLayout.jsx b/frontend/src/layouts/menu-layout/MenuLayout.jsx
index b400689a6..9ee357798 100644
--- a/frontend/src/layouts/menu-layout/MenuLayout.jsx
+++ b/frontend/src/layouts/menu-layout/MenuLayout.jsx
@@ -11,6 +11,7 @@ import { Modal } from "@/components/ui/shims/antd-overlays";
import { ToolNavBar } from "../../components/navigations/tool-nav-bar/ToolNavBar";
import { workflowService } from "../../components/workflows/workflow/workflow-service";
import { useExceptionHandler } from "../../hooks/useExceptionHandler";
+import { useWorkflowCanEdit } from "../../hooks/useWorkflowCanEdit";
import { useAlertStore } from "../../store/alert-store";
import { useSessionStore } from "../../store/session-store";
import { useWorkflowStore } from "../../store/workflow-store";
@@ -25,6 +26,7 @@ function MenuLayout({ children }) {
const { projectName, projectId, details } = useWorkflowStore();
const { setAlertDetails } = useAlertStore();
const handleException = useExceptionHandler();
+ const canEdit = useWorkflowCanEdit();
const wfService = workflowService();
const [editModalOpen, setEditModalOpen] = useState(false);
@@ -120,6 +122,7 @@ function MenuLayout({ children }) {
subtitle={details?.description}
onNavigateBack={handleNavigateBack}
onEditTitle={projectId ? handleOpenEditModal : undefined}
+ editTitleDisabled={!canEdit}
customButtons={rightButtons}
/>
<Modal