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): keep the Drive file you picked when you save your agent (#14907)
Nicholas Tindleed4d0e24e563
diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes.py b/autogpt_platform/backend/backend/api/features/graphs/routes.pyindex 81ca6c1677..4f5e8d7c9a 100644--- a/autogpt_platform/backend/backend/api/features/graphs/routes.py+++ b/autogpt_platform/backend/backend/api/features/graphs/routes.py@@ -23,6 +23,7 @@ from backend.data.onboarding import OnboardingStep, complete_onboarding_stepfrom backend.executor import utils as execution_utilsfrom backend.integrations.webhooks.graph_lifecycle_hooks import (before_graph_activate,+ clear_unowned_auto_credentials,on_graph_deactivate,)from backend.monitoring.instrumentation import record_graph_operation@@ -179,6 +180,8 @@ async def update_graph(# those edits must be persisted, hence the pre-save call.if graph.is_active:graph = await before_graph_activate(graph, user_id=user_id)+ else:+ await clear_unowned_auto_credentials(graph, user_id)new_graph_version = await graph_db.create_graph(graph,diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py b/autogpt_platform/backend/backend/api/features/graphs/routes_test.pyindex 641ac37a61..8baed45211 100644--- a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/graphs/routes_test.py@@ -14,6 +14,7 @@ from pytest_snapshot.plugin import Snapshotfrom backend.api.features.graphs.routes import routerfrom backend.api.rest_api import app as real_appfrom backend.api.rest_api import handle_internal_http_error+from backend.blocks.google.sheets import GoogleSheetsReadBlockfrom backend.data import execution as execution_dbfrom backend.data.execution import ExecutionStatusfrom backend.data.graph import GraphModel@@ -694,6 +695,137 @@ def test_create_new_graph_reassigns_ids_and_persists_in_order(assert response.json()["id"] != "submitted-id"+def _sheets_read_graph(credentials_id: str) -> dict:+ """A Google Sheets Read agent whose spreadsheet was chosen in the Drive+ picker, which embeds the credential it used as `_credentials_id`."""+ return {+ "name": "Sheets",+ "description": "",+ "nodes": [+ {+ "id": "node-1",+ "block_id": GoogleSheetsReadBlock().id,+ "input_default": {+ "spreadsheet": {+ "_credentials_id": credentials_id,+ "id": "sheet-1",+ "name": "test",+ "mimeType": "application/vnd.google-apps.spreadsheet",+ },+ "range": "A1",+ },+ }+ ],+ "links": [],+ }+++def google_sheets_enabled(monkeypatch: pytest.MonkeyPatch) -> None:+ """Google blocks disable themselves when no OAuth client is configured, as+ in CI, and graph validation rejects a disabled block."""+ monkeypatch.setattr("backend.blocks.google.sheets.GOOGLE_SHEETS_DISABLED", False)+++def _own_credentials(mocker: pytest_mock.MockFixture, *credentials_ids: str) -> None:+ mocker.patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager.store.get_all_creds",+ new=AsyncMock(return_value=[Mock(id=cid) for cid in credentials_ids]),+ )++[email protected]("google_sheets_enabled")+ "owned_ids,expected_credentials_id",+ [(["own-cred"], "own-cred"), ([], None)],+ ids=["picked-with-own-account", "imported-with-someone-elses"],+)+def test_create_new_graph_keeps_only_a_file_picked_with_the_callers_credentials(+ mocker: pytest_mock.MockFixture,+ owned_ids: list[str],+ expected_credentials_id: str | None,+) -> None:+ """[SECRT-1772] Saving a new agent kept the range but dropped the Drive+ file you had picked, because every save nulled picker inputs. A file that+ embeds someone else's credentials is still cleared."""+ _own_credentials(mocker, *owned_ids)+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph", new=AsyncMock()+ )+ mocker.patch(+ "backend.api.features.graphs.routes.library_db.create_library_agent",+ new=AsyncMock(),+ )++ response = client.post("/graphs", json={"graph": _sheets_read_graph("own-cred")})++ assert response.status_code == 200+ saved: GraphModel = create_graph_mock.await_args.args[0]+ spreadsheet = saved.nodes[0].input_default["spreadsheet"]+ assert (spreadsheet or {}).get("_credentials_id") == expected_credentials_id+ assert saved.nodes[0].input_default["range"] == "A1"++[email protected]("google_sheets_enabled")+def test_update_graph_keeps_the_file_the_owner_picked(+ mocker: pytest_mock.MockFixture,+) -> None:+ """[SECRT-1772] Saving a new version dropped the picked file the same way+ (reproduced on dev by re-picking the file and saving again)."""+ _own_credentials(mocker, "own-cred")+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",+ new=AsyncMock(return_value=[Mock(version=1, is_active=False)]),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph",+ new=AsyncMock(return_value=Mock(version=2, is_active=False)),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph",+ new=AsyncMock(side_effect=lambda *a, **k: create_graph_mock.await_args.args[0]),+ )++ response = client.put(+ "/graphs/graph-1", json={"id": "graph-1", **_sheets_read_graph("own-cred")}+ )++ assert response.status_code == 200+ saved: GraphModel = create_graph_mock.await_args.args[0]+ assert saved.nodes[0].input_default["spreadsheet"]["_credentials_id"] == "own-cred"+ assert saved.nodes[0].input_default["range"] == "A1"++[email protected]("google_sheets_enabled")+def test_update_graph_clears_someone_elses_file_in_an_inactive_version(+ mocker: pytest_mock.MockFixture,+) -> None:+ """An inactive version skips activation, but must not keep a file picked+ with someone else's credentials either: activating it later won't+ rewrite its nodes."""+ _own_credentials(mocker, "own-cred")+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",+ new=AsyncMock(return_value=[Mock(version=1, is_active=True)]),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph",+ new=AsyncMock(return_value=Mock(version=2, is_active=False)),+ )+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph",+ new=AsyncMock(side_effect=lambda *a, **k: create_graph_mock.await_args.args[0]),+ )+ graph = {"id": "graph-1", "is_active": False, **_sheets_read_graph("foreign")}++ response = client.put("/graphs/graph-1", json=graph)++ assert response.status_code == 200+ saved: GraphModel = create_graph_mock.await_args.args[0]+ assert not saved.is_active+ assert saved.nodes[0].input_default == {"spreadsheet": None, "range": "A1"}++def test_set_active_version_returns_404_for_an_unknown_version(mocker: pytest_mock.MockFixture,) -> None:diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex a5926ef91d..0852e6d65f 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -30,6 +30,7 @@ from backend.data.model import CredentialsMetaInput, GraphInputfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.integrations.webhooks.graph_lifecycle_hooks import (before_graph_activate,+ clear_unowned_auto_credentials,on_graph_deactivate,)from backend.util.clients import get_scheduler_client@@ -799,6 +800,8 @@ async def create_graph_in_library(# to a user-friendly response.if graph_model.is_active:graph_model = await before_graph_activate(graph_model, user_id=user_id)+ else:+ await clear_unowned_auto_credentials(graph_model, user_id)created_graph = await graph_db.create_graph(graph_model, user_id)@@ -836,6 +839,8 @@ async def update_graph_in_library(# version half-saved. Raises GraphActivationError for the caller.if graph_model.is_active:graph_model = await before_graph_activate(graph_model, user_id=user_id)+ else:+ await clear_unowned_auto_credentials(graph_model, user_id)created_graph = await graph_db.create_graph(graph_model, user_id)diff --git a/autogpt_platform/backend/backend/api/features/library/db_test.py b/autogpt_platform/backend/backend/api/features/library/db_test.pyindex b110a2ca2f..06e952b172 100644--- a/autogpt_platform/backend/backend/api/features/library/db_test.py+++ b/autogpt_platform/backend/backend/api/features/library/db_test.py@@ -523,6 +523,10 @@ async def test_update_graph_in_library_allows_archived_library_agent(mocker):"backend.api.features.library.db.update_library_agent_version_and_settings",new=mocker.AsyncMock(return_value=updated_library_agent),)+ mock_clear_unowned = mocker.patch(+ "backend.api.features.library.db.clear_unowned_auto_credentials",+ new=mocker.AsyncMock(),+ )result_graph, result_library_agent = await db.update_graph_in_library(graph,@@ -535,6 +539,9 @@ async def test_update_graph_in_library_allows_archived_library_agent(mocker):graph_model.reassign_ids.assert_called_once_with(user_id="test-user", reassign_graph_id=False)+ # An inactive version skips activation but still drops files picked with+ # someone else's credentials.+ mock_clear_unowned.assert_awaited_once_with(graph_model, "test-user")mock_get_library_agent.assert_awaited_once_with("test-user","graph-id",diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.pyindex b306abea87..20f41ace71 100644--- a/autogpt_platform/backend/backend/api/features/library/model.py+++ b/autogpt_platform/backend/backend/api/features/library/model.py@@ -263,6 +263,11 @@ class LibraryAgent(pydantic.BaseModel):raise ValueError("Associated Agent record is required.")graph = GraphModel.from_db(agent.AgentGraph, sub_graphs=sub_graphs)+ if agent.AgentGraph.userId != agent.userId:+ # Someone else's agent in this user's library (e.g. from the+ # marketplace): its input defaults mustn't carry the owner's+ # picked files or the credentials embedded in them.+ graph.clear_auto_credentials()created_at = agent.createdAtdiff --git a/autogpt_platform/backend/backend/api/features/library/model_test.py b/autogpt_platform/backend/backend/api/features/library/model_test.pyindex af5e5bef9d..1f8cc3ce84 100644--- a/autogpt_platform/backend/backend/api/features/library/model_test.py+++ b/autogpt_platform/backend/backend/api/features/library/model_test.py@@ -1,9 +1,12 @@import datetime+import jsonimport prisma.enumsimport prisma.modelsimport pytest+from backend.blocks.io import AgentGoogleDriveFileInputBlock+from . import model as library_model@@ -13,6 +16,8 @@ def _make_library_agent(executions: list | None = None,name: str | None = None,description: str | None = None,+ graph_owner_id: str = "u1",+ nodes: list | None = None,) -> prisma.models.LibraryAgent:return prisma.models.LibraryAgent(id="la1",@@ -36,11 +41,12 @@ def _make_library_agent(version=1,name="Agent",description="Desc",- userId="u1",+ userId=graph_owner_id,isActive=True,createdAt=datetime.datetime.now(),visibility=prisma.enums.ResourceVisibility.PRIVATE,Executions=executions,+ Nodes=nodes,),)@@ -81,6 +87,34 @@ def test_from_db_preserves_empty_marketplace_description():assert result.description == ""+def _file_input_node(graph_id: str) -> prisma.models.AgentNode:+ """An agent-level Google Drive file input whose default file was picked+ with the owner's credentials."""+ picked = {"_credentials_id": "owner-cred", "id": "sheet-1", "name": "Budget"}+ return prisma.models.AgentNode(+ id="file-input",+ agentBlockId=AgentGoogleDriveFileInputBlock().id,+ agentGraphId=graph_id,+ agentGraphVersion=1,+ constantInput=json.dumps({"name": "file", "value": picked}),+ metadata="{}",+ )+++def test_from_db_hides_the_publishers_picked_file_from_other_libraries():+ """[SECRT-1772] A marketplace agent in another user's library: its input+ schema mustn't offer the publisher's picked file, and the credentials+ embedded in it, as a default. The runner picks their own file."""+ agent = _make_library_agent(+ graph_owner_id="publisher", nodes=[_file_input_node("g1")]+ )++ result = library_model.LibraryAgent.from_db(agent)++ assert "default" not in result.input_schema["properties"]["file"]+ assert "file" in result.input_schema["required"]++def test_from_db_execution_count_override_covers_success_rate():"""Covers execution_count_override is not None branch and executions/count > 0 block."""now = datetime.datetime.now(datetime.timezone.utc)diff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.pyindex f8fbe5fd74..cc11dae01b 100644--- a/autogpt_platform/backend/backend/api/features/store/db.py+++ b/autogpt_platform/backend/backend/api/features/store/db.py@@ -384,7 +384,7 @@ async def get_available_graph(f"Store listing version {store_listing_version_id} not found",)- return (GraphModelWithoutNodes if hide_nodes else GraphModel).from_db(+ graph = (GraphModelWithoutNodes if hide_nodes else GraphModel).from_db(store_listing_version.AgentGraph,sub_graphs=(await get_sub_graphs(store_listing_version.AgentGraph)@@ -392,6 +392,10 @@ async def get_available_graph(else None),)+ # A marketplace listing is public: the publisher's picked files, and+ # the credentials embedded in them, aren't part of it.+ graph.clear_auto_credentials()+ return graphexcept Exception as e:logger.error(f"Error getting agent: {e}")diff --git a/autogpt_platform/backend/backend/api/features/store/db_test.py b/autogpt_platform/backend/backend/api/features/store/db_test.pyindex 717b4432d2..0208dbac31 100644--- a/autogpt_platform/backend/backend/api/features/store/db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py@@ -1,3 +1,4 @@+import jsonfrom datetime import datetimefrom unittest.mock import AsyncMock, patch@@ -7,6 +8,7 @@ import prisma.modelsimport pytestfrom prisma import Prisma+from backend.blocks.google.sheets import GoogleSheetsReadBlockfrom backend.util.exceptions import NotFoundErrorfrom . import categories as store_categories@@ -1243,3 +1245,39 @@ async def test_uncategorised_listings_are_hidden_when_the_setting_is_on(matches = store_agent_query.call_args.kwargs["where"]["categories"]["has_some"]assert set(store_categories.all_category_match_values()) == set(matches)++[email protected](loop_scope="session")+async def test_get_available_graph_never_carries_picked_files(mocker):+ """[SECRT-1772] A marketplace listing's graph is public, so the files the+ publisher picked, and the credentials embedded in them, are cleared."""+ picked = {"_credentials_id": "publisher-cred", "id": "sheet-1", "name": "Budget"}+ graph_row = prisma.models.AgentGraph(+ id="g-1",+ version=1,+ name="Sheets",+ description="",+ userId="publisher",+ isActive=True,+ createdAt=datetime.now(),+ visibility=prisma.enums.ResourceVisibility.PRIVATE,+ Nodes=[+ prisma.models.AgentNode(+ id="node-1",+ agentBlockId=GoogleSheetsReadBlock().id,+ agentGraphId="g-1",+ agentGraphVersion=1,+ constantInput=json.dumps({"spreadsheet": picked, "range": "A1"}),+ metadata="{}",+ )+ ],+ )+ listing_client = AsyncMock()+ listing_client.find_first.return_value = mocker.MagicMock(AgentGraph=graph_row)+ mocker.patch.object(+ prisma.models.StoreListingVersion, "prisma", return_value=listing_client+ )++ graph = await db.get_available_graph("slv-1", hide_nodes=False)++ assert graph.nodes[0].input_default == {"spreadsheet": None, "range": "A1"}diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex a58be9d91a..c42120a035 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -2,8 +2,19 @@ import asyncioimport loggingimport uuidfrom collections import defaultdict+from collections.abc import Containerfrom datetime import datetime, timezone-from typing import TYPE_CHECKING, Annotated, Any, Final, Literal, Optional, Self, cast+from typing import (+ TYPE_CHECKING,+ Annotated,+ Any,+ Final,+ Literal,+ Optional,+ Self,+ cast,+ get_args,+)from prisma.enums import SubmissionStatusfrom prisma.models import (@@ -168,6 +179,10 @@ class NodeModel(Node):wire up their own)- fields the block schema marks with `secret: true` via`SchemaField(secret=True)` (block-author-declared sensitive values)+ - files picked with an auto-credentials picker (e.g. a GoogleDriveFile),+ which name the owner's file and embed their `_credentials_id`. These+ are nulled rather than removed: an explicit None tells the executor the+ file was cleared, so importers and forks pick their own.- `webhook_id` (points at the original owner's webhook subscription)"""stripped_node = self.model_copy(deep=True)@@ -184,11 +199,56 @@ class NodeModel(Node):):stripped_node.input_default.pop(field_name, None)+ for field_name in _auto_credentials_field_names(self):+ if field_name in stripped_node.input_default:+ stripped_node.input_default[field_name] = None+stripped_node.webhook_id = Nonereturn stripped_node+def _auto_credentials_field_names(node: Node) -> list[str]:+ """Inputs of the node's block that hold a picked file: the auto-credentials+ picker fields its schema declares, plus any input typed as a file carrying+ `_credentials_id`. The second covers the default of an agent's Google Drive+ file input, whose picker is only declared per node."""+ if get_block(node.block_id) is None:+ # The block was removed, so no schema says which inputs are pickers.+ # Treat any value that embeds a `_credentials_id` as one, so a picked+ # file doesn't slip through exports and non-owner reads.+ return [+ field_name+ for field_name, value in node.input_default.items()+ if isinstance(value, dict) and "_credentials_id" in value+ ]+ input_schema = node.block.input_schema+ declared = [+ info["field_name"]+ for info in input_schema.get_auto_credentials_fields().values()+ ]+ typed = [+ field_name+ for field_name, field in input_schema.model_fields.items()+ if field_name not in declared and _holds_picked_file(field.annotation)+ ]+ return declared + typed+++def _holds_picked_file(annotation: Any) -> bool:+ """Whether a field of this type holds a picked file: a model with a+ `_credentials_id` field, like GoogleDriveFile, or an Optional of one."""+ return any(+ isinstance(candidate, type)+ and issubclass(candidate, BaseModel)+ and any(+ field.alias == "_credentials_id"+ for field in candidate.model_fields.values()+ )+ for candidate in (annotation, *get_args(annotation))+ )++class GraphBaseMeta(BaseDbModel):"""Shared base for `GraphMeta` and `BaseGraph`, with core graph metadata fields.@@ -782,20 +842,43 @@ class GraphModel(Graph, GraphMeta):) and graph_id in graph_id_map:node.input_default["graph_id"] = graph_id_map[graph_id]- # Clear auto-credentials references (e.g., _credentials_id in- # GoogleDriveFile fields) so the new user must re-authenticate- # with their own account. We null the entire field rather than- # just the _credentials_id key — a partial object (e.g. a bare- # {"id": "...", "name": "..."} left over after stripping) would- # be rejected by the auto-credentials validator added below,- # breaking fork_graph() for agents that previously had a- # picker-selected Drive file.- for node in graph.nodes:- if not node.input_default:- continue- for key, value in list(node.input_default.items()):- if isinstance(value, dict) and "_credentials_id" in value:- node.input_default[key] = None+ def clear_auto_credentials(+ self, keep_ids: Container[str] = frozenset()+ ) -> list[tuple[Node, str, Any]]:+ """+ Null every picked file (see `auto_credentials_refs`) whose embedded+ `_credentials_id` is not in `keep_ids`, in this graph and its sub-graphs,+ and return the cleared ones in the shape `auto_credentials_refs` uses.++ A save keeps the saving user's own (see `before_graph_activate`), and a+ read by someone who doesn't own the graph keeps none (see `get_graph`).+ Exports, forks and copies strip picked files in+ `NodeModel.stripped_for_export`. The whole field is nulled, not just the+ key, because a file object without a `_credentials_id` is rejected by+ the auto-credentials check in `_validate_graph`.+ """+ cleared = [+ (node, field_name, credentials_id)+ for node, field_name, credentials_id in self.auto_credentials_refs()+ if not (isinstance(credentials_id, str) and credentials_id in keep_ids)+ ]+ for node, field_name, _ in cleared:+ node.input_default[field_name] = None+ return cleared++ def auto_credentials_refs(self) -> list[tuple[Node, str, Any]]:+ """Files picked into auto-credentials inputs (e.g. a GoogleDriveFile), in+ this graph and its sub-graphs, as (node, input name, embedded+ `_credentials_id`). Other inputs are left alone even when they happen to+ hold a `_credentials_id` key."""+ return [+ (node, field_name, value["_credentials_id"])+ for graph in (self, *self.sub_graphs)+ for node in graph.nodes+ for field_name in _auto_credentials_field_names(node)+ if isinstance(value := node.input_default.get(field_name), dict)+ and "_credentials_id" in value+ ]def validate_graph(self,@@ -1434,13 +1517,19 @@ async def get_graph(if include_subgraphs or for_export:sub_graphs = await get_sub_graphs(graph)- return GraphModel.from_db(+ graph_model = GraphModel.from_db(graph=graph,sub_graphs=sub_graphs,for_export=for_export,)+ else:+ graph_model = GraphModel.from_db(graph, for_export)- return GraphModel.from_db(graph, for_export)+ if user_id is not None and not skip_access_check and graph.userId != user_id:+ # Only the owner sees the files they picked and the credentials+ # embedded in them. Marketplace readers and teammates pick their own.+ graph_model.clear_auto_credentials()+ return graph_model# PENDING is included so admin review can open a not-yet-approved submission@@ -1513,11 +1602,15 @@ async def get_store_listed_graphs(graph_ids: list[str]) -> dict[str, GraphModel]order={"agentGraphVersion": "desc"},)- return {+ graphs = {listing.agentGraphId: GraphModel.from_db(listing.AgentGraph)for listing in store_listingsif listing.AgentGraph}+ for graph in graphs.values():+ # Public reads never carry the publisher's picked files.+ graph.clear_auto_credentials()+ return graphsasync def get_graph_as_admin(@@ -1683,7 +1776,13 @@ async def get_graph_all_versions(if not graph_versions:return []- return [GraphModel.from_db(graph) for graph in graph_versions]+ versions = [GraphModel.from_db(graph) for graph in graph_versions]+ for version in versions:+ if version.user_id != user_id:+ # A teammate reading the history: only the owner sees the files+ # they picked and the credentials embedded in them.+ version.clear_auto_credentials()+ return versionsasync def delete_graph(diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.pyindex fc54bb9ef0..33c9d6d13a 100644--- a/autogpt_platform/backend/backend/data/graph_test.py+++ b/autogpt_platform/backend/backend/data/graph_test.py@@ -1,4 +1,5 @@import json+from datetime import datetime, timezonefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patchfrom uuid import UUID, uuid4@@ -6,8 +7,8 @@ from uuid import UUID, uuid4import fastapi.exceptionsimport prismaimport pytest-from prisma.enums import SubmissionStatus-from prisma.models import AgentGraph, LibraryAgent, User+from prisma.enums import ResourceVisibility, SubmissionStatus+from prisma.models import AgentGraph, AgentNode, LibraryAgent, Userfrom pytest_snapshot.plugin import Snapshotimport backend.api.features.library.db as library_db@@ -17,18 +18,29 @@ from backend.blocks._base import BlockSchema, BlockSchemaInputfrom backend.blocks.autopilot import AUTOPILOT_BLOCK_ID, AutoPilotTransportfrom backend.blocks.basic import StoreValueBlockfrom backend.blocks.code_executor import ExecuteCodeBlock-from backend.blocks.io import AgentInputBlock, AgentOutputBlock+from backend.blocks.google.sheets import GoogleSheetsReadBlock+from backend.blocks.io import (+ AgentGoogleDriveFileInputBlock,+ AgentInputBlock,+ AgentOutputBlock,+)from backend.blocks.llm import LEGACY_MODEL_MAPPINGS, LLMModelfrom backend.data.graph import (SUBMITTED_TO_MARKETPLACE,+ BaseGraph,Graph,GraphModel,Link,Node,NodeModel,+ delete_graph,+ fork_graph,get_graph,+ get_graph_all_versions,get_graph_settings,+ get_store_listed_graphs,graph_in_library_filter,+ make_graph_model,migrate_llm_models,validate_graph_execution_permissions,)@@ -258,7 +270,9 @@ async def test_clean_graph(server: SpinTestServer):2. Drops the value of any field the schema marks `secret: true` via`SchemaField(secret=True)`.3. Nulls out `webhook_id`.- 4. Leaves every other field in `input_default` untouched.+ 4. Leaves every other field in `input_default` untouched, apart from files+ picked with an auto-credentials picker, which are nulled (see+ `test_stripped_for_export_nulls_picked_files`)."""graph = Graph(id="test_clean_graph",@@ -357,10 +371,15 @@ def test_stripped_for_export_drops_declared_credentials_field():@pytest.mark.asyncio(loop_scope="session")-async def test_access_store_listing_graph(server: SpinTestServer):+async def test_access_store_listing_graph(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):"""- Test the access of a store listing graph.+ Test the access of a store listing graph, and that a reader who doesn't+ own it doesn't get the file the publisher picked [SECRT-1772]."""+ # Google blocks disable themselves without an OAuth client, as in CI.+ monkeypatch.setattr("backend.blocks.google.sheets.GOOGLE_SHEETS_DISABLED", False)graph = Graph(id="test_clean_graph",name="Test Clean Graph",@@ -375,15 +394,21 @@ async def test_access_store_listing_graph(server: SpinTestServer):"description": "Test input description",},),+ _sheets_node("sheets_node", _picked_file("publisher-cred")),],links=[],)- # Create graph and get model+ # Create graph and get model. The publisher owns the picked file's+ # credential, so the save keeps it.create_graph = CreateGraph(graph=graph)- created_graph = await server.agent_server.test_create_graph(- create_graph, DEFAULT_USER_ID- )+ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager.store.get_all_creds",+ new=AsyncMock(return_value=[MagicMock(id="publisher-cred")]),+ ):+ created_graph = await server.agent_server.test_create_graph(+ create_graph, DEFAULT_USER_ID+ )# Ensure the default user has a Profile (required for store submissions)existing_profile = await prisma.models.Profile.prisma().find_first(@@ -466,6 +491,17 @@ async def test_access_store_listing_graph(server: SpinTestServer):)assert got_graph is not None+ # The reader gets the graph without the publisher's picked file or the+ # credentials embedded in it; the publisher still has it.+ owner_graph = await server.agent_server.test_get_graph(+ created_graph.id, created_graph.version, DEFAULT_USER_ID+ )+ sheets_block_id = GoogleSheetsReadBlock().id+ [reader_sheets] = [n for n in got_graph.nodes if n.block_id == sheets_block_id]+ [owner_sheets] = [n for n in owner_graph.nodes if n.block_id == sheets_block_id]+ assert reader_sheets.input_default["spreadsheet"] is None+ assert owner_sheets.input_default["spreadsheet"] == _picked_file("publisher-cred")+# ============================================================================# Tests for Optional Credentials Feature@@ -583,153 +619,296 @@ def test_combine_preserves_regular_credential_defaults():# ============================================================================-# Tests for _reassign_ids credential clearing (Fix 3: SECRT-1772)+# Tests for picker-selected file credentials (SECRT-1772)-def test_reassign_ids_clears_credentials_id():- """- [SECRT-1772] _reassign_ids should null out the entire- GoogleDriveFile-style input_default field so forked agents- don't retain the original creator's credential references AND- don't leave a partial file object (which would be rejected by- the auto-credentials validator).- """- from backend.data.graph import GraphModel+def _picked_file(credentials_id: Any) -> dict[str, Any]:+ return {+ "_credentials_id": credentials_id,+ "id": "file-123",+ "name": "test.xlsx",+ "mimeType": "application/vnd.google-apps.spreadsheet",+ }- node = Node(- id="node-1",- block_id=StoreValueBlock().id,- input_default={- "spreadsheet": {- "_credentials_id": "original-cred-id",- "id": "file-123",- "name": "test.xlsx",- "mimeType": "application/vnd.google-apps.spreadsheet",- "url": "https://docs.google.com/spreadsheets/d/file-123",- },- },++def _sheets_node(node_id: str, spreadsheet: Any) -> Node:+ return Node(+ id=node_id,+ block_id=GoogleSheetsReadBlock().id,+ input_default={"spreadsheet": spreadsheet, "range": "A1"},)++def _graph_of(*nodes: Node, sub_graph_nodes: list[Node] | None = None) -> GraphModel:+ sub_graphs = []+ if sub_graph_nodes:+ sub_graphs.append(+ BaseGraph(+ id="sub-graph", name="Sub", description="Sub", nodes=sub_graph_nodes+ )+ )graph = Graph(id="test-graph",name="Test",description="Test",- nodes=[node],- links=[],+ nodes=list(nodes),+ sub_graphs=sub_graphs,+ )+ return make_graph_model(graph, user_id="test-user")+++def test_reassign_ids_keeps_picked_files():+ """+ [SECRT-1772] Creating and updating a graph both go through reassign_ids,+ which used to null every picker-selected input. Saving your own agent+ kept the range but dropped the Drive file you had just picked.+ """+ graph = _graph_of(_sheets_node("node-1", _picked_file("own-cred")))++ graph.reassign_ids(user_id="test-user", reassign_graph_id=True)++ assert graph.nodes[0].input_default == {+ "spreadsheet": _picked_file("own-cred"),+ "range": "A1",+ }+++def test_stripped_for_export_nulls_picked_files():+ """+ [SECRT-1772] Exports, marketplace downloads, forks and copies never carry+ a picked file: it names the owner's file and embeds their credentials. The+ field is nulled, as a fork's always was, and other inputs are untouched,+ including a plain dict that happens to hold a `_credentials_id` key.+ """+ data = {"_credentials_id": "cred-2", "note": "plain data"}+ graph = _graph_of(+ _sheets_node("node-1", _picked_file("cred-1")),+ Node(id="node-2", block_id=StoreValueBlock().id, input_default={"data": data}),)- GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})+ sheets, store_value = (node.stripped_for_export() for node in graph.nodes)- # The entire field is nulled — leaving a partial file object behind- # would be rejected by the auto-credentials validator, breaking- # fork_graph() for agents that previously had a picker-selected file.- assert graph.nodes[0].input_default["spreadsheet"] is None+ assert sheets.input_default == {"spreadsheet": None, "range": "A1"}+ assert store_value.input_default == {"data": data}+ assert graph.nodes[0].input_default["spreadsheet"] == _picked_file("cred-1")-def test_reassign_ids_preserves_non_credential_fields():+def test_clear_auto_credentials_keeps_only_listed_ids():"""- Regression guard: _reassign_ids should NOT null fields that don't- carry a _credentials_id (e.g., plain user-entered values).+ A save keeps files picked with the saving user's own credentials and+ clears the rest, sub-graphs included, along with malformed IDs a raw API+ caller could send. Inputs that aren't pickers are never touched."""- from backend.data.graph import GraphModel+ data = {"_credentials_id": "someone-elses-cred"}+ graph = _graph_of(+ _sheets_node("own", _picked_file("own-cred")),+ _sheets_node("foreign", _picked_file("someone-elses-cred")),+ _sheets_node("empty", _picked_file("")),+ _sheets_node("missing", _picked_file(None)),+ _sheets_node("malformed", _picked_file({"id": "own-cred"})),+ Node(id="data", block_id=StoreValueBlock().id, input_default={"data": data}),+ sub_graph_nodes=[_sheets_node("sub", _picked_file("someone-elses-cred"))],+ )++ cleared = graph.clear_auto_credentials(keep_ids={"own-cred"})++ assert [node.id for node, _, _ in cleared] == [+ "foreign",+ "empty",+ "missing",+ "malformed",+ "sub",+ ]+ spreadsheets = {+ node.id: node.input_default["spreadsheet"]+ for node in [*graph.nodes, *graph.sub_graphs[0].nodes]+ if node.block_id == GoogleSheetsReadBlock().id+ }+ assert spreadsheets == {+ "own": _picked_file("own-cred"),+ "foreign": None,+ "empty": None,+ "missing": None,+ "malformed": None,+ "sub": None,+ }+ assert graph.nodes[5].input_default == {"data": data}++def test_picked_files_of_a_removed_block_are_still_found():+ """+ A node whose block was removed has no schema to say which inputs are+ pickers, so any value embedding a `_credentials_id` counts as a picked+ file: exports strip it and a save keeps it only for its owner.+ """node = Node(- id="node-1",- block_id=StoreValueBlock().id,- input_default={- # No _credentials_id — a plain dict that should be preserved- "config": {- "id": "file-123",- "name": "test.xlsx",- },- },+ id="gone",+ block_id="00000000-0000-0000-0000-0000000dead00",+ input_default={"file": _picked_file("cred-1"), "note": "plain"},)+ graph = _graph_of(node)- graph = Graph(- id="test-graph",- name="Test",- description="Test",- nodes=[node],- links=[],- )+ stripped = graph.nodes[0].stripped_for_export()+ cleared = graph.clear_auto_credentials(keep_ids={"own-cred"})- GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})+ assert stripped.input_default == {"file": None, "note": "plain"}+ assert [(n.id, field_name) for n, field_name, _ in cleared] == [("gone", "file")]+ assert graph.nodes[0].input_default == {"file": None, "note": "plain"}- field = graph.nodes[0].input_default["config"]- assert field == {"id": "file-123", "name": "test.xlsx"}++def _sheets_graph_row(owner_id: str) -> AgentGraph:+ return AgentGraph(+ id="g-1",+ version=1,+ name="Sheets",+ description="",+ userId=owner_id,+ isActive=True,+ createdAt=datetime.now(timezone.utc),+ visibility=ResourceVisibility.PRIVATE,+ organizationId="org-1",+ Nodes=[+ AgentNode(+ id="node-1",+ agentBlockId=GoogleSheetsReadBlock().id,+ agentGraphId="g-1",+ agentGraphVersion=1,+ constantInput=json.dumps(+ {"spreadsheet": _picked_file("owner-cred"), "range": "A1"}+ ),+ metadata="{}",+ )+ ],+ )-def test_reassign_ids_handles_no_credentials():+def test_an_agent_file_input_default_counts_as_a_picked_file():"""- Regression guard: _reassign_ids should not error when input_default- has no dict fields with _credentials_id.+ The default file of an agent's Google Drive file input embeds the+ credentials it was picked with, like a picker field. Its block declares+ the picker only per node, so the input is recognised by its type: exports+ strip it and a save keeps it only for its owner."""- from backend.data.graph import GraphModel+ graph = _graph_of()+ # Added after make_graph_model, which computes the input schema; that+ # can't yet handle a Drive input with a default file.+ graph.nodes.append(+ NodeModel(+ id="file-input",+ graph_id=graph.id,+ graph_version=graph.version,+ block_id=AgentGoogleDriveFileInputBlock().id,+ input_default={"name": "file", "value": _picked_file("owner-cred")},+ )+ )+ [node] = graph.nodes- node = Node(- id="node-1",- block_id=StoreValueBlock().id,- input_default={- "input": "some value",- "another_input": 42,- },+ assert node.stripped_for_export().input_default["value"] is None+ graph.clear_auto_credentials(keep_ids={"owner-cred"})+ assert node.input_default["value"] == _picked_file("owner-cred")+ graph.clear_auto_credentials()+ assert node.input_default["value"] is None+++async def test_get_graph_all_versions_clears_picked_files_for_anyone_but_the_owner(+ mocker,+):+ """[SECRT-1772] A teammate reading a graph's version history through org+ visibility gets the owner's picked files cleared, as `get_graph` does."""+ graph_client = AsyncMock()+ graph_client.find_many.side_effect = lambda **_: [_sheets_graph_row("owner")]+ mocker.patch.object(prisma.models.AgentGraph, "prisma", return_value=graph_client)+ mocker.patch(+ "backend.data.graph.get_user_team_ids", AsyncMock(return_value=["team-a"]))- graph = Graph(- id="test-graph",- name="Test",- description="Test",- nodes=[node],- links=[],+ [teammate_view] = await get_graph_all_versions(+ "g-1", "teammate", organization_id="org-1"+ )+ [owner_view] = await get_graph_all_versions("g-1", "owner", organization_id="org-1")++ assert teammate_view.nodes[0].input_default["spreadsheet"] is None+ assert owner_view.nodes[0].input_default["spreadsheet"] == _picked_file(+ "owner-cred"+ )+++async def test_get_store_listed_graphs_never_carries_picked_files(mocker):+ """A public read: the publisher's picked files aren't part of it."""+ listing = MagicMock(agentGraphId="g-1", AgentGraph=_sheets_graph_row("owner"))+ listing_client = AsyncMock()+ listing_client.find_many.return_value = [listing]+ mocker.patch.object(+ prisma.models.StoreListingVersion, "prisma", return_value=listing_client)- GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})+ graphs = await get_store_listed_graphs(["g-1"])- # Should not error, fields unchanged- assert graph.nodes[0].input_default["input"] == "some value"- assert graph.nodes[0].input_default["another_input"] == 42+ assert graphs["g-1"].nodes[0].input_default["spreadsheet"] is None-def test_reassign_ids_handles_multiple_credential_fields():+async def test_get_graph_clears_picked_files_for_anyone_but_the_owner(mocker):"""- [SECRT-1772] When a node has multiple dict fields with _credentials_id,- ALL of them should be cleared.+ [SECRT-1772] Only the owner sees the files they picked and the credentials+ embedded in them. A teammate opening the graph through org visibility gets+ them cleared, like a marketplace reader does."""- from backend.data.graph import GraphModel+ graph_client = AsyncMock()+ graph_client.find_first.side_effect = lambda **_: _sheets_graph_row("owner")+ mocker.patch.object(prisma.models.AgentGraph, "prisma", return_value=graph_client)+ mocker.patch(+ "backend.data.graph.get_user_team_ids", AsyncMock(return_value=["team-a"])+ )- node = Node(- id="node-1",- block_id=StoreValueBlock().id,- input_default={- "spreadsheet": {- "_credentials_id": "cred-1",- "id": "file-1",- "name": "file1.xlsx",- },- "doc_file": {- "_credentials_id": "cred-2",- "id": "file-2",- "name": "file2.docx",- },- "plain_input": "not a dict",- },+ teammate_view = await get_graph(+ "g-1", None, user_id="teammate", organization_id="org-1")+ owner_view = await get_graph("g-1", None, user_id="owner", organization_id="org-1")- graph = Graph(- id="test-graph",- name="Test",- description="Test",- nodes=[node],- links=[],+ assert teammate_view is not None and owner_view is not None+ assert teammate_view.nodes[0].input_default == {"spreadsheet": None, "range": "A1"}+ assert owner_view.nodes[0].input_default["spreadsheet"] == _picked_file(+ "owner-cred")- GraphModel._reassign_ids(graph, user_id="new-user", graph_id_map={})- # Each auto-credential field is nulled entirely — not just the id key —- # so the validator accepts the forked graph.- assert graph.nodes[0].input_default["spreadsheet"] is None- assert graph.nodes[0].input_default["doc_file"] is None- assert graph.nodes[0].input_default["plain_input"] == "not a dict"[email protected](loop_scope="session")+async def test_fork_graph_clears_picked_files(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):+ """+ [SECRT-1772] A fork never keeps the files picked in the original: it reads+ the original through `for_export`, whose stripping nulls them.+ """+ # Google blocks disable themselves without an OAuth client, as in CI.+ monkeypatch.setattr("backend.blocks.google.sheets.GOOGLE_SHEETS_DISABLED", False)+ graph = Graph(+ id="test_fork_picked_file",+ name="Fork picked file",+ description="",+ nodes=[_sheets_node("sheets_node", _picked_file("owner-cred"))],+ )+ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager.store.get_all_creds",+ new=AsyncMock(return_value=[MagicMock(id="owner-cred")]),+ ):+ created = await server.agent_server.test_create_graph(+ CreateGraph(graph=graph), DEFAULT_USER_ID+ )++ forked = await fork_graph(created.id, created.version, DEFAULT_USER_ID)+ try:+ original = await get_graph(created.id, created.version, DEFAULT_USER_ID)+ assert original is not None+ assert original.nodes[0].input_default["spreadsheet"] == _picked_file(+ "owner-cred"+ )+ assert forked.nodes[0].input_default["spreadsheet"] is None+ finally:+ await delete_graph(forked.id, user_id=DEFAULT_USER_ID)# ============================================================================@@ -2349,7 +2528,7 @@ def test_auto_credentials_fully_hydrated_object_accepted():"""Author pre-selected a file via the builder's Drive picker: theobject carries a real `_credentials_id` plus metadata. Validatormust NOT flag this — it's the legitimate author-flow shape and- forking clears `_credentials_id` separately via `_reassign_ids`."""+ forking clears `_credentials_id` separately via `stripped_for_export`."""graph = _sheets_graph({"_credentials_id": "cred-abc-def",diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex 968fff5300..7d5a550a01 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -598,7 +598,7 @@ async def _validate_node_input_credentials(if field_value is None:# Sentry HIGH: an explicitly-None value (e.g. cleared by- # `_reassign_ids` on fork, or nulled by a mask) means+ # `stripped_for_export` on fork, or nulled by a mask) means# credentials were there and are now gone. Treat as# missing so optional fields hit `nodes_to_skip` and# required fields surface a clean re-auth message —diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.pyindex 08b4af30ab..c78f69ce98 100644--- a/autogpt_platform/backend/backend/executor/utils_test.py+++ b/autogpt_platform/backend/backend/executor/utils_test.py@@ -1707,7 +1707,7 @@ async def test_validate_node_input_credentials_auto_creds_optional_none_value_skmocker: MockerFixture,):"""Sentry HIGH regression: if input_default[field_name] is explicitly- ``None`` (e.g. cleared by ``_reassign_ids`` on fork) and the field is+ ``None`` (e.g. cleared by ``stripped_for_export`` on fork) and the field isoptional, the validator previously silently skipped the wholeauto-credentials block — ``has_missing_credentials`` never flippedtrue and the node never landed in ``nodes_to_skip``. Thendiff --git a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.pyindex 67b2b8f27f..41eaa04ea2 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks.py@@ -31,7 +31,8 @@ class GraphActivationError(Exception):async def before_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModel":"""Pre-activation hook: validates node credentials and clears stale optional- credential references in-memory. MUST be called BEFORE the graph is+ credential references in-memory, along with picked files whose embedded+ credentials don't belong to the user. MUST be called BEFORE the graph ispersisted (and before it is marked active) — a failure here means nothingshould be saved, and the returned graph carries cleanup mutations thatneed to be persisted by the caller.@@ -45,6 +46,7 @@ async def before_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModeGraphActivationError: when a required node credential is missing orunusable."""+ await clear_unowned_auto_credentials(graph, user_id)graph = await _before_graph_activate(graph, user_id)graph.sub_graphs = await asyncio.gather(*(_before_graph_activate(sub_graph, user_id) for sub_graph in graph.sub_graphs)@@ -52,6 +54,28 @@ async def before_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModereturn graph+async def clear_unowned_auto_credentials(graph: "GraphModel", user_id: str) -> None:+ """+ Keep picker-selected files (e.g. from the Google Drive picker) that embed one+ of the user's own credentials, and clear the rest. The user's own picks must+ survive a save. An agent imported from someone else's export still embeds+ their `_credentials_id`, which the executor can't resolve for this user.++ `before_graph_activate` runs this; a save that skips activation (an inactive+ version) must call it itself.+ """+ if not graph.auto_credentials_refs():+ return+ owned_ids = {c.id for c in await credentials_manager.store.get_all_creds(user_id)}+ for node, field_name, credentials_id in graph.clear_auto_credentials(+ keep_ids=owned_ids+ ):+ logger.warning(+ f"Node #{node.id}: cleared the file picked for '{field_name}' because "+ f"its credentials #{credentials_id} don't belong to user #{user_id}"+ )++@overloadasync def _before_graph_activate(graph: "GraphModel", user_id: str) -> "GraphModel": ...diff --git a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.pyindex 1b91e2328d..e4e6a3b236 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/graph_lifecycle_hooks_test.py@@ -1,10 +1,15 @@+from typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from backend.blocks.basic import StoreValueBlock+from backend.blocks.google.sheets import GoogleSheetsReadBlock+from backend.data.graph import Graph, Node, make_graph_modelfrom backend.integrations.webhooks.graph_lifecycle_hooks import (GraphActivationError,_before_graph_activate,+ before_graph_activate,on_graph_deactivate,)@@ -143,6 +148,69 @@ async def test_before_graph_activate_ignores_credential_meta_without_id():getter.assert_not_awaited()+def _graph_of(*nodes: tuple[str, dict[str, Any]]):+ graph = Graph(+ id="graph-1",+ name="Test",+ description="Test",+ nodes=[+ Node(id=f"node-{i}", block_id=block_id, input_default=input_default)+ for i, (block_id, input_default) in enumerate(nodes)+ ],+ )+ return make_graph_model(graph, user_id="user-1")+++def _sheets_node(credentials_id: str) -> tuple[str, dict[str, Any]]:+ spreadsheet = {+ "_credentials_id": credentials_id,+ "id": "sheet-1",+ "name": "test",+ "mimeType": "application/vnd.google-apps.spreadsheet",+ }+ return GoogleSheetsReadBlock().id, {"spreadsheet": spreadsheet, "range": "A1"}+++async def test_before_graph_activate_keeps_only_files_picked_with_own_credentials():+ """[SECRT-1772] A save keeps the file the user picked with their own Google+ account. A file embedding someone else's credentials, as in an agent+ imported from another user's export, is cleared so they pick it again."""+ graph = _graph_of(_sheets_node("own-cred"), _sheets_node("someone-elses-cred"))++ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.store.get_all_creds = AsyncMock(return_value=[MagicMock(id="own-cred")])+ mgr.cached_getter.return_value = AsyncMock(return_value=None)+ await before_graph_activate(graph, "user-1")++ own, foreign = graph.nodes+ assert own.input_default["spreadsheet"]["_credentials_id"] == "own-cred"+ assert own.input_default["range"] == "A1"+ assert foreign.input_default["spreadsheet"] is None+ mgr.store.get_all_creds.assert_awaited_once_with("user-1")+++async def test_before_graph_activate_skips_the_lookup_without_picked_files():+ """Saving a graph without any picked file must not load the user's+ credentials just to check ownership, and must leave inputs that aren't+ pickers alone even when they hold a `_credentials_id` key."""+ data = {"_credentials_id": "someone-elses-cred"}+ graph = _graph_of((StoreValueBlock().id, {"data": data}))++ with patch(+ "backend.integrations.webhooks.graph_lifecycle_hooks.credentials_manager"+ ) as mgr:+ mgr.store.get_all_creds = AsyncMock(return_value=[])+ mgr.cached_getter.return_value = AsyncMock(return_value=None)+ await before_graph_activate(graph, "user-1")++ mgr.store.get_all_creds.assert_not_awaited()+ assert graph.nodes[0].input_default == {"data": data}++@pytest.mark.asyncioasync def test_on_graph_deactivate_ignores_credential_meta_without_id():"""Deactivation had the same `creds_meta["id"]` indexing as activation.