Skip to content

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.

feat(backend): show people who don't own a workflow the shared version of it (#15906)

Nicholas Tindle76f2bb3f59fc
diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes.py b/autogpt_platform/backend/backend/api/features/graphs/routes.py
index 49e3181db4..4fe1345fad 100644
--- a/autogpt_platform/backend/backend/api/features/graphs/routes.py
+++ b/autogpt_platform/backend/backend/api/features/graphs/routes.py
@@ -77,7 +77,10 @@ async def get_graph(
)
if not graph:
raise HTTPException(status_code=404, detail=f"Workflow #{graph_id} not found.")
- return graph
+ # Teammates and library members can read a graph they don't own; what
+ # they get never carries the owner's stored secrets, trigger subscription
+ # or identity, whatever `for_export` says.
+ return _shared_if_not_owner(graph, user_id)
@router.get(
@@ -97,7 +100,16 @@ async def get_graph_all_versions(
)
if not graphs:
raise HTTPException(status_code=404, detail=f"Workflow #{graph_id} not found.")
- return graphs
+ return [_shared_if_not_owner(graph, user_id) for graph in graphs]
+
+
+def _shared_if_not_owner(
+ graph: graph_db.GraphModel, user_id: str
+) -> graph_db.GraphModel:
+ # An export comes back with its owner blanked, so an owner's own export
+ # takes the `shared_copy` branch too. That is harmless only as long as
+ # `shared_copy` removes nothing an export keeps.
+ return graph if graph.user_id == user_id else graph.shared_copy()
@router.post(
diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py b/autogpt_platform/backend/backend/api/features/graphs/routes_test.py
index 62a60440e1..33fbb3ca6a 100644
--- a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/graphs/routes_test.py
@@ -15,11 +15,13 @@ from backend.api.features.graphs.routes import router
from backend.api.rest_api import app as real_app
from backend.api.rest_api import handle_internal_http_error
from backend.blocks.basic import StoreValueBlock
+from backend.blocks.generic_webhook.triggers import GenericWebhookTriggerBlock
from backend.blocks.google.sheets import GoogleSheetsReadBlock
from backend.blocks.io import AgentInputBlock, AgentOutputBlock
+from backend.blocks.sql_query_block import SQLQueryBlock
from backend.data import execution as execution_db
from backend.data.execution import ExecutionStatus
-from backend.data.graph import GraphModel
+from backend.data.graph import GraphModel, NodeModel
from backend.data.onboarding import OnboardingStep
from backend.integrations.webhooks.graph_lifecycle_hooks import GraphActivationError
from backend.util.exceptions import GraphValidationError
@@ -278,6 +280,162 @@ def test_get_graph(
)
+def _graph_owned_by(owner_id: str) -> GraphModel:
+ owner = {
+ "user_id": owner_id,
+ "organization_id": "owner-org",
+ "team_id": "owner-team",
+ "created_at": datetime(2025, 9, 4, 13, 37),
+ }
+ sub_graph = GraphModel(
+ id="sub-graph",
+ name="Sub",
+ description="",
+ nodes=[
+ NodeModel(
+ id="query",
+ block_id=SQLQueryBlock().id,
+ graph_id="sub-graph",
+ graph_version=1,
+ input_default={"host": "db.internal", "query": "select 1"},
+ )
+ ],
+ **owner,
+ )
+ return GraphModel(
+ id="graph-123",
+ version=1,
+ is_active=True,
+ name="Shared",
+ description="",
+ nodes=[
+ NodeModel(
+ id="trigger",
+ block_id=GenericWebhookTriggerBlock().id,
+ graph_id="graph-123",
+ graph_version=1,
+ input_default={"secret_token": "owner-token"},
+ webhook_id="owner-webhook",
+ )
+ ],
+ sub_graphs=[sub_graph],
+ **owner,
+ )
+
+
+ "path",
+ [
+ "/graphs/graph-123",
+ "/graphs/graph-123?for_export=false",
+ "/graphs/graph-123/versions/1",
+ ],
+)
+def test_get_graph_gives_someone_who_isnt_the_owner_an_export(
+ mocker: pytest_mock.MockFixture, path: str
+) -> None:
+ """A teammate or library member reading a graph they don't own gets what
+ an export gives, whatever they ask for: no stored secrets, no trigger
+ subscription, no owner."""
+ mocker.patch(
+ "backend.api.features.graphs.routes.graph_db.get_graph",
+ return_value=_graph_owned_by("someone-else"),
+ )
+
+ response = client.get(path)
+
+ assert response.status_code == 200
+ graph = response.json()
+ assert (graph["user_id"], graph["organization_id"], graph["team_id"]) == (
+ "",
+ None,
+ None,
+ )
+ [trigger] = graph["nodes"]
+ assert trigger["webhook_id"] is None
+ assert "secret_token" not in trigger["input_default"]
+ [sub_graph] = graph["sub_graphs"]
+ assert not any(
+ sub_graph.get(key) for key in ("user_id", "organization_id", "team_id")
+ )
+ assert "host" not in sub_graph["nodes"][0]["input_default"]
+
+
+def test_get_graph_gives_the_owner_their_graph_as_saved(
+ mocker: pytest_mock.MockFixture, test_user_id: str
+) -> None:
+ mocker.patch(
+ "backend.api.features.graphs.routes.graph_db.get_graph",
+ return_value=_graph_owned_by(test_user_id),
+ )
+
+ graph = client.get("/graphs/graph-123").json()
+
+ assert (graph["user_id"], graph["organization_id"], graph["team_id"]) == (
+ test_user_id,
+ "owner-org",
+ "owner-team",
+ )
+ [trigger] = graph["nodes"]
+ assert trigger["webhook_id"] == "owner-webhook"
+ assert trigger["input_default"]["secret_token"] == "owner-token"
+ assert graph["sub_graphs"][0]["nodes"][0]["input_default"]["host"] == "db.internal"
+
+
+def test_an_owners_export_keeps_everything_the_export_kept(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """An export comes back with its owner blanked, so the route can't tell an
+ owner's export from anyone else's and sends it through `shared_copy`.
+ That has to take nothing away, such as the plain inputs an export keeps
+ on a node whose block is missing."""
+ export = GraphModel(
+ id="graph-123",
+ version=1,
+ is_active=True,
+ name="Exported",
+ description="",
+ user_id="",
+ created_at=datetime(2025, 9, 4, 13, 37),
+ nodes=[
+ NodeModel(
+ id="gone",
+ block_id="00000000-0000-0000-0000-0000000dead00",
+ graph_id="graph-123",
+ graph_version=1,
+ input_default={"note": "plain"},
+ )
+ ],
+ )
+ mocker.patch(
+ "backend.api.features.graphs.routes.graph_db.get_graph",
+ return_value=export,
+ )
+
+ graph = client.get("/graphs/graph-123?for_export=true").json()
+
+ assert graph["nodes"][0]["input_default"] == {"note": "plain"}
+
+
+def test_get_graph_all_versions_exports_only_the_versions_someone_else_owns(
+ mocker: pytest_mock.MockFixture, test_user_id: str
+) -> None:
+ mocker.patch(
+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",
+ return_value=[_graph_owned_by(test_user_id), _graph_owned_by("teammate")],
+ )
+
+ own, teammates = client.get("/graphs/graph-123/versions").json()
+
+ assert own["user_id"] == test_user_id
+ assert own["nodes"][0]["webhook_id"] == "owner-webhook"
+ assert own["nodes"][0]["input_default"]["secret_token"] == "owner-token"
+ assert teammates["user_id"] == ""
+ assert teammates["nodes"][0]["webhook_id"] is None
+ assert "secret_token" not in teammates["nodes"][0]["input_default"]
+ assert "host" not in teammates["sub_graphs"][0]["nodes"][0]["input_default"]
+
+
def test_get_graph_not_found(
mocker: pytest_mock.MockFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/api/features/otto/service.py b/autogpt_platform/backend/backend/api/features/otto/service.py
index 992021c0ca..ecde2f311b 100644
--- a/autogpt_platform/backend/backend/api/features/otto/service.py
+++ b/autogpt_platform/backend/backend/api/features/otto/service.py
@@ -32,6 +32,8 @@ class OttoService:
)
if not graph:
return None
+ if graph.user_id != user_id:
+ graph = graph.shared_copy()
nodes_data = []
for node in graph.nodes:
diff --git a/autogpt_platform/backend/backend/api/features/otto/service_test.py b/autogpt_platform/backend/backend/api/features/otto/service_test.py
new file mode 100644
index 0000000000..0eef466918
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/otto/service_test.py
@@ -0,0 +1,69 @@
+from datetime import datetime
+
+import pytest
+import pytest_mock
+
+from backend.blocks.generic_webhook.triggers import GenericWebhookTriggerBlock
+from backend.data.graph import GraphModel, NodeModel
+
+from .models import ChatRequest
+from .service import OttoService
+
+
+def _graph_owned_by(owner_id: str) -> GraphModel:
+ return GraphModel(
+ id="graph-1",
+ version=1,
+ name="Listed",
+ description="",
+ user_id=owner_id,
+ created_at=datetime(2026, 1, 1),
+ nodes=[
+ NodeModel(
+ id="trigger",
+ block_id=GenericWebhookTriggerBlock().id,
+ graph_id="graph-1",
+ graph_version=1,
+ input_default={"secret_token": "owner-token", "constants": {}},
+ )
+ ],
+ )
+
+
+async def _graph_data_for(
+ mocker: pytest_mock.MockFixture, user_id: str, graph: GraphModel
+):
+ mocker.patch(
+ "backend.api.features.otto.service.graph_db.get_graph",
+ mocker.AsyncMock(return_value=graph),
+ )
+ request = ChatRequest(
+ query="What does this do?",
+ conversation_history=[],
+ message_id="message-1",
+ include_graph_data=True,
+ graph_id="graph-1",
+ )
+ return await OttoService._fetch_graph_data(request, user_id)
+
+
+async def test_someone_elses_graph_goes_to_otto_without_its_stored_secrets(
+ mocker: pytest_mock.MockFixture,
+):
+ data = await _graph_data_for(mocker, "library-member", _graph_owned_by("publisher"))
+
+ assert data is not None
+ [node] = data.nodes
+ assert node["data"] == {"constants": {}}
+
+
+async def test_the_owners_graph_goes_to_otto_as_saved(
+ mocker: pytest_mock.MockFixture,
+):
+ data = await _graph_data_for(mocker, "owner", _graph_owned_by("owner"))
+
+ assert data is not None
+ [node] = data.nodes
+ assert node["data"]["secret_token"] == "owner-token"
diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.py
index 2451b00c55..24420fb34b 100644
--- a/autogpt_platform/backend/backend/api/features/store/routes.py
+++ b/autogpt_platform/backend/backend/api/features/store/routes.py
@@ -297,7 +297,8 @@ async def get_graph_meta_by_store_listing_version_id(
) -> backend.data.graph.GraphModelWithoutNodes:
"""Get outline of graph belonging to a specific marketplace listing version"""
graph = await store_db.get_available_graph(store_listing_version_id)
- return graph
+ # Public outline: it names the workflow, not the account that published it.
+ return graph.shared_copy()
@router.get(
diff --git a/autogpt_platform/backend/backend/api/features/store/routes_test.py b/autogpt_platform/backend/backend/api/features/store/routes_test.py
index 02a9d7f0ae..a323e131d4 100644
--- a/autogpt_platform/backend/backend/api/features/store/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/routes_test.py
@@ -12,6 +12,7 @@ from pydantic import BaseModel
from pytest_snapshot.plugin import Snapshot
from backend.api.features.store.db import StoreAgentsSortOptions
+from backend.data.graph import GraphModelWithoutNodes
from . import model as store_model
from . import routes as store_routes
@@ -988,6 +989,39 @@ class _DownloadedGraph(BaseModel):
version: int
+def test_listing_graph_outline_names_no_publisher_account(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Any signed-in user can read a listing's outline, so it carries no ids
+ of the account or organization that published the workflow."""
+ mocker.patch(
+ "backend.api.features.store.db.get_available_graph",
+ mocker.AsyncMock(
+ return_value=GraphModelWithoutNodes(
+ id="graph-1",
+ version=1,
+ name="Listed",
+ description="",
+ user_id="publisher",
+ organization_id="publisher-org",
+ team_id="publisher-team",
+ created_at=FIXED_NOW,
+ )
+ ),
+ )
+
+ response = client.get("/listings/versions/slv-1/graph")
+
+ assert response.status_code == 200
+ outline = response.json()
+ assert outline["id"] == "graph-1"
+ assert (outline["user_id"], outline["organization_id"], outline["team_id"]) == (
+ "",
+ None,
+ None,
+ )
+
+
def test_download_agent_file_sends_listing_downloaded(
mocker: pytest_mock.MockFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py
index 90b89476b2..9a132709d8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/core.py
@@ -698,4 +698,8 @@ async def get_agent_as_json(
if not graph:
return None
+ if graph.user_id != user_id:
+ # A library copy of someone else's workflow: the file the caller gets
+ # mustn't carry the owner's stored secrets or references.
+ graph = graph.shared_copy()
return graph_to_json(graph)
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/core_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/core_test.py
new file mode 100644
index 0000000000..5fb4e2f682
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/core_test.py
@@ -0,0 +1,91 @@
+from datetime import datetime
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.blocks.agent import AgentExecutorBlock
+from backend.blocks.generic_webhook.triggers import GenericWebhookTriggerBlock
+from backend.copilot.tools.agent_generator.core import get_agent_as_json
+from backend.copilot.tools.agent_generator.validator import AgentValidator
+from backend.data.graph import GraphModel, NodeModel
+
+
+def _graph_owned_by(owner_id: str) -> GraphModel:
+ return GraphModel(
+ id="graph-1",
+ version=1,
+ name="Listed",
+ description="",
+ user_id=owner_id,
+ created_at=datetime(2026, 1, 1),
+ nodes=[
+ NodeModel(
+ id="trigger",
+ block_id=GenericWebhookTriggerBlock().id,
+ graph_id="graph-1",
+ graph_version=1,
+ input_default={"secret_token": "owner-token", "constants": {}},
+ )
+ ],
+ )
+
+
+async def _agent_json_for(user_id: str, graph: GraphModel) -> dict | None:
+ db = MagicMock()
+ db.get_graph = AsyncMock(return_value=graph)
+ with patch("backend.copilot.tools.agent_generator.core.graph_db", return_value=db):
+ return await get_agent_as_json("graph-1", user_id)
+
+
+async def test_a_library_copy_of_someone_elses_workflow_comes_stripped():
+ """A workflow from the marketplace is readable from the caller's library,
+ but the JSON they get (written to their workspace, edited) is the one an
+ export gives: no secrets the publisher stored on it."""
+ agent_json = await _agent_json_for("library-member", _graph_owned_by("publisher"))
+
+ assert agent_json is not None
+ [trigger] = agent_json["nodes"]
+ assert trigger["input_default"] == {"constants": {}}
+
+
+async def test_a_sub_agent_node_in_someone_elses_workflow_stays_valid():
+ """A sub-agent node names the account that saved the graph. The copy
+ blanks that id instead of dropping it: the field is required, and the
+ validator checks an edited copy before the save stamps the saver's id."""
+ graph = _graph_owned_by("publisher")
+ graph.nodes.append(
+ NodeModel(
+ id="sub-agent",
+ block_id=AgentExecutorBlock().id,
+ graph_id="graph-1",
+ graph_version=1,
+ input_default={
+ "user_id": "publisher",
+ "graph_id": "child-graph",
+ "graph_version": 1,
+ "inputs": {},
+ "input_schema": {},
+ "output_schema": {},
+ },
+ )
+ )
+
+ agent_json = await _agent_json_for("library-member", graph)
+
+ assert agent_json is not None
+ validator = AgentValidator()
+ blocks = [AgentExecutorBlock().get_info().model_dump()]
+ assert validator.validate_required_inputs(agent_json, blocks), validator.errors
+ sub_agent = next(n for n in agent_json["nodes"] if n["id"] == "sub-agent")
+ assert sub_agent["input_default"]["user_id"] == ""
+
+
+async def test_the_owner_gets_their_workflow_as_saved():
+ agent_json = await _agent_json_for("owner", _graph_owned_by("owner"))
+
+ assert agent_json is not None
+ [trigger] = agent_json["nodes"]
+ assert trigger["input_default"]["secret_token"] == "owner-token"
diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.py
index 4f8d85ee32..fff265334c 100644
--- a/autogpt_platform/backend/backend/data/graph.py
+++ b/autogpt_platform/backend/backend/data/graph.py
@@ -148,37 +148,9 @@ class Node(BaseDbModel):
return _UnknownBlockBase(self.block_id)
return block
-
-class NodeModel(Node):
- graph_id: str
- graph_version: int
-
- webhook_id: Optional[str] = None
- # webhook: Optional["Webhook"] = None # deprecated
-
- @staticmethod
- def from_db(node: AgentNode, for_export: bool = False) -> "NodeModel":
- obj = NodeModel(
- id=node.id,
- block_id=node.agentBlockId,
- input_default=type_utils.convert(node.constantInput, BlockInput),
- metadata=type_utils.convert(node.metadata, dict[str, Any]),
- graph_id=node.agentGraphId,
- graph_version=node.agentGraphVersion,
- webhook_id=node.webhookId,
- )
- obj.input_links = [Link.from_db(link) for link in node.Input or []]
- obj.output_links = [Link.from_db(link) for link in node.Output or []]
- if for_export:
- return obj.stripped_for_export()
- return obj
-
- def is_triggered_by_event_type(self, event_type: str) -> bool:
- return self.block.is_triggered_by_event_type(self.input_default, event_type)
-
- def stripped_for_export(self) -> "NodeModel":
+ def stripped_for_export(self) -> Self:
"""
- Returns a copy of the node model with non-transferable references removed:
+ Returns a copy of the node with non-transferable input values removed:
- fields the block schema declares as a `CredentialsMetaInput`
(point at the original owner's credentials store; importers must
wire up their own)
@@ -188,10 +160,16 @@ class NodeModel(Node):
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)
+ - a sub-agent node's `user_id`, which `reassign_ids` stamps with the
+ owner's id on save and stamps again with the importer's. It is
+ blanked rather than removed: the field is required, and the agent
+ generator validates an edited copy before its save stamps the id.
"""
stripped_node = self.model_copy(deep=True)
+ if self.block_id == AgentExecutorBlock().id:
+ stripped_node.input_default["user_id"] = ""
+
if stripped_node.input_default:
for field_name in self.block.input_schema.get_credentials_fields():
stripped_node.input_default.pop(field_name, None)
@@ -208,8 +186,41 @@ class NodeModel(Node):
if field_name in stripped_node.input_default:
stripped_node.input_default[field_name] = None
- stripped_node.webhook_id = None
+ return stripped_node
+
+class NodeModel(Node):
+ graph_id: str
+ graph_version: int
+
+ webhook_id: Optional[str] = None
+ # webhook: Optional["Webhook"] = None # deprecated
+
+ @staticmethod
+ def from_db(node: AgentNode, for_export: bool = False) -> "NodeModel":
+ obj = NodeModel(
+ id=node.id,
+ block_id=node.agentBlockId,
+ input_default=type_utils.convert(node.constantInput, BlockInput),
+ metadata=type_utils.convert(node.metadata, dict[str, Any]),
+ graph_id=node.agentGraphId,
+ graph_version=node.agentGraphVersion,
+ webhook_id=node.webhookId,
+ )
+ obj.input_links = [Link.from_db(link) for link in node.Input or []]
+ obj.output_links = [Link.from_db(link) for link in node.Output or []]
+ if for_export:
+ return obj.stripped_for_export()
+ return obj
+
+ def is_triggered_by_event_type(self, event_type: str) -> bool:
+ return self.block.is_triggered_by_event_type(self.input_default, event_type)
+
+ def stripped_for_export(self) -> Self:
+ """`Node.stripped_for_export`, and also drops `webhook_id` (points at
+ the original owner's webhook subscription)."""
+ stripped_node = super().stripped_for_export()
+ stripped_node.webhook_id = None
return stripped_node
@@ -1316,6 +1327,37 @@ class GraphModel(Graph, GraphMeta):
"""
return GraphModelWithoutNodes.model_validate(self, from_attributes=True)
+ def shared_copy(self) -> Self:
+ """A copy safe to show someone who doesn't own this graph.
+
+ Every node, sub-graphs' included, is stripped the way an export strips
+ it (`stripped_for_export`), and the owner's identity is blanked, as
+ `from_db(..., for_export=True)` does. It works on an already-loaded
+ model, so a route can decide by ownership once it knows the owner.
+ Internal callers that act on the owner's behalf (presets, triggers, the
+ executor) keep reading the full graph.
+ """
+ return self.model_copy(
+ update={
+ "user_id": "",
+ "organization_id": None,
+ "team_id": None,
+ "nodes": [node.stripped_for_export() for node in self.nodes],
+ # Sub-graphs serialize without their owner's ids only because
+ # they are typed `BaseGraph`, which has no such fields.
+ "sub_graphs": [
+ sub_graph.model_copy(
+ update={
+ "nodes": [
+ node.stripped_for_export() for node in sub_graph.nodes
+ ]
+ }
+ )
+ for sub_graph in self.sub_graphs
+ ],
+ }
+ )
+
def _describe_node_errors(
graph: BaseGraph, node_errors: Mapping[str, Mapping[str, str]]
diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.py
index 71aeab0855..e51fc155b3 100644
--- a/autogpt_platform/backend/backend/data/graph_test.py
+++ b/autogpt_platform/backend/backend/data/graph_test.py
@@ -16,10 +16,13 @@ import backend.api.features.library.db as library_db
import backend.api.features.store.model as store
from backend.api.features.graphs import routes as graphs_routes
from backend.api.model import CreateGraph
-from backend.blocks._base import BlockSchema, BlockSchemaInput
+from backend.blocks import _all_subclasses, load_all_blocks
+from backend.blocks._base import Block, BlockSchema, BlockSchemaInput
+from backend.blocks.agent import AgentExecutorBlock
from backend.blocks.autopilot import AUTOPILOT_BLOCK_ID, AutoPilotTransport
from backend.blocks.basic import StoreValueBlock
from backend.blocks.code_executor import ExecuteCodeBlock
+from backend.blocks.generic_webhook.triggers import GenericWebhookTriggerBlock
from backend.blocks.google.sheets import GoogleSheetsReadBlock
from backend.blocks.io import (
AgentGoogleDriveFileInputBlock,
@@ -27,6 +30,7 @@ from backend.blocks.io import (
AgentOutputBlock,
)
from backend.blocks.llm import LEGACY_MODEL_MAPPINGS, LLMModel
+from backend.blocks.sql_query_block import SQLQueryBlock
from backend.data.graph import (
SUBMITTED_TO_MARKETPLACE,
BaseGraph,
@@ -758,6 +762,140 @@ def test_picked_files_of_a_removed_block_are_still_found():
assert graph.nodes[0].input_default == {"file": None, "note": "plain"}
+def _sub_agent_node(user_id: str) -> Node:
+ return Node(
+ id="sub-agent",
+ block_id=AgentExecutorBlock().id,
+ input_default={
+ "user_id": user_id,
+ "graph_id": "child-graph",
+ "graph_version": 1,
+ "inputs": {},
+ "input_schema": {},
+ "output_schema": {},
+ },
+ )
+
+
+def test_stripped_for_export_blanks_a_sub_agent_nodes_user_id():
+ """A sub-agent node holds the id of the account that saved the graph. An
+ export blanks it, and the copy still works: saving it stamps the id of
+ whoever saves it."""
+ graph = _graph_of(_sub_agent_node("owner-user"))
+
+ exported = graph.nodes[0].stripped_for_export()
+
+ assert exported.input_default["user_id"] == ""
+ assert exported.input_default["graph_id"] == "child-graph"
+ assert graph.nodes[0].input_default["user_id"] == "owner-user"
+
+ copy = _graph_of(
+ Node(
+ id="sub-agent",
+ block_id=exported.block_id,
+ input_default=exported.input_default,
+ )
+ )
+ copy.reassign_ids(user_id="importer", reassign_graph_id=True)
+ assert copy.nodes[0].input_default["user_id"] == "importer"
+
+
+def test_shared_copy_strips_every_node_and_names_no_owner():
+ """What someone who doesn't own a graph is shown: every node, sub-graphs'
+ included, stripped as an export strips it, and no owner. The graph it was
+ copied from is untouched, and the run form built from it is the same."""
+ trigger = Node(
+ id="trigger",
+ block_id=GenericWebhookTriggerBlock().id,
+ input_default={"secret_token": "owner-token", "constants": {"k": "v"}},
+ )
+ code = Node(
+ id="code",
+ block_id=ExecuteCodeBlock().id,
+ input_default={
+ "credentials": {"id": "owner-e2b", "provider": "e2b", "type": "api_key"},
+ "code": "print('hi')",
+ },
+ )
+ sql = Node(
+ id="sql",
+ block_id=SQLQueryBlock().id,
+ input_default={"host": "db.internal", "database": "app", "query": "select 1"},
+ )
+ graph = _graph_of(
+ trigger, code, _sub_agent_node("test-user"), sub_graph_nodes=[sql]
+ )
+ graph.organization_id, graph.team_id = "owner-org", "owner-team"
+ graph.nodes[0].webhook_id = "owner-webhook"
+
+ shared = graph.shared_copy()
+
+ assert (shared.user_id, shared.organization_id, shared.team_id) == ("", None, None)
+ assert [node.webhook_id for node in shared.nodes] == [None, None, None]
+ assert shared.nodes[0].input_default == {"constants": {"k": "v"}}
+ assert shared.nodes[1].input_default == {"code": "print('hi')"}
+ assert shared.nodes[2].input_default["user_id"] == ""
+ assert shared.sub_graphs[0].nodes[0].input_default == {
+ "database": "app",
+ "query": "select 1",
+ }
+
+ assert graph.user_id == "test-user"
+ assert graph.nodes[0].webhook_id == "owner-webhook"
+ assert graph.nodes[0].input_default["secret_token"] == "owner-token"
+ assert graph.sub_graphs[0].nodes[0].input_default["host"] == "db.internal"
+
+ assert shared.input_schema == graph.input_schema
+ assert shared.credentials_input_schema == graph.credentials_input_schema
+ assert shared.trigger_setup_info == graph.trigger_setup_info
+
+
+def test_only_known_block_fields_are_marked_secret():
+ """Guard on what `stripped_for_export` strips. It finds secret inputs by
+ the `secret` flag in the block's current schema, so a value saved under a
+ field (or block) that has since been renamed or removed is no longer
+ recognised, and exports and shared copies would carry it. Before removing
+ or renaming one of these, scrub the stored values with a data migration;
+ a newly added one only needs adding here.
+
+ Every block class counts, including those this environment leaves out of
+ `load_all_blocks()` because their provider isn't configured."""
+ load_all_blocks() # imports every block module
+ block_classes = {
+ block_cls
+ for block_cls in _all_subclasses(Block)
+ if block_cls.__module__.startswith("backend.blocks.")
+ and not block_cls.__name__.endswith("Base")
+ }
+
+ secret_fields = set()
+ construction_failures: list[str] = []
+ for block_cls in block_classes:
+ try:
+ block = block_cls()
+ except Exception as e:
+ # Never skip silently: an excluded block is one this guard did not
+ # actually check.
+ construction_failures.append(f"{block_cls.__name__}: {e!r}")
+ continue
+ properties = block.input_schema.jsonschema().get("properties", {})
+ for name, field_schema in properties.items():
+ if isinstance(field_schema, dict) and field_schema.get("secret") is True:
+ secret_fields.add((block.name, name))
+
+ assert not construction_failures, (
+ "blocks failed to construct, so they were not covered by this guard: "
+ + "; ".join(construction_failures)
+ )
+ assert secret_fields == {
+ ("AllQuietIncidentTriggerBlock", "signing_secret"),
+ ("AutoPilotBlock", "codex_credentials"),
+ ("GenericWebhookTriggerBlock", "secret_token"),
+ ("PublishToMediumBlock", "author_id"),
+ ("SQLQueryBlock", "host"),
+ }
+
+
def _sheets_graph_row(owner_id: str) -> AgentGraph:
return AgentGraph(
id="g-1",