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.

fix(backend/transfers): execute transfers atomically and re-check ownership (#15325)

Nicholas Tindle876a7fd0f587
diff --git a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
index f8604d1707..d979ec9b71 100644
--- a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
+++ b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
@@ -9,6 +9,7 @@ Tests mock at the Prisma model boundary (``ModelName.prisma()``) so the
real Python logic is exercised while no database connection is needed.
"""
+from contextlib import asynccontextmanager
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
@@ -2533,6 +2534,12 @@ class TestPR16Transfers:
self.mock_prisma = MagicMock()
mocker.patch("backend.api.features.transfers.db.prisma", self.mock_prisma)
+ @asynccontextmanager
+ async def _tx():
+ yield self.mock_prisma
+
+ mocker.patch("backend.api.features.transfers.db.transaction", _tx)
+
def _make_transfer_row(
self,
*,
@@ -2622,7 +2629,10 @@ class TestPR16Transfers:
status="SOURCE_APPROVED",
source_approved_by=USER_ID,
)
- self.mock_prisma.transferrequest.update = AsyncMock(return_value=updated)
+ self.mock_prisma.transferrequest.update_many = AsyncMock(return_value=1)
+ self.mock_prisma.transferrequest.find_unique_or_raise = AsyncMock(
+ return_value=updated
+ )
from backend.api.features.transfers.db import approve_transfer
@@ -2633,7 +2643,9 @@ class TestPR16Transfers:
)
assert result.status == "SOURCE_APPROVED"
- update_data = self.mock_prisma.transferrequest.update.call_args.kwargs["data"]
+ update_data = self.mock_prisma.transferrequest.update_many.call_args.kwargs[
+ "data"
+ ]
assert update_data["sourceApprovedByUserId"] == USER_ID
assert update_data["status"] == "SOURCE_APPROVED"
@@ -2648,7 +2660,10 @@ class TestPR16Transfers:
status="TARGET_APPROVED",
target_approved_by="user-target",
)
- self.mock_prisma.transferrequest.update = AsyncMock(return_value=updated)
+ self.mock_prisma.transferrequest.update_many = AsyncMock(return_value=1)
+ self.mock_prisma.transferrequest.find_unique_or_raise = AsyncMock(
+ return_value=updated
+ )
from backend.api.features.transfers.db import approve_transfer
@@ -2659,7 +2674,9 @@ class TestPR16Transfers:
)
assert result.status == "TARGET_APPROVED"
- update_data = self.mock_prisma.transferrequest.update.call_args.kwargs["data"]
+ update_data = self.mock_prisma.transferrequest.update_many.call_args.kwargs[
+ "data"
+ ]
assert update_data["targetApprovedByUserId"] == "user-target"
assert update_data["status"] == "TARGET_APPROVED"
@@ -2680,7 +2697,13 @@ class TestPR16Transfers:
target_approved_by="user-target",
completed_at=datetime(2025, 7, 1, tzinfo=timezone.utc),
)
- self.mock_prisma.transferrequest.update = AsyncMock(return_value=completed)
+ self.mock_prisma.transferrequest.find_unique_or_raise = AsyncMock(
+ return_value=completed
+ )
+ self.mock_prisma.transferrequest.update_many = AsyncMock(return_value=1)
+ graph_row = MagicMock()
+ graph_row.organizationId = "org-1"
+ self.mock_prisma.agentgraph.find_first = AsyncMock(return_value=graph_row)
self.mock_prisma.agentgraph.update_many = AsyncMock(return_value=1)
self.mock_prisma.auditlog.create = AsyncMock(return_value=MagicMock())
@@ -2694,12 +2717,51 @@ class TestPR16Transfers:
assert result.status == "COMPLETED"
# Verify the resource was moved to target org, ALL versions, landing
- # at org-home (teamId=None) so it's visible in the target org.
+ # at org-home (teamId=None) so it's visible in the target org, and
+ # only while the source org still owns it (#15271).
self.mock_prisma.agentgraph.update_many.assert_called_once()
move_call = self.mock_prisma.agentgraph.update_many.call_args.kwargs
assert move_call["data"]["organizationId"] == "org-2"
assert move_call["data"]["teamId"] is None
- assert move_call["where"] == {"id": GRAPH_ID}
+ assert move_call["where"] == {"id": GRAPH_ID, "organizationId": "org-1"}
+ # Json columns must get SafeJson, not bare dicts (#15267).
+ from prisma import Json
+
+ assert self.mock_prisma.auditlog.create.call_count == 2
+ for call in self.mock_prisma.auditlog.create.call_args_list:
+ assert isinstance(call.kwargs["data"]["afterJson"], Json)
+ assert isinstance(call.kwargs["data"]["beforeJson"], Json)
+
+ @pytest.mark.asyncio
+ async def test_execute_store_listing_move_is_scoped_to_source_org(self):
+ """A StoreListing move only matches while the source org owns it;
+ a zero-row move aborts and rejects the transfer (#15271)."""
+ approved = self._make_transfer_row(
+ status="SOURCE_APPROVED",
+ resource_type="StoreListing",
+ resource_id="listing-1",
+ source_approved_by=USER_ID,
+ target_approved_by="user-target",
+ )
+ self.mock_prisma.transferrequest.find_unique = AsyncMock(return_value=approved)
+ self.mock_prisma.transferrequest.update_many = AsyncMock(return_value=1)
+ listing = MagicMock()
+ listing.isDeleted = False
+ listing.owningOrgId = "org-1"
+ self.mock_prisma.storelisting.find_unique = AsyncMock(return_value=listing)
+ self.mock_prisma.storelisting.update_many = AsyncMock(return_value=0)
+ self.mock_prisma.auditlog.create = AsyncMock(return_value=MagicMock())
+
+ from backend.api.features.transfers.db import execute_transfer
+
+ with pytest.raises(ValueError, match="no longer belongs"):
+ await execute_transfer(transfer_id="tr-1", user_id=USER_ID, org_id="org-1")
+
+ move_call = self.mock_prisma.storelisting.update_many.call_args.kwargs
+ assert move_call["where"] == {"id": "listing-1", "owningOrgId": "org-1"}
+ self.mock_prisma.auditlog.create.assert_not_called()
+ reject_call = self.mock_prisma.transferrequest.update_many.call_args.kwargs
+ assert reject_call["data"] == {"status": "REJECTED"}
@pytest.mark.asyncio
async def test_execute_rejects_non_party_org(self):
@@ -2752,7 +2814,10 @@ class TestPR16Transfers:
self.mock_prisma.transferrequest.find_unique = AsyncMock(return_value=pending)
rejected = self._make_transfer_row(status="REJECTED")
- self.mock_prisma.transferrequest.update = AsyncMock(return_value=rejected)
+ self.mock_prisma.transferrequest.update_many = AsyncMock(return_value=1)
+ self.mock_prisma.transferrequest.find_unique_or_raise = AsyncMock(
+ return_value=rejected
+ )
from backend.api.features.transfers.db import reject_transfer
@@ -2763,8 +2828,12 @@ class TestPR16Transfers:
)
assert result.status == "REJECTED"
- update_data = self.mock_prisma.transferrequest.update.call_args.kwargs["data"]
- assert update_data["status"] == "REJECTED"
+ call = self.mock_prisma.transferrequest.update_many.call_args.kwargs
+ assert call["data"] == {"status": "REJECTED"}
+ # Conditional, so it can't overwrite a transfer that just completed.
+ assert call["where"]["status"] == {
+ "not_in": ["COMPLETED", "REJECTED", "CANCELLED"]
+ }
@pytest.mark.asyncio
async def test_list_transfers_returns_both_directions(self):
@@ -3530,18 +3599,22 @@ class TestReviewFindings:
async def capture_update(*, where, data):
update_capture.update(data)
- result = self._make_transfer(
- status=data.get("status", "SOURCE_APPROVED"),
- sourceApprovedByUserId=USER_ID,
- targetApprovedByUserId="user-target",
- )
- return result
+ return 1
with patch("backend.api.features.transfers.db.prisma") as mock_prisma:
mock_prisma.transferrequest.find_unique = AsyncMock(
return_value=source_approved
)
- mock_prisma.transferrequest.update = AsyncMock(side_effect=capture_update)
+ mock_prisma.transferrequest.update_many = AsyncMock(
+ side_effect=capture_update
+ )
+ mock_prisma.transferrequest.find_unique_or_raise = AsyncMock(
+ side_effect=lambda **kwargs: self._make_transfer(
+ status=update_capture.get("status", "SOURCE_APPROVED"),
+ sourceApprovedByUserId=USER_ID,
+ targetApprovedByUserId="user-target",
+ )
+ )
from backend.api.features.transfers.db import approve_transfer
diff --git a/autogpt_platform/backend/backend/api/features/transfers/approval_test.py b/autogpt_platform/backend/backend/api/features/transfers/approval_test.py
new file mode 100644
index 0000000000..20c9efd949
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/transfers/approval_test.py
@@ -0,0 +1,95 @@
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.models import TransferRequest
+
+from backend.api.features.transfers import db as transfers_db
+
+
[email protected](loop_scope="session")
[email protected]("terminal_status", ["REJECTED", "CANCELLED", "COMPLETED"])
+async def test_stale_approval_cannot_reopen_terminal_transfer(
+ transfer_world, terminal_status
+):
+ world = transfer_world
+ transfer = await transfers_db.create_transfer(
+ world["org_a"],
+ world["org_b"],
+ world["resource_type"],
+ world["resource_id"],
+ world["source_user"],
+ )
+ await transfers_db.approve_transfer(
+ transfer.id, world["source_user"], world["org_a"]
+ )
+ stale = await TransferRequest.prisma().find_unique_or_raise(
+ where={"id": transfer.id}
+ )
+ if terminal_status == "COMPLETED":
+ await transfers_db.approve_transfer(
+ transfer.id, world["target_user"], world["org_b"]
+ )
+ await transfers_db.execute_transfer(
+ transfer.id, world["source_user"], world["org_a"]
+ )
+ else:
+ await TransferRequest.prisma().update(
+ where={"id": transfer.id}, data={"status": terminal_status}
+ )
+ before = await TransferRequest.prisma().find_unique_or_raise(
+ where={"id": transfer.id}
+ )
+
+ with patch.object(
+ type(transfers_db.prisma.transferrequest),
+ "find_unique",
+ AsyncMock(return_value=stale),
+ ), pytest.raises(ValueError):
+ await transfers_db.approve_transfer(
+ transfer.id, world["target_user"], world["org_b"]
+ )
+
+ after = await TransferRequest.prisma().find_unique_or_raise(
+ where={"id": transfer.id}
+ )
+ assert after == before
+
+
[email protected](loop_scope="session")
[email protected]("same_side", [True, False])
+async def test_concurrent_approvals_preserve_both_sides(transfer_world, same_side):
+ world = transfer_world
+ transfer = await transfers_db.create_transfer(
+ world["org_a"],
+ world["org_b"],
+ world["resource_type"],
+ world["resource_id"],
+ world["source_user"],
+ )
+ results = await asyncio.gather(
+ transfers_db.approve_transfer(
+ transfer.id, world["source_user"], world["org_a"]
+ ),
+ transfers_db.approve_transfer(
+ transfer.id,
+ world["source_user"] if same_side else world["target_user"],
+ world["org_a"] if same_side else world["org_b"],
+ ),
+ return_exceptions=True,
+ )
+ errors = [r for r in results if isinstance(r, BaseException)]
+ assert len(errors) == int(same_side), results
+ assert all(isinstance(error, ValueError) for error in errors)
+ stored = await TransferRequest.prisma().find_unique_or_raise(
+ where={"id": transfer.id}
+ )
+ assert stored.sourceApprovedByUserId == world["source_user"]
+ assert stored.targetApprovedByUserId == (
+ None if same_side else world["target_user"]
+ )
+ if not same_side:
+ result = await transfers_db.execute_transfer(
+ transfer.id, world["source_user"], world["org_a"]
+ )
+ assert result.status == "COMPLETED"
diff --git a/autogpt_platform/backend/backend/api/features/transfers/conftest.py b/autogpt_platform/backend/backend/api/features/transfers/conftest.py
new file mode 100644
index 0000000000..245877e58f
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/transfers/conftest.py
@@ -0,0 +1,86 @@
+from uuid import uuid4
+
+import pytest_asyncio
+from prisma.models import (
+ AgentGraph,
+ AuditLog,
+ Organization,
+ Profile,
+ StoreListing,
+ Team,
+ TransferRequest,
+ User,
+)
+
+
+@pytest_asyncio.fixture(loop_scope="session", params=["AgentGraph", "StoreListing"])
+async def transfer_world(server, request):
+ """Disposable resource, three organizations, and two users in the real DB."""
+ source_user, target_user = str(uuid4()), str(uuid4())
+ for user_id in (source_user, target_user):
+ await User.prisma().create(
+ data={"id": user_id, "email": f"transfer-{user_id}@example.com"}
+ )
+ orgs = [
+ (
+ await Organization.prisma().create(
+ data={"name": f"Transfer {name}", "slug": f"transfer-{name}-{uuid4()}"}
+ )
+ ).id
+ for name in ("a", "b", "c")
+ ]
+ org_a, org_b, org_c = orgs
+ team = await Team.prisma().create(
+ data={"orgId": org_a, "name": "Transfer source", "slug": str(uuid4())}
+ )
+ graph_id = str(uuid4())
+ for version in (1, 2):
+ await AgentGraph.prisma().create(
+ data={
+ "id": graph_id,
+ "version": version,
+ "userId": source_user,
+ "organizationId": org_a,
+ "teamId": team.id,
+ "isActive": version == 2,
+ }
+ )
+ resource_id = graph_id
+ if request.param == "StoreListing":
+ await Profile.prisma().create(
+ data={
+ "userId": source_user,
+ "name": "Transfer creator",
+ "username": f"transfer-{uuid4()}",
+ "description": "",
+ "links": [],
+ }
+ )
+ listing = await StoreListing.prisma().create(
+ data={
+ "agentGraphId": graph_id,
+ "owningUserId": source_user,
+ "owningOrgId": org_a,
+ "slug": f"transfer-{uuid4()}",
+ }
+ )
+ resource_id = listing.id
+
+ yield {
+ "source_user": source_user,
+ "target_user": target_user,
+ "org_a": org_a,
+ "org_b": org_b,
+ "org_c": org_c,
+ "graph_id": graph_id,
+ "resource_id": resource_id,
+ "resource_type": request.param,
+ }
+
+ await AuditLog.prisma().delete_many(where={"organizationId": {"in": orgs}})
+ await TransferRequest.prisma().delete_many(where={"resourceId": resource_id})
+ await StoreListing.prisma().delete_many(where={"agentGraphId": graph_id})
+ await AgentGraph.prisma().delete_many(where={"id": graph_id})
+ await Team.prisma().delete(where={"id": team.id})
+ await Organization.prisma().delete_many(where={"id": {"in": orgs}})
+ await User.prisma().delete_many(where={"id": {"in": [source_user, target_user]}})
diff --git a/autogpt_platform/backend/backend/api/features/transfers/db.py b/autogpt_platform/backend/backend/api/features/transfers/db.py
index bababdff6e..2a642654fd 100644
--- a/autogpt_platform/backend/backend/api/features/transfers/db.py
+++ b/autogpt_platform/backend/backend/api/features/transfers/db.py
@@ -1,16 +1,29 @@
"""Database operations for resource transfer management."""
import logging
-from datetime import datetime, timezone
+from datetime import UTC, datetime
+from typing import NoReturn
-from backend.data.db import prisma
+from prisma import Prisma
+from prisma.models import TransferRequest
+from prisma.types import TransferRequestWhereInput
+
+from backend.data.db import prisma, transaction
from backend.util.exceptions import NotFoundError
+from backend.util.json import SafeJson
from .model import TransferResponse
logger = logging.getLogger(__name__)
_VALID_RESOURCE_TYPES = {"AgentGraph", "StoreListing"}
+_OPEN_STATUSES = ["PENDING", "SOURCE_APPROVED", "TARGET_APPROVED"]
+_TERMINAL_STATUSES = ["COMPLETED", "REJECTED", "CANCELLED"]
+
+
+class _SourceNoLongerOwnsResource(Exception):
+ """Raised inside the execute transaction to roll it back when the source
+ org no longer owns the resource (e.g. a competing transfer ran first)."""
async def create_transfer(
@@ -87,15 +100,20 @@ async def approve_transfer(
if tr is None:
raise NotFoundError(f"Transfer request {transfer_id} not found")
- if tr.status in ("COMPLETED", "REJECTED"):
+ if tr.status in _TERMINAL_STATUSES:
raise ValueError(f"Cannot approve a transfer with status '{tr.status}'")
update_data: dict = {}
+ where: TransferRequestWhereInput = {
+ "id": transfer_id,
+ "status": {"in": _OPEN_STATUSES},
+ }
if org_id == tr.sourceOrganizationId:
if tr.sourceApprovedByUserId is not None:
raise ValueError("Source organization has already approved this transfer")
update_data["sourceApprovedByUserId"] = user_id
+ where["sourceApprovedByUserId"] = None
if tr.targetApprovedByUserId is not None:
# Both sides approved — ready for execution (NOT completed yet)
update_data["status"] = "TARGET_APPROVED"
@@ -106,6 +124,7 @@ async def approve_transfer(
if tr.targetApprovedByUserId is not None:
raise ValueError("Target organization has already approved this transfer")
update_data["targetApprovedByUserId"] = user_id
+ where["targetApprovedByUserId"] = None
if tr.sourceApprovedByUserId is not None:
# Both sides approved — ready for execution (NOT completed yet)
update_data["status"] = "SOURCE_APPROVED"
@@ -115,9 +134,13 @@ async def approve_transfer(
else:
raise ValueError("Your active organization is not a party to this transfer")
- updated = await prisma.transferrequest.update(
- where={"id": transfer_id},
- data=update_data,
+ approved = await prisma.transferrequest.update_many(where=where, data=update_data)
+ if approved == 0:
+ raise ValueError(
+ "Transfer is no longer open or your organization already approved"
+ )
+ updated = await prisma.transferrequest.find_unique_or_raise(
+ where={"id": transfer_id}
)
return TransferResponse.from_db(updated)
@@ -132,16 +155,23 @@ async def reject_transfer(
if tr is None:
raise NotFoundError(f"Transfer request {transfer_id} not found")
- if tr.status in ("COMPLETED", "REJECTED"):
+ if tr.status in _TERMINAL_STATUSES:
raise ValueError(f"Cannot reject a transfer with status '{tr.status}'")
if org_id not in (tr.sourceOrganizationId, tr.targetOrganizationId):
raise ValueError("Your active organization is not a party to this transfer")
- updated = await prisma.transferrequest.update(
- where={"id": transfer_id},
+ # Conditional, so a reject racing an execute can't flip a COMPLETED
+ # transfer (whose resource has already moved) to REJECTED.
+ rejected = await prisma.transferrequest.update_many(
+ where={"id": transfer_id, "status": {"not_in": _TERMINAL_STATUSES}},
data={"status": "REJECTED"},
)
+ if rejected == 0:
+ raise ValueError("Transfer is no longer open")
+ updated = await prisma.transferrequest.find_unique_or_raise(
+ where={"id": transfer_id}
+ )
return TransferResponse.from_db(updated)
@@ -150,12 +180,10 @@ async def execute_transfer(
user_id: str,
org_id: str,
) -> TransferResponse:
- """Execute an approved transfer -- move the resource to the target org.
+ """Atomically execute a transfer approved by both organizations.
- Requires both source and target approvals, and the caller's active org
- must be a party to the transfer — TRANSFER_RESOURCES is granted to every
- personal-org owner, so without this check any authenticated user could
- execute an approved transfer between two unrelated orgs.
+ The caller's active org must be a party, since TRANSFER_RESOURCES alone
+ is granted to every personal-org owner.
"""
tr = await prisma.transferrequest.find_unique(where={"id": transfer_id})
if tr is None:
@@ -172,26 +200,18 @@ async def execute_transfer(
if tr.status == "COMPLETED":
raise ValueError("Transfer has already been executed")
- if tr.status == "REJECTED":
- raise ValueError("Cannot execute a rejected transfer")
-
- await _move_resource(
- resource_type=tr.resourceType,
- resource_id=tr.resourceId,
- target_org_id=tr.targetOrganizationId,
- )
+ if tr.status in _TERMINAL_STATUSES:
+ raise ValueError(f"Cannot execute a transfer with status '{tr.status}'")
- now = datetime.now(timezone.utc)
- updated = await prisma.transferrequest.update(
- where={"id": transfer_id},
- data={"status": "COMPLETED", "completedAt": now},
- )
+ try:
+ async with transaction() as tx:
+ await _execute_in_transaction(tx, tr, user_id)
+ except _SourceNoLongerOwnsResource:
+ await _reject_stale_transfer(transfer_id)
- await _create_audit_logs(
- transfer=updated,
- actor_user_id=user_id,
+ updated = await prisma.transferrequest.find_unique_or_raise(
+ where={"id": transfer_id}
)
-
return TransferResponse.from_db(updated)
@@ -200,12 +220,87 @@ async def execute_transfer(
# ---------------------------------------------------------------------------
+async def _execute_in_transaction(
+ tx: Prisma, transfer: TransferRequest, user_id: str
+) -> None:
+ """Move, complete, audit and close competing requests in the caller's transaction.
+
+ Lock the resource before any TransferRequest row to serialize competing executes.
+ """
+ try:
+ await _validate_resource_ownership(
+ transfer.resourceType,
+ transfer.resourceId,
+ transfer.sourceOrganizationId,
+ db=tx,
+ )
+ except ValueError as e:
+ raise _SourceNoLongerOwnsResource() from e
+
+ moved = await _move_resource(
+ resource_type=transfer.resourceType,
+ resource_id=transfer.resourceId,
+ source_org_id=transfer.sourceOrganizationId,
+ target_org_id=transfer.targetOrganizationId,
+ db=tx,
+ )
+ if moved == 0:
+ raise _SourceNoLongerOwnsResource()
+
+ await _claim_completion(tx, transfer.id)
+ await _create_audit_logs(transfer=transfer, actor_user_id=user_id, db=tx)
+ await _reject_competing_transfers(tx, transfer)
+
+
+async def _claim_completion(tx: Prisma, transfer_id: str) -> None:
+ """Claim an open, fully approved request after its resource has been locked."""
+ claimed = await tx.transferrequest.update_many(
+ where={
+ "id": transfer_id,
+ "status": {"not_in": _TERMINAL_STATUSES},
+ "sourceApprovedByUserId": {"not": None},
+ "targetApprovedByUserId": {"not": None},
+ },
+ data={"status": "COMPLETED", "completedAt": datetime.now(UTC)},
+ )
+ if claimed == 0:
+ raise ValueError("Transfer is no longer open for execution")
+
+
+async def _reject_competing_transfers(tx: Prisma, transfer: TransferRequest) -> None:
+ """Close other open requests whose source can no longer transfer this resource."""
+ await tx.transferrequest.update_many(
+ where={
+ "id": {"not": transfer.id},
+ "resourceType": transfer.resourceType,
+ "resourceId": transfer.resourceId,
+ "status": {"in": _OPEN_STATUSES},
+ },
+ data={"status": "REJECTED"},
+ )
+
+
+async def _reject_stale_transfer(transfer_id: str) -> NoReturn:
+ """Reject after rollback without overwriting a concurrent terminal state."""
+ rejected = await prisma.transferrequest.update_many(
+ where={"id": transfer_id, "status": {"not_in": _TERMINAL_STATUSES}},
+ data={"status": "REJECTED"},
+ )
+ if rejected == 0:
+ raise ValueError("Transfer is no longer open for execution")
+ raise ValueError(
+ "Resource was deleted or no longer belongs to the source "
+ "organization; the transfer has been rejected"
+ )
+
+
async def _validate_resource_ownership(
- resource_type: str, resource_id: str, org_id: str
+ resource_type: str, resource_id: str, org_id: str, db: Prisma | None = None
) -> None:
"""Verify the resource exists and belongs to the given org."""
+ db = db if db is not None else prisma
if resource_type == "AgentGraph":
- graph = await prisma.agentgraph.find_first(
+ graph = await db.agentgraph.find_first(
where={"id": resource_id, "isActive": True}
)
if graph is None:
@@ -214,7 +309,7 @@ async def _validate_resource_ownership(
raise ValueError("AgentGraph does not belong to the source organization")
elif resource_type == "StoreListing":
- listing = await prisma.storelisting.find_unique(where={"id": resource_id})
+ listing = await db.storelisting.find_unique(where={"id": resource_id})
if listing is None or listing.isDeleted:
raise NotFoundError(f"StoreListing '{resource_id}' not found")
if listing.owningOrgId != org_id:
@@ -224,54 +319,67 @@ async def _validate_resource_ownership(
async def _move_resource(
resource_type: str,
resource_id: str,
+ source_org_id: str,
target_org_id: str,
-) -> None:
- """Move the resource to the target organization."""
+ db: Prisma | None = None,
+) -> int:
+ """Move the resource from the source to the target organization.
+
+ Returns the number of rows moved; 0 means the source org no longer owns it.
+ """
+ db = db if db is not None else prisma
if resource_type == "AgentGraph":
# Move ALL versions, not just the active one, and land the graph at
# org-home (teamId=None) — a stale source-org teamId would fail every
# clause of the target org's visibility_filter, making the graph
# invisible to all target-org members.
- await prisma.agentgraph.update_many(
- where={"id": resource_id},
+ return await db.agentgraph.update_many(
+ where={"id": resource_id, "organizationId": source_org_id},
data={"organizationId": target_org_id, "teamId": None},
)
elif resource_type == "StoreListing":
- await prisma.storelisting.update(
- where={"id": resource_id},
+ return await db.storelisting.update_many(
+ where={"id": resource_id, "owningOrgId": source_org_id},
data={"owningOrgId": target_org_id},
)
+ return 0
-async def _create_audit_logs(transfer, actor_user_id: str) -> None:
+
+async def _create_audit_logs(
+ transfer, actor_user_id: str, db: Prisma | None = None
+) -> None:
"""Create audit log entries for both source and target organizations."""
+ db = db if db is not None else prisma
+ # Json columns need SafeJson; a bare dict is rejected by prisma (#15267).
+ after_json = SafeJson(
+ {
+ "resourceType": transfer.resourceType,
+ "resourceId": transfer.resourceId,
+ "sourceOrganizationId": transfer.sourceOrganizationId,
+ "targetOrganizationId": transfer.targetOrganizationId,
+ }
+ )
common = {
"actorUserId": actor_user_id,
"entityType": "TransferRequest",
"entityId": transfer.id,
"action": "TRANSFER_EXECUTED",
- "afterJson": {
- "resourceType": transfer.resourceType,
- "resourceId": transfer.resourceId,
- "sourceOrganizationId": transfer.sourceOrganizationId,
- "targetOrganizationId": transfer.targetOrganizationId,
- },
+ "afterJson": after_json,
"correlationId": transfer.id,
}
- await prisma.auditlog.create(
- data={
- **common,
- "organizationId": transfer.sourceOrganizationId,
- "beforeJson": {"organizationId": transfer.sourceOrganizationId},
- }
- )
-
- await prisma.auditlog.create(
- data={
- **common,
- "organizationId": transfer.targetOrganizationId,
- "beforeJson": {"organizationId": transfer.sourceOrganizationId},
- }
- )
+ for organization_id in (
+ transfer.sourceOrganizationId,
+ transfer.targetOrganizationId,
+ ):
+ await db.auditlog.create(
+ data={
+ **common,
+ "organizationId": organization_id,
+ "beforeJson": SafeJson(
+ {"organizationId": transfer.sourceOrganizationId}
+ ),
+ }
+ )
diff --git a/autogpt_platform/backend/backend/api/features/transfers/db_test.py b/autogpt_platform/backend/backend/api/features/transfers/db_test.py
new file mode 100644
index 0000000000..c66a7cc530
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/transfers/db_test.py
@@ -0,0 +1,253 @@
+"""DB-backed tests for execute_transfer (#15267, #15271).
+
+These run against the real database on purpose: the original audit-log bug
+was invisible to tests that mock ``prisma.auditlog.create``.
+"""
+
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.models import AgentGraph, AuditLog, StoreListing, TransferRequest
+
+from backend.api.features.transfers import db as transfers_db
+
+
+async def _approved_transfer(world: dict, target_org: str) -> str:
+ tr = await transfers_db.create_transfer(
+ source_org_id=world["org_a"],
+ target_org_id=target_org,
+ resource_type=world["resource_type"],
+ resource_id=world["resource_id"],
+ user_id=world["source_user"],
+ )
+ await transfers_db.approve_transfer(tr.id, world["source_user"], world["org_a"])
+ await transfers_db.approve_transfer(tr.id, world["target_user"], target_org)
+ return tr.id
+
+
+async def _resource_orgs(world: dict) -> set[str | None]:
+ if world["resource_type"] == "StoreListing":
+ listing = await StoreListing.prisma().find_unique_or_raise(
+ where={"id": world["resource_id"]}
+ )
+ return {listing.owningOrgId}
+ rows = await AgentGraph.prisma().find_many(where={"id": world["graph_id"]})
+ return {row.organizationId for row in rows}
+
+
+async def _status(transfer_id: str) -> str:
+ tr = await TransferRequest.prisma().find_unique_or_raise(where={"id": transfer_id})
+ return tr.status
+
+
[email protected](loop_scope="session")
+async def test_execute_moves_resource_and_writes_audit_rows(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+
+ result = await transfers_db.execute_transfer(
+ t1, world["source_user"], world["org_a"]
+ )
+
+ assert result.status == "COMPLETED"
+ assert await _resource_orgs(world) == {world["org_b"]}
+ if world["resource_type"] == "AgentGraph":
+ versions = await AgentGraph.prisma().find_many(where={"id": world["graph_id"]})
+ assert len(versions) == 2
+ assert all(
+ v.teamId is None and v.userId == world["source_user"] for v in versions
+ )
+ else:
+ listing = await StoreListing.prisma().find_unique_or_raise(
+ where={"id": world["resource_id"]}
+ )
+ assert listing.owningUserId == world["source_user"]
+ versions = await AgentGraph.prisma().find_many(where={"id": world["graph_id"]})
+ assert all(v.organizationId == world["org_a"] for v in versions)
+ audit = await AuditLog.prisma().find_many(where={"entityId": t1})
+ assert len(audit) == 2
+ assert {row.organizationId for row in audit} == {world["org_a"], world["org_b"]}
+ for row in audit:
+ assert row.action == "TRANSFER_EXECUTED"
+ assert row.afterJson == {
+ "resourceType": world["resource_type"],
+ "resourceId": world["resource_id"],
+ "sourceOrganizationId": world["org_a"],
+ "targetOrganizationId": world["org_b"],
+ }
+ assert row.beforeJson == {"organizationId": world["org_a"]}
+
+
[email protected](loop_scope="session")
+async def test_audit_failure_rolls_back_the_move(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ t2 = await _approved_transfer(world, world["org_c"])
+ audit_actions = type(transfers_db.prisma.auditlog)
+ create_audit = audit_actions.create
+ inserted = []
+
+ async def fail_second_audit(self, **kwargs):
+ if inserted:
+ raise RuntimeError("second audit down")
+ row = await create_audit(self, **kwargs)
+ inserted.append(row.id)
+ return row
+
+ with (
+ patch.object(audit_actions, "create", fail_second_audit),
+ pytest.raises(RuntimeError, match="second audit down"),
+ ):
+ await transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+
+ assert len(inserted) == 1
+ assert await _resource_orgs(world) == {world["org_a"]}
+ assert await _status(t1) == "SOURCE_APPROVED"
+ assert await _status(t2) == "SOURCE_APPROVED"
+ assert await AuditLog.prisma().count(where={"entityId": t1}) == 0
+
+
[email protected](loop_scope="session")
+async def test_stale_transfer_cannot_move_resource_away_from_new_owner(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ t2 = await _approved_transfer(world, world["org_c"])
+
+ await transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+
+ # Executing T1 closes the competing T2...
+ assert await _status(t2) == "REJECTED"
+ with pytest.raises(ValueError):
+ await transfers_db.execute_transfer(t2, world["source_user"], world["org_a"])
+ assert await _resource_orgs(world) == {world["org_b"]}
+
+ # ...and even if T2 were still open, execute re-checks ownership.
+ await TransferRequest.prisma().update(
+ where={"id": t2}, data={"status": "SOURCE_APPROVED"}
+ )
+ with pytest.raises(ValueError, match="no longer belongs"):
+ await transfers_db.execute_transfer(t2, world["source_user"], world["org_a"])
+ assert await _resource_orgs(world) == {world["org_b"]}
+ assert await _status(t2) == "REJECTED"
+
+
[email protected](loop_scope="session")
+async def test_deleted_resource_rejects_the_transfer(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ if world["resource_type"] == "AgentGraph":
+ await AgentGraph.prisma().update_many(
+ where={"id": world["graph_id"]}, data={"isActive": False}
+ )
+ else:
+ await StoreListing.prisma().update(
+ where={"id": world["resource_id"]}, data={"isDeleted": True}
+ )
+
+ with pytest.raises(ValueError):
+ await transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+
+ assert await _resource_orgs(world) == {world["org_a"]}
+ assert await _status(t1) == "REJECTED"
+
+
[email protected](loop_scope="session")
+async def test_cancelled_transfer_cannot_be_executed(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ await TransferRequest.prisma().update(
+ where={"id": t1}, data={"status": "CANCELLED"}
+ )
+
+ with pytest.raises(ValueError):
+ await transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+
+ assert await _resource_orgs(world) == {world["org_a"]}
+ assert await _status(t1) == "CANCELLED"
+
+
[email protected](loop_scope="session")
+async def test_reject_racing_execute_cannot_undo_a_completed_transfer(
+ transfer_world,
+):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ # The reject read the transfer while it was still open...
+ stale = await TransferRequest.prisma().find_unique_or_raise(where={"id": t1})
+
+ # ...then the execute committed before the reject wrote.
+ await transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+
+ # The actions object uses __slots__, so patch its class for this call.
+ with patch.object(
+ type(transfers_db.prisma.transferrequest),
+ "find_unique",
+ AsyncMock(return_value=stale),
+ ), pytest.raises(ValueError):
+ await transfers_db.reject_transfer(t1, world["target_user"], world["org_b"])
+
+ assert await _status(t1) == "COMPLETED"
+ assert await _resource_orgs(world) == {world["org_b"]}
+
+
[email protected](loop_scope="session")
+async def test_concurrent_competing_transfers_move_resource_once(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ t2 = await _approved_transfer(world, world["org_c"])
+
+ results = await asyncio.gather(
+ transfers_db.execute_transfer(t1, world["source_user"], world["org_a"]),
+ transfers_db.execute_transfer(t2, world["source_user"], world["org_a"]),
+ return_exceptions=True,
+ )
+
+ completed = [r for r in results if not isinstance(r, BaseException)]
+ assert len(completed) == 1, results
+ # The loser gets a clean ValueError (400), not a DB/deadlock error.
+ assert all(isinstance(r, ValueError) for r in results if r not in completed)
+ winner_org = completed[0].target_organization_id
+ assert await _resource_orgs(world) == {winner_org}
+ statuses = sorted([await _status(t1), await _status(t2)])
+ assert statuses == ["COMPLETED", "REJECTED"]
+
+
[email protected](loop_scope="session")
+async def test_concurrent_double_execute_moves_once(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+
+ results = await asyncio.gather(
+ *(
+ transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+ for _ in range(2)
+ ),
+ return_exceptions=True,
+ )
+
+ assert sum(not isinstance(r, BaseException) for r in results) == 1, results
+ assert all(
+ isinstance(r, (ValueError, transfers_db.TransferResponse)) for r in results
+ ), results
+ assert await _status(t1) == "COMPLETED"
+ assert await AuditLog.prisma().count(where={"entityId": t1}) == 2
+
+
[email protected](loop_scope="session")
+async def test_execute_claim_rechecks_status_after_stale_read(transfer_world):
+ world = transfer_world
+ t1 = await _approved_transfer(world, world["org_b"])
+ stale = await TransferRequest.prisma().find_unique_or_raise(where={"id": t1})
+ await transfers_db.reject_transfer(t1, world["target_user"], world["org_b"])
+
+ with patch.object(
+ type(transfers_db.prisma.transferrequest),
+ "find_unique",
+ AsyncMock(return_value=stale),
+ ), pytest.raises(ValueError, match="no longer open"):
+ await transfers_db.execute_transfer(t1, world["source_user"], world["org_a"])
+
+ assert await _resource_orgs(world) == {world["org_a"]}
+ assert await _status(t1) == "REJECTED"
+ assert await AuditLog.prisma().count(where={"entityId": t1}) == 0