AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): require library membership AND marketplace submission for graph access (#14205)
Reinier van der Leera3c5b17ec2ae
diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.pyindex c3e6b2d3f6..0e11372b01 100644--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes.py@@ -164,8 +164,8 @@ async def admin_add_agent_to_library(Add a pending marketplace agent to the admin's library for review.Uses admin-level access to bypass marketplace APPROVED-only checks.- The builder can load the graph because get_graph() checks library- membership as a fallback: "you added it, you keep it."+ The builder can then load the graph: get_graph() grants a library+ version that was submitted, and PENDING counts as submitted."""return await library_db.add_store_agent_to_library_as_admin(store_listing_version_id=store_listing_version_id,diff --git a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.pyindex 8b3e057298..972a072db1 100644--- a/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/admin/store_admin_routes_test.py@@ -16,8 +16,9 @@ import fastapi.testclientimport pytestimport pytest_mockfrom autogpt_libs.auth.jwt_utils import get_jwt_payload+from prisma.enums import SubmissionStatus-from backend.data.graph import get_graph_as_admin+from backend.data.graph import get_graph, get_graph_as_adminfrom backend.util.exceptions import NotFoundErrorfrom .store_admin_routes import router as store_admin_router@@ -295,8 +296,13 @@ async def test_resolve_graph_regular_uses_get_graph() -> None:assert result is mock_graph_modelassert resolved_slv is mock_slv+ # `skip_access_check` is required: the agent isn't in the user's library+ # yet, so get_graph() would deny the install it is being called for.mock_regular.assert_awaited_once_with(- graph_id=GRAPH_ID, version=GRAPH_VERSION, user_id="regular-user-id"+ graph_id=GRAPH_ID,+ version=GRAPH_VERSION,+ user_id="regular-user-id",+ skip_access_check=True,)mock_admin.assert_not_awaited()mock_prisma.return_value.find_first.assert_awaited_once()@@ -308,7 +314,9 @@ async def test_resolve_graph_regular_uses_get_graph() -> None:@pytest.mark.asyncioasync def test_library_member_can_view_pending_agent_in_builder() -> None:"""After adding a pending agent to their library, the user should be- able to load the graph in the builder via get_graph()."""+ able to load the graph in the builder via get_graph(). This is why+ PENDING counts as submitted — requiring APPROVED would break review.+ """mock_graph = _make_mock_graph()mock_graph_model = MagicMock(name="GraphModel")mock_library_agent = MagicMock()@@ -316,9 +324,6 @@ async def test_library_member_can_view_pending_agent_in_builder() -> None:with (patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,patch("backend.data.graph.GraphModel.from_db",@@ -326,13 +331,10 @@ async def test_library_member_can_view_pending_agent_in_builder() -> None:),):mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)mock_lib_prisma.return_value.find_first = AsyncMock(return_value=mock_library_agent)- from backend.data.graph import get_graph-result = await get_graph(graph_id=GRAPH_ID,version=GRAPH_VERSION,@@ -340,3 +342,11 @@ async def test_library_member_can_view_pending_agent_in_builder() -> None:)assert result is mock_graph_model, "Library membership should grant graph access"+ # Review would break if PENDING were not an accepted status.+ lib_where = mock_lib_prisma.return_value.find_first.await_args.kwargs["where"]+ statuses = set(+ lib_where["AgentGraph"]["is"]["StoreListingVersions"]["some"][+ "submissionStatus"+ ]["in"]+ )+ assert SubmissionStatus.PENDING in statusesdiff --git a/autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.py b/autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.pyindex 845186fee8..aa5bf6b5d9 100644--- a/autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.py+++ b/autogpt_platform/backend/backend/api/features/executions/review/review_routes_test.py@@ -716,7 +716,7 @@ async def test_process_review_action_auto_approve_creates_auto_approval_records(# Verify get_graph_settings was called with correct parametersmock_get_settings.assert_called_once_with(- user_id=test_user_id, graph_id="test_graph_789"+ user_id=test_user_id, graph_id="test_graph_789", graph_version=1)# Verify add_graph_execution was called with proper ExecutionContextdiff --git a/autogpt_platform/backend/backend/api/features/executions/review/routes.py b/autogpt_platform/backend/backend/api/features/executions/review/routes.pyindex fd0ff2a259..76152eaafc 100644--- a/autogpt_platform/backend/backend/api/features/executions/review/routes.py+++ b/autogpt_platform/backend/backend/api/features/executions/review/routes.py@@ -333,7 +333,9 @@ async def process_review_action(try:user = await get_user_by_id(user_id)settings = await get_graph_settings(- user_id=user_id, graph_id=first_review.graph_id+ user_id=user_id,+ graph_id=first_review.graph_id,+ graph_version=first_review.graph_version,)user_timezone = (diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex 199911b3db..2f27c65f94 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -77,6 +77,7 @@ from backend.integrations.providers import ProviderName, provider_keyfrom backend.integrations.webhooks import get_webhook_managerfrom backend.util.exceptions import (ExpertRunPausedError,+ GraphNotAccessibleError,GraphNotInLibraryError,MissingConfigError,NeedConfirmation,@@ -1250,14 +1251,20 @@ async def _execute_webhook_preset_trigger()return+ # Read-authorization must not decide this: `None` would then also mean+ # "not allowed to read", and the write below would silently kill a live+ # trigger. add_graph_execution() is the authorization gate for this path.graph = await get_graph(- preset.graph_id, preset.graph_version, user_id=webhook.user_id+ preset.graph_id,+ preset.graph_version,+ user_id=webhook.user_id,+ skip_access_check=True,)if not graph:logger.error(f"User #{webhook.user_id} has preset #{preset.id} for graph "f"#{preset.graph_id} v{preset.graph_version}, "- "but no access to the graph itself."+ "but the graph version does not exist.")logger.info(f"Automatically deactivating broken preset #{preset.id}")await update_preset(preset.user_id, preset.id, is_active=False)@@ -1308,12 +1315,20 @@ async def _execute_webhook_preset_trigger(except GraphNotInLibraryError as e:logger.warning(f"Webhook #{webhook_id} execution blocked for "- f"deleted/archived graph #{preset.graph_id} (preset #{preset.id}): {e}"+ f"deleted graph #{preset.graph_id} (preset #{preset.id}): {e}")# Clean up orphaned webhook trigger for this graphawait _cleanup_orphaned_webhook_for_graph(preset.graph_id, webhook.user_id, webhook_id)+ except GraphNotAccessibleError as e:+ # Permanent, unlike the transient failures below: every future+ # delivery fails the same way while the preset still reads as Active.+ logger.error(+ f"Webhook #{webhook_id} preset #{preset.id} is permanently blocked: "+ f"user #{webhook.user_id} may not execute graph "+ f"#{preset.graph_id} v{preset.graph_version}: {e}"+ )except Exception:logger.exception(f"Failed to execute preset #{preset.id} via webhook #{webhook_id}"diff --git a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.pyindex b05da8f111..e5e02b9de6 100644--- a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py@@ -582,6 +582,44 @@ async def test_preset_trigger_refuses_foreign_owner(mocker):add_exec.assert_not_awaited()+async def test_preset_trigger_deactivates_only_when_the_graph_version_is_gone(mocker):+ """The graph read here locates the webhook input node; authorization to run+ happens in add_graph_execution. Without `skip_access_check` a read denial+ also reads as `None` and permanently disables a live trigger, which is a+ one-way write the user has to undo by hand.+ """+ from backend.api.features.integrations import router as ingress_router++ mocker.patch.object(ingress_router, "add_graph_execution", new_callable=AsyncMock)+ update = mocker.patch.object(+ ingress_router, "update_preset", new_callable=AsyncMock+ )+ get_graph = mocker.patch.object(+ ingress_router,+ "get_graph",+ new_callable=AsyncMock,+ return_value=_make_trigger_graph(),+ )+ preset = _make_expert_preset()+ preset.expert_id = None+ webhook = _make_webhook(ProviderName.GITHUB)++ await ingress_router._execute_webhook_preset_trigger(+ preset, webhook, WEBHOOK_ID, "pull_request", {}+ )++ assert get_graph.await_args.kwargs["skip_access_check"] is True+ update.assert_not_awaited()++ # Only a genuinely missing graph version disables the preset.+ get_graph.return_value = None+ await ingress_router._execute_webhook_preset_trigger(+ preset, webhook, WEBHOOK_ID, "pull_request", {}+ )++ update.assert_awaited_once_with(preset.user_id, preset.id, is_active=False)++def _make_expert_preset(*,organization_id: str | None = "personal-org",@@ -691,6 +729,7 @@ async def test_expert_preset_trigger_uses_current_tenancy_after_conversion(get_graph.assert_awaited_once()add_exec.assert_awaited_once()assert add_exec.await_args.kwargs["organization_id"] == "personal-org"+ assert get_graph.await_args.kwargs["skip_access_check"] is Trueassert add_exec.await_args.kwargs["team_id"] == "personal-team"assert add_exec.await_args.kwargs["expert_id"] == "expert-1"diff --git a/autogpt_platform/backend/backend/api/features/library/_add_to_library.py b/autogpt_platform/backend/backend/api/features/library/_add_to_library.pyindex 437285b351..9cc635175f 100644--- a/autogpt_platform/backend/backend/api/features/library/_add_to_library.py+++ b/autogpt_platform/backend/backend/api/features/library/_add_to_library.py@@ -75,7 +75,11 @@ async def resolve_graph_model_for_library(*,admin: bool,) -> GraphModel:- """Resolve the graph for an already-validated marketplace version."""+ """Resolve the graph for an already-validated marketplace version.++ `skip_access_check`: the agent isn't in the user's library yet, so+ `get_graph()` would deny; `resolve_store_version_for_library()` authorized.+ """ag = _require_graph(store_listing_version)graph_model = (@@ -84,7 +88,10 @@ async def resolve_graph_model_for_library()if adminelse await graph_db.get_graph(- graph_id=ag.id, version=ag.version, user_id=user_id+ graph_id=ag.id,+ version=ag.version,+ user_id=user_id,+ skip_access_check=True,))if not graph_model:diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex ea51bd43b9..7081f2d013 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -2068,8 +2068,8 @@ async def create_preset(logger.debug(f"Creating preset ({repr(preset.name)}) for user #{user_id}",)- # A preset may only reference a graph the caller can access (own / store /- # library); get_graph() enforces that and a foreign/unknown graph is None.+ # A preset may only reference a graph the caller can access (owned, or in+ # their library and submitted); get_graph() enforces that, None if not.# The preset then inherits the graph's org/team (resource-follows-parent),# resolved here so callers can't forget it.graph = await graph_db.get_graph(diff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.pyindex c9451835c6..c22b608b81 100644--- a/autogpt_platform/backend/backend/api/features/store/db.py+++ b/autogpt_platform/backend/backend/api/features/store/db.py@@ -27,6 +27,7 @@ from . import exceptions as store_exceptionsfrom . import model as store_modelfrom .embeddings import ensure_embeddingfrom .hybrid_search import hybrid_search+from .store_listing_versions import installable_store_version_wherelogger = logging.getLogger(__name__)settings = Settings()@@ -1401,9 +1402,16 @@ async def get_my_agents(async def get_agent(store_listing_version_id: str) -> GraphModel:- """Get agent using the version ID and store listing version ID."""- slv = await prisma.models.StoreListingVersion.prisma().find_unique(- where={"id": store_listing_version_id}+ """Get the graph behind a store listing version, for public download.++ Unauthenticated endpoint: the installable-listing check below *is* the+ authorization, so `get_graph()` is told to skip its own (it would deny).+ """+ slv = await prisma.models.StoreListingVersion.prisma().find_first(+ where={+ "id": store_listing_version_id,+ **installable_store_version_where(),+ })if not slv:@@ -1416,6 +1424,7 @@ async def get_agent(store_listing_version_id: str) -> GraphModel:version=slv.agentGraphVersion,user_id=None,for_export=True,+ skip_access_check=True,)if not graph:raise NotFoundError(diff --git a/autogpt_platform/backend/backend/api/features/store/db_test.py b/autogpt_platform/backend/backend/api/features/store/db_test.pyindex a36327f3a9..9829f8d373 100644--- a/autogpt_platform/backend/backend/api/features/store/db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py@@ -7,6 +7,8 @@ import prisma.modelsimport pytestfrom prisma import Prisma+from backend.util.exceptions import NotFoundError+from . import dbfrom .model import MyAgentsSortBy, Profile, SubmissionStats@@ -1133,3 +1135,61 @@ async def test_get_store_submissions_without_org_strict_ownership(mocker):where = mock_client.find_many.call_args.kwargs["where"]assert where["user_id"] == "user-1"assert "AND" not in where+++# ---- Public agent download: the listing version is the authorization ---- #++[email protected](loop_scope="session")+async def test_get_agent_requires_installable_listing_version(mocker):+ """`get_agent()` serves the unauthenticated download endpoint, so it must+ gate on the listing version being publicly installable — APPROVED, not+ deleted, available, on a listing that still exists."""+ mock_client = AsyncMock()+ mock_client.find_first.return_value = None+ mocker.patch.object(+ prisma.models.StoreListingVersion, "prisma", return_value=mock_client+ )+ mock_get_graph = mocker.patch.object(db, "get_graph", new_callable=AsyncMock)++ with pytest.raises(NotFoundError):+ await db.get_agent("version123")++ where = mock_client.find_first.call_args.kwargs["where"]+ assert where["id"] == "version123"+ assert where["submissionStatus"] == prisma.enums.SubmissionStatus.APPROVED+ assert where["isDeleted"] is False+ assert where["isAvailable"] is True+ assert where["StoreListing"] == {"is": {"isDeleted": False}}+ # A non-installable version must never reach the graph.+ mock_get_graph.assert_not_awaited()++[email protected](loop_scope="session")+async def test_get_agent_skips_graph_access_check(mocker):+ """The caller is anonymous, so `get_graph()` would deny — `get_agent()`+ authorizes against the listing instead and passes `skip_access_check`."""+ mock_slv = mocker.Mock()+ mock_slv.agentGraphId = "graph-1"+ mock_slv.agentGraphVersion = 3++ mock_client = AsyncMock()+ mock_client.find_first.return_value = mock_slv+ mocker.patch.object(+ prisma.models.StoreListingVersion, "prisma", return_value=mock_client+ )+ mock_graph = mocker.Mock()+ mock_get_graph = mocker.patch.object(+ db, "get_graph", new_callable=AsyncMock, return_value=mock_graph+ )++ result = await db.get_agent("version123")++ assert result is mock_graph+ mock_get_graph.assert_awaited_once_with(+ graph_id="graph-1",+ version=3,+ user_id=None,+ for_export=True,+ skip_access_check=True,+ )diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex b94231ed3e..72faee0dfa 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -3,7 +3,7 @@ import loggingimport uuidfrom collections import defaultdictfrom datetime import datetime, timezone-from typing import TYPE_CHECKING, Annotated, Any, Literal, Optional, Self, cast+from typing import TYPE_CHECKING, Annotated, Any, Final, Literal, Optional, Self, castfrom prisma.enums import SubmissionStatusfrom prisma.models import (@@ -18,7 +18,7 @@ from prisma.types import (AgentGraphWhereInput,AgentNodeCreateInput,AgentNodeLinkCreateInput,- StoreListingVersionWhereInput,+ LibraryAgentWhereInput,)from pydantic import BaseModel, BeforeValidator, Fieldfrom pydantic.fields import computed_field@@ -1341,14 +1341,22 @@ async def get_graph(Retrieves a graph from the DB.Defaults to the version with `is_active` if `version` is not passed.+ Access: the caller owns it, or has that exact version in their library+ AND that version was submitted to the marketplace. Neither half of the+ latter suffices alone.+With ``organization_id`` (from a membership-verified RequestContext),org/team visibility rules apply — a member can open any graph thelist endpoints show them (own + org-home + member-team graphs).- See also: `get_graph_as_admin()` which bypasses ownership and marketplace- checks for admin-only routes.+ ``skip_access_check=True`` is for callers that authorized the read+ themselves: the executor, and the marketplace install/download paths,+ which validate the StoreListingVersion instead.- Returns `None` if the record is not found.+ See also: `get_graph_as_admin()`, which bypasses this check entirely for+ admin-only routes.++ Returns `None` if the record is not found or not accessible."""graph = None@@ -1381,38 +1389,13 @@ async def get_graph(order={"version": "desc"},)- # Use store listed graph to find not owned graph- if graph is None:- store_where_clause: StoreListingVersionWhereInput = {- "agentGraphId": graph_id,- "submissionStatus": SubmissionStatus.APPROVED,- "isDeleted": False,- }- if version is not None:- store_where_clause["agentGraphVersion"] = version-- if store_listing := await StoreListingVersion.prisma().find_first(- where=store_where_clause,- order={"agentGraphVersion": "desc"},- include={"AgentGraph": {"include": AGENT_GRAPH_INCLUDE}},- ):- graph = store_listing.AgentGraph-- # Fall back to library membership: if the user has the agent in their- # library (non-deleted, non-archived), grant access even if the agent is- # no longer published. "You added it, you keep it."- if graph is None and user_id is not None:- library_where: dict[str, object] = {- "userId": user_id,- "agentGraphId": graph_id,- "isDeleted": False,- "isArchived": False,- }- if version is not None:- library_where["agentGraphVersion"] = version-+ # The only non-owner path. A store listing on its own must not grant+ # access, so there is deliberately no marketplace lookup beside this one.+ # validate_graph_execution_permissions() reuses this same filter, so+ # execute can never be looser than read. See the invariant note there.+ if graph is None and user_id is not None and not skip_access_check:library_agent = await LibraryAgent.prisma().find_first(- where=library_where,+ where=graph_in_library_filter(user_id, graph_id, version),include={"AgentGraph": {"include": AGENT_GRAPH_INCLUDE}},order={"agentGraphVersion": "desc"},)@@ -1433,11 +1416,55 @@ async def get_graph(return GraphModel.from_db(graph, for_export)+# PENDING is included so admin review can open a not-yet-approved submission+# from the reviewer's library. A deleted listing still counts as once-submitted.+SUBMITTED_TO_MARKETPLACE: Final = (+ SubmissionStatus.PENDING,+ SubmissionStatus.APPROVED,+ SubmissionStatus.REJECTED,+)+_SUBMITTED_STATUSES: Final = list(SUBMITTED_TO_MARKETPLACE)+++def graph_in_library_filter(+ user_id: str, graph_id: str, version: int | None+) -> LibraryAgentWhereInput:+ """Non-owner read access: version in the user's library AND submitted.++ One joined query, not two: `AgentGraph` here is the exact `(id, version)`+ pair, so separate queries could match the library row and the submission+ on different versions when `version is None`.+ """+ where: LibraryAgentWhereInput = {+ "userId": user_id,+ "agentGraphId": graph_id,+ # Archiving hides an agent, it does not revoke it; isDeleted is the+ # membership signal.+ "isDeleted": False,+ "AgentGraph": {+ "is": {+ "StoreListingVersions": {+ # agentGraphId is redundant -- the relation already pins+ # (id, version) -- but it gives the subquery an indexed+ # predicate instead of a scan over every listing version.+ "some": {+ "agentGraphId": graph_id,+ "submissionStatus": {"in": _SUBMITTED_STATUSES},+ }+ }+ }+ },+ }+ if version is not None:+ where["agentGraphVersion"] = version+ return where++async def get_store_listed_graphs(graph_ids: list[str]) -> dict[str, GraphModel]:"""Batch-fetch multiple store-listed graphs by their IDs.- Only returns graphs that have approved store listings (publicly available).- Does not require permission checks since store-listed graphs are public.+ The APPROVED-listing filter below *is* the authorization: an approved+ listing is public, so no per-caller permission check is applied.Args:graph_ids: List of graph IDs to fetch@@ -1651,16 +1678,37 @@ async def delete_graph(return entries_count-async def get_graph_settings(user_id: str, graph_id: str) -> GraphSettings:- lib = await LibraryAgent.prisma().find_first(- where={- "userId": user_id,- "agentGraphId": graph_id,- "isDeleted": False,- "isArchived": False,- },- order={"agentGraphVersion": "desc"},- )+async def get_graph_settings(+ user_id: str, graph_id: str, graph_version: int | None = None+) -> GraphSettings:+ """Settings of the library entry for the version being run.++ Falls back to the user's other live entries when that version has none,+ which is how an owner running a version they never added to their library+ still gets their own safe-mode settings instead of the defaults.+ """+ # Archived entries stay eligible -- an archived agent still runs -- but the+ # running version's own entry wins, so a hidden version can never turn the+ # user's sensitive_action_safe_mode back off.+ lib = None+ if graph_version is not None:+ lib = await LibraryAgent.prisma().find_first(+ where={+ "userId": user_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": graph_version,+ "isDeleted": False,+ },+ )+ if lib is None:+ lib = await LibraryAgent.prisma().find_first(+ where={+ "userId": user_id,+ "agentGraphId": graph_id,+ "isDeleted": False,+ },+ order=[{"isArchived": "asc"}, {"agentGraphVersion": "desc"}],+ )if not lib or not lib.settings:return GraphSettings()@@ -1684,10 +1732,12 @@ async def validate_graph_execution_permissions(## LogicA user can execute a graph if any of these is true:- 1. They own the graph and some version of it is still listed in their library- 2. The graph is in the user's library (non-deleted, non-archived)- 3. The graph is published in the marketplace and listed in their library- 4. The graph is published in the marketplace and is being executed as a sub-agent+ 1. They own the graph and some version of it is still in their library+ 2. They can *read* the exact version -- it is in their library and that+ version was submitted to the marketplace (`graph_in_library_filter()`)+ 3. It is published in the marketplace and is executed as a sub-agent.+ This is the only case where execute is allowed without read; see+ SECRT-1125 and the INVARIANT comment in the body below.Args:graph_id: The ID of the graph to check@@ -1698,20 +1748,26 @@ async def validate_graph_execution_permissions(Raises:GraphNotAccessibleError: If the graph is not accessible to the user.- GraphNotInLibraryError: If the graph is not in the user's library (deleted/archived).+ GraphNotInLibraryError: If the graph is not in the user's library (deleted).NotAuthorizedError: If the user lacks execution permissions for other reasons"""- graph, library_agent = await asyncio.gather(+ graph, library_agent, any_live_library_entry = await asyncio.gather(AgentGraph.prisma().find_unique(where={"graphVersionId": {"id": graph_id, "version": graph_version}}),+ # The read gate's own predicate, reused rather than restated, so the+ # two can't drift apart.+ LibraryAgent.prisma().find_first(+ where=graph_in_library_filter(user_id, graph_id, graph_version)+ ),+ # Only the owner branch reads this, but an owner running their own+ # unpublished agent never matches the filter above, so fetching it+ # here keeps the common case at one round trip instead of two.LibraryAgent.prisma().find_first(where={"userId": user_id,"agentGraphId": graph_id,- "agentGraphVersion": graph_version,"isDeleted": False,- "isArchived": False,}),)@@ -1719,42 +1775,36 @@ async def validate_graph_execution_permissions(# Step 1: Check if user owns this graphuser_owns_graph = graph and graph.userId == user_id- # Step 2: Check if the exact graph version is in the library.- user_has_in_library = library_agent is not None- owner_has_live_library_entry = user_has_in_library- if user_owns_graph and not user_has_in_library:- # Owners are allowed to execute a new version as long as some live- # library entry still exists for the graph. Non-owners stay- # version-specific.- owner_has_live_library_entry = (- await LibraryAgent.prisma().find_first(- where={- "userId": user_id,- "agentGraphId": graph_id,- "isDeleted": False,- "isArchived": False,- }- )- is not None- )+ # Step 2: Check if the exact graph version is readable from the library.+ version_readable_from_library = library_agent is not None+ # Owners may execute a new version while some live entry for the graph+ # remains; non-owners stay version-specific.+ owner_has_live_library_entry = version_readable_from_library or (+ bool(user_owns_graph) and any_live_library_entry is not None+ )# Step 3: Apply permission logic- # Access is granted if the user owns it, it's in the marketplace, OR- # it's in the user's library ("you added it, you keep it").+ # INVARIANT: execution must never be more permissive than read access+ # (`get_graph()` / `graph_in_library_filter()`). The one sanctioned+ # exception is SECRT-1125: a non-owner may EXECUTE a marketplace-listed+ # graph they are denied read of, because the graph -- and its run's+ # intermediate outputs -- would let them reconstruct a non-public graph.if not (user_owns_graph- or user_has_in_library+ or version_readable_from_libraryor await is_graph_published_in_marketplace(graph_id, graph_version)):raise GraphNotAccessibleError(f"You do not have access to graph #{graph_id} v{graph_version}: "- "it is not owned by you, not in your library, "- "and not available in the Marketplace"+ "it is not owned by you, not in your library as a submitted "+ "version, and not available in the Marketplace")- elif not (user_has_in_library or owner_has_live_library_entry or is_sub_graph):+ elif not (+ version_readable_from_library or owner_has_live_library_entry or is_sub_graph+ ):raise GraphNotInLibraryError(f"Graph #{graph_id} is not in your library")- # Step 6: Check execution-specific permissions (raises generic NotAuthorizedError)+ # Step 4: Check execution-specific permissions (raises generic NotAuthorizedError)# Additional authorization checks beyond the above:# 1. Check if user has execution credits (future)# 2. Check if graph is suspended/disabled (future)diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.pyindex 29c7f47301..d55787b1e4 100644--- a/autogpt_platform/backend/backend/data/graph_test.py+++ b/autogpt_platform/backend/backend/data/graph_test.py@@ -1,13 +1,16 @@import jsonfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch-from uuid import UUID+from uuid import UUID, uuid4import fastapi.exceptionsimport prismaimport pytest+from prisma.enums import SubmissionStatus+from prisma.models import AgentGraph, LibraryAgent, Userfrom pytest_snapshot.plugin import Snapshot+import backend.api.features.library.db as library_dbimport backend.api.features.store.model as storefrom backend.api.model import CreateGraphfrom backend.blocks._base import BlockSchema, BlockSchemaInput@@ -17,12 +20,15 @@ from backend.blocks.code_executor import ExecuteCodeBlockfrom backend.blocks.io import AgentInputBlock, AgentOutputBlockfrom backend.blocks.llm import LEGACY_MODEL_MAPPINGS, LLMModelfrom backend.data.graph import (+ SUBMITTED_TO_MARKETPLACE,Graph,GraphModel,Link,Node,NodeModel,get_graph,+ get_graph_settings,+ graph_in_library_filter,migrate_llm_models,validate_graph_execution_permissions,)@@ -30,6 +36,7 @@ from backend.data.model import SchemaFieldfrom backend.data.user import DEFAULT_USER_IDfrom backend.usecases.sample import create_test_userfrom backend.util.exceptions import GraphNotAccessibleError, GraphNotInLibraryError+from backend.util.json import SafeJsonfrom backend.util.test import SpinTestServer@@ -405,12 +412,13 @@ async def test_access_store_listing_graph(server: SpinTestServer):categories=[],)- # First we check the graph an not be accessed by a different user+ # First we check the graph can not be accessed by a different user+ other_user = await create_test_user(alt_user=True)with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:await server.agent_server.test_get_graph(created_graph.id,created_graph.version,- "3e53486c-cf57-477e-ba2a-cb02dc828e1b",+ other_user.id,)assert exc_info.value.status_code == 404assert "Graph" in str(exc_info.value.detail)@@ -431,19 +439,30 @@ async def test_access_store_listing_graph(server: SpinTestServer):assert slv_id is not None- admin_user = await create_test_user(alt_user=True)await server.agent_server.test_review_store_listing(store.ReviewSubmissionRequest(store_listing_version_id=slv_id,is_approved=True,comments="Test comments",),- user_id=admin_user.id,+ user_id=other_user.id,)- # Now we check the graph can be accessed by a user that does not own the graph+ # An approved listing on its own grants nothing: without a library entry+ # the non-owner still can't read the graph.+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:+ await server.agent_server.test_get_graph(+ created_graph.id, created_graph.version, other_user.id+ )+ assert exc_info.value.status_code == 404++ # Adding it to their library is what unlocks it — and the install itself+ # has to work without prior access to the graph.+ await library_db.add_store_agent_to_library(+ store_listing_version_id=slv_id, user_id=other_user.id+ )got_graph = await server.agent_server.test_get_graph(- created_graph.id, created_graph.version, "3e53486c-cf57-477e-ba2a-cb02dc828e1b"+ created_graph.id, created_graph.version, other_user.id)assert got_graph is not None@@ -948,115 +967,263 @@ def test_mcp_credential_combine_no_discriminator_values():# --------------- get_graph access-control truth table --------------- ##-# Full matrix of access scenarios for get_graph() and get_graph_as_admin().-# Access priority: ownership > marketplace APPROVED > library membership.-# Library is version-specific. get_graph_as_admin bypasses everything.+# Access: owner, OR (in library AND submitted). "Submitted" is any status but+# DRAFT. Archiving hides an agent, it does not revoke it, so only isDeleted+# ends membership. get_graph_as_admin() and skip_access_check=True bypass it.#-# | User | Owns? | Marketplace | Library | Version | Result | Test+# | User | Owns? | Submitted | Library | Version | Result | Test# |----------|-------|-------------|------------------|---------|---------|------# | regular | yes | any | any | v1 | ACCESS | test_get_graph_library_not_queried_when_owned-# | regular | no | APPROVED | any | v1 | ACCESS | test_get_graph_non_owner_approved_marketplace_agent-# | regular | no | not listed | active, same ver | v1 | ACCESS | test_get_graph_library_member_can_access_unpublished-# | regular | no | not listed | active, diff ver | v2 | DENIED | test_get_graph_library_wrong_version_denied-# | regular | no | not listed | deleted | v1 | DENIED | test_get_graph_deleted_library_agent_denied-# | regular | no | not listed | archived | v1 | DENIED | test_get_graph_archived_library_agent_denied-# | regular | no | not listed | not present | v1 | DENIED | test_get_graph_non_owner_pending_not_in_library_denied-# | regular | no | PENDING | active v1 | v2 | DENIED | test_library_v1_does_not_grant_access_to_pending_v2-# | regular | no | not listed | null AgentGraph | v1 | DENIED | test_get_graph_library_with_null_agent_graph_denied-# | anon | no | not listed | - | v1 | DENIED | test_get_graph_library_fallback_not_used_for_anonymous-# | anon | no | APPROVED | - | v1 | ACCESS | test_get_graph_anonymous_approved_marketplace_access+# | regular | yes | any | any | v1 | ACCESS | test_get_graph_access_matrix / test_get_graph_library_not_queried_when_owned+# | regular | no | yes | active, same ver | v1 | ACCESS | test_get_graph_access_matrix+# | regular | no | yes | not present | v1 | DENIED | test_get_graph_access_matrix / test_get_graph_submitted_but_not_in_library_denied+# | regular | no | no | active, same ver | v1 | DENIED | test_get_graph_access_matrix / test_get_graph_in_library_but_never_submitted_denied+# | regular | no | no | not present | v1 | DENIED | test_get_graph_access_matrix+# | regular | no | yes | active, diff ver | v2 | DENIED | test_get_graph_library_wrong_version_denied+# | regular | no | yes | deleted | v1 | DENIED | test_get_graph_deleted_library_agent_denied+# | regular | no | yes | archived | v1 | ACCESS | test_get_graph_archived_library_agent_allowed+# | regular | no | yes | null AgentGraph | v1 | DENIED | test_get_graph_library_with_null_agent_graph_denied+# | anon | no | yes | - | v1 | DENIED | test_get_graph_anonymous_denied_for_submitted_graph# | admin* | no | PENDING | - | v2 | ACCESS | test_admin_can_access_pending_v2_via_get_graph_as_admin#+# | regular | no | v1 only | active, v1 + v2 | none | v1 | test_get_graph_version_none_ignores_unsubmitted_newer_version+# | regular | no | v1 + v2 | active, v1 + v2 | none | v2 | test_get_graph_version_none_picks_latest_submitted_version+## Efficiency (no unnecessary queries):-# | regular | yes | - | - | v1 | no mkt/lib | test_get_graph_library_not_queried_when_owned-# | regular | no | APPROVED | - | v1 | no lib | test_get_graph_library_not_queried_when_marketplace_approved+# | regular | yes | - | - | v1 | no lib | test_get_graph_library_not_queried_when_owned+# | anon | - | - | - | v1 | no query| test_get_graph_anonymous_denied_for_submitted_graph## * = via get_graph_as_admin (admin-only routes)-def _make_mock_db_graph(user_id: str = "owner-user-id") -> MagicMock:+def _make_mock_db_graph(user_id: str = "owner-user-id", version: int = 1) -> MagicMock:graph = MagicMock()graph.userId = user_idgraph.id = "graph-id"- graph.version = 1+ graph.version = versiongraph.Nodes = []return graph+class _LibraryRow:+ """A LibraryAgent row as far as the access check is concerned."""++ def __init__(+ self,+ *,+ user_id: str,+ graph_id: str,+ version: int,+ submitted: bool,+ is_deleted: bool = False,+ is_archived: bool = False,+ agent_graph: MagicMock | None = None,+ ) -> None:+ self.userId = user_id+ self.agentGraphId = graph_id+ self.agentGraphVersion = version+ self.submitted = submitted+ self.isDeleted = is_deleted+ self.isArchived = is_archived+ self.AgentGraph = agent_graph+++def _library_row_matches(row: _LibraryRow, where: dict[str, Any]) -> bool:+ """Evaluate `graph_in_library_filter()`'s where-clause against a row.++ Raises on any operator it doesn't implement, so a rewritten predicate+ can't silently keep passing here without this matcher being updated too.+ """+ for key, expected in where.items():+ if key == "AgentGraph":+ some = expected["is"]["StoreListingVersions"]["some"]+ statuses = set(some["submissionStatus"]["in"])+ assert statuses == {+ SubmissionStatus.PENDING,+ SubmissionStatus.APPROVED,+ SubmissionStatus.REJECTED,+ }, f"unexpected submitted-status set: {statuses}"+ if not row.submitted:+ return False+ elif isinstance(expected, (str, int, bool)):+ if getattr(row, key) != expected:+ return False+ else:+ raise AssertionError(+ f"matcher does not support where clause {key}={expected!r}"+ )+ return True+++def _fake_graph_db(+ *,+ owner_id: str,+ library_rows: list[_LibraryRow],+) -> tuple[MagicMock, MagicMock]:+ """Build AgentGraph/LibraryAgent prisma doubles that honour their where-clause.++ The graph always exists and is owned by `owner_id`, so denial can only+ come from the where-clause — never from a missing row.+ """+ db_graph = _make_mock_db_graph(owner_id)++ async def find_first_graph(**kwargs: Any) -> MagicMock | None:+ where = kwargs["where"]+ if where.get("id") != db_graph.id:+ return None+ if "version" in where and where["version"] != db_graph.version:+ return None+ if "userId" in where and where["userId"] != owner_id:+ return None+ return db_graph++ async def find_first_library(**kwargs: Any) -> _LibraryRow | None:+ matches = [+ row for row in library_rows if _library_row_matches(row, kwargs["where"])+ ]+ order = kwargs["order"]["agentGraphVersion"]+ assert order in ("asc", "desc"), f"unsupported order {order!r}"+ matches.sort(key=lambda row: row.agentGraphVersion, reverse=order == "desc")+ return matches[0] if matches else None++ ag_prisma = MagicMock()+ ag_prisma.return_value.find_first = AsyncMock(side_effect=find_first_graph)+ lib_prisma = MagicMock()+ lib_prisma.return_value.find_first = AsyncMock(side_effect=find_first_library)+ return ag_prisma, lib_prisma+++# Every combination of (owner / not) x (in library / not) x (submitted / not).+ ("is_owner", "in_library", "submitted", "expect_access"),+ [+ (True, True, True, True),+ (True, True, False, True),+ (True, False, True, True),+ (True, False, False, True),+ (False, True, True, True),+ (False, True, False, False),+ (False, False, True, False),+ (False, False, False, False),+ ],+)@pytest.mark.asyncio-async def test_get_graph_non_owner_approved_marketplace_agent() -> None:- """A non-owner should be able to access a graph that has an APPROVED- marketplace listing. This is the normal marketplace download flow."""+async def test_get_graph_access_matrix(+ is_owner: bool, in_library: bool, submitted: bool, expect_access: bool+) -> None:owner_id = "owner-user-id"- requester_id = "different-user-id"+ requester_id = owner_id if is_owner else "different-user-id"graph_id = "graph-id"- mock_graph = _make_mock_db_graph(owner_id)mock_graph_model = MagicMock(name="GraphModel")- mock_listing = MagicMock()- mock_listing.AgentGraph = mock_graph+ library_rows = (+ [+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=submitted,+ agent_graph=_make_mock_db_graph(owner_id),+ )+ ]+ if in_library+ else []+ )+ ag_prisma, lib_prisma = _fake_graph_db(owner_id=owner_id, library_rows=library_rows)with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),patch("backend.data.graph.GraphModel.from_db",return_value=mock_graph_model,),):- # First lookup (owned graph) returns None — requester != owner- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- # Marketplace fallback finds an APPROVED listing- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=mock_listing)-- result = await get_graph(- graph_id=graph_id,- version=1,- user_id=requester_id,- )+ result = await get_graph(graph_id=graph_id, version=1, user_id=requester_id)- assert result is not None, "Non-owner should access APPROVED marketplace agent"+ assert (result is not None) is expect_access, (+ f"owner={is_owner} in_library={in_library} submitted={submitted} "+ f"should {'grant' if expect_access else 'deny'} access"+ )@pytest.mark.asyncio-async def test_get_graph_non_owner_pending_not_in_library_denied() -> None:- """A non-owner with no library membership and no APPROVED marketplace- listing must be denied access."""- requester_id = "different-user-id"+async def test_get_graph_in_library_but_never_submitted_denied() -> None:+ """The graph version sits in the user's library but was never submitted to+ the marketplace. Library membership alone must not grant access."""+ requester_id = "library-user-id"graph_id = "graph-id"+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=False,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )+with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,- patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_lib_prisma.return_value.find_first = AsyncMock(return_value=None)+ result = await get_graph(graph_id=graph_id, version=1, user_id=requester_id)- result = await get_graph(- graph_id=graph_id,- version=1,- user_id=requester_id,- )+ assert result is None, "Library membership without a submission must be denied"- assert (- result is None- ), "User without ownership, marketplace, or library access must be denied"+ lib_where = lib_prisma.return_value.find_first.await_args.kwargs["where"]+ assert lib_where["userId"] == requester_id+ assert lib_where["agentGraphId"] == graph_id+ assert lib_where["agentGraphVersion"] == 1+ assert lib_where["isDeleted"] is False+ assert "isArchived" not in lib_where, "archiving hides, it does not revoke"+ # The submission requirement must be part of the same query, so the two+ # halves can never resolve to different graph versions.+ submitted_statuses = set(+ lib_where["AgentGraph"]["is"]["StoreListingVersions"]["some"][+ "submissionStatus"+ ]["in"]+ )+ assert SubmissionStatus.DRAFT not in submitted_statuses+++async def test_get_graph_submitted_but_not_in_library_denied() -> None:+ """The graph version was submitted to (and approved on) the marketplace,+ but the user never added it to their library. Denied."""+ requester_id = "different-user-id"+ graph_id = "graph-id"+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ # Submitted, in *someone else's* library — not the requester's.+ _LibraryRow(+ user_id="some-other-user-id",+ graph_id=graph_id,+ version=1,+ submitted=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )-# --------------- Library membership grants graph access --------------- #-# "You added it, you keep it" — product decision from SECRT-2167.+ with (+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),+ ):+ result = await get_graph(graph_id=graph_id, version=1, user_id=requester_id)++ assert result is None, "A marketplace listing alone must not grant graph access"@pytest.mark.asyncio-async def test_get_graph_library_member_can_access_unpublished() -> None:- """A user who has the agent in their library should be able to access it- even if it's no longer published in the marketplace."""+async def test_get_graph_library_member_can_access_submitted_agent() -> None:+ """A user who downloaded a marketplace agent keeps access to that version+ even after the listing is taken down — the submission still happened."""requester_id = "library-user-id"graph_id = "graph-id"mock_graph = _make_mock_db_graph("original-creator-id")@@ -1067,9 +1234,6 @@ async def test_get_graph_library_member_can_access_unpublished() -> None:with (patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,patch("backend.data.graph.GraphModel.from_db",@@ -1078,9 +1242,7 @@ async def test_get_graph_library_member_can_access_unpublished() -> None:):# Not ownedmock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- # Not in marketplace (unpublished)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)- # But IS in user's library+ # In the user's library, and the version was submittedmock_lib_prisma.return_value.find_first = AsyncMock(return_value=mock_library_agent)@@ -1091,9 +1253,9 @@ async def test_get_graph_library_member_can_access_unpublished() -> None:user_id=requester_id,)- assert result is mock_graph_model, "Library member should access unpublished agent"+ assert result is mock_graph_model, "Library member should access submitted agent"- # Verify library query filters on non-deleted, non-archived+ # Verify library query filters on non-deleted (archived stays readable)lib_call = mock_lib_prisma.return_value.find_firstlib_call.assert_awaited_once()assert lib_call.await_args is not None@@ -1101,197 +1263,301 @@ async def test_get_graph_library_member_can_access_unpublished() -> None:assert lib_where["userId"] == requester_idassert lib_where["agentGraphId"] == graph_idassert lib_where["isDeleted"] is False- assert lib_where["isArchived"] is False+ assert "isArchived" not in lib_where@pytest.mark.asyncioasync def test_get_graph_deleted_library_agent_denied() -> None:"""If the user soft-deleted the agent from their library, they should- NOT get access via the library fallback."""+ NOT get access, even though the version was submitted."""requester_id = "library-user-id"graph_id = "graph-id"+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=True,+ is_deleted=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )+with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,- patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)- # Library query returns None because isDeleted=False filter excludes it- mock_lib_prisma.return_value.find_first = AsyncMock(return_value=None)-- result = await get_graph(- graph_id=graph_id,- version=1,- user_id=requester_id,- )+ result = await get_graph(graph_id=graph_id, version=1, user_id=requester_id)assert result is None, "Deleted library agent should not grant graph access"@pytest.mark.asyncio-async def test_get_graph_anonymous_approved_marketplace_access() -> None:- """Anonymous users (user_id=None) should still access APPROVED marketplace- agents — the marketplace fallback doesn't require authentication."""+async def test_get_graph_archived_library_agent_allowed() -> None:+ """Archiving is a display state, not a revocation: tidying an agent out of+ the library view must not cost the user run history, forking, scheduling+ or webhook presets. `isDeleted` is what ends membership."""+ requester_id = "library-user-id"graph_id = "graph-id"- mock_graph = _make_mock_db_graph("creator-id")mock_graph_model = MagicMock(name="GraphModel")- mock_listing = MagicMock()- mock_listing.AgentGraph = mock_graph+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=True,+ is_archived=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),patch("backend.data.graph.GraphModel.from_db",return_value=mock_graph_model,),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=mock_listing)+ result = await get_graph(graph_id=graph_id, version=1, user_id=requester_id)- result = await get_graph(- graph_id=graph_id,- version=1,- user_id=None,- )-- assert (- result is mock_graph_model- ), "Anonymous user should access APPROVED marketplace agent"+ assert result is mock_graph_model, "Archiving must not revoke graph access"@pytest.mark.asyncio-async def test_get_graph_library_fallback_not_used_for_anonymous() -> None:- """Anonymous requests (user_id=None) must not trigger the library- fallback — there's no user to check library membership for."""+async def test_get_graph_anonymous_denied_for_submitted_graph() -> None:+ """Anonymous callers (user_id=None) have no library, so they can never+ satisfy the access rule — not even for a graph that is on the marketplace+ and in someone's library. The public download path goes through+ `store.db.get_agent()` instead.++ Neither table is touched: with no user and no team there is nothing to+ match on, so both lookups are skipped rather than run and discarded.+ """graph_id = "graph-id"+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id="some-other-user-id",+ graph_id=graph_id,+ version=1,+ submitted=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )+with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,- patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)-- result = await get_graph(- graph_id=graph_id,- version=1,- user_id=None,- )+ result = await get_graph(graph_id=graph_id, version=1, user_id=None)- assert result is None- # Library should never be queried for anonymous users- mock_lib_prisma.return_value.find_first.assert_not_called()+ assert result is None, "Anonymous callers must not reach a graph via get_graph"+ ag_prisma.return_value.find_first.assert_not_called()+ lib_prisma.return_value.find_first.assert_not_called()@pytest.mark.asyncio-async def test_get_graph_library_not_queried_when_owned() -> None:- """If the user owns the graph, the library fallback should NOT be- triggered — ownership is sufficient."""- owner_id = "owner-user-id"+async def test_get_graph_skip_access_check_bypasses_library_lookup() -> None:+ """`skip_access_check=True` fetches the row directly. Callers that use it+ (the executor, the marketplace install/download paths) have authorized the+ read themselves, so the library rule must not be applied on top."""graph_id = "graph-id"- mock_graph = _make_mock_db_graph(owner_id)+ mock_graph = _make_mock_db_graph("original-creator-id")mock_graph_model = MagicMock(name="GraphModel")with (patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,patch("backend.data.graph.GraphModel.from_db",return_value=mock_graph_model,),):- # User owns the graph — first lookup succeedsmock_ag_prisma.return_value.find_first = AsyncMock(return_value=mock_graph)result = await get_graph(graph_id=graph_id,version=1,- user_id=owner_id,+ user_id="unrelated-user-id",+ skip_access_check=True,)assert result is mock_graph_model- # Neither marketplace nor library should be queried- mock_slv_prisma.return_value.find_first.assert_not_called()+ ag_where = mock_ag_prisma.return_value.find_first.await_args.kwargs["where"]+ assert "userId" not in ag_where, "skip_access_check must not scope by owner"mock_lib_prisma.return_value.find_first.assert_not_called()@pytest.mark.asyncio-async def test_get_graph_library_not_queried_when_marketplace_approved() -> None:- """If the graph is APPROVED in the marketplace, the library fallback- should NOT be triggered — marketplace access is sufficient."""- requester_id = "different-user-id"- graph_id = "graph-id"- mock_graph = _make_mock_db_graph("original-creator-id")- mock_graph_model = MagicMock(name="GraphModel")+async def test_get_graph_skip_access_check_denies_missing_graph_despite_library() -> (+ None+):+ """The flag must gate the library branch itself, not just the owner scope:+ a caller that authorized its own read gets the row or nothing, never a+ second chance through someone's library."""+ requester_id = "library-user-id"+ missing_graph_id = "other-graph-id"- mock_listing = MagicMock()- mock_listing.AgentGraph = mock_graph+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=missing_graph_id,+ version=1,+ submitted=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,- patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,- patch(- "backend.data.graph.GraphModel.from_db",- return_value=mock_graph_model,- ),+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=mock_listing)-result = await get_graph(- graph_id=graph_id,+ graph_id=missing_graph_id,version=1,user_id=requester_id,+ skip_access_check=True,)- assert result is mock_graph_model- # Library should not be queried — marketplace was sufficient- mock_lib_prisma.return_value.find_first.assert_not_called()+ assert result is None, "skip_access_check must not fall back to the library"+ lib_prisma.return_value.find_first.assert_not_called()@pytest.mark.asyncio-async def test_get_graph_archived_library_agent_denied() -> None:- """If the user archived the agent in their library, they should- NOT get access via the library fallback."""+async def test_get_graph_version_none_ignores_unsubmitted_newer_version() -> None:+ """Why the two halves are one joined query: with no version pinned, a newer+ never-submitted library row must not shadow the submitted one — separate+ queries would resolve the membership and the submission to different+ versions and grant access to v2."""requester_id = "library-user-id"graph_id = "graph-id"+ submitted_v1 = _make_mock_db_graph("original-creator-id", version=1)++ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=2,+ submitted=False,+ agent_graph=_make_mock_db_graph("original-creator-id", version=2),+ ),+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=True,+ agent_graph=submitted_v1,+ ),+ ],+ )++ with (+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),+ patch("backend.data.graph.GraphModel.from_db") as mock_from_db,+ ):+ result = await get_graph(graph_id=graph_id, version=None, user_id=requester_id)++ assert result is mock_from_db.return_value+ assert (+ mock_from_db.call_args.args[0] is submitted_v1+ ), "version=None must resolve to the submitted version, not the newest row"+ lib_where = lib_prisma.return_value.find_first.await_args.kwargs["where"]+ assert "agentGraphVersion" not in lib_where+++async def test_get_graph_version_none_picks_latest_submitted_version() -> None:+ """With several submitted versions in the library and no version pinned,+ the newest wins — same as the owner path's `order={"version": "desc"}`."""+ requester_id = "library-user-id"+ graph_id = "graph-id"+ submitted_v2 = _make_mock_db_graph("original-creator-id", version=2)++ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=True,+ agent_graph=_make_mock_db_graph("original-creator-id", version=1),+ ),+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=2,+ submitted=True,+ agent_graph=submitted_v2,+ ),+ ],+ )++ with (+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),+ patch("backend.data.graph.GraphModel.from_db") as mock_from_db,+ ):+ result = await get_graph(graph_id=graph_id, version=None, user_id=requester_id)++ assert result is mock_from_db.return_value+ assert mock_from_db.call_args.args[0] is submitted_v2+++def test_submitted_to_marketplace_is_every_status_but_draft() -> None:+ """A new `SubmissionStatus` member has to be triaged by hand: silently+ inheriting "submitted" would grant its holders read access to the graph."""+ assert set(SUBMITTED_TO_MARKETPLACE) == set(SubmissionStatus) - {+ SubmissionStatus.DRAFT+ }+++async def test_get_graph_library_not_queried_when_owned() -> None:+ """If the user owns the graph, the library lookup should NOT be+ triggered — ownership is sufficient."""+ owner_id = "owner-user-id"+ graph_id = "graph-id"+ mock_graph = _make_mock_db_graph(owner_id)+ mock_graph_model = MagicMock(name="GraphModel")with (patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch(+ "backend.data.graph.GraphModel.from_db",+ return_value=mock_graph_model,+ ),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)- # Library query returns None because isArchived=False filter excludes it- mock_lib_prisma.return_value.find_first = AsyncMock(return_value=None)+ # User owns the graph — first lookup succeeds+ mock_ag_prisma.return_value.find_first = AsyncMock(return_value=mock_graph)result = await get_graph(graph_id=graph_id,version=1,- user_id=requester_id,+ user_id=owner_id,)- assert result is None, "Archived library agent should not grant graph access"+ assert result is mock_graph_model+ mock_lib_prisma.return_value.find_first.assert_not_called()@pytest.mark.asyncio@@ -1306,13 +1572,9 @@ async def test_get_graph_library_with_null_agent_graph_denied() -> None:with (patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,):mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)mock_lib_prisma.return_value.find_first = AsyncMock(return_value=mock_library_agent)@@ -1330,36 +1592,34 @@ async def test_get_graph_library_with_null_agent_graph_denied() -> None:@pytest.mark.asyncioasync def test_get_graph_library_wrong_version_denied() -> None:- """Having version 1 in your library must NOT grant access to version 2."""+ """Having version 1 in your library must NOT grant access to version 2,+ even when both versions were submitted to the marketplace."""requester_id = "library-user-id"graph_id = "graph-id"+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )+with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,- patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),):- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)- # Library has version 1 but we're requesting version 2 —- # the where clause includes agentGraphVersion so this returns None- mock_lib_prisma.return_value.find_first = AsyncMock(return_value=None)-- result = await get_graph(- graph_id=graph_id,- version=2,- user_id=requester_id,- )+ result = await get_graph(graph_id=graph_id, version=2, user_id=requester_id)assert (result is None), "Library agent for version 1 must not grant access to version 2"- # Verify version was included in the library query- lib_call = mock_lib_prisma.return_value.find_first- lib_call.assert_called_once()- lib_where = lib_call.call_args.kwargs["where"]+ lib_where = lib_prisma.return_value.find_first.await_args.kwargs["where"]assert lib_where["agentGraphVersion"] == 2@@ -1370,25 +1630,24 @@ async def test_library_v1_does_not_grant_access_to_pending_v2() -> None:requester_id = "regular-user-id"graph_id = "graph-id"+ ag_prisma, lib_prisma = _fake_graph_db(+ owner_id="original-creator-id",+ library_rows=[+ _LibraryRow(+ user_id=requester_id,+ graph_id=graph_id,+ version=1,+ submitted=True,+ agent_graph=_make_mock_db_graph("original-creator-id"),+ )+ ],+ )+with (- patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,- patch(- "backend.data.graph.StoreListingVersion.prisma",- ) as mock_slv_prisma,- patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch("backend.data.graph.AgentGraph.prisma", ag_prisma),+ patch("backend.data.graph.LibraryAgent.prisma", lib_prisma),):- # Not owned- mock_ag_prisma.return_value.find_first = AsyncMock(return_value=None)- # v2 is not APPROVED in marketplace- mock_slv_prisma.return_value.find_first = AsyncMock(return_value=None)- # Library has v1 but not v2 — version filter excludes it- mock_lib_prisma.return_value.find_first = AsyncMock(return_value=None)-- result = await get_graph(- graph_id=graph_id,- version=2,- user_id=requester_id,- )+ result = await get_graph(graph_id=graph_id, version=2, user_id=requester_id)assert result is None, "Regular user with v1 in library must not access pending v2"@@ -1428,9 +1687,20 @@ async def test_admin_can_access_pending_v2_via_get_graph_as_admin() -> None:# --------------- execution permission truth table --------------- ### validate_graph_execution_permissions() has two gates:-# 1. Accessible graph: owner OR exact-version library entry OR marketplace-published-# 2. Runnable graph: exact-version library entry OR owner fallback to any live-# library entry for the graph OR sub-graph exception+# 1. Accessible graph: owner OR the exact version is READABLE from the library+# (in library AND submitted -- the same graph_in_library_filter() the read+# path uses) OR marketplace-published+# 2. Runnable graph: that readable entry OR owner fallback to any live library+# entry for the graph OR sub-graph exception+#+# Both library lookups are issued in one asyncio.gather, so LibraryAgent+# find_first is awaited twice on every call: [0] is the strict read predicate,+# [1] the loose owner fallback. The fallback is only consulted for owners --+# reading it for a non-owner would grant cross-version execution.+#+# INVARIANT: gate 1 must never be looser than get_graph()'s read rule. The one+# exception is SECRT-1125 -- a marketplace-published graph runs as a sub-agent+# without read, so the caller can't reconstruct a non-public graph from it.## Desired owner behavior differs from non-owners:# owners should be allowed to run a new version when some non-archived/non-deleted@@ -1439,11 +1709,12 @@ async def test_admin_can_access_pending_v2_via_get_graph_as_admin() -> None:## | User | Owns? | Marketplace | Library state | is_sub_graph | Result | Test# |----------|-------|-------------|------------------------------|--------------|----------|------# | regular | no | no | exact version present | false | ALLOW | test_validate_graph_execution_permissions_library_member_same_version_allowed+# | regular | no | submitted | exact version present | false | ALLOW | test_validate_graph_execution_permissions_library_member_same_version_allowed+# | regular | no | no | exact version, NEVER submitted| false | DENY acc | test_validate_graph_execution_permissions_library_member_never_submitted_denied# | owner | yes | no | exact version present | false | ALLOW | test_validate_graph_execution_permissions_owner_same_version_in_library_allowed# | owner | yes | no | previous version present | false | ALLOW | test_validate_graph_execution_permissions_owner_previous_library_version_allowed# | owner | yes | no | none present | false | DENY lib | test_validate_graph_execution_permissions_owner_without_library_denied-# | owner | yes | no | only archived/deleted older | false | DENY lib | test_validate_graph_execution_permissions_owner_previous_archived_library_version_denied+# | owner | yes | no | only archived older | false | ALLOW | test_validate_graph_execution_permissions_owner_previous_archived_library_version_allowed# | regular | no | yes | none present | false | DENY lib | test_validate_graph_execution_permissions_marketplace_graph_not_in_library_denied# | admin | no | no | none present | false | DENY acc | test_validate_graph_execution_permissions_admin_without_library_or_marketplace_denied# | regular | no | yes | none present | true | ALLOW | test_validate_graph_execution_permissions_marketplace_sub_graph_without_library_allowed@@ -1479,8 +1750,50 @@ async def test_validate_graph_execution_permissions_library_member_same_version_)mock_is_published.assert_not_awaited()- lib_where = mock_lib_prisma.return_value.find_first.call_args.kwargs["where"]+ lib_where = mock_lib_prisma.return_value.find_first.await_args_list[0].kwargs[+ "where"+ ]assert lib_where["agentGraphVersion"] == graph_version+ # The alignment itself: execute queries the read gate's own predicate, so+ # it cannot be looser than read. Everything the read tests prove about+ # graph_in_library_filter() therefore holds here too.+ assert lib_where == graph_in_library_filter(requester_id, graph_id, graph_version)+++async def test_validate_graph_execution_permissions_library_member_never_submitted_denied() -> (+ None+):+ """Library membership alone does not grant execution: the version must also+ have been submitted. Execution is never more permissive than read, so a+ version the user cannot open is a version they cannot run."""+ requester_id = "library-user-id"+ graph_id = "graph-id"+ graph_version = 2+ mock_graph = MagicMock(userId="creator-user-id")++ with (+ patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,+ patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch(+ "backend.data.graph.is_graph_published_in_marketplace",+ new_callable=AsyncMock,+ return_value=False,+ ) as mock_is_published,+ ):+ mock_ag_prisma.return_value.find_unique = AsyncMock(return_value=mock_graph)+ # graph_in_library_filter() requires a submission, so an unsubmitted+ # row is simply not found.+ mock_lib_prisma.return_value.find_first = AsyncMock(return_value=None)++ with pytest.raises(GraphNotAccessibleError):+ await validate_graph_execution_permissions(+ user_id=requester_id,+ graph_id=graph_id,+ graph_version=graph_version,+ )++ mock_is_published.assert_awaited_once_with(graph_id, graph_version)@pytest.mark.asyncio@@ -1511,7 +1824,9 @@ async def test_validate_graph_execution_permissions_owner_same_version_in_librar)mock_is_published.assert_not_awaited()- lib_where = mock_lib_prisma.return_value.find_first.call_args.kwargs["where"]+ lib_where = mock_lib_prisma.return_value.find_first.await_args_list[0].kwargs[+ "where"+ ]assert lib_where["agentGraphVersion"] == graph_version@@ -1597,14 +1912,15 @@ async def test_validate_graph_execution_permissions_owner_without_library_denied"userId": requester_id,"agentGraphId": graph_id,"isDeleted": False,- "isArchived": False,- }+ }, "archiving hides an agent, it must not revoke the owner's run rights"@pytest.mark.asyncio-async def test_validate_graph_execution_permissions_owner_previous_archived_library_version_denied() -> (+async def test_validate_graph_execution_permissions_owner_previous_archived_library_version_allowed() -> (None):+ """An owner whose only remaining library entry is archived can still run a+ new version: the fallback query must not filter on isArchived."""requester_id = "owner-user-id"graph_id = "graph-id"graph_version = 2@@ -1620,14 +1936,15 @@ async def test_validate_graph_execution_permissions_owner_previous_archived_libr) as mock_is_published,):mock_ag_prisma.return_value.find_unique = AsyncMock(return_value=mock_graph)- mock_lib_prisma.return_value.find_first = AsyncMock(side_effect=[None, None])+ mock_lib_prisma.return_value.find_first = AsyncMock(+ side_effect=[None, MagicMock(name="ArchivedLibraryAgent")]+ )- with pytest.raises(GraphNotInLibraryError):- await validate_graph_execution_permissions(- user_id=requester_id,- graph_id=graph_id,- graph_version=graph_version,- )+ await validate_graph_execution_permissions(+ user_id=requester_id,+ graph_id=graph_id,+ graph_version=graph_version,+ )mock_is_published.assert_not_awaited()assert mock_lib_prisma.return_value.find_first.await_count == 2@@ -1642,8 +1959,43 @@ async def test_validate_graph_execution_permissions_owner_previous_archived_libr"userId": requester_id,"agentGraphId": graph_id,"isDeleted": False,- "isArchived": False,- }+ }, "archiving hides an agent, it must not revoke the owner's run rights"+++async def test_validate_graph_execution_permissions_non_owner_other_version_denied() -> (+ None+):+ """The owner fallback is fetched for everyone but must be read only for+ owners. A non-owner holding a live entry for a *different* version of a+ marketplace graph stays version-specific and is denied."""+ requester_id = "library-user-id"+ graph_id = "graph-id"+ graph_version = 2+ mock_graph = MagicMock(userId="creator-user-id")++ with (+ patch("backend.data.graph.AgentGraph.prisma") as mock_ag_prisma,+ patch("backend.data.graph.LibraryAgent.prisma") as mock_lib_prisma,+ patch(+ "backend.data.graph.is_graph_published_in_marketplace",+ new_callable=AsyncMock,+ return_value=True,+ ),+ ):+ mock_ag_prisma.return_value.find_unique = AsyncMock(return_value=mock_graph)+ # Strict predicate misses this version; the loose fallback finds the+ # user's entry for another version of the same graph.+ mock_lib_prisma.return_value.find_first = AsyncMock(+ side_effect=[None, MagicMock(name="OtherVersionLibraryAgent")]+ )++ with pytest.raises(GraphNotInLibraryError):+ await validate_graph_execution_permissions(+ user_id=requester_id,+ graph_id=graph_id,+ graph_version=graph_version,+ )@pytest.mark.asyncio@@ -1800,10 +2152,84 @@ async def test_validate_graph_execution_permissions_library_wrong_version_denied)mock_is_published.assert_awaited_once_with(graph_id, graph_version)- lib_where = mock_lib_prisma.return_value.find_first.call_args.kwargs["where"]+ lib_where = mock_lib_prisma.return_value.find_first.await_args_list[0].kwargs[+ "where"+ ]assert lib_where["agentGraphVersion"] == graph_version+# ============================================================================+# Tests for get_graph_settings version resolution (real DB)+# ============================================================================+++ "running_version, expected_session_id, expected_safe_mode",+ [+ (1, "settings-v1", True),+ (2, "settings-v2", False),+ (3, "settings-v1", True),+ ],+ ids=[+ "live-version-keeps-its-own-settings",+ "archived-version-keeps-its-own-settings",+ "version-without-an-entry-falls-back-to-the-live-one",+ ],+)[email protected](loop_scope="session")+async def test_get_graph_settings_resolves_against_the_running_version(+ server: SpinTestServer,+ running_version: int,+ expected_session_id: str,+ expected_safe_mode: bool,+) -> None:+ """An archived entry must not override the version actually running."""+ user_id = f"graph-settings-{uuid4()}"+ graph_id = str(uuid4())+ await User.prisma().create(+ data={"id": user_id, "email": f"{user_id}@example.com", "name": "Settings Test"}+ )+ try:+ for version in (1, 2, 3):+ await AgentGraph.prisma().create(+ data={+ "id": graph_id,+ "version": version,+ "name": f"Settings Test v{version}",+ "description": "test",+ "userId": user_id,+ "isActive": version == 3,+ }+ )+ for version, archived, safe_mode in ((1, False, True), (2, True, False)):+ await LibraryAgent.prisma().create(+ data={+ "userId": user_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": version,+ "isArchived": archived,+ "isCreatedByUser": True,+ "settings": SafeJson(+ {+ "sensitive_action_safe_mode": safe_mode,+ "builder_chat_session_id": f"settings-v{version}",+ }+ ),+ }+ )++ settings = await get_graph_settings(+ user_id=user_id, graph_id=graph_id, graph_version=running_version+ )++ assert settings.builder_chat_session_id == expected_session_id+ assert settings.sensitive_action_safe_mode is expected_safe_mode+ finally:+ await LibraryAgent.prisma().delete_many(where={"userId": user_id})+ await AgentGraph.prisma().delete_many(where={"id": graph_id})+ await User.prisma().delete_many(where={"id": user_id})++# ============================================================================# Tests for _generate_schema AttributeError → ValueError conversion# ============================================================================diff --git a/autogpt_platform/backend/backend/executor/automod/manager.py b/autogpt_platform/backend/backend/executor/automod/manager.pyindex 2eef4f6eca..bcbbfc79ee 100644--- a/autogpt_platform/backend/backend/executor/automod/manager.py+++ b/autogpt_platform/backend/backend/executor/automod/manager.py@@ -52,14 +52,35 @@ class AutoModManager:logger.debug(f"AutoMod feature not enabled for user {graph_exec.user_id}")return None- # Get graph model and collect all inputs+ # Get graph model and collect all inputs.+ # add_graph_execution() already authorized this run, and SECRT-1125+ # lets a marketplace sub-agent run without read access — gating the+ # read here would deny exactly those runs.graph_model = await db_client.get_graph(graph_exec.graph_id,user_id=graph_exec.user_id,version=graph_exec.graph_version,+ skip_access_check=True,)- if not graph_model or not graph_model.nodes:+ # The graph version is gone, so the inputs can't be collected at all —+ # that is moderation failing to run, not content passing it.+ if not graph_model:+ logger.warning(+ f"Cannot moderate inputs for graph execution "+ f"{graph_exec.graph_exec_id}: graph #{graph_exec.graph_id} "+ f"v{graph_exec.graph_version} no longer exists"+ )+ if self.config.fail_open:+ return None+ return ModerationError(+ message="Execution failed due to input content moderation error",+ user_id=graph_exec.user_id,+ graph_exec_id=graph_exec.graph_exec_id,+ moderation_type="input",+ )++ if not graph_model.nodes:return Noneall_inputs = []diff --git a/autogpt_platform/backend/backend/executor/automod/manager_test.py b/autogpt_platform/backend/backend/executor/automod/manager_test.pynew file mode 100644index 0000000000..b2acd9efcc--- /dev/null+++ b/autogpt_platform/backend/backend/executor/automod/manager_test.py@@ -0,0 +1,107 @@+"""Input-moderation behaviour when the graph can't be resolved.++`moderate_graph_execution_inputs()` needs the graph's nodes to collect the+inputs it moderates. The read bypasses the caller's access check — the run is+already authorized by then — so an empty lookup means the version is gone, not+that the runner may not read it. Whether that kills the run or lets it through+unmoderated is the `automod_fail_open` operator setting, not an accident of+control flow.+"""++from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.util.exceptions import ModerationError++from .manager import AutoModManager+++async def test_missing_graph_fails_closed_by_default() -> None:+ """A graph that no longer exists means moderation could not run. Reporting+ that as "passed" would let the execution through unvetted."""+ manager, db_client = _manager_with_graph(None, fail_open=False)++ result = await manager.moderate_graph_execution_inputs(+ db_client=db_client, graph_exec=_graph_exec()+ )++ assert isinstance(result, ModerationError)+++async def test_missing_graph_passes_when_fail_open_is_set() -> None:+ """`automod_fail_open` is the operator's explicit choice to keep executions+ running when moderation is unavailable."""+ manager, db_client = _manager_with_graph(None, fail_open=True)++ result = await manager.moderate_graph_execution_inputs(+ db_client=db_client, graph_exec=_graph_exec()+ )++ assert result is None+++async def test_graph_without_nodes_passes() -> None:+ """An empty graph is not a failure to moderate -- there is genuinely+ nothing to moderate -- so it must not take the fail-closed branch."""+ manager, db_client = _manager_with_graph(MagicMock(nodes=[]), fail_open=False)++ result = await manager.moderate_graph_execution_inputs(+ db_client=db_client, graph_exec=_graph_exec()+ )++ assert result is None+++async def test_marketplace_sub_agent_run_is_moderated_not_denied() -> None:+ """SECRT-1125 lets a user execute a marketplace graph they cannot read, as+ a sub-agent. Resolving the graph through their read gate would return None+ for exactly those runs and fail them closed on an unrelated error, so the+ read is bypassed: the run was already authorized by add_graph_execution().+ """+ graph = MagicMock(nodes=[])+ manager, db_client = _manager_with_graph(graph, fail_open=False)++ result = await manager.moderate_graph_execution_inputs(+ db_client=db_client, graph_exec=_graph_exec()+ )++ assert result is None, "an authorized sub-agent run must not be failed here"+ assert db_client.get_graph.await_args.kwargs["skip_access_check"] is True+ # Still the runner's own execution, and still version-specific.+ assert db_client.get_graph.await_args.kwargs["user_id"] == "runner-user-id"+ assert db_client.get_graph.await_args.kwargs["version"] == 3+++def _graph_exec() -> MagicMock:+ return MagicMock(+ user_id="runner-user-id",+ graph_id="graph-id",+ graph_version=3,+ graph_exec_id="exec-id",+ nodes_input_masks=None,+ )+++def _manager_with_graph(graph, *, fail_open: bool) -> tuple[AutoModManager, MagicMock]:+ with patch.object(AutoModManager, "_load_config") as load_config:+ load_config.return_value = MagicMock(enabled=True, fail_open=fail_open)+ manager = AutoModManager()++ db_client = MagicMock()+ db_client.get_graph = AsyncMock(return_value=graph)+ return manager, db_client++[email protected](autouse=True)+def _automod_flag_enabled():+ with patch(+ "backend.executor.automod.manager.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ ):+ yielddiff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex 31995a6fdd..b3b29f0478 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -1510,7 +1510,11 @@ async def _add_graph_execution(# Generate execution context if it's not providedif execution_context is None:user = await udb.get_user_by_id(user_id)- settings = await gdb.get_graph_settings(user_id=user_id, graph_id=graph_id)+ settings = await gdb.get_graph_settings(+ user_id=user_id,+ graph_id=graph_id,+ graph_version=graph_exec.graph_version,+ )workspace = await wdb.get_or_create_workspace(user_id)execution_context = ExecutionContext(diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 2396ba9ebd..8223ec59a2 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -13578,7 +13578,7 @@"post": {"tags": ["v2", "admin", "store", "admin"],"summary": "Admin Add Pending Agent to Library",- "description": "Add a pending marketplace agent to the admin's library for review.\nUses admin-level access to bypass marketplace APPROVED-only checks.\n\nThe builder can load the graph because get_graph() checks library\nmembership as a fallback: \"you added it, you keep it.\"",+ "description": "Add a pending marketplace agent to the admin's library for review.\nUses admin-level access to bypass marketplace APPROVED-only checks.\n\nThe builder can then load the graph: get_graph() grants a library\nversion that was submitted, and PENDING counts as submitted.","operationId": "postV2Admin add pending agent to library","security": [{ "HTTPBearerJWT": [] }],"parameters": [