Skip to content

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

UN-3739 [FIX] Prompt Studio owner-access check validates requester, not just profile creator (#2183)

Athul70eebacc1710
diff --git a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
index 4247938ff..ff46d14a3 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/prompt_studio_helper.py
@@ -88,7 +88,6 @@ from unstract.sdk1.utils.tool import ToolUtils
logger = logging.getLogger(__name__)
CHOICES_JSON = "/static/select_choices.json"
-ERROR_MSG = "User %s doesn't have access to adapter %s"
logger = logging.getLogger(__name__)
@@ -205,80 +204,116 @@ class PromptStudioHelper:
@staticmethod
def validate_profile_manager_owner_access(
profile_manager: ProfileManager,
+ request_user: User | None = None,
) -> None:
- """Helper method to validate the owner's access to the profile manager.
+ """Validate adapter access for a profile before using its adapters.
+
+ This is a revocation guard on the profile *creator*, not a
+ requester ACL: users with project access deliberately piggyback on
+ the creator's adapter access. Bypasses (UN-3739): an org-admin
+ requester (implicit access to all adapters); a None creator —
+ profiles whose creating user was deleted, which includes
+ platform-API users removed on key deletion since ``created_by``
+ is SET_NULL; a service-account creator (platform-API profiles
+ hold no adapter shares by design); and an org-admin creator.
Args:
- profile_manager (ProfileManager): The profile manager instance to
- validate.
+ profile_manager: The profile whose adapters will be used.
+ request_user: The user triggering the action. Defaults to None
+ only for the legacy, currently-uncalled ``index_document`` /
+ ``prompt_responder`` chain (UN-3756); all live callers pass
+ a requester.
Raises:
- PermissionError: If the owner does not have permission to perform
- the action.
+ PermissionError: If the profile creator no longer has access to
+ one or more adapters and no bypass applies.
"""
- profile_manager_owner = profile_manager.created_by
- if profile_manager_owner is None:
+ if OrganizationMemberService.is_user_organization_admin(request_user):
return
- if OrganizationMemberService.is_user_organization_admin(profile_manager_owner):
+ owner = profile_manager.created_by
+ if owner is None:
return
- owner = profile_manager_owner
- is_llm_owned = _adapter_accessible_by(profile_manager.llm, owner)
- is_vector_store_owned = _adapter_accessible_by(
- profile_manager.vector_store, owner
- )
- is_embedding_model_owned = _adapter_accessible_by(
- profile_manager.embedding_model, owner
- )
- is_x2text_owned = _adapter_accessible_by(profile_manager.x2text, owner)
+ if getattr(owner, "is_service_account", False):
+ return
- if not (
- is_llm_owned
- and is_vector_store_owned
- and is_embedding_model_owned
- and is_x2text_owned
- ):
- adapter_names = set()
- if not is_llm_owned:
- logger.error(
- ERROR_MSG,
- profile_manager_owner.user_id,
- profile_manager.llm.id,
- )
- adapter_names.add(profile_manager.llm.adapter_name)
- if not is_vector_store_owned:
- logger.error(
- ERROR_MSG,
- profile_manager_owner.user_id,
- profile_manager.vector_store.id,
- )
- adapter_names.add(profile_manager.vector_store.adapter_name)
- if not is_embedding_model_owned:
- logger.error(
- ERROR_MSG,
- profile_manager_owner.user_id,
- profile_manager.embedding_model.id,
- )
- adapter_names.add(profile_manager.embedding_model.adapter_name)
- if not is_x2text_owned:
- logger.error(
- ERROR_MSG,
- profile_manager_owner.user_id,
- profile_manager.x2text.id,
- )
- adapter_names.add(profile_manager.x2text.adapter_name)
- if len(adapter_names) > 1:
- error_msg = (
- f"Multiple permission errors were encountered with {', '.join(adapter_names)}", # noqa: E501
- )
- else:
- error_msg = (
- f"Permission Error: You do not have access to {adapter_names.pop()}", # noqa: E501
- )
+ if OrganizationMemberService.is_user_organization_admin(owner):
+ return
+
+ adapters = [
+ profile_manager.llm,
+ profile_manager.vector_store,
+ profile_manager.embedding_model,
+ profile_manager.x2text,
+ ]
+ # Access = org share, owner/viewer role, or group (UN-2202);
+ # see _adapter_accessible_by.
+ denied = [
+ adapter for adapter in adapters if not _adapter_accessible_by(adapter, owner)
+ ]
+ if not denied:
+ return
+ logger.error(
+ "Adapter access denied for profile '%s': creator %s lacks access"
+ " to adapters %s, requester %s",
+ profile_manager.profile_name,
+ owner.user_id,
+ [str(adapter.id) for adapter in denied],
+ getattr(request_user, "user_id", None),
+ )
+
+ # Third-party identity stays in server logs only — user-facing text
+ # carries no PII.
+ denied_names = ", ".join(
+ dict.fromkeys(adapter.adapter_name for adapter in denied)
+ )
+ if request_user is not None and owner.pk == request_user.pk:
+ # The requester IS the creator — "created by another user"
+ # would be false, and they can be addressed directly.
+ adapter_ref = (
+ f"the adapter '{denied_names}', which you no longer have" f" access to"
+ if len(denied) == 1
+ else f"adapters you no longer have access to: {denied_names}"
+ )
+ error_msg = (
+ f"Permission Error: This project's LLM profile"
+ f" '{profile_manager.profile_name}' uses {adapter_ref}."
+ f" Ask an org admin to re-share access with you or share with"
+ f" everyone, or recreate the profile with adapters you can"
+ f" access."
+ )
raise PermissionError(error_msg)
+ profile_ref = (
+ f"This project's LLM profile '{profile_manager.profile_name}' was"
+ f" created by another user"
+ )
+ if not OrganizationMemberService.get_user_by_id(owner.id):
+ error_msg = (
+ f"Permission Error: {profile_ref} who is no longer a member of"
+ f" this organization. Ask an org admin to recreate the default"
+ f" profile, or to share these adapters with everyone:"
+ f" {denied_names}."
+ )
+ elif len(denied) > 1:
+ error_msg = (
+ f"Permission Error: {profile_ref} who no longer has access to"
+ f" these adapters: {denied_names}. Ask an org admin to re-share"
+ f" them with the profile's creator, share them with everyone,"
+ f" or recreate the profile."
+ )
+ else:
+ error_msg = (
+ f"Permission Error: {profile_ref} who no longer has access to"
+ f" the adapter '{denied_names}'. Ask an org admin to re-share"
+ f" it with the profile's creator, share it with everyone, or"
+ f" recreate the profile."
+ )
+
+ raise PermissionError(error_msg)
+
@staticmethod
def _publish_log(
component: dict[str, str], level: str, state: str, message: str
@@ -317,6 +352,8 @@ class PromptStudioHelper:
stem: str,
extract_file_path: str,
platform_api_key: str,
+ *,
+ request_user: User | None,
) -> tuple[dict[str, Any] | None, str, "ProfileManager"]:
"""Build summarize_params dict if summarization is enabled.
@@ -340,7 +377,9 @@ class PromptStudioHelper:
if summary_profile != default_profile:
PromptStudioHelper.validate_adapter_status(summary_profile)
- PromptStudioHelper.validate_profile_manager_owner_access(summary_profile)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ summary_profile, request_user=request_user
+ )
llm_adapter_id = (
str(tool.summarize_llm_adapter.id)
@@ -483,6 +522,8 @@ class PromptStudioHelper:
user_id: str,
document_id: str,
run_id: str,
+ *,
+ request_user: User | None,
) -> tuple[ExecutionContext, dict[str, Any]]:
"""Build ide_index ExecutionContext for fire-and-forget dispatch.
@@ -504,7 +545,9 @@ class PromptStudioHelper:
raise DefaultProfileError()
PromptStudioHelper.validate_adapter_status(default_profile)
- PromptStudioHelper.validate_profile_manager_owner_access(default_profile)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ default_profile, request_user=request_user
+ )
# Common path decomposition used by extract, summarize, and index
directory, filename = os.path.split(file_path)
@@ -521,6 +564,7 @@ class PromptStudioHelper:
stem,
extract_file_path,
platform_api_key,
+ request_user=request_user,
)
)
@@ -702,6 +746,8 @@ class PromptStudioHelper:
document_id: str,
run_id: str,
profile_manager_id: str | None = None,
+ *,
+ request_user: User | None,
) -> tuple[ExecutionContext | None, dict[str, Any]]:
"""Build answer_prompt ExecutionContext for fire-and-forget dispatch.
@@ -723,7 +769,9 @@ class PromptStudioHelper:
monitor_llm, challenge_llm = PromptStudioHelper._resolve_llm_ids(tool)
PromptStudioHelper.validate_adapter_status(profile_manager)
- PromptStudioHelper.validate_profile_manager_owner_access(profile_manager)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ profile_manager, request_user=request_user
+ )
vector_db = str(profile_manager.vector_store.id)
embedding_model = str(profile_manager.embedding_model.id)
@@ -920,6 +968,8 @@ class PromptStudioHelper:
document_id: str,
run_id: str,
profile_manager_id: str | None = None,
+ *,
+ request_user: User | None,
) -> tuple[ExecutionContext | None, dict[str, Any]]:
"""Build answer_prompt payload for multiple prompts in one task.
@@ -941,7 +991,9 @@ class PromptStudioHelper:
raise DefaultProfileError()
PromptStudioHelper.validate_adapter_status(profile_manager)
- PromptStudioHelper.validate_profile_manager_owner_access(profile_manager)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ profile_manager, request_user=request_user
+ )
monitor_llm, challenge_llm = PromptStudioHelper._resolve_llm_ids(tool)
@@ -1109,6 +1161,8 @@ class PromptStudioHelper:
user_id: str,
document_id: str,
run_id: str,
+ *,
+ request_user: User | None,
) -> tuple[ExecutionContext, dict[str, Any]]:
"""Build single_pass_extraction ExecutionContext.
@@ -1132,7 +1186,9 @@ class PromptStudioHelper:
challenge_llm = str(default_profile.llm.id)
PromptStudioHelper.validate_adapter_status(default_profile)
- PromptStudioHelper.validate_profile_manager_owner_access(default_profile)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ default_profile, request_user=request_user
+ )
default_profile.chunk_size = 0
if prompt_grammar:
@@ -1313,6 +1369,7 @@ class PromptStudioHelper:
user_id: str,
document_id: str,
run_id: str = None,
+ request_user: User | None = None,
) -> Any:
"""Method to index a document.
@@ -1369,12 +1426,16 @@ class PromptStudioHelper:
PromptStudioHelper.validate_adapter_status(default_profile)
# Need to check the user who created profile manager
# has access to adapters configured in profile manager
- PromptStudioHelper.validate_profile_manager_owner_access(default_profile)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ default_profile, request_user=request_user
+ )
# Also validate summary profile if it's different from default
if tool.summarize_context and summary_profile != default_profile:
PromptStudioHelper.validate_adapter_status(summary_profile)
- PromptStudioHelper.validate_profile_manager_owner_access(summary_profile)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ summary_profile, request_user=request_user
+ )
fs_instance = EnvHelper.get_storage(
storage_type=StorageType.PERMANENT,
@@ -1502,6 +1563,7 @@ class PromptStudioHelper:
id: str | None = None,
run_id: str = None,
profile_manager_id: str | None = None,
+ request_user: User | None = None,
) -> Any:
"""Execute chain/single run of the prompts. Makes a call to prompt
service and returns the dict of response.
@@ -1537,6 +1599,7 @@ class PromptStudioHelper:
document_id=document_id,
run_id=run_id,
profile_manager_id=profile_manager_id,
+ request_user=request_user,
)
else:
return PromptStudioHelper._execute_prompts_in_single_pass(
@@ -1546,6 +1609,7 @@ class PromptStudioHelper:
org_id=org_id,
document_id=document_id,
run_id=run_id,
+ request_user=request_user,
)
@staticmethod
@@ -1559,6 +1623,7 @@ class PromptStudioHelper:
document_id,
run_id,
profile_manager_id,
+ request_user: User | None = None,
):
prompt_instance = PromptStudioHelper._fetch_prompt_from_id(id)
@@ -1625,6 +1690,7 @@ class PromptStudioHelper:
run_id=run_id,
profile_manager_id=profile_manager_id,
user_id=user_id,
+ request_user=request_user,
)
return PromptStudioHelper._handle_response(
response=response,
@@ -1664,6 +1730,7 @@ class PromptStudioHelper:
org_id,
document_id,
run_id,
+ request_user: User | None = None,
):
prompts = PromptStudioHelper.fetch_prompt_from_tool(tool_id)
prompts = [
@@ -1694,6 +1761,7 @@ class PromptStudioHelper:
org_id=org_id,
document_id=document_id,
run_id=run_id,
+ request_user=request_user,
)
return PromptStudioHelper._handle_response(
response=response,
@@ -1780,6 +1848,7 @@ class PromptStudioHelper:
run_id: str,
user_id: str,
profile_manager_id: str | None = None,
+ request_user: User | None = None,
) -> Any:
"""Utility function to invoke prompt service. Used internally.
@@ -1833,7 +1902,9 @@ class PromptStudioHelper:
PromptStudioHelper.validate_adapter_status(profile_manager)
# Need to check the user who created profile manager
# has access to adapters
- PromptStudioHelper.validate_profile_manager_owner_access(profile_manager)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ profile_manager, request_user=request_user
+ )
# Not checking reindex here as there might be
# change in Profile Manager
vector_db = str(profile_manager.vector_store.id)
@@ -2214,6 +2285,7 @@ class PromptStudioHelper:
org_id: str,
document_id: str,
run_id: str = None,
+ request_user: User | None = None,
) -> Any:
tool_id: str = str(tool.tool_id)
outputs: list[dict[str, Any]] = []
@@ -2233,7 +2305,9 @@ class PromptStudioHelper:
# Need to check the user who created profile manager
PromptStudioHelper.validate_adapter_status(default_profile)
# has access to adapters configured in profile manager
- PromptStudioHelper.validate_profile_manager_owner_access(default_profile)
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ default_profile, request_user=request_user
+ )
default_profile.chunk_size = 0 # To retrive full context
if prompt_grammar:
for word, synonyms in prompt_grammar.items():
diff --git a/backend/prompt_studio/prompt_studio_core_v2/tests/test_build_index_payload.py b/backend/prompt_studio/prompt_studio_core_v2/tests/test_build_index_payload.py
index d82156b14..234de45e1 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/tests/test_build_index_payload.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/tests/test_build_index_payload.py
@@ -29,6 +29,10 @@ from prompt_studio.prompt_studio_core_v2 import prompt_studio_helper as _psh_mod
PromptStudioHelper = _psh_mod.PromptStudioHelper
IKeys = _psh_mod.IKeys
+# Sentinel requester object handed to build_index_payload by every test —
+# distinct from the file-path ``user_id`` ("user-1") by construction.
+_REQUEST_USER = MagicMock(name="request-user")
+
def _make_tool(enable_highlight: bool = False, summarize_context: bool = False):
tool = MagicMock(name="CustomTool")
@@ -55,6 +59,7 @@ def _dispatch_build(
read_return: str | Exception,
tool: Any = None,
profile: Any = None,
+ validate_owner_mock: Any = None,
):
"""Run ``build_index_payload`` with all collaborators patched.
@@ -69,6 +74,7 @@ def _dispatch_build(
"""
tool = tool or _make_tool()
profile = profile or _make_profile()
+ validate_owner_mock = validate_owner_mock or MagicMock(return_value=None)
fs_instance = MagicMock(name="fs_instance")
if isinstance(read_return, Exception):
@@ -90,14 +96,22 @@ def _dispatch_build(
"get_or_create_prompt_studio_subdirectory",
MagicMock(return_value="/prompt-studio/org/user/tool"),
),
- (_psh_mod.ProfileManager, "get_default_llm_profile", MagicMock(return_value=profile)),
+ (
+ _psh_mod.ProfileManager,
+ "get_default_llm_profile",
+ MagicMock(return_value=profile),
+ ),
(PromptStudioHelper, "validate_adapter_status", MagicMock(return_value=None)),
(
PromptStudioHelper,
"validate_profile_manager_owner_access",
- MagicMock(return_value=None),
+ validate_owner_mock,
+ ),
+ (
+ PromptStudioHelper,
+ "_get_platform_api_key",
+ MagicMock(return_value="pk-test"),
),
- (PromptStudioHelper, "_get_platform_api_key", MagicMock(return_value="pk-test")),
(
PromptStudioHelper,
"_build_summarize_params",
@@ -105,7 +119,11 @@ def _dispatch_build(
),
(_psh_mod.EnvHelper, "get_storage", MagicMock(return_value=fs_instance)),
(_psh_mod.PromptStudioIndexHelper, "check_extraction_status", check_mock),
- (_psh_mod.IndexingUtils, "generate_index_key", MagicMock(return_value="doc-key-1")),
+ (
+ _psh_mod.IndexingUtils,
+ "generate_index_key",
+ MagicMock(return_value="doc-key-1"),
+ ),
(_psh_mod, "PromptIdeBaseTool", MagicMock(return_value=MagicMock())),
(_psh_mod.StateStore, "get", MagicMock(return_value="")),
):
@@ -118,6 +136,7 @@ def _dispatch_build(
user_id="user-1",
document_id="doc-1",
run_id="run-1",
+ request_user=_REQUEST_USER,
)
return context, cb_kwargs, fs_instance, check_mock
@@ -173,3 +192,24 @@ class TestBuildIndexPayloadMarker:
"falling back to full extraction" in rec.getMessage()
for rec in caplog.records
)
+
+
+class TestOwnerAccessPlumbing:
+ """UN-3739: the REQUESTER must reach the owner-access check.
+
+ ``user_id`` in these helpers is the file-path owner (the project
+ creator) — views pass ``tool.created_by.user_id`` there. The
+ requesting user travels separately as the ``request_user`` object;
+ asserting the sentinel arrives pins that the two identities are never
+ conflated again.
+ """
+
+ def test_owner_access_receives_requesting_user(self) -> None:
+ validate_owner_mock = MagicMock(return_value=None)
+ _dispatch_build(
+ check_return=True,
+ read_return="extracted text",
+ validate_owner_mock=validate_owner_mock,
+ )
+ _args, kwargs = validate_owner_mock.call_args
+ assert kwargs.get("request_user") is _REQUEST_USER
diff --git a/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_profile_manager_owner_access.py b/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_profile_manager_owner_access.py
new file mode 100644
index 000000000..086a0d600
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio_core_v2/tests/test_validate_profile_manager_owner_access.py
@@ -0,0 +1,433 @@
+"""Tests for ``PromptStudioHelper.validate_profile_manager_owner_access``.
+
+UN-3739: the check used to validate only the profile *creator*'s adapter
+access — the requesting user was never passed in, so org admins were
+denied on any project whose profile creator lost adapter access (share
+revoked, member offboarded, or profile created by a service account via
+the platform API).
+
+Contract pinned here (evaluation order):
+
+ 1. Requester (a ``User`` object) is an org admin → pass
+ 2. ``created_by`` is None → pass (unchanged)
+ 3. Creator is a service account → pass (platform-API)
+ 4. Creator is an org admin → pass (unchanged)
+ 5. Creator has access to all 4 adapters → pass (delegated use)
+ 6. Otherwise → PermissionError blaming the creator role (never "You"),
+ PII-free, as a plain string.
+
+Unit tests: the real helper module is imported and collaborators are
+patched per-test, so no database is touched.
+"""
+
+from __future__ import annotations
+
+import inspect
+from contextlib import ExitStack
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from prompt_studio.prompt_studio_core_v2 import prompt_studio_helper as _psh_mod
+from prompt_studio.prompt_studio_core_v2.exceptions import (
+ PermissionError as PSPermissionError,
+)
+
+PromptStudioHelper = _psh_mod.PromptStudioHelper
+
+
+def _user(user_id: str, email: str, *, service_account: bool = False) -> MagicMock:
+ user = MagicMock(name=f"user-{user_id}")
+ user.id = f"pk-{user_id}"
+ user.user_id = user_id
+ user.email = email
+ user.is_service_account = service_account
+ return user
+
+
+def _adapter(name: str, owner: MagicMock) -> MagicMock:
+ """Adapter mock for the UN-2202 access model: created_by is audit-only;
+ access flows from owner/viewer membership roles, org share, or groups."""
+ adapter = MagicMock(name=f"adapter-{name}")
+ adapter.adapter_name = name
+ adapter.shared_to_org = False
+ adapter.owner_set = {owner}
+ adapter.viewer_set = set()
+ return adapter
+
+
+def _profile(creator: MagicMock | None, adapter_owner: MagicMock) -> MagicMock:
+ """Profile whose 4 adapters are all owned by ``adapter_owner``."""
+ profile = MagicMock(name="ProfileManager")
+ profile.profile_name = "Default"
+ profile.created_by = creator
+ profile.llm = _adapter("llm-1", adapter_owner)
+ profile.vector_store = _adapter("vdb-1", adapter_owner)
+ profile.embedding_model = _adapter("emb-1", adapter_owner)
+ profile.x2text = _adapter("x2t-1", adapter_owner)
+ return profile
+
+
+def _run_check(
+ profile: MagicMock,
+ *,
+ request_user: MagicMock | None = None,
+ admin_users: tuple[MagicMock, ...] = (),
+ group_access: bool = False,
+ creator_is_member: bool = True,
+) -> None:
+ """Invoke the validator with OrganizationMemberService / group access patched.
+
+ ``admin_users`` are Users for whom ``is_user_organization_admin``
+ returns True.
+ """
+ oms = MagicMock(name="OrganizationMemberService")
+ oms.is_user_organization_admin.side_effect = lambda u: u in admin_users
+ oms.get_user_by_id.return_value = (
+ MagicMock(name="creator-membership") if creator_is_member else None
+ )
+
+ with ExitStack() as stack:
+ stack.enter_context(patch.object(_psh_mod, "OrganizationMemberService", oms))
+ stack.enter_context(
+ patch.object(
+ _psh_mod,
+ "_is_resource_owner",
+ MagicMock(side_effect=lambda user, adapter: user in adapter.owner_set),
+ )
+ )
+ stack.enter_context(
+ patch.object(
+ _psh_mod,
+ "_is_resource_viewer",
+ MagicMock(side_effect=lambda user, adapter: user in adapter.viewer_set),
+ )
+ )
+ stack.enter_context(
+ patch.object(
+ _psh_mod, "has_group_access", MagicMock(return_value=group_access)
+ )
+ )
+ PromptStudioHelper.validate_profile_manager_owner_access(
+ profile, request_user=request_user
+ )
+
+
+class TestRequesterBypass:
+ """Contract case 1: the reported bug (and its case-6 guard)."""
+
+ def test_admin_requester_passes_when_creator_lost_access(self) -> None:
+ """Admin indexing a project whose creator lost adapter access → pass."""
+ admin = _user("admin-1", "[email protected]")
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(creator, adapter_owner=other)
+
+ _run_check(profile, request_user=admin, admin_users=(admin,))
+
+ def test_non_admin_requester_with_lapsed_creator_is_still_blocked(self) -> None:
+ """Contract case 6: the revocation guard must survive the fix."""
+ requester = _user("userc", "[email protected]")
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(creator, adapter_owner=other)
+
+ with pytest.raises(PSPermissionError):
+ _run_check(profile, request_user=requester)
+
+ def test_none_requester_falls_through_to_creator_checks(self) -> None:
+ """Worker paths pass no requester — creator checks still decide."""
+ creator = _user("userb", "[email protected]")
+ profile = _profile(creator, adapter_owner=creator)
+
+ _run_check(profile, request_user=None)
+
+
+class TestCreatorBypasses:
+ def test_service_account_creator_passes(self) -> None:
+ """Contract case 3: platform-API projects referencing others' adapters."""
+ sa_creator = _user("sa-1", "[email protected]", service_account=True)
+ other = _user("userx", "[email protected]")
+ profile = _profile(sa_creator, adapter_owner=other)
+
+ _run_check(profile)
+
+ def test_admin_creator_passes(self) -> None:
+ """Contract case 4: existing behavior kept — creator-admin bypass."""
+ admin_creator = _user("admin-1", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(admin_creator, adapter_owner=other)
+
+ _run_check(profile, admin_users=(admin_creator,))
+
+ def test_none_creator_passes(self) -> None:
+ """Contract case 2: SET_NULL creator skips the check (unchanged)."""
+ other = _user("userx", "[email protected]")
+ profile = _profile(None, adapter_owner=other)
+
+ _run_check(profile)
+
+ def test_creator_with_access_passes_for_any_requester(self) -> None:
+ """Contract case 5: delegated use — creator owns the adapters."""
+ creator = _user("userb", "[email protected]")
+ requester = _user("userc", "[email protected]")
+ profile = _profile(creator, adapter_owner=creator)
+
+ _run_check(profile, request_user=requester)
+
+
+class TestCreatorAccessDisjuncts:
+ """Each non-ownership access path must independently satisfy the guard.
+
+ Review sabotage-check: reducing ``_adapter_accessible_by`` to its
+ owner-role disjunct alone must fail these.
+ """
+
+ def _lapsed_profile(self) -> MagicMock:
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ return _profile(creator, adapter_owner=other)
+
+ def test_org_shared_adapters_pass(self) -> None:
+ profile = self._lapsed_profile()
+ for attr in ("llm", "vector_store", "embedding_model", "x2text"):
+ getattr(profile, attr).shared_to_org = True
+
+ _run_check(profile)
+
+ def test_viewer_shared_adapters_pass(self) -> None:
+ profile = self._lapsed_profile()
+ for attr in ("llm", "vector_store", "embedding_model", "x2text"):
+ getattr(profile, attr).viewer_set.add(profile.created_by)
+
+ _run_check(profile)
+
+ def test_group_shared_adapters_pass(self) -> None:
+ profile = self._lapsed_profile()
+
+ _run_check(profile, group_access=True)
+
+
+class TestDenialMessage:
+ """The message must blame the creator role (never 'You'), carry no PII,
+ and be a plain string.
+
+ Post-fix the only audience for these denials is non-admin
+ collaborators, so the creator's email stays in server logs only.
+ """
+
+ def _denied(self, *, creator_is_member: bool) -> PSPermissionError:
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(creator, adapter_owner=other)
+ # Creator has access to all but the LLM adapter — mirrors the
+ # reported single-adapter denial.
+ for attr in ("vector_store", "embedding_model", "x2text"):
+ getattr(profile, attr).owner_set.add(creator)
+
+ with pytest.raises(PSPermissionError) as exc_info:
+ _run_check(profile, creator_is_member=creator_is_member)
+ return exc_info.value
+
+ def test_message_blames_creator_without_pii(self) -> None:
+ exc = self._denied(creator_is_member=True)
+
+ # A tuple detail (the old ``error_msg = (f"...",)`` bug) becomes a
+ # list in DRF's APIException — detail must stay a plain string.
+ assert isinstance(exc.detail, str), "error detail must be a string"
+ message = str(exc)
+ assert "[email protected]" not in message, "no PII in user-facing errors"
+ assert "created" in message
+ assert "llm-1" in message
+ assert "You do not have access" not in message
+ assert "admin" in message, "remediation must point at an org admin"
+ # Single-denial branch must use singular copy, not the multi branch.
+ assert "the adapter 'llm-1'" in message
+ assert "these adapters" not in message
+
+ def test_message_addresses_creator_requester_directly(self) -> None:
+ """When the requester IS the creator, 'created by another user' is
+ false — the message must speak to them directly (still PII-free)."""
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(creator, adapter_owner=other)
+ for attr in ("vector_store", "embedding_model", "x2text"):
+ getattr(profile, attr).owner_set.add(creator)
+
+ with pytest.raises(PSPermissionError) as exc_info:
+ _run_check(profile, request_user=creator)
+ message = str(exc_info.value)
+
+ assert "another user" not in message, "requester is the creator"
+ assert "you no longer have access" in message
+ assert "llm-1" in message
+ assert "[email protected]" not in message
+
+ def test_message_dedupes_adapter_names(self) -> None:
+ """Adapters of different types can share a name — list it once."""
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(creator, adapter_owner=other)
+ for attr in ("llm", "vector_store", "embedding_model", "x2text"):
+ getattr(profile, attr).adapter_name = "shared-name"
+
+ with pytest.raises(PSPermissionError) as exc_info:
+ _run_check(profile)
+
+ assert str(exc_info.value).count("shared-name") == 1
+
+ def test_message_flags_former_member_creator(self) -> None:
+ """Contract case 6, former-member sub-branch: offboarded creator — say so."""
+ exc = self._denied(creator_is_member=False)
+ message = str(exc)
+
+ assert isinstance(exc.detail, str)
+ assert "[email protected]" not in message
+ assert "no longer a member" in message
+
+ def test_message_lists_all_inaccessible_adapters(self) -> None:
+ creator = _user("userb", "[email protected]")
+ other = _user("userx", "[email protected]")
+ profile = _profile(creator, adapter_owner=other)
+
+ with pytest.raises(PSPermissionError) as exc_info:
+ _run_check(profile)
+ message = str(exc_info.value)
+
+ assert isinstance(exc_info.value.detail, str)
+ for adapter_name in ("llm-1", "vdb-1", "emb-1", "x2t-1"):
+ assert adapter_name in message
+ # Multi-denial branch must use plural copy, not the single branch.
+ assert "these adapters:" in message
+ assert "the adapter '" not in message
+
+
+class TestBuilderSignatures:
+ """``request_user`` must be keyword-only with NO default on the four
+ view-facing builders and the live summarize hop — a dropped plumb must
+ fail loudly (TypeError), never silently revert to pre-fix behavior."""
+
+ @pytest.mark.parametrize(
+ "builder",
+ [
+ PromptStudioHelper.build_index_payload,
+ PromptStudioHelper.build_fetch_response_payload,
+ PromptStudioHelper.build_bulk_fetch_response_payload,
+ PromptStudioHelper.build_single_pass_payload,
+ PromptStudioHelper._build_summarize_params,
+ ],
+ )
+ def test_request_user_is_required_keyword_only(self, builder) -> None:
+ param = inspect.signature(builder).parameters["request_user"]
+ assert param.kind is inspect.Parameter.KEYWORD_ONLY
+ assert param.default is inspect.Parameter.empty
+
+
+class TestSummarizeHopForwarding:
+ """The summarize-profile validation inside ``_build_summarize_params``
+ must receive the requester — it guards a live second validator call."""
+
+ def test_summarize_profile_check_receives_requesting_user(self) -> None:
+ request_user = MagicMock(name="request-user")
+ validator = MagicMock(side_effect=_Forwarded())
+ tool = MagicMock(name="tool")
+ tool.summarize_context = True
+ tool.summarize_llm_adapter = None
+ summary_profile = MagicMock(name="summary-profile")
+
+ with ExitStack() as stack:
+ for target, attr, value in (
+ (
+ _psh_mod.SummarizeMigrationUtils,
+ "migrate_tool_to_adapter_based",
+ MagicMock(),
+ ),
+ (
+ _psh_mod.ProfileManager,
+ "objects",
+ MagicMock(get=MagicMock(return_value=summary_profile)),
+ ),
+ (PromptStudioHelper, "validate_adapter_status", MagicMock()),
+ (
+ PromptStudioHelper,
+ "validate_profile_manager_owner_access",
+ validator,
+ ),
+ ):
+ stack.enter_context(patch.object(target, attr, value))
+ with pytest.raises(_Forwarded):
+ PromptStudioHelper._build_summarize_params(
+ tool,
+ MagicMock(name="default-profile"),
+ "/dir",
+ "stem",
+ "/dir/extract/stem.txt",
+ "pk-test",
+ request_user=request_user,
+ )
+
+ _args, kwargs = validator.call_args
+ assert kwargs.get("request_user") is request_user
+
+
+class _Forwarded(Exception):
+ """Sentinel raised by the patched validator to abort the builder."""
+
+
+class TestBuilderForwarding:
+ """Each builder must hand the requester object to the validator."""
+
+ REQUEST_USER = MagicMock(name="request-user")
+
+ @pytest.mark.parametrize(
+ "builder_name, extra_kwargs_factory",
+ [
+ (
+ "build_fetch_response_payload",
+ lambda: {"prompt": MagicMock(name="prompt")},
+ ),
+ (
+ "build_bulk_fetch_response_payload",
+ lambda: {"prompts": [MagicMock(name="prompt")]},
+ ),
+ (
+ "build_single_pass_payload",
+ lambda: {"prompts": [MagicMock(name="prompt")]},
+ ),
+ ],
+ )
+ def test_builder_forwards_requester(self, builder_name, extra_kwargs_factory) -> None:
+ validator = MagicMock(side_effect=_Forwarded())
+ builder = getattr(PromptStudioHelper, builder_name)
+ call_kwargs = {
+ "tool": MagicMock(name="tool"),
+ "doc_path": "/doc",
+ "doc_name": "doc.pdf",
+ "org_id": "org-1",
+ "user_id": "owner-1",
+ "document_id": "doc-1",
+ "run_id": "run-1",
+ "request_user": self.REQUEST_USER,
+ **extra_kwargs_factory(),
+ }
+ with ExitStack() as stack:
+ for target, attr, value in (
+ (
+ _psh_mod.ProfileManager,
+ "get_default_llm_profile",
+ MagicMock(return_value=MagicMock(name="profile")),
+ ),
+ (
+ PromptStudioHelper,
+ "_resolve_llm_ids",
+ MagicMock(return_value=("m", "c")),
+ ),
+ (PromptStudioHelper, "validate_adapter_status", MagicMock()),
+ (PromptStudioHelper, "validate_profile_manager_owner_access", validator),
+ ):
+ stack.enter_context(patch.object(target, attr, value))
+ with pytest.raises(_Forwarded):
+ builder(**call_kwargs)
+
+ _args, kwargs = validator.call_args
+ assert kwargs.get("request_user") is self.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 45a0c423b..2443aecb4 100644
--- a/backend/prompt_studio/prompt_studio_core_v2/views.py
+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py
@@ -466,9 +466,12 @@ class PromptStudioCoreView(
tool_id=str(tool.tool_id),
file_name=file_name,
org_id=UserSessionUtils.get_organization_id(request),
+ # user_id is the file-path owner (project creator);
+ # request_user is who triggered the action (UN-3739)
user_id=tool.created_by.user_id,
document_id=document_id,
run_id=run_id,
+ request_user=request.user,
)
dispatcher = PromptStudioHelper._get_dispatcher()
@@ -627,6 +630,7 @@ class PromptStudioCoreView(
document_id=document_id,
run_id=run_id,
profile_manager_id=profile_manager_id,
+ request_user=request.user,
)
# If document is being indexed, return pending status
@@ -739,6 +743,7 @@ class PromptStudioCoreView(
document_id=document_id,
run_id=run_id,
profile_manager_id=profile_manager_id,
+ request_user=request.user,
)
if context is None:
@@ -845,6 +850,7 @@ class PromptStudioCoreView(
user_id=user_id,
document_id=document_id,
run_id=run_id,
+ request_user=request.user,
)
dispatcher = PromptStudioHelper._get_dispatcher()