Skip to content

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

[FEAT] Allow unpublishing an exported tool; derive API-key target from the URL (#2206)

Hari John Kuriakose88eed95b7710
diff --git a/backend/api_v2/api_key_views.py b/backend/api_v2/api_key_views.py
index 9f6b8532e..69307f2c0 100644
--- a/backend/api_v2/api_key_views.py
+++ b/backend/api_v2/api_key_views.py
@@ -3,7 +3,7 @@ from typing import Any
from permissions.permission import IsOwnerOrSharedUser, IsParentDeploymentOwner
from pipeline_v2.exceptions import PipelineNotFound
from pipeline_v2.pipeline_processor import PipelineProcessor
-from rest_framework import serializers, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
@@ -33,6 +33,102 @@ class APIKeyViewSet(viewsets.ModelViewSet):
return APIKeyListSerializer
return APIKeySerializer
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ """Create an API key for the deployment or pipeline being targeted.
+
+ `POST keys/api/<api_id>/` and `POST keys/pipeline/<pipeline_id>/`
+ already name the resource in the path, so callers need not repeat it
+ in the body. The body-only routes (`keys/api/`, `keys/pipeline/`) name
+ it in `api` / `pipeline` instead.
+
+ Whichever route is used, the target is resolved and **ownership is
+ checked here**, because `create` is collection-level: DRF resolves
+ `IsParentDeploymentOwner` for it but never calls `get_object()`, so
+ `has_object_permission` never runs on its own. Without this, any org
+ member could mint a live key for a deployment they do not own. The
+ check must cover the body-only routes too — otherwise the same hole is
+ simply reachable by moving the identifier from the path into the body.
+
+ The path target is authoritative: a body naming the *other* target is
+ a contradiction, not an override, and is refused rather than silently
+ creating a key for whichever one wins. A body repeating the *same*
+ target with the *same* value is accepted and overwritten -- it agrees
+ with the path, so there is nothing to refuse. A body naming the same
+ field with a *different* value is refused for the same reason as the
+ cross-type case: silently minting a key for the path's resource while
+ the caller named another one is a wrong-resource credential, not a
+ harmless override.
+ """
+ # A JSON array (or scalar) body has no `.copy()` returning a mapping;
+ # reject it as a 400 rather than letting `AttributeError` become a 500.
+ if not isinstance(request.data, dict):
+ raise serializers.ValidationError(
+ {"non_field_errors": "Request body must be a JSON object."}
+ )
+ request_data = request.data.copy()
+
+ api_id = kwargs.get("api_id")
+ pipeline_id = kwargs.get("pipeline_id")
+
+ if api_id and request_data.get("pipeline"):
+ raise serializers.ValidationError(
+ {
+ "pipeline": "This endpoint creates a key for the API "
+ "deployment named in the URL; remove `pipeline` from the body."
+ }
+ )
+ if pipeline_id and request_data.get("api"):
+ raise serializers.ValidationError(
+ {
+ "api": "This endpoint creates a key for the pipeline named "
+ "in the URL; remove `api` from the body."
+ }
+ )
+
+ # Same field, different value: the caller named one resource in the
+ # path and another in the body. Overwriting silently would mint a live
+ # key for a resource they did not ask for -- refuse, as for the
+ # cross-type contradictions above. An empty body value is not a
+ # disagreement; it simply does not name anything.
+ for field, path_value in (("api", api_id), ("pipeline", pipeline_id)):
+ body_value = request_data.get(field)
+ if path_value and body_value and str(body_value) != str(path_value):
+ raise serializers.ValidationError(
+ {
+ field: f"`{field}` in the body names a different resource "
+ "than the URL; remove it or make the two agree."
+ }
+ )
+
+ # The path wins where it names a target; otherwise fall back to the
+ # body, so the body-only routes resolve to the same guarded path.
+ api_id = api_id or request_data.get("api")
+ pipeline_id = pipeline_id or request_data.get("pipeline")
+
+ if api_id:
+ api = DeploymentHelper.get_api_by_id(api_id=api_id)
+ if not api:
+ raise APINotFound()
+ self.check_object_permissions(request, api)
+ request_data["api"] = api_id
+ elif pipeline_id:
+ # `check_active=False`: minting a key does not require a running
+ # pipeline, and `get_active_pipeline` would both 422 on a paused
+ # one and disclose its state before the ownership check below.
+ pipeline = PipelineProcessor.get_pipeline_by_id(pipeline_id=pipeline_id)
+ if not pipeline:
+ raise PipelineNotFound()
+ self.check_object_permissions(request, pipeline)
+ request_data["pipeline"] = pipeline_id
+ # Neither named: let the serializer raise its "one of api/pipeline"
+ # error rather than inventing a second wording for the same condition.
+
+ serializer = self.get_serializer(data=request_data)
+ serializer.is_valid(raise_exception=True)
+ self.perform_create(serializer)
+ headers = self.get_success_headers(serializer.data)
+ return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
+
@action(detail=True, methods=["get"])
def api_keys(
self,
diff --git a/backend/api_v2/tests/test_api_key_create_target.py b/backend/api_v2/tests/test_api_key_create_target.py
new file mode 100644
index 000000000..20e1d0853
--- /dev/null
+++ b/backend/api_v2/tests/test_api_key_create_target.py
@@ -0,0 +1,631 @@
+"""Guards on ``APIKeyViewSet.create`` for the path-derived target.
+
+``POST keys/api/<api_id>/`` and ``POST keys/pipeline/<pipeline_id>/`` name the
+target in the URL. Deriving it there removed the need to repeat it in the body,
+but ``create`` is a *collection*-level action: DRF resolves
+``IsParentDeploymentOwner`` for it and then never calls ``get_object()``, so
+``has_object_permission`` never ran. Any authenticated org member could mint a
+live key for a deployment they do not own. The view now performs the object
+check itself.
+
+Three things are pinned here, all cheap to break:
+
+1. **Every route authorizes.** The check must cover the body-only routes
+ (``keys/api/``, ``keys/pipeline/``) as well as the path ones -- guarding
+ only the path form leaves the identical hole reachable by moving the
+ identifier into the body.
+
+2. **``IsParentDeploymentOwner`` accepts the parent itself.** The view hands it
+ an ``APIDeployment``/``Pipeline``, neither of which declares an ``api`` or
+ ``pipeline`` field. A plain ``obj.api`` raises ``AttributeError`` -> 500 on
+ every key creation; the lookups must be shape-guarded. An object matching
+ neither shape is denied, not admitted.
+
+3. **The path target is authoritative.** A body naming the *other* target is a
+ contradiction and must be refused, not silently resolved to whichever wins.
+
+These are unit tests over the real method bodies -- Django settings are not
+configured in the unit tier, so collaborators are stubbed and the source is
+extracted, mirroring
+``prompt_studio_registry_v2/tests/test_registry_tool_delete_guards.py``.
+``create`` is *executed* rather than grepped: an earlier version asserted on
+source text and so passed against an inverted ``isinstance`` guard and against
+the wrong object being handed to ``check_object_permissions``.
+
+What runs here is the method body, not the routing -- and that is a real gap,
+not merely a deferral: because the body is ``exec``-ed out of its class, moving
+``create`` into a dead class (reopening the IDOR) or dropping an import it uses
+at request time both leave this suite green. ``tests_common/test_route_wiring.py``
+asserts the binding and fails on either. The live request cycle against a
+database remains integration-tier.
+"""
+
+from __future__ import annotations
+
+import logging
+import textwrap
+from pathlib import Path
+from typing import Any
+
+import pytest
+from django.core.exceptions import ValidationError as DjangoValidationError
+from tests_common.source_extraction import exec_def, extract_defs
+
+BACKEND_DIR = Path(__file__).resolve().parents[2]
+PERMISSION_MODULE = BACKEND_DIR / "permissions" / "permission.py"
+
+START_MARKER = "class IsParentDeploymentOwner(permissions.BasePermission):"
+
+
+class _User:
+ def __init__(self, name: str) -> None:
+ self.name = name
+
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
+ return f"<User {self.name}>"
+
+
+class _Request:
+ def __init__(self, user: _User) -> None:
+ self.user = user
+
+
+class _APIDeployment:
+ """A deployment as the permission class actually receives it.
+
+ Deliberately declares neither ``api`` nor ``pipeline`` -- that is what the
+ real model looks like (``APIKey.api`` points *at* it with
+ ``related_name="api_keys"``), and it is the shape that made a bare
+ ``obj.api`` a 500. ``memberships`` is how the permission class recognises
+ a parent; both real models get it from ``HasMembersMixin``.
+ """
+
+ def __init__(self, owner: _User) -> None:
+ self.owner = owner
+ self.memberships = ()
+
+
+class _APIKey:
+ """A key row, whose ownership is inherited from its parent."""
+
+ def __init__(self, api: Any = None, pipeline: Any = None, owner: Any = None) -> None:
+ self.api = api
+ self.pipeline = pipeline
+ self.owner = owner
+
+
+def _build_permission(*, org_admins: set[str]) -> Any:
+ """Extract the real ``IsParentDeploymentOwner`` against stubbed collaborators."""
+ (body,) = extract_defs(PERMISSION_MODULE, (START_MARKER,), ("\nclass ",))
+
+ class _BasePermission:
+ pass
+
+ class _Permissions:
+ BasePermission = _BasePermission
+
+ def _is_resource_owner(user: _User, obj: Any) -> bool:
+ return getattr(obj, "owner", None) is user
+
+ def _is_service_account(request: _Request) -> bool:
+ return getattr(request.user, "is_service_account", False)
+
+ def _is_organization_admin(request: _Request) -> bool:
+ return request.user.name in org_admins
+
+ class _SilentLogger:
+ def warning(self, *_: Any, **__: Any) -> None:
+ pass
+
+ namespace: dict[str, Any] = {
+ "permissions": _Permissions,
+ "_is_resource_owner": _is_resource_owner,
+ "_is_service_account": _is_service_account,
+ "_is_organization_admin": _is_organization_admin,
+ "logger": _SilentLogger(),
+ "Request": object,
+ "APIView": object,
+ "Any": Any,
+ }
+ exec(compile(body, str(PERMISSION_MODULE), "exec"), namespace)
+ return namespace["IsParentDeploymentOwner"]()
+
+
+OWNER = _User("owner")
+STRANGER = _User("stranger")
+ADMIN = _User("admin")
+
+
+class TestParentDeploymentOwnerAcceptsTheParent:
+ """``create`` passes the parent directly; that must not 500 or over-admit."""
+
+ def test_deployment_owner_is_admitted(self) -> None:
+ permission = _build_permission(org_admins=set())
+ deployment = _APIDeployment(owner=OWNER)
+
+ assert permission.has_object_permission(_Request(OWNER), None, deployment) is True
+
+ def test_non_owner_is_refused(self) -> None:
+ """The IDOR this check closes: same-org, not the deployment's owner."""
+ permission = _build_permission(org_admins=set())
+ deployment = _APIDeployment(owner=OWNER)
+
+ allowed = permission.has_object_permission(_Request(STRANGER), None, deployment)
+
+ assert allowed is False, (
+ "A member who does not own the deployment must not be able to mint "
+ "an API key for it"
+ )
+
+ def test_org_admin_is_admitted(self) -> None:
+ permission = _build_permission(org_admins={"admin"})
+ deployment = _APIDeployment(owner=OWNER)
+
+ assert permission.has_object_permission(_Request(ADMIN), None, deployment) is True
+
+ def test_a_parent_without_api_or_pipeline_fields_does_not_raise(self) -> None:
+ """The regression that a bare ``obj.api`` would reintroduce.
+
+ ``APIDeployment``/``Pipeline`` declare no ``api`` or ``pipeline``
+ field, so an unguarded attribute access is an ``AttributeError`` --
+ surfacing as a 500 on every single key creation, which is worse than
+ the hole it was meant to close.
+ """
+ permission = _build_permission(org_admins=set())
+ deployment = _APIDeployment(owner=OWNER)
+
+ assert not hasattr(deployment, "api")
+ assert not hasattr(deployment, "pipeline")
+ # Must return a verdict rather than raising.
+ assert (
+ permission.has_object_permission(_Request(STRANGER), None, deployment)
+ is False
+ )
+
+ def test_key_rows_still_resolve_through_their_parent(self) -> None:
+ """The pre-existing detail-route behaviour must be unchanged."""
+ permission = _build_permission(org_admins=set())
+ key = _APIKey(api=_APIDeployment(owner=OWNER), owner=STRANGER)
+
+ assert permission.has_object_permission(_Request(OWNER), None, key) is True
+ assert permission.has_object_permission(_Request(STRANGER), None, key) is False
+
+ def test_parentless_key_falls_back_to_its_own_owner(self) -> None:
+ permission = _build_permission(org_admins=set())
+ key = _APIKey(api=None, pipeline=None, owner=OWNER)
+
+ assert permission.has_object_permission(_Request(OWNER), None, key) is True
+ assert permission.has_object_permission(_Request(STRANGER), None, key) is False
+
+ def test_an_unrecognised_object_is_denied(self) -> None:
+ """An authz gate that cannot identify its subject must fail closed.
+
+ A permissive fallthrough would admit any object that happens to expose
+ a matching owner, turning a wrong-type programming error into a silent
+ grant instead of a loud failure.
+ """
+
+ class _Unexpected:
+ def __init__(self, owner: _User) -> None:
+ self.owner = owner
+
+ permission = _build_permission(org_admins=set())
+
+ assert (
+ permission.has_object_permission(
+ _Request(OWNER), None, _Unexpected(owner=OWNER)
+ )
+ is False
+ )
+
+
+VIEW_MODULE = BACKEND_DIR / "api_v2" / "api_key_views.py"
+
+CREATE_MARKER = (
+ " def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:"
+)
+
+
+class _ValidationError(Exception):
+ """Stand-in for ``serializers.ValidationError`` (a 400)."""
+
+
+class _NotFound(Exception):
+ """Stand-in for ``APINotFound`` / ``PipelineNotFound`` (a 404)."""
+
+
+class _PermissionDenied(Exception):
+ """Raised by the stub ``check_object_permissions`` (a 403)."""
+
+
+class _Target:
+ """A resolvable APIDeployment/Pipeline row."""
+
+ def __init__(self, target_id: str, owner: _User) -> None:
+ self.id = target_id
+ self.owner = owner
+
+
+MALFORMED_ID = "not-a-uuid"
+
+
+def _lookup(rows: dict[str, _Target] | None, key: Any) -> _Target | None:
+ """Model the real ``get_api_by_id`` / ``get_pipeline_by_id`` contract.
+
+ ``pk`` is a UUID column, so the ORM raises ``ValidationError`` (not
+ ``DoesNotExist``) on a non-UUID string. Both helpers catch it and return
+ ``None``; a stub that quietly returned ``None`` for *every* unknown key
+ would hide a caller that reintroduces the 500.
+ """
+ if not isinstance(key, str) or key == MALFORMED_ID:
+ return None
+ return (rows or {}).get(key)
+
+
+def _build_create(
+ *,
+ apis: dict[str, _Target] | None = None,
+ pipelines: dict[str, _Target] | None = None,
+ requester: _User = OWNER,
+) -> Any:
+ """Extract and execute the real ``create`` body against stubs.
+
+ Source extraction is used for the same reason as ``_build_permission``:
+ Django settings are unconfigured in the unit tier, so the module cannot be
+ imported. Executing the real body is what makes these behavioural -- the
+ previous version asserted on source *text*, and so passed against an
+ inverted ``isinstance`` guard and against the wrong object being handed to
+ ``check_object_permissions``.
+ """
+ (body,) = extract_defs(VIEW_MODULE, (CREATE_MARKER,), ("\n def ", "\n @"))
+ body = textwrap.dedent(body)
+
+ checked: list[Any] = []
+
+ class _Serializers:
+ ValidationError = _ValidationError
+
+ class _DeploymentHelper:
+ @staticmethod
+ def get_api_by_id(api_id: str) -> _Target | None:
+ return _lookup(apis, api_id)
+
+ class _PipelineProcessor:
+ @staticmethod
+ def get_pipeline_by_id(pipeline_id: str) -> _Target | None:
+ return _lookup(pipelines, pipeline_id)
+
+ class _View:
+ """Minimal DRF-ish host for the extracted method."""
+
+ def check_object_permissions(self, request: Any, obj: Any) -> None:
+ checked.append(obj)
+ # Mirrors IsParentDeploymentOwner: only the owner passes.
+ if getattr(obj, "owner", None) is not request.user:
+ raise _PermissionDenied()
+
+ def get_serializer(self, data: Any) -> Any:
+ return _Serializer(data)
+
+ def perform_create(self, serializer: Any) -> None:
+ serializer.saved = True
+
+ def get_success_headers(self, data: Any) -> dict[str, str]:
+ return {}
+
+ class _Serializer:
+ def __init__(self, data: Any) -> None:
+ self.data = data
+ self.saved = False
+
+ def is_valid(self, raise_exception: bool = False) -> bool:
+ api = self.data.get("api")
+ pipeline = self.data.get("pipeline")
+ if api and pipeline:
+ raise _ValidationError("only one of api/pipeline")
+ if not api and not pipeline:
+ raise _ValidationError("at least one of api/pipeline")
+ return True
+
+ class _Response:
+ def __init__(self, data: Any, status: Any = None, headers: Any = None) -> None:
+ self.data = data
+ self.status = status
+
+ class _Status:
+ HTTP_201_CREATED = 201
+
+ namespace: dict[str, Any] = {
+ "serializers": _Serializers,
+ "DeploymentHelper": _DeploymentHelper,
+ "PipelineProcessor": _PipelineProcessor,
+ "APINotFound": _NotFound,
+ "PipelineNotFound": _NotFound,
+ "Response": _Response,
+ "status": _Status,
+ "Request": object,
+ "Any": Any,
+ }
+ exec(compile(body, str(VIEW_MODULE), "exec"), namespace)
+
+ view = _View()
+ view.create = namespace["create"].__get__(view, _View)
+ view.checked = checked
+ view.requester = requester
+ return view
+
+
+class _Req:
+ def __init__(self, data: Any, user: _User) -> None:
+ self.data = data
+ self.user = user
+
+
+class TestCreateAuthorizesEveryRoute:
+ """The IDOR fix, exercised rather than grepped.
+
+ The hole is reachable from four routes -- api/pipeline, each by path and
+ by body. Every one must resolve the target and object-check it.
+ """
+
+ def test_path_route_admits_the_owner(self) -> None:
+ target = _Target("api-1", OWNER)
+ view = _build_create(apis={"api-1": target})
+
+ response = view.create(_Req({}, OWNER), api_id="api-1")
+
+ assert response.status == 201
+ assert view.checked == [target], "the target must be object-checked"
+
+ def test_path_route_refuses_a_non_owner(self) -> None:
+ view = _build_create(apis={"api-1": _Target("api-1", OWNER)})
+
+ with pytest.raises(_PermissionDenied):
+ view.create(_Req({}, STRANGER), api_id="api-1")
+
+ def test_body_only_route_refuses_a_non_owner(self) -> None:
+ """The route the path-only fix left open.
+
+ Moving the identifier from the path into the body must not bypass the
+ ownership check -- otherwise the IDOR is simply relocated.
+ """
+ view = _build_create(apis={"api-1": _Target("api-1", OWNER)})
+
+ with pytest.raises(_PermissionDenied):
+ view.create(_Req({"api": "api-1"}, STRANGER))
+
+ def test_body_only_route_admits_the_owner(self) -> None:
+ target = _Target("api-1", OWNER)
+ view = _build_create(apis={"api-1": target})
+
+ response = view.create(_Req({"api": "api-1"}, OWNER))
+
+ assert response.status == 201
+ assert view.checked == [target]
+
+ def test_body_only_pipeline_route_refuses_a_non_owner(self) -> None:
+ view = _build_create(pipelines={"pipe-1": _Target("pipe-1", OWNER)})
+
+ with pytest.raises(_PermissionDenied):
+ view.create(_Req({"pipeline": "pipe-1"}, STRANGER))
+
+ def test_pipeline_path_route_checks_the_pipeline_not_the_api(self) -> None:
+ """Guards against the wrong object reaching the permission check."""
+ target = _Target("pipe-1", OWNER)
+ view = _build_create(pipelines={"pipe-1": target})
+
+ view.create(_Req({}, OWNER), pipeline_id="pipe-1")
+
+ assert view.checked == [target]
+
+ def test_unknown_target_is_a_404(self) -> None:
+ view = _build_create(apis={})
+
+ with pytest.raises(_NotFound):
+ view.create(_Req({}, OWNER), api_id="missing")
+
+
+class TestCreateBodyContract:
+ def test_non_mapping_body_is_a_400(self) -> None:
+ """A JSON array body must 400, not ``AttributeError`` into a 500."""
+ view = _build_create(apis={"api-1": _Target("api-1", OWNER)})
+
+ with pytest.raises(_ValidationError):
+ view.create(_Req([{"api": "api-1"}], OWNER), api_id="api-1")
+
+ def test_body_naming_the_other_target_is_refused(self) -> None:
+ view = _build_create(
+ apis={"api-1": _Target("api-1", OWNER)},
+ pipelines={"pipe-1": _Target("pipe-1", OWNER)},
+ )
+
+ with pytest.raises(_ValidationError):
+ view.create(_Req({"pipeline": "pipe-1"}, OWNER), api_id="api-1")
+
+ def test_pipeline_path_with_api_body_is_refused(self) -> None:
+ view = _build_create(
+ apis={"api-1": _Target("api-1", OWNER)},
+ pipelines={"pipe-1": _Target("pipe-1", OWNER)},
+ )
+
+ with pytest.raises(_ValidationError):
+ view.create(_Req({"api": "api-1"}, OWNER), pipeline_id="pipe-1")
+
+ def test_same_field_naming_a_different_resource_is_refused(self) -> None:
+ """A body naming another API than the path is a contradiction too.
+
+ The cross-type guards above do not catch this: path and body agree on
+ the *field* and disagree on the *value*. Overwriting silently mints a
+ live key for the path's deployment while the caller asked for another.
+ """
+ view = _build_create(
+ apis={"api-1": _Target("api-1", OWNER), "api-2": _Target("api-2", OWNER)}
+ )
+
+ with pytest.raises(_ValidationError):
+ view.create(_Req({"api": "api-2"}, OWNER), api_id="api-1")
+
+ def test_same_pipeline_field_naming_a_different_resource_is_refused(self) -> None:
+ view = _build_create(
+ pipelines={
+ "pipe-1": _Target("pipe-1", OWNER),
+ "pipe-2": _Target("pipe-2", OWNER),
+ }
+ )
+
+ with pytest.raises(_ValidationError):
+ view.create(_Req({"pipeline": "pipe-2"}, OWNER), pipeline_id="pipe-1")
+
+ def test_body_repeating_the_path_target_verbatim_is_accepted(self) -> None:
+ """Agreement is not a contradiction -- the redundant body still works."""
+ target = _Target("api-1", OWNER)
+ view = _build_create(apis={"api-1": target})
+
+ response = view.create(_Req({"api": "api-1"}, OWNER), api_id="api-1")
+
+ assert response.status == 201
+ assert view.checked == [target]
+
+ def test_empty_string_body_value_does_not_defeat_the_path(self) -> None:
+ """``setdefault`` used to let ``{"api": ""}`` through as a present key."""
+ target = _Target("api-1", OWNER)
+ view = _build_create(apis={"api-1": target})
+
+ response = view.create(_Req({"api": ""}, OWNER), api_id="api-1")
+
+ assert response.status == 201
+ assert view.checked == [target]
+
+ def test_no_target_anywhere_is_a_400(self) -> None:
+ view = _build_create()
+
+ with pytest.raises(_ValidationError):
+ view.create(_Req({}, OWNER))
+
+ def test_malformed_identifier_in_the_body_is_not_a_server_fault(self) -> None:
+ """A non-UUID body value must 404, not 500.
+
+ The body is read before the serializer runs, so the value goes
+ straight into ``objects.get(pk=...)``. ``pk`` is a UUID column, which
+ raises ``ValidationError`` rather than ``DoesNotExist`` -- unhandled,
+ that surfaces as a 500 with a traceback for ordinary client garbage.
+ """
+ view = _build_create(apis={"api-1": _Target("api-1", OWNER)})
+
+ with pytest.raises(_NotFound):
+ view.create(_Req({"api": MALFORMED_ID}, OWNER))
+
+ def test_malformed_identifier_in_the_path_is_not_a_server_fault(self) -> None:
+ """Path segments are ``<str:>``, so they are unvalidated too."""
+ view = _build_create(pipelines={"pipe-1": _Target("pipe-1", OWNER)})
+
+ with pytest.raises(_NotFound):
+ view.create(_Req({}, OWNER), pipeline_id=MALFORMED_ID)
+
+
+class _DoesNotExist(Exception):
+ """Stand-in for ``Model.DoesNotExist``."""
+
+
+def _raising_manager(exc: BaseException) -> Any:
+ """A ``.objects`` whose ``get()`` raises ``exc``."""
+
+ class _Objects:
+ @staticmethod
+ def get(**_: Any) -> Any:
+ raise exc
+
+ return _Objects()
+
+
+class TestLookupHelpersTolerateMalformedIds:
+ """The fix lives in the helpers, so pin the contract there.
+
+ Both are reached with unvalidated caller input. Catching only
+ ``DoesNotExist`` leaves ``ValidationError`` to escape as a 500.
+
+ The real ``django.core.exceptions.ValidationError`` is used -- Django is
+ installed in the unit tier even though *settings* are unconfigured, so the
+ exception class is importable and the ``except`` clause is exercised for
+ real rather than matched as source text.
+ """
+
+ @staticmethod
+ def _build_get_api_by_id(raises: BaseException) -> Any:
+ class _APIDeploymentModel:
+ objects = _raising_manager(raises)
+ DoesNotExist = _DoesNotExist
+
+ namespace = exec_def(
+ BACKEND_DIR / "api_v2" / "utils.py",
+ " def get_api_by_id(api_id: str) -> APIDeployment | None:",
+ ("\n @",),
+ {
+ "APIDeployment": _APIDeploymentModel,
+ "ValidationError": DjangoValidationError,
+ "Any": Any,
+ "logger": logging.getLogger("test-stub"),
+ },
+ )
+ return namespace["get_api_by_id"]
+
+ @staticmethod
+ def _build_get_pipeline_by_id(raises: BaseException) -> Any:
+ class _PipelineModel:
+ DoesNotExist = _DoesNotExist
+
+ class _Cls:
+ @staticmethod
+ def fetch_pipeline(pipeline_id: str, check_active: bool = True) -> Any:
+ raise raises
+
+ namespace = exec_def(
+ BACKEND_DIR / "pipeline_v2" / "pipeline_processor.py",
+ " def get_pipeline_by_id(cls, pipeline_id: str) -> Pipeline | None:",
+ ("\n @",),
+ {
+ "Pipeline": _PipelineModel,
+ "ValidationError": DjangoValidationError,
+ "Any": Any,
+ "logger": logging.getLogger("test-stub"),
+ },
+ )
+ return lambda pipeline_id: namespace["get_pipeline_by_id"](_Cls, pipeline_id)
+
+ def test_get_api_by_id_returns_none_for_a_malformed_id(self) -> None:
+ """A non-UUID id raises ValidationError, not DoesNotExist.
+
+ Left uncaught it escapes the view as a 500 with a traceback, for what
+ is ordinary client garbage.
+ """
+ get_api_by_id = self._build_get_api_by_id(DjangoValidationError("bad uuid"))
+
+ assert get_api_by_id(MALFORMED_ID) is None
+
+ def test_get_api_by_id_still_returns_none_when_the_row_is_absent(self) -> None:
+ get_api_by_id = self._build_get_api_by_id(_DoesNotExist())
+
+ assert get_api_by_id("api-1") is None
+
+ def test_get_pipeline_by_id_returns_none_for_a_malformed_id(self) -> None:
+ get_pipeline_by_id = self._build_get_pipeline_by_id(
+ DjangoValidationError("bad uuid")
+ )
+
+ assert get_pipeline_by_id(MALFORMED_ID) is None
+
+ def test_get_pipeline_by_id_still_returns_none_when_the_row_is_absent(self) -> None:
+ get_pipeline_by_id = self._build_get_pipeline_by_id(_DoesNotExist())
+
+ assert get_pipeline_by_id("pipe-1") is None
+
+ def test_an_unexpected_error_is_not_swallowed(self) -> None:
+ """The catch must stay narrow -- a real fault must still surface.
+
+ Broadening to a bare ``except Exception`` would turn database outages
+ into silent 404s.
+ """
+ get_api_by_id = self._build_get_api_by_id(RuntimeError("database is down"))
+
+ with pytest.raises(RuntimeError):
+ get_api_by_id("api-1")
diff --git a/backend/api_v2/utils.py b/backend/api_v2/utils.py
index 9806afcb9..6167d270e 100644
--- a/backend/api_v2/utils.py
+++ b/backend/api_v2/utils.py
@@ -1,8 +1,13 @@
+import logging
+
+from django.core.exceptions import ValidationError
from workflow_manager.workflow_v2.models.execution import WorkflowExecution
from api_v2.models import APIDeployment
from api_v2.notification import APINotification
+logger = logging.getLogger(__name__)
+
class APIDeploymentUtils:
@staticmethod
@@ -15,12 +20,25 @@ class APIDeploymentUtils:
Returns:
Optional[APIDeployment]: The APIDeployment instance if found,
otherwise None.
+
+ A malformed identifier is "not found", not a fault: ``pk`` is a UUID
+ column, so a non-UUID string raises ``ValidationError`` out of
+ ``to_python`` rather than ``DoesNotExist``. Callers reach this with
+ unvalidated caller input (path segments are ``<str:>``, and request
+ bodies are read before the serializer runs), so letting that escape
+ turns ordinary client garbage into a 500.
"""
try:
api_deployment: APIDeployment = APIDeployment.objects.get(pk=api_id)
return api_deployment
except APIDeployment.DoesNotExist:
return None
+ except ValidationError:
+ # Logged so a malformed identifier stays distinguishable from an
+ # absent row: both answer 404, and without this the difference is
+ # invisible when triaging.
+ logger.debug("Malformed API deployment identifier: %s", api_id)
+ return None
@staticmethod
def send_notification(
diff --git a/backend/permissions/permission.py b/backend/permissions/permission.py
index 0c0a3b88e..ad29da0dc 100644
--- a/backend/permissions/permission.py
+++ b/backend/permissions/permission.py
@@ -1,3 +1,4 @@
+import logging
from typing import Any
from adapter_processor_v2.models import AdapterInstance
@@ -7,6 +8,8 @@ from rest_framework.views import APIView
from tenant_account_v2.organization_member_service import OrganizationMemberService
from utils.user_context import UserContext
+logger = logging.getLogger(__name__)
+
_REQUEST_ADMIN_CACHE_ATTR = "_cached_is_organization_admin"
@@ -166,12 +169,39 @@ class IsParentDeploymentOwner(permissions.BasePermission):
one is set). Admits the parent's owner (creator + co-owners), org admin,
or service account -- mirrors ``IsParentToolOwner`` (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
+ action, so DRF never calls ``get_object()`` for it and there is no
+ ``APIKey`` yet to check — the view hands the target ``APIDeployment`` /
+ ``Pipeline`` straight to ``check_object_permissions``.
+
+ An ``APIKey`` is recognised by declaring both parent FKs; a parent by
+ carrying ``memberships`` (both models use ``HasMembersMixin``). Anything
+ else is **denied** rather than guessed at — an authorization gate that
+ cannot identify its subject must fail closed. Note this cannot collapse to
+ ``obj.api or obj.pipeline or obj``: the parents declare no ``api``
+ attribute, so that raises ``AttributeError`` (500) on every ``create``.
"""
def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
if _is_service_account(request):
return True
- owner_resource = obj.api or obj.pipeline or obj
+
+ if hasattr(obj, "api") and hasattr(obj, "pipeline"):
+ # An APIKey: ownership is inherited from whichever parent is set,
+ # falling back to the key itself when both are null.
+ owner_resource = obj.api or obj.pipeline or obj
+ elif hasattr(obj, "memberships"):
+ # The parent deployment/pipeline, handed over by ``create``.
+ owner_resource = obj
+ else:
+ logger.warning(
+ "IsParentDeploymentOwner received an unsupported object type "
+ "%s; denying.",
+ type(obj).__name__,
+ )
+ return False
+
if _is_resource_owner(request.user, owner_resource):
return True
return _is_organization_admin(request)
diff --git a/backend/pipeline_v2/pipeline_processor.py b/backend/pipeline_v2/pipeline_processor.py
index b2967f1aa..24042f3bc 100644
--- a/backend/pipeline_v2/pipeline_processor.py
+++ b/backend/pipeline_v2/pipeline_processor.py
@@ -1,5 +1,6 @@
import logging
+from django.core.exceptions import ValidationError
from django.utils import timezone
from pipeline_v2.exceptions import InactivePipelineError
@@ -44,11 +45,52 @@ class PipelineProcessor:
@classmethod
def get_active_pipeline(cls, pipeline_id: str) -> Pipeline | None:
- """Retrieves a list of active pipelines."""
+ """Retrieve a pipeline, requiring it to be active.
+
+ Raises ``InactivePipelineError`` (422) when the row exists but is
+ paused; use :meth:`get_pipeline_by_id` when merely identifying the row.
+
+ A malformed identifier is "not found", not a fault -- see
+ :meth:`get_pipeline_by_id` for why ``ValidationError`` is caught here.
+ This path is reached *unauthenticated*: the public execution endpoint
+ looks the pipeline up before validating the API key, so letting it
+ escape turns any non-UUID path segment into a 500.
+ """
try:
return cls.fetch_pipeline(pipeline_id, check_active=True)
except Pipeline.DoesNotExist:
return None
+ except ValidationError:
+ logger.debug("Malformed pipeline identifier: %s", pipeline_id)
+ return None
+
+ @classmethod
+ def get_pipeline_by_id(cls, pipeline_id: str) -> Pipeline | None:
+ """Retrieve a pipeline regardless of whether it is currently active.
+
+ The active/inactive distinction matters to callers that are about to
+ *run* something. Callers that only need to identify the row -- to check
+ ownership, say -- must not be forced through ``get_active_pipeline``,
+ which raises ``InactivePipelineError`` (422) and logs at ERROR for what
+ is an ordinary request against a paused pipeline.
+
+ A malformed identifier is "not found", not a fault: ``pk`` is a UUID
+ column, so a non-UUID string raises ``ValidationError`` out of
+ ``to_python`` rather than ``DoesNotExist``. Callers reach this with
+ unvalidated caller input (path segments are ``<str:>``, and request
+ bodies are read before the serializer runs), so letting that escape
+ turns ordinary client garbage into a 500.
+ """
+ try:
+ return cls.fetch_pipeline(pipeline_id, check_active=False)
+ except Pipeline.DoesNotExist:
+ return None
+ except ValidationError:
+ # Logged so a malformed identifier stays distinguishable from an
+ # absent row: both answer 404, and without this the difference is
+ # invisible when triaging.
+ logger.debug("Malformed pipeline identifier: %s", pipeline_id)
+ return None
@staticmethod
def _update_pipeline_status(
diff --git a/backend/pipeline_v2/tests/test_pipeline_lookup_guards.py b/backend/pipeline_v2/tests/test_pipeline_lookup_guards.py
new file mode 100644
index 000000000..71062684c
--- /dev/null
+++ b/backend/pipeline_v2/tests/test_pipeline_lookup_guards.py
@@ -0,0 +1,66 @@
+"""Both pipeline lookups must treat a malformed identifier as "not found".
+
+``Pipeline.pk`` is a UUID column, so a non-UUID string raises Django's
+``ValidationError`` out of ``to_python`` rather than ``DoesNotExist``. Left
+uncaught it escapes as a 500 for what is ordinary client garbage.
+
+This matters most on ``get_active_pipeline``, which is reached *before*
+authentication: ``BaseAPIKeyValidator`` checks only that some ``Bearer`` string
+is present, then ``PipelineDeploymentHelper.validate_and_process`` looks the
+pipeline up and only afterwards validates the key. So an unauthenticated caller
+sending any non-UUID path segment to the public execution endpoint could force a
+500 with a traceback.
+
+The real module is imported and its collaborators patched (Django is loaded by
+the rig's test env), so no database is touched and these stay in the unit tier.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+from django.core.exceptions import ValidationError
+
+from pipeline_v2.models import Pipeline
+from pipeline_v2.pipeline_processor import PipelineProcessor
+
+MALFORMED_ID = "not-a-uuid"
+
+
+class TestMalformedIdentifierIsNotAServerFault:
+ """A non-UUID id resolves to ``None``, never an unhandled exception."""
+
+ @pytest.mark.parametrize(
+ "lookup",
+ ["get_active_pipeline", "get_pipeline_by_id"],
+ )
+ def test_validation_error_becomes_none(self, lookup: str) -> None:
+ with patch.object(
+ PipelineProcessor, "fetch_pipeline", side_effect=ValidationError("bad uuid")
+ ):
+ assert getattr(PipelineProcessor, lookup)(MALFORMED_ID) is None
+
+ @pytest.mark.parametrize(
+ "lookup",
+ ["get_active_pipeline", "get_pipeline_by_id"],
+ )
+ def test_absent_row_still_becomes_none(self, lookup: str) -> None:
+ with patch.object(
+ PipelineProcessor, "fetch_pipeline", side_effect=Pipeline.DoesNotExist
+ ):
+ assert getattr(PipelineProcessor, lookup)(MALFORMED_ID) is None
+
+ @pytest.mark.parametrize(
+ "lookup",
+ ["get_active_pipeline", "get_pipeline_by_id"],
+ )
+ def test_an_unexpected_error_is_not_swallowed(self, lookup: str) -> None:
+ """The catch must stay narrow -- a database outage is not a 404."""
+ with patch.object(
+ PipelineProcessor,
+ "fetch_pipeline",
+ side_effect=RuntimeError("database is down"),
+ ):
+ with pytest.raises(RuntimeError):
+ getattr(PipelineProcessor, lookup)(MALFORMED_ID)
diff --git a/backend/prompt_studio/permission.py b/backend/prompt_studio/permission.py
index 6f2441898..43eb9c75d 100644
--- a/backend/prompt_studio/permission.py
+++ b/backend/prompt_studio/permission.py
@@ -31,3 +31,26 @@ class PromptAcesssToUser(permissions.BasePermission):
if has_group_access(request.user, tool):
return True
return OrganizationMemberService.is_user_organization_admin(request.user)
+
+
+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).
+
+ Read access is deliberately broader (see
+ ``PromptStudioRegistry.objects.list_tools``); deleting is restricted to
+ owners and org admins.
+ """
+
+ def has_object_permission(self, request: Request, view: APIView, obj: Any) -> bool:
+ if getattr(request.user, "is_service_account", False):
+ return True
+ owner_resource = obj.custom_tool or obj
+ if _is_resource_owner(request.user, owner_resource):
+ return True
+ return OrganizationMemberService.is_user_organization_admin(request.user)
diff --git a/backend/prompt_studio/prompt_studio_core_v2/views.py b/backend/prompt_studio/prompt_studio_core_v2/views.py
index cd65f2de7..5741c7ccd 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py
@@ -8,7 +8,6 @@ from typing import Any
import magic
from account_v2.custom_exceptions import DuplicateData
-from api_v2.models import APIDeployment
from celery import signature
from celery.result import AsyncResult
from django.db import IntegrityError
@@ -22,20 +21,17 @@ from permissions.permission import IsOwner, IsOwnerOrSharedUserOrSharedToOrg
from permissions.resource_share_views import ResourceShareManagementMixin
from permissions.roles import ResourceRole
from pg_queue.flags import PG_QUEUE_FLAG_KEY
-from pipeline_v2.models import Pipeline
from plugins import get_plugin
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 rest_framework.versioning import URLPathVersioning
-from tool_instance_v2.models import ToolInstance
from utils.file_storage.helpers.prompt_studio_file_helper import PromptStudioFileHelper
from utils.hubspot_notify import notify_hubspot_event
from utils.pagination import OptionalPagination
from utils.user_context import UserContext
from utils.user_session import UserSessionUtils
-from workflow_manager.endpoint_v2.models import WorkflowEndpoint
from backend.celery_service import app as celery_app
from prompt_studio.lookup_utils import (
@@ -50,7 +46,6 @@ from prompt_studio.prompt_profile_manager_v2.constants import (
from prompt_studio.prompt_profile_manager_v2.models import ProfileManager
from prompt_studio.prompt_profile_manager_v2.serializers import ProfileManagerSerializer
from prompt_studio.prompt_studio_core_v2.constants import (
- DeploymentType,
FileViewTypes,
ToolStudioErrors,
ToolStudioPromptKeys,
@@ -85,6 +80,11 @@ from prompt_studio.prompt_studio_registry_v2.serializers import (
from prompt_studio.prompt_studio_v2.constants import ToolStudioPromptErrors
from prompt_studio.prompt_studio_v2.models import ToolStudioPrompt
from prompt_studio.prompt_studio_v2.serializers import ToolStudioPromptSerializer
+from prompt_studio.tool_usage import (
+ dependent_workflow_ids,
+ deployment_types_for,
+ join_deployment_types,
+)
from unstract.core.data_models import PgTaskStatus
from unstract.flags.feature_flag import check_feature_flag_status
from unstract.sdk1.utils.common import Utils as CommonUtils
@@ -235,83 +235,27 @@ class PromptStudioCoreView(
instance.delete(organization_id)
def _check_tool_usage_in_workflows(self, instance: CustomTool) -> tuple[bool, set]:
- """Check if a tool is being used in any workflows.
-
- Args:
- instance: The CustomTool instance to check
+ """Whether ``instance``'s exported tool is in use, and by which workflows.
- Returns:
- Tuple of (is_used: bool, dependent_workflows: set)
+ An unexported project has no registry row and so no dependants.
"""
registry = getattr(instance, "prompt_studio_registries", None)
if not registry:
return False, set()
- dependent_wfs = set(
- ToolInstance.objects.filter(tool_id=registry.pk)
- .values_list("workflow_id", flat=True)
- .distinct()
- )
+ dependent_wfs = dependent_workflow_ids(registry.pk)
return bool(dependent_wfs), dependent_wfs
def _get_deployment_types(self, workflow_ids: set) -> set:
- """Get all deployment types where the tool is used.
-
- Args:
- workflow_ids: Set of workflow IDs to check
-
- Returns:
- Set of deployment type strings
- """
- deployment_types: set = set()
-
- # Check API Deployments (include inactive to prevent drift)
- if APIDeployment.objects.filter(workflow_id__in=workflow_ids).exists():
- deployment_types.add(DeploymentType.API_DEPLOYMENT)
-
- # Check Pipelines using mapping instead of if/elif
- pipeline_type_mapping = {
- Pipeline.PipelineType.ETL: DeploymentType.ETL_PIPELINE,
- Pipeline.PipelineType.TASK: DeploymentType.TASK_PIPELINE,
- }
- pipelines = (
- Pipeline.objects.filter(workflow_id__in=workflow_ids)
- .values_list("pipeline_type", flat=True)
- .distinct()
- )
- for pipeline_type in pipelines:
- if pipeline_type in pipeline_type_mapping:
- deployment_types.add(pipeline_type_mapping[pipeline_type])
-
- # Check for Manual Review
- if WorkflowEndpoint.objects.filter(
- workflow_id__in=workflow_ids,
- connection_type=WorkflowEndpoint.ConnectionType.MANUALREVIEW,
- ).exists():
- deployment_types.add(DeploymentType.HUMAN_QUALITY_REVIEW)
-
- return deployment_types
+ """Deployment kinds reachable from ``workflow_ids``."""
+ return deployment_types_for(workflow_ids)
def _format_deployment_types_message(self, deployment_types: set) -> str:
- """Format deployment types into human-readable message.
-
- Args:
- deployment_types: Set of deployment type strings
-
- Returns:
- Formatted message string or empty string if no types
- """
- if not deployment_types:
+ """Render the "re-export needed" notice, or "" when nothing is deployed."""
+ types_text = join_deployment_types(deployment_types)
+ if not types_text:
return ""
- types_list = sorted(deployment_types)
- if len(types_list) == 1:
- types_text = types_list[0]
- elif len(types_list) == 2:
- types_text = f"{types_list[0]} or {types_list[1]}"
- else:
- types_text = ", ".join(types_list[:-1]) + f", or {types_list[-1]}"
-
return (
f"You have made changes to this Prompt Studio project. "
f"This project is used in {types_text}. "
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/exceptions.py b/backend/prompt_studio/prompt_studio_registry_v2/exceptions.py
index cb0e3c71b..5c01902a0 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/exceptions.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/exceptions.py
@@ -31,3 +31,11 @@ class InValidCustomToolError(APIException):
"This prompt studio project cannot be exported. It probably "
"has some empty or unexecuted prompts."
)
+
+
+class RegistryToolInUseError(APIException):
+ status_code = 409
+ default_detail = (
+ "This exported tool is still used by one or more workflows. "
+ "Remove those usages before deleting it."
+ )
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
new file mode 100644
index 000000000..acb772e65
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio_registry_v2/tests/test_registry_tool_delete_guards.py
@@ -0,0 +1,506 @@
+"""Regression tests for the two guards on ``DELETE registry/<pk>/``.
+
+The route added in this PR is the first by-PK operation on
+``PromptStudioRegistryView``, which previously exposed only ``list``. Two
+things gate it, and both are load-bearing:
+
+1. **Authorization** (``IsRegistryToolOwner``). The viewset carries no
+ ``permission_classes`` and ``DEFAULT_PERMISSION_CLASSES`` is empty, so
+ without this every member of an organization could delete any other
+ member's exported tool by PK. ``OrganizationFilterBackend`` runs inside
+ ``get_object()`` and blocks *cross-org* access, but not intra-org.
+
+2. **In-use refusal** (409). An exported tool still attached to a workflow must
+ not be deletable, or those workflows break.
+
+``has_object_permission`` is pure logic over collaborators, so these tests stub
+the Django-coupled boundary (``permissions.permission``,
+``OrganizationMemberService``) and exercise the real method body, sliced out of
+the source by ``tests_common.source_extraction``. A rename fails these tests
+rather than silently skipping them.
+
+The in-use check is driven the same way: ``destroy``, ``_refuse_if_in_use`` and
+the shared helpers in ``prompt_studio/tool_usage.py`` are all executed against a
+stubbed ORM. ``destroy`` is included deliberately -- covering only the guard
+left its *call site* unpinned, and deleting that one line made in-use tools
+deletable with the whole suite still green.
+
+**Known blind spot of this technique.** The bodies are ``exec``-ed out of
+context, so nothing here binds them to the class, the URLconf, or DRF dispatch:
+code that is present but *unreachable* looks identical to code that is wired.
+Deleting the DELETE route outright, or unwiring ``IsRegistryToolOwner`` from
+``destroy``, each left this suite fully green while reopening the hole it exists
+to close. ``tests_common/test_route_wiring.py`` covers binding from the other
+side and fails on both. Two further sharp edges: inserting a decorator above an
+extracted definition silently truncates its slice, so the tests then assert
+against a *different* body than ships; and a cosmetic annotation change can
+break the marker match outright.
+
+Retiring the technique for the conventional import-and-``patch`` pattern is
+deferred to its own change -- it rewrites both suites wholesale. Note the
+premise it was built on does not hold: Django *is* importable in this tier
+(``tests/groups.yaml`` sets ``DJANGO_SETTINGS_MODULE`` for ``unit-backend``),
+``backend/conftest.py`` auto-marks only ``django_db``/``TestCase`` tests as
+``integration``, and ``prompt_studio_core_v2/tests/test_build_index_payload.py``
+already imports its module directly for exactly this reason.
+"""
+
+from __future__ import annotations
+
+import heapq
+from pathlib import Path
+from typing import Any
+
+import pytest
+from tests_common.source_extraction import extract_defs
+
+BACKEND_DIR = Path(__file__).resolve().parents[3]
+PERMISSION_MODULE = BACKEND_DIR / "prompt_studio" / "permission.py"
+
+START_MARKER = "class IsRegistryToolOwner(permissions.BasePermission):"
+
+
+class _User:
+ def __init__(self, name: str, is_service_account: bool = False) -> None:
+ self.name = name
+ self.is_service_account = is_service_account
+
+ def __repr__(self) -> str: # pragma: no cover - debugging aid
+ return f"<User {self.name}>"
+
+
+class _CustomTool:
+ """Stand-in for the parent Prompt Studio project."""
+
+ def __init__(self, owner: _User) -> None:
+ self.owner = owner
+
+
+class _RegistryRow:
+ """Stand-in for a ``PromptStudioRegistry`` row.
+
+ ``custom_tool`` is nullable, so it may be ``None`` for legacy rows exported
+ before the link existed; those fall back to the row's own owner.
+ """
+
+ def __init__(self, custom_tool: _CustomTool | None, owner: _User) -> None:
+ self.custom_tool = custom_tool
+ self.owner = owner
+
+
+class _Request:
+ def __init__(self, user: _User) -> None:
+ self.user = user
+
+
+def _build_permission(*, org_admins: set[str]) -> Any:
+ """Extract the real ``IsRegistryToolOwner`` against stubbed collaborators."""
+ (body,) = extract_defs(PERMISSION_MODULE, (START_MARKER,), ("\nclass ",))
+
+ class _BasePermission:
+ pass
+
+ class _Permissions:
+ BasePermission = _BasePermission
+
+ def _is_resource_owner(user: _User, obj: Any) -> bool:
+ return getattr(obj, "owner", None) is user
+
+ class _OrganizationMemberService:
+ @staticmethod
+ def is_user_organization_admin(user: _User) -> bool:
+ return user.name in org_admins
+
+ namespace: dict[str, Any] = {
+ "permissions": _Permissions,
+ "_is_resource_owner": _is_resource_owner,
+ "OrganizationMemberService": _OrganizationMemberService,
+ "Request": object,
+ "APIView": object,
+ "Any": Any,
+ }
+ exec(compile(body, str(PERMISSION_MODULE), "exec"), namespace)
+ return namespace["IsRegistryToolOwner"]()
+
+
+OWNER = _User("owner")
+STRANGER = _User("stranger")
+ADMIN = _User("admin")
+SERVICE = _User("service", is_service_account=True)
+
+
+def _linked_row(owner: _User = OWNER) -> _RegistryRow:
+ """A normal row whose parent project is owned by ``owner``."""
+ return _RegistryRow(custom_tool=_CustomTool(owner=owner), owner=_User("unused"))
+
+
+class TestRegistryToolDeleteAuthorization:
+ def test_project_owner_may_delete(self) -> None:
+ permission = _build_permission(org_admins=set())
+ assert (
+ permission.has_object_permission(_Request(OWNER), None, _linked_row()) is True
+ )
+
+ def test_other_org_member_may_not_delete(self) -> None:
+ """The IDOR this guard exists to close.
+
+ Org filtering already blocks cross-org access; this covers a member of
+ the *same* org who does not own the project.
+ """
+ permission = _build_permission(org_admins=set())
+
+ allowed = permission.has_object_permission(
+ _Request(STRANGER), None, _linked_row()
+ )
+
+ assert allowed is False, (
+ "A non-owner in the same organization must not be able to delete "
+ "another member's exported tool"
+ )
+
+ def test_org_admin_may_delete(self) -> None:
+ permission = _build_permission(org_admins={"admin"})
+ assert (
+ permission.has_object_permission(_Request(ADMIN), None, _linked_row()) is True
+ )
+
+ def test_service_account_may_delete(self) -> None:
+ permission = _build_permission(org_admins=set())
+ assert (
+ permission.has_object_permission(_Request(SERVICE), None, _linked_row())
+ is True
+ )
+
+ def test_ownership_follows_the_parent_project_not_the_row(self) -> None:
+ """Ownership is inherited from ``custom_tool``, mirroring IsParentToolOwner.
+
+ 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.
+ """
+ row = _RegistryRow(custom_tool=_CustomTool(owner=OWNER), owner=STRANGER)
+ permission = _build_permission(org_admins=set())
+
+ assert permission.has_object_permission(_Request(STRANGER), None, row) is False
+ assert permission.has_object_permission(_Request(OWNER), None, row) is True
+
+ def test_unlinked_legacy_row_falls_back_to_its_own_owner(self) -> None:
+ """``custom_tool`` is nullable; those rows must stay deletable by their owner."""
+ row = _RegistryRow(custom_tool=None, owner=OWNER)
+ permission = _build_permission(org_admins=set())
+
+ assert permission.has_object_permission(_Request(OWNER), None, row) is True
+ assert permission.has_object_permission(_Request(STRANGER), None, row) is False
+
+
+VIEWS_MODULE = BACKEND_DIR / "prompt_studio" / "prompt_studio_registry_v2" / "views.py"
+TOOL_USAGE_MODULE = BACKEND_DIR / "prompt_studio" / "tool_usage.py"
+
+GUARD_MARKERS = (
+ " def destroy(",
+ " def _refuse_if_in_use(self, instance: PromptStudioRegistry) -> None:",
+ " @staticmethod\n def _in_use_detail(deployment_types: set) -> str:",
+)
+
+# The shared helpers live in ``prompt_studio/tool_usage.py``; they are pulled
+# in the same way so the guard runs against the real query and the real
+# grammar rather than a restatement of either.
+HELPER_MARKERS = (
+ "def dependent_workflow_ids(registry_pk: str) -> set:",
+ "def deployment_types_for(workflow_ids: set) -> set:",
+ "def join_deployment_types(deployment_types: set) -> str:",
+)
+
+
+class _InUseError(Exception):
+ """Stand-in for ``RegistryToolInUseError``, whose 409 is asserted separately."""
+
+ status_code = 409
+
+ def __init__(self, detail: str = "") -> None:
+ super().__init__(detail)
+ self.detail = detail
+
+
+def _queryset(rows: list[Any], *, required_filters: tuple[str, ...] = ()) -> Any:
+ """Minimal chainable stand-in for the ORM calls the guard makes.
+
+ ``required_filters`` names the kwargs the real query must narrow on. A
+ query that stops filtering returns nothing rather than silently returning
+ every row -- otherwise dropping ``tool_id=`` would look identical to a
+ correct lookup and no test could tell the difference.
+ """
+
+ class _QS:
+ def __init__(self, matched: bool = False) -> None:
+ self._matched = matched or not required_filters
+
+ def filter(self, **kwargs: Any) -> _QS:
+ if required_filters and not all(k in kwargs for k in required_filters):
+ # `required_filters` is non-empty here, so this is unmatched.
+ return _QS()
+ return _QS(matched=True)
+
+ def values_list(self, *_: Any, **__: Any) -> _QS:
+ return self
+
+ def distinct(self) -> _QS:
+ return self
+
+ def exists(self) -> bool:
+ return bool(rows) and self._matched
+
+ def __iter__(self) -> Any:
+ return iter(rows if self._matched else [])
+
+ return _QS()
+
+
+# Sentinel returned by the stub base ``destroy``, proving the delete ran.
+# A comment rather than an attribute docstring: `check-docstring-first` reads a
+# bare module-level string as a second module docstring and fails the file.
+DELETED = object()
+
+
+class _BaseView:
+ """Stands in for ``viewsets.ModelViewSet`` under the extracted ``destroy``.
+
+ Recording the ``super().destroy()`` hand-off is what lets a test assert
+ that an unused tool actually reaches the delete, and — more importantly —
+ that an in-use one never does.
+ """
+
+ def destroy(self, request: Any, *args: Any, **kwargs: Any) -> Any:
+ return DELETED
+
+
+def _logged_workflow_limit() -> int:
+ """Read the real cap rather than restating it."""
+ source = VIEWS_MODULE.read_text()
+ marker = "_LOGGED_WORKFLOW_LIMIT = "
+ if marker not in source:
+ pytest.fail(f"Could not find {marker!r} in {VIEWS_MODULE}.")
+ return int(source.split(marker)[1].split("\n")[0].strip())
+
+
+class _SilentLogger:
+ def info(self, *_: Any, **__: Any) -> None:
+ pass
+
+ def warning(self, *_: Any, **__: Any) -> None:
+ pass
+
+
+def _build_guard(
+ *,
+ workflow_ids: list[str],
+ api_deployments: bool = False,
+ pipeline_types: list[str] | None = None,
+ manual_review: bool = False,
+) -> Any:
+ """Extract the real in-use guard against a stubbed ORM.
+
+ Same technique as ``_build_permission``: the bodies come from ``views.py``
+ and ``tool_usage.py``, so a change to the query, the raise, or the message
+ wording lands here rather than passing against a restated copy.
+
+ ``destroy`` is extracted alongside the guard so its *call* to
+ ``_refuse_if_in_use`` is covered too. Testing the guard alone left the
+ wiring unpinned: dropping that one line made in-use tools deletable with
+ the whole suite still green.
+ """
+ view_parts = extract_defs(VIEWS_MODULE, GUARD_MARKERS, ("\n def ", "\n @"))
+ helper_parts = extract_defs(TOOL_USAGE_MODULE, HELPER_MARKERS, ("\ndef ",))
+
+ body = (
+ "\n".join(helper_parts)
+ + "\n\nclass _Guard(_BaseView):\n"
+ + "\n".join(view_parts)
+ + "\n"
+ )
+
+ class _Model:
+ def __init__(self, qs: Any) -> None:
+ self.objects = qs
+
+ class _PipelineType:
+ ETL = "ETL"
+ TASK = "TASK"
+
+ class _Pipeline:
+ objects = None
+ PipelineType = _PipelineType
+
+ _Pipeline.objects = _queryset(pipeline_types or [])
+
+ class _ConnectionType:
+ MANUALREVIEW = "MANUALREVIEW"
+
+ class _WorkflowEndpoint:
+ objects = _queryset([1] if manual_review else [])
+ ConnectionType = _ConnectionType
+
+ class _DeploymentType:
+ API_DEPLOYMENT = "API Deployment"
+ ETL_PIPELINE = "ETL Pipeline"
+ TASK_PIPELINE = "Task Pipeline"
+ HUMAN_QUALITY_REVIEW = "Human in the Loop"
+
+ namespace: dict[str, Any] = {
+ "heapq": heapq,
+ "_BaseView": _BaseView,
+ "ToolInstance": _Model(_queryset(workflow_ids, required_filters=("tool_id",))),
+ "APIDeployment": _Model(_queryset([1] if api_deployments else [])),
+ "Pipeline": _Pipeline,
+ "WorkflowEndpoint": _WorkflowEndpoint,
+ "DeploymentType": _DeploymentType,
+ "RegistryToolInUseError": _InUseError,
+ "PromptStudioRegistry": object,
+ "_LOGGED_WORKFLOW_LIMIT": _logged_workflow_limit(),
+ "logger": _SilentLogger(),
+ "Request": object,
+ "Response": object,
+ "Any": Any,
+ }
+ exec(compile(body, str(VIEWS_MODULE), "exec"), namespace)
+ return namespace["_Guard"]()
+
+
+class _Instance:
+ def __init__(self) -> None:
+ self.pk = "tool-1"
+ self.prompt_registry_id = "tool-1"
+
+
+class TestRegistryToolInUseRefusal:
+ """The 409 guard, driven through the real method bodies from ``views.py``.
+
+ These exercise ``_refuse_if_in_use`` itself -- the workflow query, the
+ raise, and the message construction. The previous version restated the
+ predicate as ``bool(ids)``, which passed regardless of what the view did.
+
+ Route binding and permission wiring need a live request cycle (and so a
+ database); ``backend/conftest.py`` auto-marks such tests ``integration``,
+ which runs in the rig's integration tier rather than this PR's unit tier.
+ That boundary is why these stop at the guard.
+ """
+
+ def test_tool_used_by_a_workflow_is_refused(self) -> None:
+ guard = _build_guard(workflow_ids=["wf-1"], api_deployments=True)
+
+ with pytest.raises(_InUseError) as excinfo:
+ guard._refuse_if_in_use(_Instance())
+
+ assert excinfo.value.status_code == 409, (
+ "An in-use tool is a caller-correctable conflict, not a server "
+ "fault; the neighbouring ToolDeleteError's 500 is the wrong model"
+ )
+
+ def test_unused_tool_is_deletable(self) -> None:
+ """No dependants means the guard stands aside -- it is not a blanket ban."""
+ guard = _build_guard(workflow_ids=[])
+
+ assert guard._refuse_if_in_use(_Instance()) is None
+
+ def test_refusal_names_the_blocking_deployment(self) -> None:
+ """The 409 must say *where* the tool is used, or the caller cannot act."""
+ guard = _build_guard(workflow_ids=["wf-1"], api_deployments=True)
+
+ with pytest.raises(_InUseError) as excinfo:
+ guard._refuse_if_in_use(_Instance())
+
+ assert "API Deployment" in excinfo.value.detail
+
+ def test_refusal_names_every_distinct_blocker(self) -> None:
+ guard = _build_guard(
+ workflow_ids=["wf-1", "wf-2"],
+ api_deployments=True,
+ pipeline_types=["ETL"],
+ manual_review=True,
+ )
+
+ with pytest.raises(_InUseError) as excinfo:
+ guard._refuse_if_in_use(_Instance())
+
+ detail = excinfo.value.detail
+ for expected in ("API Deployment", "ETL Pipeline", "Human in the Loop"):
+ assert expected in detail
+
+ def test_two_blockers_are_joined_with_or(self) -> None:
+ """The 2-item branch has its own grammar; assert the whole sentence."""
+ guard = _build_guard(
+ workflow_ids=["wf-1"],
+ api_deployments=True,
+ pipeline_types=["ETL"],
+ )
+
+ with pytest.raises(_InUseError) as excinfo:
+ guard._refuse_if_in_use(_Instance())
+
+ assert excinfo.value.detail == (
+ "This exported tool is still used in API Deployment or ETL Pipeline. "
+ "Remove those usages before deleting it."
+ )
+
+ def test_refusal_falls_back_when_no_deployment_is_identifiable(self) -> None:
+ """A workflow need not be deployed anywhere; the refusal still stands."""
+ guard = _build_guard(workflow_ids=["wf-1"])
+
+ with pytest.raises(_InUseError) as excinfo:
+ guard._refuse_if_in_use(_Instance())
+
+ assert "one or more workflows" in excinfo.value.detail
+
+ def test_in_use_error_is_a_409(self) -> None:
+ """Deleting an in-use tool is a conflict, not a server error.
+
+ The neighbouring ``ToolDeleteError`` is a 500; this must not be modelled
+ on it, since the condition is caller-correctable.
+ """
+ source = (
+ BACKEND_DIR / "prompt_studio" / "prompt_studio_registry_v2" / "exceptions.py"
+ ).read_text()
+
+ assert "class RegistryToolInUseError" in source, (
+ "RegistryToolInUseError is missing; the in-use guard has no way to "
+ "signal a conflict"
+ )
+ body = source[source.index("class RegistryToolInUseError") :]
+ assert "status_code = 409" in body.split("class ")[1], (
+ "RegistryToolInUseError must be a 409 so callers can distinguish a "
+ "correctable conflict from a server fault"
+ )
+
+
+class TestDestroyIsWiredToTheGuard:
+ """``destroy`` must actually *call* the guard.
+
+ Testing ``_refuse_if_in_use`` in isolation left this unpinned: removing
+ the single call from ``destroy`` deleted in-use tools with the whole suite
+ still green. These drive the extracted ``destroy`` body, so the wiring —
+ not just the guard — is what fails when it breaks.
+ """
+
+ @staticmethod
+ def _view(guard: Any, instance: _Instance) -> Any:
+ guard.get_object = lambda: instance
+ return guard
+
+ def test_destroy_refuses_an_in_use_tool_before_deleting(self) -> None:
+ instance = _Instance()
+ guard = self._view(
+ _build_guard(workflow_ids=["wf-1"], api_deployments=True),
+ instance,
+ )
+
+ with pytest.raises(_InUseError) as excinfo:
+ guard.destroy(object())
+
+ assert excinfo.value.status_code == 409
+ assert "API Deployment" in excinfo.value.detail
+
+ def test_destroy_deletes_an_unused_tool(self) -> None:
+ """The guard must not become a blanket ban on deletion."""
+ instance = _Instance()
+ guard = self._view(_build_guard(workflow_ids=[]), instance)
+
+ assert guard.destroy(object()) is DELETED
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/urls.py b/backend/prompt_studio/prompt_studio_registry_v2/urls.py
index b2c303289..86f0760da 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/urls.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/urls.py
@@ -9,6 +9,11 @@ urlpatterns = [
PromptStudioRegistryView.as_view({"get": "list"}),
name="prompt_studio_registry_list",
),
+ path(
+ "registry/<uuid:pk>/",
+ PromptStudioRegistryView.as_view({"delete": "destroy"}),
+ name="prompt_studio_registry_detail",
+ ),
]
# Optional: Apply format suffix patterns
diff --git a/backend/prompt_studio/prompt_studio_registry_v2/views.py b/backend/prompt_studio/prompt_studio_registry_v2/views.py
index 0b4e64e76..92134f803 100644
--- a/backend/prompt_studio/prompt_studio_registry_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_registry_v2/views.py
@@ -1,19 +1,34 @@
+import heapq
import logging
+from typing import Any
from django.db.models import QuerySet
from rest_framework import viewsets
+from rest_framework.request import Request
+from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from utils.filtering import FilterHelper
+from prompt_studio.permission import IsRegistryToolOwner
from prompt_studio.prompt_studio_registry_v2.constants import PromptStudioRegistryKeys
from prompt_studio.prompt_studio_registry_v2.serializers import (
PromptStudioRegistrySerializer,
)
+from prompt_studio.tool_usage import (
+ dependent_workflow_ids,
+ deployment_types_for,
+ join_deployment_types,
+)
+from .exceptions import RegistryToolInUseError
from .models import PromptStudioRegistry
logger = logging.getLogger(__name__)
+# Blocking workflow IDs are logged so an operator can find the rows; capped so
+# a heavily-reused tool cannot emit an unbounded log line.
+_LOGGED_WORKFLOW_LIMIT = 20
+
class PromptStudioRegistryView(viewsets.ModelViewSet):
"""Driver class to handle export and registering of custom tools to private
@@ -23,14 +38,109 @@ class PromptStudioRegistryView(viewsets.ModelViewSet):
versioning_class = URLPathVersioning
serializer_class = PromptStudioRegistrySerializer
- def get_queryset(self) -> QuerySet | None:
+ def get_permissions(self) -> list[Any]:
+ # `list` stays as it was - visibility is already derived by
+ # `list_tools`. Only the destructive detail route is gated.
+ if self.action == "destroy":
+ return [IsRegistryToolOwner()]
+ return super().get_permissions()
+
+ def get_queryset(self) -> QuerySet:
+ # Detail routes address a single row by PK; the list filters below are
+ # query-param driven and would resolve to an empty queryset, so
+ # get_object() could never find the row. Keyed off the URL kwarg rather
+ # than `self.detail`, which DRF only populates for router-generated
+ # views (it is None under as_view()).
+ if self.kwargs.get("pk"):
+ return PromptStudioRegistry.objects.all()
+
filterArgs = FilterHelper.build_filter_args(
self.request,
PromptStudioRegistryKeys.PROMPT_REGISTRY_ID,
"custom_tool",
)
- queryset = None
- if filterArgs:
- queryset = PromptStudioRegistry.objects.filter(**filterArgs)
+ # `none()` rather than None: DRF hands this straight to filter_queryset
+ # and the paginator, neither of which accepts None -- an unfiltered
+ # `list` used to 500 instead of returning nothing.
+ if not filterArgs:
+ return PromptStudioRegistry.objects.none()
+
+ return PromptStudioRegistry.objects.filter(**filterArgs)
+
+ def destroy(
+ self, request: Request, *args: tuple[Any], **kwargs: dict[str, Any]
+ ) -> Response:
+ """Unpublish an exported tool without deleting its Prompt Studio project.
+
+ Deleting the project cascades to its registry entry, but that is a blunt
+ instrument - it gives no way to unpublish a tool while keeping the
+ project. Guarded by the same in-use check `prompt-studio delete`
+ performs, so a tool still attached to a workflow is refused.
+
+ Note that unpublishing is not reversible in place: re-exporting mints a
+ fresh `prompt_registry_id` and does not carry over `shared_to_org` /
+ `shared_users`, so anything holding the old UUID must be updated.
+
+ The dependent workflow IDs are materialised rather than reduced to an
+ `.exists()` -- they are what names the blocking deployments below, which
+ is the difference between an actionable 409 and one the caller cannot
+ act on.
+ """
+ instance: PromptStudioRegistry = self.get_object()
+ self._refuse_if_in_use(instance)
+ return super().destroy(request, *args, **kwargs)
+
+ def _refuse_if_in_use(self, instance: PromptStudioRegistry) -> None:
+ """Raise a 409 naming the blockers when workflows still use ``instance``.
+
+ Split from ``destroy`` so the guard can be exercised without standing
+ up DRF's delete machinery.
+ """
+ dependent_wfs = dependent_workflow_ids(instance.pk)
+ if not dependent_wfs:
+ return
+
+ deployment_types = deployment_types_for(dependent_wfs)
+ # The IDs are what an operator needs to find the blocking rows;
+ # `nsmallest` bounds the work for a pathological fan-out rather than
+ # sorting the whole set just to slice it.
+ blockers = heapq.nsmallest(
+ _LOGGED_WORKFLOW_LIMIT, (str(wf) for wf in dependent_wfs)
+ )
+ # An unresolved deployment type is worth calling out: the deployment
+ # tables are org-scoped while ``ToolInstance`` is not, so an empty set
+ # can mean the dependants sit outside the active org rather than that
+ # the workflows are genuinely undeployed. One line either way.
+ logger.warning(
+ "Cannot delete exported tool %s, depended by %d workflow(s) %s: %s",
+ instance.prompt_registry_id,
+ len(dependent_wfs),
+ sorted(deployment_types) or "(no deployment type resolved)",
+ blockers,
+ )
+ raise RegistryToolInUseError(self._in_use_detail(deployment_types))
- return queryset
+ @staticmethod
+ def _in_use_detail(deployment_types: set) -> str:
+ """Spell out which deployments block the delete, when any are known.
+
+ A tool can be attached to a workflow that is not deployed anywhere, so
+ an empty set is normal and falls back to the generic wording.
+ """
+ types_text = join_deployment_types(deployment_types)
+ if not types_text:
+ # No resolved type has two causes: the workflows are genuinely
+ # undeployed, or they belong to another organization -- the
+ # deployment tables are org-scoped while `ToolInstance` is not.
+ # Say so, rather than directing the user to remove usages they may
+ # have no way to see.
+ return (
+ "This exported tool is still used by one or more workflows. "
+ "Remove those usages before deleting it. If you cannot find "
+ "them, they may belong to another organization -- contact an "
+ "administrator."
+ )
+ return (
+ f"This exported tool is still used in {types_text}. "
+ "Remove those usages before deleting it."
+ )
diff --git a/backend/prompt_studio/tool_usage.py b/backend/prompt_studio/tool_usage.py
new file mode 100644
index 000000000..acebf457e
--- /dev/null
+++ b/backend/prompt_studio/tool_usage.py
@@ -0,0 +1,83 @@
+"""Shared "is this exported tool still in use?" logic.
+
+Two delete paths need the same answer: deleting a Prompt Studio project
+(``prompt_studio_core_v2``) and unpublishing its exported tool
+(``prompt_studio_registry_v2``). Both refuse when a workflow still references
+the registry row, and both want to name *where* it is referenced.
+
+Keeping one copy matters because the set of deployment kinds is open — adding a
+fourth would otherwise leave one caller silently reporting a stale set, telling
+the user to clear usages in the wrong places.
+"""
+
+from api_v2.models import APIDeployment
+from pipeline_v2.models import Pipeline
+from tool_instance_v2.models import ToolInstance
+from workflow_manager.endpoint_v2.models import WorkflowEndpoint
+
+from prompt_studio.prompt_studio_core_v2.constants import DeploymentType
+
+
+def dependent_workflow_ids(registry_pk: str) -> set:
+ """Workflow IDs whose tool instances reference ``registry_pk``.
+
+ An exported tool's ``ToolInstance.tool_id`` is its ``prompt_registry_id``,
+ stored as a plain ``CharField`` rather than a foreign key -- which is why
+ the database cannot enforce this and callers must check explicitly.
+ """
+ return set(
+ ToolInstance.objects.filter(tool_id=registry_pk)
+ .values_list("workflow_id", flat=True)
+ .distinct()
+ )
+
+
+def deployment_types_for(workflow_ids: set) -> set:
+ """Name the deployment kinds reachable from ``workflow_ids``.
+
+ Inactive deployments count: they still reference the tool and would break
+ on re-activation.
+ """
+ deployment_types: set = set()
+ if not workflow_ids:
+ return deployment_types
+
+ if APIDeployment.objects.filter(workflow_id__in=workflow_ids).exists():
+ deployment_types.add(DeploymentType.API_DEPLOYMENT)
+
+ pipeline_type_mapping = {
+ Pipeline.PipelineType.ETL: DeploymentType.ETL_PIPELINE,
+ Pipeline.PipelineType.TASK: DeploymentType.TASK_PIPELINE,
+ }
+ pipeline_types = (
+ Pipeline.objects.filter(workflow_id__in=workflow_ids)
+ .values_list("pipeline_type", flat=True)
+ .distinct()
+ )
+ for pipeline_type in pipeline_types:
+ if pipeline_type in pipeline_type_mapping:
+ deployment_types.add(pipeline_type_mapping[pipeline_type])
+
+ if WorkflowEndpoint.objects.filter(
+ workflow_id__in=workflow_ids,
+ connection_type=WorkflowEndpoint.ConnectionType.MANUALREVIEW,
+ ).exists():
+ deployment_types.add(DeploymentType.HUMAN_QUALITY_REVIEW)
+
+ return deployment_types
+
+
+def join_deployment_types(deployment_types: set) -> str:
+ """Render deployment kinds as an English list ("A", "A or B", "A, B, or C").
+
+ Returns an empty string for an empty set so callers can choose their own
+ fallback wording.
+ """
+ if not deployment_types:
+ return ""
+ types_list = sorted(deployment_types)
+ if len(types_list) == 1:
+ return types_list[0]
+ if len(types_list) == 2:
+ return f"{types_list[0]} or {types_list[1]}"
+ return ", ".join(types_list[:-1]) + f", or {types_list[-1]}"
diff --git a/backend/tests_common/__init__.py b/backend/tests_common/__init__.py
new file mode 100644
index 000000000..93a02246b
--- /dev/null
+++ b/backend/tests_common/__init__.py
@@ -0,0 +1,6 @@
+"""Helpers shared between test modules in different Django apps.
+
+Kept out of any one app because its consumers span several
+(``api_v2``, ``prompt_studio``); ``permissions/tests/base.py`` is the
+app-scoped equivalent for helpers with a single consumer.
+"""
diff --git a/backend/tests_common/source_extraction.py b/backend/tests_common/source_extraction.py
new file mode 100644
index 000000000..f2318b477
--- /dev/null
+++ b/backend/tests_common/source_extraction.py
@@ -0,0 +1,86 @@
+"""Run real method bodies against stubbed collaborators, without the class.
+
+These helpers slice a definition out of its source file and ``exec`` it in a
+namespace of stubs, so assertions run against the shipped body rather than a
+restatement of it that would pass no matter what the real code does.
+
+**Prefer importing the module.** Django settings *are* configured in the unit
+tier (``tests/groups.yaml`` sets ``DJANGO_SETTINGS_MODULE`` for
+``unit-backend``), and ``backend/conftest.py`` auto-marks only ``django_db`` and
+``TestCase`` tests as ``integration`` -- so a plain import plus
+``unittest.mock.patch`` runs per-PR and is the established pattern here (see
+``prompt_studio_core_v2/tests/test_build_index_payload.py``). Reach for these
+helpers only where that genuinely will not do.
+
+**Limitations, because they are not obvious:**
+
+* The extracted body is not bound to its class, the URLconf, or DRF dispatch,
+ so a test using it cannot tell wired code from unreachable code. Pair it with
+ an explicit wiring test (``tests_common/test_route_wiring.py``).
+* Names resolve from the supplied namespace, never from the module's own import
+ block -- a deleted or renamed import is invisible here.
+* Slicing stops at the first ``stops`` needle, so inserting a decorator above a
+ definition silently truncates it and the assertions then cover a *different*
+ body than ships.
+* The marker must match the definition line verbatim, so a cosmetic annotation
+ change breaks the match.
+"""
+
+from __future__ import annotations
+
+import textwrap
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+
+def extract_defs(
+ module: Path, markers: tuple[str, ...], stops: tuple[str, ...]
+) -> list[str]:
+ """Slice each named definition out of ``module``'s source.
+
+ Each marker is the definition's opening line, verbatim; the slice runs to
+ the first ``stops`` needle after it. ``pytest.fail`` on a missing marker
+ rather than skipping: a rename must break loudly, since a silently-skipped
+ guard test is worse than none.
+ """
+ source = module.read_text()
+ parts = []
+ for marker in markers:
+ if marker not in source:
+ pytest.fail(
+ f"Could not find {marker!r} in {module}. If it was renamed or "
+ "inlined, update this test rather than deleting it."
+ )
+ start = source.index(marker)
+ rest = source[start + len(marker) :]
+ end = len(rest)
+ for needle in stops:
+ found = rest.find(needle)
+ if found != -1:
+ end = min(end, found)
+ parts.append(marker + rest[:end])
+ return parts
+
+
+def _line_offset(source: str, marker: str) -> int:
+ """0-based line on which ``marker`` starts."""
+ return source.count("\n", 0, source.index(marker))
+
+
+def exec_def(module: Path, marker: str, stops: tuple[str, ...], namespace: Any) -> Any:
+ """Extract one definition, ``exec`` it in ``namespace``, and hand it back.
+
+ The body is dedented so a method can be executed at module level, which is
+ what lets a view method be driven without standing up the class.
+
+ Blank lines are prepended so the snippet sits at its real line number.
+ ``compile`` is given the true path, so without the padding a traceback
+ would pair a genuine filename with a snippet-relative line -- pointing
+ whoever debugs a failure at whatever unrelated source sits there.
+ """
+ (body,) = extract_defs(module, (marker,), stops)
+ padding = "\n" * _line_offset(module.read_text(), marker)
+ exec(compile(padding + textwrap.dedent(body), str(module), "exec"), namespace)
+ return namespace
diff --git a/backend/tests_common/test_route_wiring.py b/backend/tests_common/test_route_wiring.py
new file mode 100644
index 000000000..0bf55f9a6
--- /dev/null
+++ b/backend/tests_common/test_route_wiring.py
@@ -0,0 +1,201 @@
+"""Pin that the guarded routes this PR adds are actually *wired*.
+
+The behavioural suites for these two features drive method bodies extracted
+from source (``tests_common.source_extraction``), which asserts what a function
+does but not that anything reaches it. That leaves a blind spot the guards
+themselves cannot cover: code present in the file but unreachable in production
+is indistinguishable from code that is dispatched. Deleting the registry DELETE
+route, or unwiring ``IsRegistryToolOwner`` from ``destroy``, both left those
+suites fully green while reopening the exact holes they exist to close.
+
+These tests close that spot from the other side -- they assert the *binding*
+and nothing about behaviour:
+
+* the URLconf maps the expected HTTP verb to the expected action, and
+* the viewset resolves the expected permission class for the destructive action.
+
+They import the real modules rather than extracting source, so a deleted or
+renamed import in either view module fails here at collection time. No database
+is touched: URL resolution and ``get_permissions()`` are pure, so these stay in
+the per-PR unit tier rather than being auto-marked ``integration`` by
+``backend/conftest.py``.
+"""
+
+from __future__ import annotations
+
+import ast
+import builtins
+import inspect
+import sys
+import textwrap
+
+from api_v2.api_key_views import APIKeyViewSet
+from django.urls import resolve, reverse
+from permissions.permission import IsParentDeploymentOwner
+from prompt_studio.permission import IsRegistryToolOwner
+from prompt_studio.prompt_studio_registry_v2.models import PromptStudioRegistry
+from prompt_studio.prompt_studio_registry_v2.views import PromptStudioRegistryView
+from utils.filters.organization_filter import OrganizationFilterBackend, get_org_path
+
+REGISTRY_URLCONF = "prompt_studio.prompt_studio_registry_v2.urls"
+API_URLCONF = "api_v2.urls"
+
+_SAMPLE_UUID = "00000000-0000-0000-0000-000000000001"
+
+
+def _actions(name: str, urlconf: str, **kwargs: str) -> dict[str, str]:
+ """Verb -> action map the URLconf binds for ``name``."""
+ url = reverse(name, kwargs=kwargs, urlconf=urlconf)
+ return resolve(url, urlconf=urlconf).func.actions
+
+
+class TestRegistryDeleteRouteIsWired:
+ """``DELETE registry/<pk>/`` -- the route and its authorization gate."""
+
+ def test_delete_verb_is_bound_to_destroy(self) -> None:
+ """Removing the route entirely left the guard suite green."""
+ assert _actions(
+ "prompt_studio_registry_detail", REGISTRY_URLCONF, pk=_SAMPLE_UUID
+ ) == {"delete": "destroy"}
+
+ def test_destroy_resolves_the_owner_permission(self) -> None:
+ """Unwiring the gate left ``destroy`` open to any org member."""
+ view = PromptStudioRegistryView()
+ view.action = "destroy"
+
+ assert any(
+ isinstance(perm, IsRegistryToolOwner) for perm in view.get_permissions()
+ )
+
+ def test_list_is_not_gated_by_the_owner_permission(self) -> None:
+ """Read visibility is derived by ``list_tools``; only deletes narrow.
+
+ Asserts the *resolution* path ran, not merely that the owner class is
+ absent: an empty permission list would satisfy the negative on its own
+ and prove nothing.
+ """
+ view = PromptStudioRegistryView()
+ view.action = "list"
+
+ permissions = view.get_permissions()
+
+ assert permissions == super(PromptStudioRegistryView, view).get_permissions()
+ assert not any(isinstance(perm, IsRegistryToolOwner) for perm in permissions)
+
+
+class TestRegistryDeleteIsOrganizationScoped:
+ """The detail route resolves rows only within the caller's organization.
+
+ Review flagged ``get_queryset`` returning ``objects.all()`` on the detail
+ route as allowing a caller -- or an org admin -- to delete another
+ organization's exported tool by PK. It does not, and these pin the two
+ facts that make it so, because neither is visible at the call site.
+ """
+
+ def test_registry_rows_have_a_discoverable_organization_path(self) -> None:
+ """``OrganizationFilterBackend`` finds the FK path by BFS.
+
+ Without a path it fails closed to ``none()``, so the delete would 404
+ rather than leak -- but the scoping this route relies on would be
+ gone. Pin the path so a model change surfaces here.
+ """
+ assert get_org_path(PromptStudioRegistry) == "organization"
+
+ def test_the_org_filter_runs_before_the_permission_check(self) -> None:
+ """``get_object()`` filters, *then* object-checks -- ordering matters.
+
+ A foreign-org PK is a 404 from ``get_object_or_404`` before
+ ``IsRegistryToolOwner`` is consulted, so the org-admin branch inside it
+ is never reached for another organization's row.
+ """
+ source = inspect.getsource(PromptStudioRegistryView.get_object)
+
+ assert source.index("filter_queryset") < source.index("check_object_permissions")
+
+ def test_the_viewset_does_not_opt_out_of_org_filtering(self) -> None:
+ """``skip_org_filter``/``filter_backends`` overrides would bypass it."""
+ assert getattr(PromptStudioRegistryView, "skip_org_filter", False) is False
+ assert "filter_backends" not in vars(PromptStudioRegistryView)
+ assert OrganizationFilterBackend in PromptStudioRegistryView().filter_backends
+
+
+class TestApiKeyRoutesAreWired:
+ """``keys/{api,pipeline}/...`` -- the routes whose ``create`` closes an IDOR."""
+
+ def test_api_path_route_binds_post_to_create(self) -> None:
+ """``create`` moved out of the viewset left the create suite green."""
+ assert _actions("api_key_api", API_URLCONF, api_id="api-1")["post"] == "create"
+
+ def test_pipeline_path_route_binds_post_to_create(self) -> None:
+ assert (
+ _actions("api_key_pipeline", API_URLCONF, pipeline_id="pipeline-1")["post"]
+ == "create"
+ )
+
+ def test_body_only_routes_bind_post_to_create(self) -> None:
+ """The body-only routes reach the same guarded ``create``."""
+ assert _actions("api_keys_api", API_URLCONF)["post"] == "create"
+ assert _actions("api_keys_pipeline", API_URLCONF)["post"] == "create"
+
+ def test_create_is_overridden_on_the_viewset(self) -> None:
+ """``create`` must be *this* viewset's, not ``ModelViewSet``'s default.
+
+ ``callable(APIKeyViewSet.create)`` is not enough: the inherited
+ ``CreateModelMixin.create`` satisfies it, so moving the override to a
+ dead class -- reopening the IDOR it closes -- would still pass. Assert
+ the override is defined in the class body itself.
+ """
+ assert "create" in vars(APIKeyViewSet)
+
+ def test_every_global_create_uses_resolves(self) -> None:
+ """A deleted or renamed import 500s ``create`` at request time only.
+
+ ``create`` reaches ``status``/``Response``/``serializers`` on its
+ success path, so a missing import raises ``NameError`` per request
+ rather than at import time -- invisible to a test that merely imports
+ the module. Resolve each global the body loads instead.
+ """
+ module = sys.modules[APIKeyViewSet.__module__]
+ # Parse the override itself rather than walking the module for any
+ # ``create``: a second definition anywhere in the file would otherwise
+ # break this with an unpack error naming nothing about the defect.
+ source = textwrap.dedent(inspect.getsource(vars(APIKeyViewSet)["create"]))
+ (func,) = ast.parse(source).body
+ loaded = {
+ node.id
+ for node in ast.walk(func)
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
+ }
+ local = {"self", "request", "args", "kwargs"} | {
+ node.id
+ for node in ast.walk(func)
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store)
+ }
+
+ unresolved = [
+ name
+ for name in sorted(loaded - local)
+ if not hasattr(module, name) and not hasattr(builtins, name)
+ ]
+ assert not unresolved, f"create() references unimported names: {unresolved}"
+
+ def test_create_object_checks_its_target(self) -> None:
+ """The IDOR fix is ``create`` calling ``check_object_permissions``.
+
+ ``create`` is collection-level, so DRF never calls ``get_object()`` and
+ ``has_object_permission`` never runs on its own. The override must make
+ that call itself, or any org member can mint a key for a deployment
+ they do not own.
+ """
+ source = inspect.getsource(vars(APIKeyViewSet)["create"])
+
+ assert "check_object_permissions" in source
+
+ def test_create_resolves_the_parent_deployment_permission(self) -> None:
+ """``create`` object-checks the target; the class must be resolved for it."""
+ view = APIKeyViewSet()
+ view.action = "create"
+
+ assert any(
+ isinstance(perm, IsParentDeploymentOwner) for perm in view.get_permissions()
+ )